Compare commits

...
Author SHA1 Message Date
feder-cr 4161449bee ci: the drive gate launches through the core (the engine waits for the session's road; bare Playwright never sends it); the declaration test does not resolve an engine 2026-11-12 03:19:43 +01:00
feder-crandClaude Sonnet 5.5 fd564c38f4 tests: the chain by name declares the FakeDoh's own provider (doh.gateway.test): the DoH of Mozilla is HSTS-preloaded and takes no override
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-11 23:07:23 +01:00
feder-crandClaude Sonnet 5.5 d84f24b6e5 tests: the fake DoH of the e2e uses a name that is not HSTS-preloaded (doh.gateway.test at 192.0.2.53), declared through extra_prefs
Firefox refuses certificate overrides for HSTS-preloaded/pinned hosts, so a self-signed fake for
mozilla.cloudflare-dns.com could never be accepted. The test now declares its own provider
(network.trr.uri, network.trr.bootstrapAddr) and counts every connection of the browser, including
the background traffic of the default context whose TLS fails by design, at the gateways.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-11 23:04:44 +01:00
feder-crandClaude Sonnet 5.5 6f25adc2e5 tests: the git identity of the verdict test is a plain word
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-11 20:47:48 +01:00
feder-crandClaude Sonnet 5.5 cd062e2c59 tests: the DoH prefs follow the new split (the core declares the provider, the engine the state and the excluded names)
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-11 20:45:16 +01:00
feder-crandClaude Sonnet 5.5 5a617dd899 ci: the verdict judge closes the holes a review found (main comparison, complete, exact counts, xunit2, commit, list validation, DoH trap)
- main: --main-required compares when the file is there; --main-has-no-list (the gate's declaration that main was checked
  out and has none) passes declared; a missing path without it is red. A failed download is no longer "main has no list".
- complete: every (suite, os) of the list reported a green result, no stranger, one commit, one binary per OS.
- exact: every row says whether collected must equal min_tests; the result json carries verdict green|red.
- the junit must be xunit2 (classname present, no file/line); the commit is --commit or git HEAD, never GITHUB_SHA;
  --binary is mandatory and must exist; --seal is read (it carries no sha256 of the binary: said, not compared).
- the list is validated by args, judge and complete (exit 2 with the reason); against main also exact, os, tests, marker.
- DoH e2e: with INVPW_REQUIRE_TRAP=1 a resolver trap that cannot run or bind is a failure, not a silent skip.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-11 20:37:00 +01:00
feder-crandClaude Sonnet 5.5 793ea3d191 tests: the DoH negative control does not skip where the resolver trap cannot run (Windows reaches the page by a name the system resolves by itself)
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-11 20:24:38 +01:00
feder-crandClaude Sonnet 5.5 154a9de475 ci: the list of mandatory suites and its one judge (ci/required-suites.json, scripts/ci_verdict.py)
The list names three suites with the least number of tests each must collect (wrapper.e2e.udp 51,
wrapper.e2e.doh 8, wrapper.unit.udp 86). ci_verdict.py prints the pytest arguments of a suite and judges
its junit: a failure, an error, a skip, too few tests, a required file or node id that did not pass, and
a list that lost a suite, a minimum or a test against main are all red, each said with its reason.

The leak watcher's file defined a test that skipped on every host; the two resolver-trap tests now exist
one per host (collected, never skipped), so the unit suite allows no skip.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-11 20:24:09 +01:00
feder-crandClaude Sonnet 5.5 7ef736ca73 tests: the UDP line e2e need the engine that carries it (firefox-63); a missing websockets, aioquic or h2 is a failure, not a skip
The dev extra installs all three; a gate that skips for want of one proves nothing. main's e2e fetches the published engine 62, where the
declared network, the DoH through the proxy and the SOCKS5 UDP layer do not exist: those tests skip there and run on the candidate.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-11 20:17:28 +01:00
feder-crandClaude Sonnet 5.5 d6f5c884b4 tests: the TURN name of the udp chain is resolved by the DoH through the proxy, not by the gateway
Chain is now a DohGateway (one SOCKS5 gateway in tests/): a CONNECT to the DoH goes to a FakeDoh whose zone is the TURN and
the page names, the datagram to TURN_IP goes to the TURN server by address (type 1), a name on the relay or a query to port 53
is dropped and recorded. DnsServer and the type-3 branch are gone. DohGateway takes the Gateway options (UDP relay, rtt) and
delays its tunnels by half the round trip like the base gateway. explain() lists what the DoH, the gateway, the TURN server and
the page saw, and says why.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-11 20:15:44 +01:00
feder-crandClaude Sonnet 5.5 183219ce18 tests: the names of a proxied session go to DoH through the proxy (written ahead of the engine)
E2E for the contract of core-19/motore-18, plus the hermetic helpers they stand
on, which are unit-tested now: a hand-written DoH server (h2 and HTTP/1.1), a
SOCKS5 gateway and an HTTP proxy that hand the DoH CONNECT to it and tag each
query with their name, a connection watcher and a resolver trap. The e2e skip
without a binary and cannot be green before the engine that keeps the contract.
test_integration follows the core: no host_ip pref, no DNS gate switch, TRR mode 3.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-11 20:10:33 +01:00
feder-crandClaude Sonnet 5.5 5c66186464 tests: a page reached over IPv6 gathers host candidates on a machine declared without IPv6 (hermetic, [::1], no proxy)
Red on an engine before ddaf867f03: the gathering is empty. Needs the firefox-63 build to run: not run here.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-11 20:08:21 +01:00
feder-crandClaude Sonnet 5.5 7ddb451af7 tests: the stock Playwright client is required by the networkidle e2e (explicit failure, never a skip); the dev extra pins it
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-11 20:06:56 +01:00
feder-crandClaude Sonnet 5.5 98d9a799f6 server: the answer to a request the browser has already closed is not an error (Cannot find request), as stock sendMayFail
A page cancels requests while a route is deciding (a fetch aborted, an image replaced, an iframe removed, a beacon with
its document). The engine takes the request out of its held set at once and the late continue/abort/fulfill meets
"Cannot find request". Stock Playwright sends the interception commands as may-fail and tells the client nothing; ours
passed the error up, the client kept it as the error of the whole connection and raised it on the NEXT route command,
which was then never sent: its request stayed held in the engine, its handler failed too, and so on down the page. Seen
on a real news page: six held requests in a row, one a beacon, and networkidle never came.

RouteDispatcher._send now treats "Cannot find request" and a closed target as done (still disposed); any other protocol
error still reaches the client.

Tests: the e2e with a plain handler (no try) on a page that removes an iframe whose requests are held (red before: networkidle
never, 25 s; green after; the fetch and image shapes were green before too), and a static guard that every op of
RouteDispatcher (abort, continue, fulfill, redirect) goes through _send and that _send swallows exactly those two.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-11 20:06:10 +01:00
feder-crandClaude Sonnet 5.5 f9221ae3c2 tests: networkidle through a served browser whose context routes every request, on a reused page
launch_server() plus a stock Playwright client, a context route that aborts image/font/media and continues the rest, a
page with sendBeacon, the same font twice, a frame of another site, a worker, redirects, requests the page cancels while a
slow route decides, 100 requests at once, and a slow client that answers concurrently (async). Every shape reaches
networkidle on firefox-62; one page reused for twelve addresses too. The leak that tf-fetch meets on real sites needs
end events the engine loses, which no local page produces: its deterministic red/green is in the core
(tests/test_networkidle_on_a_reused_page.py of invisible-core); this file guards the remote path end to end.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-11 20:06:10 +01:00
feder-crandClaude Sonnet 5.5 41f7bec7a7 dev extra: aioquic, so the two HTTP/3 e2e run in the gate instead of being skipped by importorskip
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-11 19:31:39 +01:00
feder-crandClaude Sonnet 5.5 56b33a7740 UDP line: the e2e of the proxy for a context, the chain by name, the declared host network, and the wrapper that declares it
Squash of the local integration branch (one branch for the candidate):
- e2e behind a gateway with coherent UDP (the cost of a gather, two contexts, a proxy without UDP, TURN over TCP of a context,
  HTTP/3 through the proxy) and one hermetic SOCKS5 gateway helper under them;
- the whole UDP chain by name behind a gateway at 130 ms (hermetic);
- the declared host network e2e (interfaces, ports, two connections);
- the wrapper declares the host network from the session seed (no srflx, no UDP verdict, no host_ip any more);
- the integration test follows the declared network and the DoH of the session proxy.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-11 18:34:26 +01:00
Federico EliaandClaude Opus 5.5 b6d32402f2 README: browser launches up top, in a big badge row (#453)
The launch count was a small badge at the very bottom. It now opens the
README, under the banner, next to engine downloads and stars. The daily
counters job also writes launches.json and downloads.json on the badges
branch; shields.io draws the big badges from them, so the numbers still
come only from our snapshot.

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-11 15:15:12 +01:00
Federico EliaandClaude Opus 5.5 82d88c848f Release 0.50.0: engine firefox-62 (Fission strategy 1), pin invisible-core 62.63.0 (#450)
* grant_permissions: the permission names are the engine's, a name outside the table is refused, and no origin is every origin

The wrapper passed the web names (geolocation, notifications) to the engine, which keeps a grant under its own
(geo, desktop-notification) and stored one under a name it never reads: a page of a context that had been granted
geolocation and given a position was still denied. The table is the Playwright client's for this browser
(playwright-core ffBrowser.js, doGrantPermissions); a name outside it is an error, as there. A grant with no
origin was sent as the empty string, which the engine's lookup reads as false and answers with '*', where nothing
was held: it is now '*'. Tests: the table and the refusals as units, and the position of a granted page as an e2e
that fails on the old code (denied, or no answer).

* tests: the sentinels of the isolation strategy hold strategy 1, not 0

The baseline of a core that runs Fission (strategy 1, autostart, four isolated content processes) is what the
firefox-62 engine is built for: the Juggler reaches an iframe of another process like any other. The four unit
tests of test_cross_origin_iframe.py held the opposite (strategy 0, autostart off, one isolated process) and are
turned round: strategy 1, autostart on, fission.autostart.session absent (the parent writes it), four isolated
processes, the default of a translated profile 1, and an override to 0 only when a caller sets it. They fail on
invisible-core 61.62.0 and pass on a core with the strategy-1 baseline (invisible_core ffced25); the pin moves with
that core. The module text says why a harness of two ports of one host is one site and where the iframes that leave
the process are held.

* changelog: Fission (strategy 1) and the permission names, to be confirmed by the firefox-62 build

* e2e: the bench for Fission strategy 1 (a.test / b.test, a -> b -> a): two tests that hold it, eight that say what is not done yet

The prefs are an overlay of the file (strategy 1, autostart, four isolated processes, the test hosts through
network.dns.localDomains); the wrapper's baseline stays at strategy 0. Tests 1 and 2 pass today (a cross-site
frame adds a content process, a same-site one does not); tests 3 to 10 fail today on the empty url of a frame of
another process, the missing context, the missing parent chain, describeNode on a cross-origin element, the init
script that does not reach the other process, and the console that does not arrive.

(cherry picked from commit a8edf34d5f2da5e5e142359efe0dfaa801f5d57d)

* e2e: the bench of Fission strategy 1 reads the client's events while it waits, and holds three cases of step 1

The sync client takes the engine's events only inside its own calls: the waits of the bench now go through
page.wait_for_timeout. Added: a context of the top survives a frame of another process coming and going (a guard),
the frame of another process comes back after the top is restored from the back-forward cache, and a removed frame
of another process leaves page.frames and the page keeps answering.

(cherry picked from commit b9483514bb0be7712f378e1fbdc9ffd5701634b3)

* e2e: the bench splits the restore from the back-forward cache in the frames that come back and the url and contexts that come with them

The first is green with the parent re-announcing the frames it knows; the second stays red until the parent's
registry of navigations (step 3) and the mux's re-announcement of contexts (step 2b). set_extra_http_headers is not
in the wrapper's perimeter, so the removed-frame test uses the init script alone.

(cherry picked from commit 47a9d6f59ab237e173fe3c271fa37cbafe6e0668)

* e2e: element-to-frame and iframe geometry across processes (Fission strategy 1)

(cherry picked from commit 3ec3752333e76baaebdbbd78263028237fdda86a)

* tests: the crash of an iframe's process leaves the tab (firefox-62, Fission)

Kills the process that holds the iframe (found through the engine over Marionette, required to differ from the top's) and asserts the tab stays, no Page.crashed or close, and the page answers. Red on firefox-61: the unpatched engine closes the tab.

(cherry picked from commit 1e90ff23b3c3827cac943f926f30eeccaa6ec3aa)

* tests: the mouse events of the page and of a same-process iframe keep their order and values

Sequences recorded on firefox-61 (click, double click, right click with contextmenu, moves with the button down), through page.mouse; the test passes there and has to pass on the engine whose mouse takes the APZ route (a click on an iframe of another site needs the hit test).

(cherry picked from commit 4374fcab3c3e6718239cd36bad9c2970e1626aec)

* Test that the identity is the same in the top document and in every iframe

One local server on 127.0.0.1, 127.0.0.2 and 127.0.0.3 serves a top page with an
iframe on a second site (holding a nested frame on the top's own site) and an
iframe on a third site. Each document reads a fixed canvas drawing, a fixed
OfflineAudioContext buffer, the WebGL debug renderer info, the Intl time zone,
the navigator language and user agent, the screen geometry, the pixel ratio and
a font of the bundle, and posts them to the top; the test asserts they are equal
everywhere. screenX and screenY are read and not compared.

It runs under strategy 0 (what the core writes today) and under strategy 1
(fission.autostart and webContentIsolationStrategy=1 as extra_prefs). Each run
proves where the iframes ran from inside the page: one iframe spins for 400 ms
and the top times a 10 ms timer, which stalls only in a shared process.

The negative case is the machine the seed describes (WebGL renderer and screen),
because the 2D canvas and the audio buffer carry no per-seed value. The pure
comparison has unit tests with known-bad inputs.

(cherry picked from commit 76cae1a19abd65b30b72ea317dc42110541c8745)

* e2e: an iframe nested too deep names no frame, and a frame of another process comes out of the cache with the top

(cherry picked from commit 7f71460d799d8271346f470b0b2ad06c0a5315fb)

* e2e: the Fission tests that firefox-61 cannot pass wait for firefox-62

Measured on the released firefox-61 (Linux, run_e2e.py, 4 browsers): these twelve fail there and nothing else in
the six Fission files does. Ten of the bench (the steps that are not in firefox-61) and two of the
element-to-frame file (an <embed> of another process and the detach of a removed iframe). They now take
engine_at_least("firefox-62"), so the gate on firefox-61 is green (43 passed, 13 skipped) and the candidate runs them.

* e2e: a navigation that changes the process is stopped, replaced, refused or cut the way one that does not is

* e2e: an iframe whose src goes to another site shows the new address in the frame list

* A frame that left the page answers a call with "Frame was detached", not "Target page, context or browser has been closed"

The server disposed the dispatcher of a frame as soon as the lifecycle retired it, so the next call on the Frame object (an
iframe a script or a framework removed) named a guid that no longer existed and was answered as if the page had closed.
Measured with a process per site and without it: frame_element, evaluate, content and query_selector on a removed iframe,
all four. Playwright's driver never disposes a Frame at detach; the call reaches its dispatcher, which refuses it with
"Frame was detached". The frame stays registered (collected with its page or by its bucket, as the driver's), refuses every
call, and its element handles go with it.

Test: test_a_detached_frame_answers_detached.py (7 of its 10 fail on the old server code); test_frame_dispatch.py still
passes; test_a_removed_iframe_is_detached (the Fission e2e) passes on an engine with the Juggler of the integration.

* e2e: a worker leaves with its page for the back-forward cache and comes back the same (Fission strategy 1)

A document starts a worker that counts; the top goes forward (same site or another, by page.goto or by the page's
own location.href) and comes back from the cache (pageshow.persisted is checked). The protocol events the client
receives must say: workerCreated, workerDestroyed before the new page commits, workerCreated again with the same
workerId once after the restore's contexts are cleared, no workerDestroyed after it, one live worker that answers 3.
The worker lives in the top or in a frame of another site. engine_at_least("firefox-62"): it skips on firefox-61.

Measured on repacks of fission/integration (Linux, strategy 1): red on bdf02eb9d8 and on 1e9ff6dec0. In the top the
worker comes back under a new workerId; in the out-of-process frame it is not announced again.

* changelog: the Fission and permission-name entries are under 0.50.0

* e2e: the frames have their urls when goto returns (an iframe of another site, 50 runs, nothing waited for)

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>

* e2e: a goto to the address the page is at ends, 20 times, on nine kinds of page (sites isolated)

Plain, big, revalidated with a 304, fresh in the cache, never stored, a frame of its own site, a frame of another
site (also revalidated), a -> b -> a, and the same query twice. Red on the engine of fission/integration 14e826b7b5
(load not reached, navigation started and neither committed nor aborted), green with the Juggler fix.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>

* A launch that names no session gets one: op_launch writes a composed session into every profile

A bare BrowserType.launch on the server (Playwright's own suite, any client of invisible_playwright._pw)
sent no prefs, and op_launch wrote into user.js only what the client sent: the engine came up with
Mozilla's defaults, no persona, every value a page reads taken from the machine. On Linux the first window
then also held the first-run policy tab of TelemetryReportingPolicy (the Terms of Use the core declares
accepted were not), and the first new_page failed with "Browser.newPage: Unexpected number of tabs in the
new window: 2": 15 of 15 bare launches on firefox-61 and on the firefox-62 candidate; with
datareporting.policy.firstRunURL emptied alone, 1 tab every time.

The launcher marks what it composes (COMPOSED_PREF, taken out before user.js like the seed); an unmarked
launch gets the session InvisiblePlaywright() composes with the server's defaults (new seed, humanize off as
in launch_server), with the caller's prefs on top. launch_server already sent a composed session: its e2e
and a unit test on the mark guard it. The one network step of composing (the egress IP) has one name,
_session.session_geo, which the unit tests answer offline.

Tests: test_a_launch_without_a_session_gets_one.py (4 unit: red on the old code, the profile held 0 prefs),
test_a_launch_without_a_session_gets_one_e2e.py (a bare launch has one tab and says Windows on the Linux
engine: red on the old code with "Unexpected number of tabs: 2"; every context of a served browser is the
same Windows machine). Unit suite 1128 passed on the firefox-62 candidate image.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* A launch that names no session also gets the session's environment variables

The variables `build_env` adds (the font manifest, the display backend, the crash reporter, the WebRTC
declaration with a proxy) are added to the environment of a launch that names no session, wherever the
caller named none of the same name. Unit tests: the manifest reaches a bare launch, a variable the caller
names wins, a composed launch gets nothing it did not send.

Measured before keeping it: no page-visible difference. On the firefox-62 candidate (Linux) and on
firefox-61 (Windows) a page of a bare launch lists the same families with and without the manifest: the
bundle's (Segoe UI, Calibri, the substitutes such as Helv and MS Sans Serif), none of the host's (FreeSans,
Unifont, Liberation Sans in the container; Segoe UI Variable on the Windows host). The engine uses its
packaged copy when the variable is absent.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* The session of a bare launch is composed through the launch's proxy; e2e: behind a proxy the page reads the egress as its srflx

`launch(proxy=...)` reaches `session_for_launch`, and the session is composed through it as
`InvisiblePlaywright(proxy=...)` composes: the egress measured there is the address the session's
environment declares for WebRTC (STEALTHFOX_WEBRTC_PUBLIC_IP). The engine is still told the proxy by
op_launch (Browser.setBrowserProxy), as before.

e2e test_a_bare_launch_behind_a_proxy_declares_the_egress_as_its_srflx: a bare launch behind the local
TCP-only SOCKS5 of test_webrtc_realness.py, the egress answered with 203.0.113.7 (RFC 5737). The page must
read a srflx of that address. Red on the prefs-only commit (no srflx of the egress: host candidates only)
and on release/firefox-62 (the two-tab refusal); green here. Unit suite green on the firefox-62 candidate.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* tests: the named environment of an unmarked launch carries the session's variables, and still nothing of the server's

test_the_launch_handler_hands_the_named_environment_to_the_engine asserted the engine got exactly the named
variables (plus the session's TMP). An unmarked launch now also gets the variables of the session the server
composes for it (font manifest, display backend, crash reporter): the test reads them from
_session.default_session and keeps its point, WAYLAND_DISPLAY of the server's own process stays out.
It went red on 36cffac, which I committed without running the whole unit suite.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* tests: the same-document navigation test attaches the frame it reports on

The engine announces a frame (Page.frameAttached) before any event of it, and from invisible-core's fix on
release/firefox-62 the lifecycle makes frames of that event alone: an event of a frame it does not know is
dropped. The three tests of this file reported events of a frame "F1" they never attached, which only the old
auto-creation accepted. Green with the old core and with the new one.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* tests: the gates of the shelved line ask for firefox-63 again; firefox-62 is the Fission release

#444 renumbered the engine gates when the shelved line (idwr text, canvas colours and ICC readback, maths,
media decoding, WebGL arithmetic, the Linux system-theme refusal) was firefox-62. That line is firefox-63 now
and firefox-62 is Fission (one process per site), which has none of those properties: on the firefox-62
candidate 14 of those tests ran and failed (WebGL dot, canvas text, ClearType, ICC, fonts and colours,
WebCodecs). The seventeen files #444 touched ask for firefox-63 (comments and docstrings too), conftest.py
names the same number, and tests/unit/test_engine_at_least.py checks that 61 and 62 skip a gate that asks 63.
The Fission tests (bench, worker, crash, oop_frame_element, goto to the same url, raw launch, mouse events,
cross-origin iframe) keep firefox-62. Default suite: 1131 passed, 8 skipped; the three reds are the install
metadata of the shared Python.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>

* tests: the hand-built InjectedScript of the adopt test has the detached frames the wait for a world reads

invisible-core 62's wait for a frame's world ends at the frame's detach and reads InjectedScript._gone, which __init__
makes. test_adopt_is_one_wire_call_for_both_crossings builds the object without __init__ and sets what __init__ gives
it by hand; it now sets _gone too. (Red on the core with the detach wait: "no attribute '_gone'".)

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>

* Release 0.50.0: pin invisible-core 62.63.0 (engine firefox-62, Fission strategy 1)

CHANGELOG 0.50.0: the engine entry, and the fixes of the bare launch and of a detached frame; the
Fission and permission-name entries were waiting for the firefox-62 build, which shows them (candidate #6).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* tests: the docstring of the bare-launch e2e says what the served browser is for, not who runs it

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* tests: the gates of the shelved line ask for firefox-64; firefox-63 is the coherent UDP

The 16 e2e files of the shelved line (idwr text, colours, maths, media, WebGL, host-free Linux),
conftest's description of engine_at_least and its unit test: firefox-62 and firefox-63 skip them.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* tests: the refused iframe's address is read by scheme and host, not by a prefix of the string

CodeQL (incomplete URL substring sanitization) flagged the startswith on the frame's url; the
split url says the same thing and cannot match a longer host. The file passes on firefox-62 (5 of 5).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

---------

Co-authored-by: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-11 12:39:30 +01:00
github-actions[bot]andfeder-cr e2a006d1c9 record 0.49.1 as published (#449)
Co-authored-by: feder-cr <85809106+feder-cr@users.noreply.github.com>
2026-11-10 20:17:23 +01:00
Federico EliaandClaude Sonnet 5.5 c33b9dd8f2 0.49.1: the firefox-61 engine through invisible-core 61.62.0 (#448)
* Add INVPW_GC_EVERY_NAV: optional Heap.collectGarbage every N main-frame navigations

Off by default. The collection is sent from a daemon thread (never from the
reader thread, which would deadlock), with at most one in flight; a round
due while one runs is skipped and counted, and every error is swallowed.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>

* INVPW_GC_EVERY_NAV: send the collection with the page session; fix page.request_gc

Juggler answers Heap.collectGarbage from its page handler. Sent with the
browser-level connection it fails with 'Handler for does not implement method',
so the first version of the option counted every collection as failed, and
page.request_gc() has been failing the same way.

The option now sends with the session of the page that committed (a thread of its
own, one in flight); op_request_gc uses the page session too. Tests fail on the
old code and pass on the fix; measured on the engine: collections take 0.02-0.09 s
and the values a page reads are identical with the option on and off.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>

* INVPW_GC_MODE=minimize: the option can send Heap.minimizeMemory, with a fallback to gc

INVPW_GC_MODE=gc|minimize (default gc) says what INVPW_GC_EVERY_NAV sends. minimize sends the
Juggler command that runs about:memory's "Minimize memory usage" (engine commit 2423b7c242 of
the engine's juggler/minimize branch); on an engine without it the first round logs one
warning and falls back to Heap.collectGarbage for that round and every later one (the
engine's answer, "method '...' is not supported", is the sign).

Unit tests for the mode, the fallback and the other errors; e2e (engine_at_least firefox-61)
that the engine takes the command and, as documentation, that minimize evicts the bfcache
(pageshow.persisted false on go_back) where nothing sent leaves it true. Measured on the
engine with the command, and on the one without: the first and third e2e fail there.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>

* INVPW_GC_MODE: the command must be named in the error that makes minimize fall back to gc

A fallback on any error saying "is not supported" would turn the mode down for good on an
unrelated error; the sign of an engine without the command is its answer naming it
("method 'Heap.minimizeMemory' is not supported", or 'does not implement method "..."').
Also the docs say what the command is: the memory manager's MinimizeMemoryUsage.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>

* tests: the minimize e2e uses a plain protocol client, and the protocol-name scan lets the engine-gated name through

The e2e imported the installed Playwright (test_fork forbids it) and the vendored client has no
connect: it now speaks the protocol over the served WebSocket, like the other served-browser e2e.
Re-run on an engine with the command (all three pass) and on one without (the first and the third
fail, with the fallback warning).

Heap.minimizeMemory is written by navgc.py for an engine the published core's protocol mirror does
not describe yet, behind a fallback to the older command. test_protocol_names_are_declared keeps it
in AHEAD_OF_THE_MIRROR, still checks every other name, and a last test fails when the mirror gets
the command, saying to delete it from the list.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>

* The periodic collection option is out: only the page.request_gc() fix stays

The engine has no behaviour that stock Playwright's Juggler lacks, and a server option that
sends a memory command on a schedule is one. INVPW_GC_EVERY_NAV and INVPW_GC_MODE, navgc.py,
the hook in the commit path, their unit tests, the e2e of the engine command and the entry in
the protocol-name scan leave the branch.

What stays is a defect of the standard API: page.request_gc() sent Heap.collectGarbage on the
browser connection, whose handler does not have it, so it failed on every call; it is now sent
with the session of the page. The test fails on main's server.py and passes here.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>

* 0.49.1: page.request_gc() works on a served browser

A change to the package's code takes a new version and a changelog entry: 0.49.0 is published.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>

* tests: the web fonts of closed contexts leave WebRender's shared archive (firefox-61)

A probe opens N contexts, each with a page that loads a web font of its own
bytes, closes them, and reads explicit/gfx/webrender/resource-cache/fonts from
a memory report (Marionette, chrome scope) before, with contexts open, and
after. On firefox-60 the archive keeps ~1 MB per closed context (10/20/40
contexts: 10.4/19.8/40.7 MB, measured); the test asserts it is back at what it
was from firefox-61 and is skipped on an older engine.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>

* Disable the context cache while a route is active, as upstream

Playwright's ffBrowser.doUpdateRequestInterception sends
Browser.setCacheDisabled with the same flag as Browser.setRequestInterception.
The server sent only the second, so a routed context filled the engine's cache2
on disk. op_set_interception now sends both, for the same context.

* tests: a context that ends leaves no content process (e2e, from firefox-61)

A page that registers a service worker whose script is `for (;;) {}` kept its content process alive
after its context was closed. The test closes three such contexts and counts the web content
processes after each; on an engine without the fix the count grows by one per context ([4, 5, 6]),
with it it does not. Skipped on an engine older than firefox-61.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>

* 0.49.1: the firefox-61 engine through invisible-core 61.62.0 (prepared, not pushed)

Pin to the core that carries the firefox-61 seal (the core is not published yet) and the changelog of the
engine's four fixes, on top of the four open branches this release carries: page.request_gc() (#442), the
context route and the cache (#447), the web fonts of closed contexts (#445) and the processes of an ended
context (#446).

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>

* tests: the process count of an ended context is compared from the second context on, over five

On the Linux gate the count after the three contexts was [2, 3, 3]: the first context adds one process
that is not the leak (a spare content process the engine starts when the first page takes one) and
then the line is flat, and counts[2] <= counts[0] failed on the engine WITH the fix. Five contexts, and
the last must not be above the second: with the fix [.., 3, 3, 3], on the old engine every context adds
one ([4, 5, 6, 7, 8] measured on Windows). Run on both engines locally.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>

---------

Co-authored-by: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-10 19:46:25 +01:00
Federico EliaandClaude Sonnet 5.5 ebaed54e0e tests: the engine gates that ask for firefox-61 ask for firefox-62 (#444)
The corrections release is firefox-61 now, and the shelved line (idwr text, canvas colours and ICC
readback, maths, media decoding, WebGL arithmetic, the Linux system-theme refusal) is firefox-62.
The seventeen files whose engine_at_least gate asked for firefox-61 ask for firefox-62, comments and
docstrings too; conftest.py names the same number in its comment and docstring.

tests/unit/test_engine_at_least.py: the engines firefox-61 and firefox-61-candidate are skipped by a
gate that asks for 62. With the old minimum (61) three of its cases fail; with 62 the file passes.

Default suite in a clean checkout: 1084 passed, 9 skipped.

Co-authored-by: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-10 16:55:10 +01:00
github-actions[bot]andfeder-cr 8de4cd2c9f record 0.49.0 as published (#443)
Co-authored-by: feder-cr <85809106+feder-cr@users.noreply.github.com>
2026-11-10 15:03:28 +01:00
Federico EliaandClaude Opus 5.5 087117dfc6 0.49.0: the firefox-60 engine through invisible-core 60.61.0 (#441)
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-10 14:27:39 +01:00
Federico EliaandClaude Sonnet 5.5 b85c8f49a1 tests: the body of a document the tab left is evicted (e2e, from firefox-60) (#440)
The engine of firefox-60 evicts, when the main frame commits a navigation, the bodies of the documents the tab
left, as Chromium does; a body over the cap already answered 'evicted'. The test serves two pages from a local
server, reads the bodies of the current document, then of the one that was left, and checks that the second
context and the page still work after the bodies are gone.

Gated with engine_at_least('firefox-60'): skipped on firefox-59 (checked with the real gate), and run by hand
against a copy of the firefox-59 engine with the fix it passes, against the unmodified one the first test fails
with 'DID NOT RAISE'.

Co-authored-by: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-10 12:07:59 +01:00
Federico EliaandClaude Sonnet 5.5 e82ae18bac tests: the engine gates that ask for "firefox-60" ask for "firefox-61", the name of the shelved line (#439)
Seventeen e2e files skip unless the engine is at least "firefox-60": the idwr text, the canvas
colours and ICC readback, the maths, the media decoding, the WebGL arithmetic, the Linux system
theme refusal. Those are the goals of the line that is now called firefox-61. The name firefox-60
is the next release of the engine (firefox-59 plus the Juggler memory fixes), which has none of
them: with the gates at 60 they would have run on it and failed. They ask for 61 now, and a unit
test says that engines 60 and 60-candidate are skipped by a gate that asks for 61 (it fails with
the old minimum, which let 60 run).

Co-authored-by: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-10 12:01:53 +01:00
github-actions[bot]andfeder-cr b1887220a3 record 0.48.1 as published (#438)
Co-authored-by: feder-cr <85809106+feder-cr@users.noreply.github.com>
2026-11-10 11:03:31 +01:00
Federico EliaandClaude Sonnet 5.5 f3d083aa85 0.48.1: the browser never opens its crash reporter, launch_server is public (#437)
* e2e: the run stops at the first refusal of the engine instead of launching for 26 minutes

Against a firefox-59 engine whose gate wanted a declaration the core no longer made (59.58.0), the
suite went on for 26 minutes, launching the browser for each test, being refused each time with the
same sentence, and opening a crash window per refusal on the desktop. tests/engine_refusal.py reads
the text of a failed e2e report and, when it holds the engine's own refusal ("stealth: X is not
declared. Engine rule 7" or the scale refusal), stops the run with that sentence as the reason:
session.shouldstop on the serial path, the controller's shouldstop under xdist (a worker is never
stopped alone). A test that expects a refusal passes, so it never reaches the plugin; a unit test
that only quotes the sentence does not count.

The unit tests read the sentence; the integration tests run pytest over twenty e2e-marked tests of
which the second fails with the refusal, serial and with -n 2: the old suite ran all twenty (the two
fail without the plugin, and a failure that is not a refusal still runs all twenty).

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>

* launch_server, launch_server_async and RemoteServer are on the package; the README shows a server and a client

The server API was reachable only through invisible_playwright._juggler.remote, a private path.
`from invisible_playwright import launch_server` now works, with launch_server_async and
RemoteServer, and they are in __all__. The README section "Serving one browser to many clients"
gets a complete example: a server with launch_server() and a Playwright for Python client that
connects to its ws_endpoint, how to install the extra, where it listens and how the browser ends,
and one line for a client in another language. The example was run against the real engine (the
server printed its address, the client read "Example Domain" and closed, the server's browser stayed
up until Enter).

The test checks the exports and reads the README block against the package; four of its five tests
fail on the old code.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>

* 0.48.1: invisible-core 59.60.0 (the browser never opens its crash reporter), launch_server on the package

Pins invisible-core 59.60.0, whose launch environment carries MOZ_CRASHREPORTER_DISABLE=1. The
version is 0.48.1 and the CHANGELOG names the crash reporter, the exported launch_server with its
README example and the e2e run that stops at the engine's first refusal.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>

---------

Co-authored-by: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-10 10:29:20 +01:00
github-actions[bot]andfeder-cr 8f86007065 record 0.48.0 as published (#436)
Co-authored-by: feder-cr <85809106+feder-cr@users.noreply.github.com>
2026-11-10 09:16:28 +01:00
Federico EliaandClaude Sonnet 5.5 1ff8ed5785 0.48.0: launch_server, and the engine firefox-59 through invisible-core 59.59.0 (#435)
* wire: a protocol message is JSON, and a transport that proves it

_juggler/wire.py: dumps/loads/round_trip, and WireError naming the path of the first
value JSON would change or lose (bytes, sets, objects, non-string keys, NaN/inf).
JsonWireTransport (INVPW_WIRE=json) puts that wire between the client and the server
of the in-process transport, in both directions: a non-JSON client message raises from
send, a non-JSON reply fails its call with the path, a non-JSON event is recorded in
wire_errors. Local use is unchanged (no JSON unless asked).

tests/test_the_wire_is_json.py: 12 unit tests; the reply-that-is-not-JSON test fails
when emit_message forwards unchecked. The unit suite has the same results with and
without INVPW_WIRE=json; running the e2e suite on the wire is the next step.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>

* wire: the server reads a 1.62 message like a 1.61 one, fixed at Dispatcher.handle

Playwright 1.62 moved the call's timeout from the parameters to the metadata,
so a 1.62 client's timeout was lost and every call waited 30 s. handle() now
folds the variants into one shape (_juggler/variants.py), with no version
check: a timeout in the parameters wins, one in the metadata fills the gap,
unknown fields pass unread. scroll is ignored on purpose (documented); a
webp screenshot, screencastFrameAck, waitForFunction on a selector and
virtual credentials refuse that one command with their reason.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>

* wire: a 1.62 screencastFrameAck is accepted and does nothing

The server already acknowledges each screencast frame to the engine, so a client that
acknowledges every frame (1.62's does) is answered, not failed.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>

* wire: a Dialog is an object of the protocol, and the server stops reading the client's registry

The Dialog was a fused class: no __create__, no guid, no channel. The server
built it with Server.twin(page guid), looked into the client's guid registry
(bind_impl_objects/bind_twins) and called BrowserContext._on_dialog through
Connection.deliver_event.

Now DialogDispatcher (TYPE Dialog, parent the Page, initializer type/message/
defaultValue/page, methods accept/dismiss) is announced with __create__ and
then carried by the context's `dialog` event; _dialog.py is a ChannelOwner as
in Playwright, with its case in _object_factory.py, and the event reaches the
listener through Connection.dispatch like any other. Removed: _emit_fused_dialog,
send_async, Server.bind_twins/twin/deliver/run_blocking/call_soon, the
transport's bind_impl_objects/run_blocking/call_soon, Connection.deliver_event
(dispatch is upstream's again) and the bind calls in both context managers.
The reader's pause stays: accept/dismiss answer through
PageDispatcher.answer_dialog, in the worker. diff_protocol no longer lists
Dialog as an expected difference.

Tests: test_a_dialog_is_a_protocol_object.py fails on the old code; the pause
test now covers the answer over the channel.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>

* remote: launch_server() serves one browser to any protocol client over a WebSocket

One launch, one registry, a connection per client: objects are owned by the
client that made them, a client leaving closes its contexts and not the browser.
initialize answers with BrowserType, LocalUtils, Browser and a Playwright root
carrying preLaunchedBrowser. No version check, no limit of ours; the identity
stays the server's. A dialog, which cannot cross the wire, is dismissed.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>

* remote: the Playwright initializer names every required type of spec 1.62

A client built on the 1.62 spec (playwright-go's newPlaywright) reads chromium, firefox, webkit,
android and electron from the Playwright initializer without checking for a missing one and
panics: 'fromChannel: expected *channel, got <nil>'. chromium and webkit are BrowserTypes whose
calls refuse with a reason; Android and Electron likewise. Announced before Playwright.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>

* pin invisible_core 59.57.0 (the pin PR 413 proposes), engine firefox-59

One core for the image that serves this wrapper: the unit suite and a quick e2e (the served
browser answering a plain client, add_script_tag, dialog pause) run on core 59.57.0.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>

* server: "no-override" is not sent to the engine as a colour scheme, motion or forced-colors value

The Go client (and Playwright's null) says "not overridden" with the string
"no-override". The server passed it to Browser.setColorScheme (and the motion
and forced-colors commands), whose enum has no such member, so the engine
refused the whole newContext. Now nothing is sent and the context keeps the
persona's declared theme; explicit dark/light/no-preference still go out.
Page.setEmulatedMedia treats it as a reset (field left out, empty medium).

Tests: unit (6 of 11 fail on the old server) and an e2e with a light and a
dark persona that reads prefers-color-scheme through a Go-style context.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>

* remote: the pointer's walk is drawn by the server, once, for every client

The in-process client patched Frame._click/hover/dblclick/tap/check,
Mouse.click and Mouse.wheel and sent N mouseMove before each action; a
client that is not ours sent one Frame.click and the page saw one
mousemove (measured with humanize=True on a served browser). The walk
(approach, off-centre landing, idle fidget, scroll detents) moves to
_juggler/pointer.py, built per page from the session seed, the page's
number and the humanize budget, and called by FrameDispatcher and the
Page mouse ops. The in-process client now sends the plain action.

- an explicit mouse.move stays the caller's: the server walks it only
  when the in-process client marks it (humanise); a standard client's
  move reaches the page as the exact point it named
- who draws travels in the launch prefs (invisible.server.pointer), so
  the engine's own expansion and INVPW_CURSOR_ENGINE=off are not
  humanised twice
- golden from 5d9ad70 (tests/data/pointer_golden.json, with its origin
  and generator): a Frame.click reaching the server draws the same
  engine events, same coordinates and instants, as the client did

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>

* server: Mouse.click puts one mousemove on its point, not two

Pointer.click_at sent the endpoint as a move of its own and then Actions.click_at
moved onto it again as its own approach before the press: the engine got two
mousemove with the same coordinates at the same instant, which no mouse reports
and a page can count. The defect predates the move of the walk to the server
(it was the client's Mouse._click); it is corrected at the source instead of
being preserved, for every transport (op_mouse_click is the one path).

- pointer.py: click_at sends the stroke and lets the click's own approach be the
  one move onto the point; the hand is re-synced after the click.
- golden: only the explicit_pointer session (the one with a Mouse.click)
  changes, regenerated by tests/data/pointer_golden_origin.py
  --revise-mouse-click, which refuses unless the result is the old session minus
  that one repeated move; the origin says why.
- tests: no two consecutive equal mousemove in a humanised Mouse.click (fails on
  the old code), plus an e2e with one real browser that counts them in the page.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>

* server: a stroke from standstill does not open with the point it stands on

The first waypoint of a stroke is its start. When the engine has already been
told the pointer is on that pixel (a move that stopped there, then a pause), the
stroke sent it again: a zero-displacement mousemove no mouse reports. Pointer.
_travel now skips a first waypoint that coincides with the position the engine
knows; a pointer the engine was never told about (the page's first movement,
from the seeded start point) still opens with its first waypoint.

- golden: only the explicit_pointer session changes (one mousemove fewer; t, x,
  y and type of every other event unchanged, latency draws follow the ordinal),
  regenerated by pointer_golden_origin.py --revise-standstill, which refuses
  unless the other three sessions equal the server's run event for event.
- tests: no repeated or zero-displacement mousemove from standstill after 0, 0.2
  and 5 s, for click and move (fail on the old code); e2e with one real browser.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>

* server: a closed context leaves nothing in the registry, the browser's lists or the wire's error log

The three children of a context (Debugger, Tracing, APIRequestContext) were
announced under the browser and adopted by the context on the wire, but dispose
forgets a subtree by walking parent, so they outlived every context: 3 registry
entries per context (500 contexts: 1,500). browser.contexts kept every closed
context with its options and owner, browser._artifacts every download, and a
Stream's file stayed open when its parent's dispose forgot it (the cascade does
not call dispose on a descendant). New Dispatcher.released(), called for the
object and for each descendant the cascade forgets, lets go of what other
objects hold of it. RemoteEndpoint.wire_errors keeps the last 32, not all.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>

* remote: an opt-in memory probe (INVPW_MEM_LOG) and malloc trim (INVPW_MALLOC_TRIM), both off by default

INVPW_MEM_LOG=<file> writes a JSON line every INVPW_MEM_LOG_INTERVAL seconds
(default 2) and at each context close: uss/rss, registry objects, contexts,
clients, the bytes and messages queued in the clients' outboxes (read from the
queue at sampling time, free when the probe is off), gc counts and glibc
mallinfo2. INVPW_MALLOC_TRIM=1 calls malloc_trim(0) after each message of 64 KiB
or more has been sent and at each context close (Linux only; elsewhere ignored
with one warning). With both off nothing is built or loaded and the wire is
byte-identical.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>

* server: the guid registry collects its oldest dispatchers like Playwright's server

Per bucket (the object's type; Frame is MainFrame or Frame), past the limit the oldest
tenth is disposed with __dispose__ {reason: "gc"} to its owner and its subtree silently,
as dispatchers/dispatcher.ts of Playwright 1.62 does: 10000, JSHandle and ElementHandle
100000, one value per type in dispatcher.GC_LIMITS (INVPW_GC_LIMITS lowers some without
editing code). The registry is walked once per batch, not once per object. An event on a
disposed object is dropped, a request or frame already collected is not named again.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>

* server: a request and a response keep what they hold, not what the wire carried

Measured on a real browser (one context, 95 navigations, ~100 subresources each) a Request
was 4.5 KB and a Response 6.0 KB: headers as a list of dicts kept twice (initializer and
raw_headers), the POST body and the timing in the initializer. Headers are now a tuple of
interned (name, value) pairs rebuilt on demand, the certificate is one object per distinct
certificate, the remote address a pair, and the initializer is replaced after the
__create__ by a copy without headers, postData and timing (a new dict: a message waiting in
a queue still holds the old one). Dispatcher.announced() is the hook; released() clears a
request's and a response's state when they leave the registry. 0.84 KB each, and the same
run ends at 73 MB instead of 149 MB.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>

* server: Request, Response and Route collect at 2000, and nothing younger than 10 s is collected

Two declared differences from Playwright's collector (dispatcher.GC_LIMITS, docstring):
the three network types have a limit of 2000 instead of 10000, and an object younger than
GC_MIN_AGE_S is never a victim, so what a client was just handed (the Go client uses a
request inside the callback of its event) stays valid however fast the bucket fills.
Measured on a real browser, one context, 95 navigations of pages with ~100 subresources
and heavy headers: 193 MB at 10000, 74 MB (flat from navigation 25) at 2000.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>

* remote: malloc_trim is on by default on Linux; INVPW_MALLOC_TRIM=0 turns it off

After a context closes and after each message of 64 KiB or more is sent, the served browser
calls malloc_trim(0) when the libc has it (glibc on Linux). Slack's runs of 95 navigations: the
free memory glibc held (fordblks) went from 13 MB to 177 MB by default. Off Linux, with musl or
a libc without the function, nothing is called and nothing is said. No mallopt here:
MALLOC_ARENA_MAX=2 is process-wide, the launcher's to set (README). The probe stays off
and free unless INVPW_MEM_LOG is set.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>

* docs: the registry's collection limits and what they mean for a program that holds many old requests

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>

* release 0.48.0: launch_server, and the engine firefox-59 through invisible-core 59.57.0

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>

* ci: the missing-websockets message is spelled by the installer, and two tests share a fixture without redefining it

The message named a written pip install, which the way-in check refuses; it is built with
invisible_core.installer now, as _engine.py does. The two tests imported a fixture and
took it as an argument (F811); they bind it by assignment instead.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>

* ci: the pointer test reaches its fixture module the way the other tests do, not through a tests package that CI does not have

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>

* test: the trim test waits for the trim, which the writer runs after the send

A fixed read of the trim count right after the reply failed on a slow runner (the client
holds the reply before the writer's next line runs). A delayed trim fails the old test and
passes this one.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>

* test: the WebGL e2e looks at the engine processes below its own test, not at the first one on the machine

With several workers in /proc the scan over every process could be handed another worker's
browser, which had not drawn yet and maps only the host's libgallium (GTK's GLX): red on one run of
the Linux gate and green on the next, same engine and core. The test now walks the tree under its
own process, asks that at least one process there maps the engine's libEGL and libgallium and that
none maps a host libEGL; a unit test with two trees on one machine fails a whole-machine scan.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>

* test: a click's stroke is judged by its shape, not by how many mousemoves reached the page

The pacer drops a sample it cannot send on time, so the same stroke is 15 events on an idle machine
and 6 to 9 on a loaded one (Windows with 32 busy processes; the Linux gate with four workers got
9). The e2e asked for more than 10 and failed on the gate with a real stroke: it left from
(1116, 731), came in steps and ended on the click. It now asks that the stroke left from far away,
came in at least one step and ended on the target with no repeated mousemove; the standstill test
asks for something before the landing, not for 6 events. The unit test holds the gate's page events
as data: the old rule refuses them, the shape rule accepts them, and a jump, two events, a miss, a
start on the target and a repeat are refused. Ten idle runs and three loaded runs pass on Windows;
the old test fails under load.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>

* Pin invisible-core 59.58.0; the pinning page drops the two keys that core no longer accepts

59.58.0 is on PyPI. Besides the same numbers from a seed on Python 3.11 to 3.14 (the red
py3.11 job), it stops declaring the glyph coverage ladder and forces no sRGB output profile, so
the pin keys font.alpha_ladder and desktop.srgb_output are refused by the validator; the pinning
page listed both and test_pinning_doc caught it. Their rows are gone.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>

* Pin invisible-core 59.59.0 (59.57.0 and the version-independent float arithmetic)

59.59.0 is 59.57.0 plus only the fix for the two builtins that differ between Python versions
(sum() of floats and math.log2), which was the red py3.11 job. It keeps the glyph coverage
ladder the firefox-59 engine's declaration gate requires and the sRGB output pin, so the
pinning page lists font.alpha_ladder and desktop.srgb_output again.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>

* The server answers NaN, the infinities and -0 as Playwright's tag, not as a bare number

Found by the e2e run on the strict JSON wire: page.evaluate_handle("() => NaN").json_value()
passed in process and failed with "$.result.value.n: nan is not JSON". The server's serializer
answered {"n": nan}, which Python writes as the bare word NaN and no other JSON reader accepts.
Playwright sends {"v": "NaN"} (and "Infinity", "-Infinity", "-0"); so does the server now. The
unit test fails on the old serializer (9 of 11) and the e2e that found it passes on both wires.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>

---------

Co-authored-by: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-10 08:44:54 +01:00
Federico EliaandClaude Sonnet 5.5 0eee28d093 e2e: the refusal of a missing system theme pref is expected on Linux only (#433)
On Windows the engine takes the system fonts and colours from the toolkit as
retail does (StealthVerifySystemTheme returns unless MOZ_WIDGET_GTK), so a
launch without ui.highlight, ui.-moz-field or ui.font.menu does not refuse
there. Candidate 42673795394's Windows gate ran the test and got DID NOT RAISE
three times. The refusal test now skips on win32; the control launch still runs.

tests/unit/test_theme_refusal_drop.py checks the skip mark on the refusal test
and its absence on the control; it fails on the test without the mark.

Co-authored-by: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-09 21:13:45 +01:00
Federico EliaandClaude Sonnet 5.5 ccb0ff051f e2e: the refusal test launches the engine with the crash reporter off (#431)
The three missing-pref cases end in a deliberate abort (the engine refuses the launch), and each
opened the crash reporter on the desktop of whoever ran it.

Co-authored-by: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-09 17:51:34 +01:00
Federico EliaandClaude Sonnet 5 0321737429 e2e: the B-frame order test uses the RDD process, like a real user (#432)
media.rdd-process.enabled=false and media.gpu-process-decoder=false left
the content process with no video decoder at all on Linux: WebCodecs'
configure() rejected with no decoder found for video/avc (MOZ_LOG
WebCodecs:5/MediaDecoder:5 confirms it, not a guess), fast and clean. The
hang the test actually showed was separate: flush() rejects right after
that, and nothing caught it inside the test's own new Promise, so resolve()
never ran and Playwright's own 30s evaluate timeout is what finally fired.
A real user always has the RDD process; dropping those two prefs runs the
default path instead of a configuration retail never has. flush() now
settles the promise on either outcome, so a real decode failure surfaces
immediately instead of hanging for 30s.

Co-authored-by: Claude Sonnet 5 <noreply@anthropic.com>
2026-11-09 17:51:25 +01:00
Federico EliaandClaude Sonnet 5.5 e8b57121e1 e2e: the dot() reads a zero's sign as the GPU does (zeros of both signs in the vectors, the comparison keeps the sign) (#430)
The comparison treated -0 and +0 as equal, which hid a fma whose product and sum are both -0 coming back +0. The model's fma now gives IEEE's sign of a zero result, with a unit test.

Co-authored-by: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-09 17:42:17 +01:00
Federico EliaandClaude Sonnet 5.5 fa0d19cca3 e2e: the fontconfig test fails on an open of the host's configuration, not on the parent's existence probe (#429)
Candidate 42640321957 failed it on one lstat("~/.fonts.conf") of the parent: the parent builds
the content sandbox's permissions (SandboxBrokerPolicyFactory::InitContentPolicy) and asks
whether each path exists. It opens nothing, no byte of those files enters the process, and a
page cannot see it; the sandbox policy is not touched.

The criterion is now: a process that OPENS a host fontconfig or font path fails (an open
that fails with ENOENT too), and a content process that does anything there fails (stat,
access, readlink). The parent's existence probes are ignored, with the reason in the module.
tests/unit/test_fontconfig_criterion.py runs it on fake strace lines: the lstat passes; a
parent that opens /etc/fonts/fonts.conf or ~/.fonts.conf, and a content process that stats a
host font directory, fail.

Co-authored-by: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-09 17:36:37 +01:00
Federico EliaandClaude Sonnet 5.5 1e23d20e0c e2e: the missing-system-theme-pref helper's regex compiles, with a unit test that fails on the old one (#427)
The regex that finds a pref's line in user.js had a lone backslash before its closing bracket
(an unterminated character set): every case of the e2e died with re.error before launching
a browser (candidate 42624473465, Windows gate). tests/unit/test_theme_refusal_drop.py runs
the helper on a user.js of its own and fails on the old regex.

Co-authored-by: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-09 17:09:20 +01:00
Federico EliaandClaude Sonnet 5.5 3481f419c7 e2e: coloured canvas text and ClearType keys are drawn as retail Windows draws them (from firefox-60) (#428)
tests/data/canvas_text_ref only compares black text on white under one ClearType state, which
hides what a text-mask hook changes: 12 of 14 coloured cases differ from retail on an engine
that quantises its A8 masks.

New e2e, with hashes from retail Firefox 159.0 on Windows (headless, same pages, same bundled
fonts):
- the 14 coloured cases (7 colour pairs x Arial 16/33 px) with the seed's configuration;
- 39 cases (25 black of canvas_text_ref + the 14 coloured) under three ClearType keys,
  1800/100, 1400/50 and 2200/0, one launch per key with the font.cleartype_gamma and
  font.cleartype_contrast pins. The failure message lists each differing case.

The pin, the font check and the server of the existing canvas text test move to
tests/_canvas_text.py, which both tests import. The reference holds pages, hashes and
metadata only (scripts/build_canvas_text_colors_refs.py rebuilds it from the saved bytes);
tests/unit/test_canvas_text_colors_refs.py checks its structure and that the keys give
different hashes.

Co-authored-by: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-09 16:35:47 +01:00
Federico EliaandClaude Sonnet 5.5 5c0de53221 e2e: a WebGL dot() gives the bits of the GPU family the persona declares (from firefox-60) (#426)
tests/test_webgl_dot_has_the_declared_gpu_s_bits_e2e.py reads back dot() of two, three and
four components through a float-bits shader and compares the bytes with the NVIDIA fma
chain computed in exact arithmetic, for alu_class 1 and 2; class 0 is the control. The model
runs as a unit test everywhere; the browser tests are Windows only and guarded by
engine_at_least("firefox-60"). The engine's gate lists it by name.

Co-authored-by: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-09 14:25:58 +01:00
143 changed files with 21748 additions and 2880 deletions

No files matched your search

+2
View File
@@ -11,6 +11,8 @@
# counters/history.csv date,key,value - every counter, once a day
# counters/launches_daily.csv day_utc,launches - one row per measured day
# docs/badges/launches.svg, docs/badges/stars.svg
# docs/badges/launches.json, docs/badges/downloads.json - read by shields.io
# for the big row at the top of the README
#
# 00:10 UTC, so the snapshot dated D closes calendar day D-1.
name: counters
+93
View File
@@ -6,6 +6,99 @@ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/),
## [Unreleased]
## [0.50.0] - 2026-11-11
### Changed
- Engine firefox-62 through invisible-core 62.63.0, which this version pins: firefox-61 plus Fission
and the Juggler for frames in another process. When `goto` returns, the frames below have the
address of their first document (an iframe of another site used to be listed with an empty url
for a moment); a `goto` to the address the page is already at ends; a late event of a frame that
left the page no longer brings it back into `page.frames`.
- Fission: iframes of another site run in a content process of their own (isolation strategy 1,
`fission.autostart` on, four isolated content processes), as in retail Firefox on desktop. The
strategy comes from the invisible-core baseline of the firefox-62 engine, whose Juggler reaches a
frame in another process like any other. The tests that held strategy 0
(`tests/test_cross_origin_iframe.py`) now hold strategy 1, and the Fission end-to-end tests
(frame tree, element to frame, geometry, input, crash of an iframe process, identity of the
iframe and of its page) run on that engine.
### Fixed
- A launch that names no session (Playwright's own `BrowserType.launch` against the server) gets a
session composed the way `InvisiblePlaywright()` composes one: prefs, environment and, behind a
proxy, the egress the page reads as its WebRTC address. It used to come up with Mozilla's
defaults, and on Linux its first `new_page` failed with "Unexpected number of tabs in the new
window: 2".
- A frame that left the page (an iframe a script removed) answers a call with "Frame was
detached", as Playwright does, not "Target page, context or browser has been closed".
- `grant_permissions` uses the permission names of the engine. `geolocation` and `notifications` used
to reach the engine under the web names while it keeps a grant under `geo` and
`desktop-notification`, so a page of a context that had been granted geolocation and given a
position was still denied. The names are those of the Playwright client for this browser
(`geolocation`, `persistent-storage`, `push`, `notifications`, `screen-wake-lock`); any other name
raises `Unknown permission`, as it does there, and a grant with no origin is a grant for every
origin.
## [0.49.1] - 2026-11-10
### Changed
- Engine firefox-61 through invisible-core 61.62.0, which this version pins: firefox-60 plus four
fixes. A context that ends no longer leaves a content process behind when a service worker
that never stops keeps it alive (the engine kills the processes of the container that stay);
the shared font resources of a closed window leave WebRender's pool with it; `Page.screenshot`
empties its canvas on every way out; `Page.setEmulatedMedia` names the media features it
refuses, in English.
- A context route turns the context's cache off while it is active, as Playwright does.
### Fixed
- `page.request_gc()` works on a served browser. It sent the engine's `Heap.collectGarbage` on the
browser-level connection, whose handler does not have it, so every call failed with
`Handler for does not implement method "Heap.collectGarbage"`; it is now sent with the session
of the page, as the engine answers it.
## [0.49.0] - 2026-11-10
### Changed
- Engine firefox-60 through invisible-core 60.61.0, which this version pins: firefox-59 plus
the Juggler's memory fixes. A tab no longer keeps the documents it left alive (they used to
stay as detached windows after leaving the back/forward cache), and a main-frame navigation
drops the response bodies of the documents it left, as Chromium does: `response.body()` of
such a response raises the evicted error Playwright already returns for Firefox.
## [0.48.1] - 2026-11-10
### Added
- `launch_server`, `launch_server_async` and `RemoteServer` are importable from
`invisible_playwright`, and the README's "Serving one browser to many clients" has a
complete example: a server, and a Playwright for Python client that connects to its
`ws_endpoint`.
### Changed
- invisible-core 59.60.0, which this version pins. The browser never opens its crash
reporter: the launch environment carries `MOZ_CRASHREPORTER_DISABLE=1`, so an engine that
refuses a launch no longer leaves a "Crash Reporter" window on a Windows desktop.
- The e2e run stops at the first refusal of the engine instead of launching the browser for
every test (a change to the test suite, not to the package).
## [0.48.0] - 2026-11-10
### Added
- `launch_server()` serves one browser on a WebSocket to any Playwright client: the
Playwright initializer is the one of protocol 1.62, a call's timeout is read from its
metadata or its parameters, a Dialog is a protocol object, and the pointer's path is
drawn by the server, once, for every client.
### Changed
- Engine firefox-59 (Firefox 159.0), through invisible-core 59.59.0, which this version
pins. On Linux WebGL draws on the engine's own GL, never the host's, under X11 too, and
every extension the persona declares answers as on Windows. The same seed gives the same
pointer path, typing and persona on Python 3.11 to 3.14 (59.59.0 replaces the two builtins
that differ between versions).
- The server collects its oldest protocol objects as Playwright's does, with a lower limit
for `Request`, `Response` and `Route` (2000, not 10000; nothing younger than 10 seconds).
A program that holds more than 2000 requests or responses in hand for longer than 10
seconds gets "Target closed" on the oldest ones. `INVPW_GC_LIMITS` changes the limits.
- A closed context leaves nothing in the server's registry.
## [0.47.1] - 2026-11-08
### Changed
+1924
View File
File diff suppressed because it is too large. Load diff
+49 -2
View File
@@ -7,6 +7,11 @@
<source media="(prefers-color-scheme: dark)" srcset="https://raw.githubusercontent.com/feder-cr/invisible_playwright/main/docs/banner-dark.gif">
<img alt="invisible_playwright, Playwright on an anti-detect Firefox. An animation: the two-line switch from Playwright, the fingerprint set inside the engine, a mouse that moves like a hand, and the bot tests it passes." src="https://raw.githubusercontent.com/feder-cr/invisible_playwright/main/docs/banner-light.gif" width="100%">
</picture>
<p align="center">
<a href="https://github.com/feder-cr/invisible_playwright/blob/badges/counters/launches_daily.csv"><img src="https://img.shields.io/endpoint?url=https%3A%2F%2Fraw.githubusercontent.com%2Ffeder-cr%2Finvisible_playwright%2Fbadges%2Fdocs%2Fbadges%2Flaunches.json&style=for-the-badge" alt="browser launches"></a>
<a href="https://github.com/feder-cr/firefox_antidetect_patch/releases"><img src="https://img.shields.io/endpoint?url=https%3A%2F%2Fraw.githubusercontent.com%2Ffeder-cr%2Finvisible_playwright%2Fbadges%2Fdocs%2Fbadges%2Fdownloads.json&style=for-the-badge" alt="engine downloads"></a>
<a href="https://github.com/feder-cr/invisible_playwright/stargazers"><img src="https://img.shields.io/github/stars/feder-cr/invisible_playwright?style=for-the-badge&logo=github&color=e8a317" alt="GitHub stars"></a>
</p>
<h3 align="center">Playwright gets caught by anti-bots and captchas.<br>
This one runs on an anti-detect Firefox with an undetected fingerprint, compatible with your existing Playwright code.</h3>
</div>
@@ -125,6 +130,50 @@ with InvisiblePlaywright(proxy=proxy) as browser:
Schemes supported: `socks5`, `socks4`, `http`, `https`. DNS is routed through the proxy by default, no local leak.
### Serving one browser to many clients
`launch_server()` serves one browser on a WebSocket to any Playwright client. Install the
extra that carries the WebSocket library with `uv add "invisible-playwright[remote]"`.
```python
# server.py
from invisible_playwright import launch_server
with launch_server(seed=42, headless=True) as server:
print(server.ws_endpoint) # ws://127.0.0.1:<port>/<secret>
input("serving, press Enter to stop")
```
```python
# client.py: any Playwright client; this one is Playwright for Python (uv add playwright)
import sys
from playwright.sync_api import sync_playwright
with sync_playwright() as p:
browser = p.firefox.connect(sys.argv[1]) # the address the server printed
page = browser.new_page()
page.goto("https://example.com")
print(page.title())
browser.close() # ends this client; the server's browser keeps running
```
The server listens on `127.0.0.1` with a random secret path; `host=`, `port=` and `path=` choose
another address. A client in another language (Node, Java, .NET, Go) connects to the same
address with the `connect` call of its own Playwright. The browser belongs to the server and
ends with `server.close()` (or with the `with` block).
On Linux, set `MALLOC_ARENA_MAX=2` in the environment of the process that runs it (glibc keeps a memory
arena per thread otherwise); the server already hands freed memory back with `malloc_trim`
(`INVPW_MALLOC_TRIM=0` turns that off).
The server keeps its protocol objects in a registry and, like Playwright's own server,
collects the oldest ones when a type grows past a limit (`__dispose__` with reason `gc`).
Its limits are Playwright's, except `Request`, `Response` and `Route`, which are 2000
instead of 10000, and nothing younger than 10 seconds is ever collected. A client that
keeps more than 2000 requests or responses in hand for longer than that gets "Target
closed" on the oldest ones; one that uses them inside its callback is not affected. Set
`INVPW_GC_LIMITS="Request=10000,Response=10000,Route=10000"` to get Playwright's numbers.
### Timezone
The browser timezone follows `timezone=`:
@@ -323,6 +372,4 @@ This project is for educational purposes only. It is provided as-is, with no war
<a href="https://github.com/feder-cr/invisible_playwright/blob/main/LICENSE"><img src="https://raw.githubusercontent.com/feder-cr/invisible_playwright/main/docs/badges/license.svg" alt="License: MIT"></a>
<a href="https://www.python.org/downloads/"><img src="https://raw.githubusercontent.com/feder-cr/invisible_playwright/main/docs/badges/python.svg" alt="Python 3.11+"></a>
<a href="https://github.com/feder-cr/firefox_antidetect_patch/releases"><img src="https://raw.githubusercontent.com/feder-cr/invisible_playwright/main/docs/badges/firefox.svg" alt="Firefox 159.0"></a>
<img src="https://raw.githubusercontent.com/feder-cr/invisible_playwright/badges/docs/badges/launches.svg" alt="browser launches">
<a href="https://github.com/feder-cr/invisible_playwright/stargazers"><img src="https://raw.githubusercontent.com/feder-cr/invisible_playwright/badges/docs/badges/stars.svg" alt="GitHub stars"></a>
</p>
+5
View File
@@ -0,0 +1,5 @@
[
{"id": "wrapper.e2e.udp", "giro": "G2", "os": ["linux", "windows"], "min_tests": 51, "exact": true, "tests": ["tests/test_the_whole_udp_chain_by_name_e2e.py", "tests/test_declared_host_network_e2e.py", "tests/test_http3_through_the_proxy_e2e.py", "tests/test_a_page_over_ipv6_gathers_on_a_machine_declared_without_it_e2e.py", "tests/test_networkidle_through_a_served_browser_with_routes_e2e.py", "tests/test_webrtc_realness.py::test_a_gateway_with_coherent_udp_gives_the_page_a_srflx_born_through_its_relay", "tests/test_webrtc_realness.py::test_a_host_with_ipv6_addresses_gathers_through_an_ipv4_relay", "tests/test_webrtc_realness.py::test_a_gateway_that_is_far_away_still_gives_the_page_a_srflx_born_through_its_relay", "tests/test_webrtc_realness.py::test_the_first_candidate_of_a_gather_does_not_wait_for_a_gateway_that_is_far_away", "tests/test_webrtc_realness.py::test_a_gather_after_the_page_loaded_through_the_gateway_costs_only_the_road_to_the_server", "tests/test_webrtc_realness.py::test_two_contexts_with_two_proxies_each_gets_the_srflx_of_its_own", "tests/test_webrtc_realness.py::test_the_turn_over_tcp_of_a_context_goes_through_the_proxy_of_that_context", "tests/test_webrtc_realness.py::test_a_proxy_that_does_not_relay_udp_gives_no_srflx_at_all"], "marker": "e2e", "needs_root": false, "note": "Needs the candidate binary (STEALTHFOX_E2E_BINARY) and the engine that carries the UDP line. 51 = 1+7+2+1+21 from the five files + 19 from the 8 UDP-line tests of test_webrtc_realness.py (parametrized)."},
{"id": "wrapper.e2e.doh", "giro": "G2", "os": ["linux", "windows"], "min_tests": 8, "exact": true, "tests": ["tests/test_doh_through_the_proxy_e2e.py"], "marker": "e2e", "needs_root": ["linux"], "note": "Linux needs root: the resolver trap of the file (ResolverTrap) points /etc/resolv.conf at a counting resolver on port 53. Su Windows il resolver trap non gira: l'asserzione sul resolver di sistema è l'unica omessa. Run it without xdist (port 53 is one per host). On the Linux leg the gate exports INVPW_REQUIRE_TRAP=1: a trap that cannot run or bind port 53 is a failure, not a skipped assertion."},
{"id": "wrapper.unit.udp", "giro": "G1", "os": ["linux", "windows"], "min_tests": 95, "exact": true, "tests": ["tests/test_ci_drive_gate_goes_through_the_core.py", "tests/test_the_udp_chain_helper.py", "tests/test_the_fake_doh_answers.py", "tests/test_doh_session_prefs_unit.py", "tests/test_the_leak_watcher_sees_a_direct_connection.py", "tests/test_the_http_proxy_helper_asks_for_credentials.py", "tests/test_every_route_command_is_answered_may_fail.py", "tests/test_the_network_declaration_reaches_the_engine.py", "tests/test_the_resolver_trap_is_required_by_the_gate.py"], "marker": "unit", "needs_root": false, "note": "92 = 6+32+21+7+8+3+9+6. The leak watcher file defines exactly one of its two resolver-trap tests per host (7 everywhere), so no test is skipped. `exact`: min_tests is raised by hand when a test is added."}
]
+4 -3
View File
@@ -4,7 +4,7 @@ build-backend = "hatchling.build"
[project]
name = "invisible_playwright"
version = "0.47.1"
version = "0.50.0"
description = "Playwright wrapper for a patched Firefox with deterministic stealth profile."
readme = "README.md"
requires-python = ">=3.11"
@@ -69,7 +69,7 @@ dependencies = [
# metadata; nothing in src/ hardcodes a second copy (tests/test_core_pin.py
# fails if one appears). What stays invisible to install-time machinery is the
# --no-deps / lockfile residue, and _pin.py is the only layer that sees it.
"invisible_core==58.56.0",
"invisible_core==62.63.0",
# ⛔ playwright is NO LONGER a dependency: since the full fork, the Python
# client lives in src/invisible_playwright/_pw/ and its server in
# src/invisible_playwright/_juggler/ (no Node driver). Reintroducing it would not visibly
@@ -117,7 +117,8 @@ dependencies = [
]
[project.optional-dependencies]
dev = ["pytest>=7", "build>=1", "ruff>=0.6", "pytest-rerunfailures>=14", "pytest-timeout>=2", "pytest-xdist>=3", "playwright==1.61.0", "cryptography>=41"]
remote = ["websockets>=13"]
dev = ["websockets>=13", "aioquic>=1.2", "pytest>=7", "build>=1", "ruff>=0.6", "pytest-rerunfailures>=14", "pytest-timeout>=2", "pytest-xdist>=3", "playwright==1.61.0", "cryptography>=41", "h2>=4,<5"]
[tool.pytest.ini_options]
markers = [
+184
View File
@@ -0,0 +1,184 @@
"""Builds tests/data/canvas_text_ref_colors/refs.json from the bytes retail Firefox drew.
The reference of tests/test_canvas_text_colors_and_cleartype_is_windows_e2e.py: coloured
canvas text, and 39 cases (25 of black text on white, 14 coloured) under three ClearType
keys, all measured on retail Firefox 159.0 on Windows with tests/data/canvas_text_ref_colors/
index.html (the 14 coloured cases) and tests/data/canvas_text_ref/index.html (the 25 black
ones). The measuring harness saved, for every case, the RGBA bytes of the canvas
(<name>.rgba) and a <name>.json with its id, width, height and sha256:
<BYTES>/colors/retail/<name>.{json,rgba} the 14 coloured cases, retail's own
ClearType state (the seed's)
<BYTES>/keys/<gamma>_<contrast>/retail/<name>.{json,rgba}
the 39 cases under that key; the case
id of a coloured one is "color:<id>"
python -I scripts/build_canvas_text_colors_refs.py --bytes <BYTES> \
[--keys 1800_100,1400_50,2200_0] [--out tests/data/canvas_text_ref_colors/refs.json]
The repository holds no .rgba: they are 270 kB each. The script hashes an .rgba when the
directory has it (and stops if that is not the sha256 its .json says, or the size is not
width x height x 4); when only the .json is there (a byte file kept only where the engine
differed) it takes the hash the harness wrote. It stops too when the black cases under
1800/100 are not the ones tests/data/canvas_text_ref/refs.json holds for the same ids, or
when the coloured cases under 1800/100 differ from the ones of colors/retail (same machine,
same key: they are one measurement). Standard library only.
"""
from __future__ import annotations
import argparse
import hashlib
import json
import re
import sys
from pathlib import Path
ROOT = Path(__file__).resolve().parents[1]
DATA = ROOT / "tests" / "data" / "canvas_text_ref_colors"
BASE_REFS = ROOT / "tests" / "data" / "canvas_text_ref" / "refs.json"
DEFAULT_KEYS = "1800_100,1400_50,2200_0"
SEED_KEY = "1800_100"
DATE = "2026-11-09"
#: The prefs of the retail profile for the keys (user.js), gamma and contrast per key.
RETAIL_PREFS = {
"gfx.canvas.accelerated": False,
"gfx.font_rendering.cleartype_params.gamma": "<gamma>",
"gfx.font_rendering.cleartype_params.enhanced_contrast": "<contrast>",
"gfx.font_rendering.cleartype_params.cleartype_level": 100,
"gfx.font_rendering.cleartype_params.pixel_structure": 1,
"gfx.font_rendering.cleartype_params.rendering_mode": 0,
}
#: The coloured cases of colors/retail were measured with the machine's own ClearType prefs,
#: and gfx.canvas.accelerated off.
COLORS_RETAIL_PREFS = {"gfx.canvas.accelerated": False}
class BuildError(ValueError):
"""The saved bytes cannot be this reference."""
def colors_of_page(html):
"""[[name, fg, bg], ...] and [sizes] from the measuring page, as the page declares them."""
m = re.search(r"const COLORS = (\[\[.*?\]\]);", html, re.S)
s = re.search(r"const SIZES = (\[[^\]]*\]);", html)
if not m or not s:
raise BuildError("index.html declares no COLORS / SIZES")
return json.loads(m.group(1)), json.loads(s.group(1))
def read_dir(d):
"""{case id: {"width", "height", "sha256"}} of the .json files of one directory."""
d = Path(d)
if not d.is_dir():
raise BuildError("%s is not a directory" % d)
out = {}
for j in sorted(d.glob("*.json")):
m = json.loads(j.read_text(encoding="utf-8"))
sha, w, h = m["sha256"], int(m["w"]), int(m["h"])
rgba = j.with_suffix(".rgba")
if rgba.is_file():
data = rgba.read_bytes()
if len(data) != w * h * 4:
raise BuildError("%s: %d bytes, not %d x %d x 4" % (rgba, len(data), w, h))
got = hashlib.sha256(data).hexdigest()
if got != sha:
raise BuildError("%s: sha256 %s, its json says %s" % (rgba, got, sha))
if not re.fullmatch(r"[0-9a-f]{64}", sha):
raise BuildError("%s: sha256 %r is not 64 hex digits" % (j, sha))
if m["id"] in out:
raise BuildError("%s: case %r twice in %s" % (j.name, m["id"], d))
out[m["id"]] = {"width": w, "height": h, "sha256": sha}
return out
def build(bytes_dir, keys, page_html, base):
colors, sizes = colors_of_page(page_html)
color_ids = ["%s|%s" % (c[0], s) for c in colors for s in sizes]
bytes_dir = Path(bytes_dir)
seed = read_dir(bytes_dir / "colors" / "retail")
if sorted(seed) != sorted(color_ids):
raise BuildError("colors/retail has %s, the page draws %s" % (sorted(seed), sorted(color_ids)))
spec = {"%s|%s" % (c[0], s): {"name": c[0], "fg": c[1], "bg": c[2], "size": s}
for c in colors for s in sizes}
out_colors = {i: {"id": i, **spec[i], **seed[i]} for i in color_ids}
out_keys = {}
for tag in keys:
gamma, contrast = (int(x) for x in tag.split("_"))
cases = read_dir(bytes_dir / "keys" / tag / "retail")
black = {i: v for i, v in cases.items() if not i.startswith("color:")}
col = {i[len("color:"):]: v for i, v in cases.items() if i.startswith("color:")}
if sorted(col) != sorted(color_ids):
raise BuildError("key %s: coloured cases %s, the page draws %s"
% (tag, sorted(col), sorted(color_ids)))
for i in black:
if i not in base["cases"]:
raise BuildError("key %s: %r is not a case of canvas_text_ref" % (tag, i))
out_keys[tag] = {
"gamma": gamma, "contrast": contrast, "count": len(black) + len(col),
"black": {i: {"id": i, **black[i]} for i in sorted(black)},
"colors": {i: {"id": i, **col[i]} for i in color_ids},
}
if SEED_KEY in out_keys:
k = out_keys[SEED_KEY]
for i, v in k["black"].items():
if v["sha256"] != base["cases"][i]["sha256"]:
raise BuildError("%s under %s: %s, canvas_text_ref/refs.json has %s"
% (i, SEED_KEY, v["sha256"], base["cases"][i]["sha256"]))
for i, v in k["colors"].items():
if v["sha256"] != out_colors[i]["sha256"]:
raise BuildError("%s under %s differs from colors/retail: %s vs %s"
% (i, SEED_KEY, v["sha256"], out_colors[i]["sha256"]))
arial = [f for f in base["fonts"] if f["family"] == "Arial"]
if len(arial) != 1:
raise BuildError("canvas_text_ref/refs.json has no single Arial entry")
return {
"test_page": "index.html",
"black_page": "../canvas_text_ref/index.html",
"text": base["text"],
"firefox": base["firefox"],
"canvas": base["canvas"],
"cleartype": base["cleartype"],
"fonts": arial,
"capture": {
"date": DATE,
"origin": "retail Firefox 159.0 (build %s, firefox.exe sha256 %s) on Windows, "
"headless, canvases read back with getImageData; bytes saved by the "
"measuring harness: colors/retail (the 14 coloured cases) and "
"keys/<gamma>_<contrast>/retail (39 cases per key) of the win-asset "
"analysis of 2026-11-09"
% (base["firefox"]["buildid"], base["firefox"]["exe_sha256"]),
"colors_prefs": COLORS_RETAIL_PREFS,
"keys_prefs": RETAIL_PREFS,
},
"colors": {"count": len(out_colors), "cases": out_colors},
"keys": out_keys,
}
def main(argv):
ap = argparse.ArgumentParser(description=__doc__,
formatter_class=argparse.RawDescriptionHelpFormatter)
ap.add_argument("--bytes", required=True, metavar="DIR",
help="directory with colors/retail and keys/<gamma>_<contrast>/retail")
ap.add_argument("--keys", default=DEFAULT_KEYS,
help="ClearType keys, gamma_contrast, comma separated (default %(default)s)")
ap.add_argument("--out", default=str(DATA / "refs.json"))
a = ap.parse_args(argv[1:])
keys = [k for k in a.keys.split(",") if k]
try:
refs = build(a.bytes, keys, (DATA / "index.html").read_text(encoding="utf-8"),
json.loads(BASE_REFS.read_text(encoding="utf-8")))
except (BuildError, KeyError, ValueError) as e:
print("error: %s" % e, file=sys.stderr)
return 1
Path(a.out).write_text(json.dumps(refs, ensure_ascii=False, indent=1) + "\n",
encoding="utf-8", newline="\n")
print("%d coloured cases, %d keys x %d cases -> %s"
% (refs["colors"]["count"], len(refs["keys"]),
next(iter(refs["keys"].values()))["count"], a.out))
return 0
if __name__ == "__main__":
sys.exit(main(sys.argv))
+19 -34
View File
@@ -3,8 +3,20 @@
A raw `firefox --screenshot` proves nothing about automation: a juggler-less
binary renders a screenshot just fine and ships broken (firefox-8 did exactly
that). This DRIVES the binary the way users will - Playwright launches it over
the juggler pipe and exercises real paths.
that). This DRIVES the binary the way users will - the wrapper (and the core under
it) launches it over the juggler pipe and exercises real paths.
⛔ THROUGH THE CORE, NOT THROUGH BARE PLAYWRIGHT. Since firefox-63 the engine holds
every channel that asks the proxy service until the client has said how the
session leaves the host (`Browser.setBrowserProxy`, or the explicit
`Browser.setNoBrowserProxy` of a session without a proxy): nothing may leave the
host before that. Stock Playwright sends the first only when it is given a proxy,
so a bare `p.firefox.launch_persistent_context(executable_path=...)` navigates
nowhere: run 43134774602, `Page.goto: Timeout 30000ms` on every leg, three
attempts. The core's launch sends the decision FIRST, and declares the first run
(terms of use, pre-onboarding) that this script used to copy into user.js, so
the copy is gone with it. The job installs the core under test (core_ref, from
git) and the wrapper, and seals the binary, before this script runs.
Three levels (see `--click` / `--full`):
@@ -60,31 +72,9 @@ Exit 0 + "DRIVE GATE OK ..." on success; non-zero with a reason on failure.
from __future__ import annotations
import http.server
import json
import shutil
import socketserver
import sys
import tempfile
import threading
from pathlib import Path
# ⛔ THE FIRST RUN IS DECLARED HERE, A COPY OF THE CORE'S, written into the
# profile's user.js. Since firefox-55 the engine leaves Mozilla's first-run
# lines and invisible_core declares the state (terms of use accepted long ago,
# pre-onboarding off). This job installs only Playwright, so nothing declared
# it: measured 2026-11-02 on run 41388672849, Windows showed the terms-of-use
# modal ("the page did not handle mouse event") and Linux opened
# https://www.mozilla.org/en-US/privacy/firefox/ in a second tab (the legacy
# data-reporting flow) ("Unexpected number of tabs in the new window: 2").
# Upstream Playwright sends its own defaults in Browser.enable, which this
# engine refuses, so a raw launch runs on Mozilla's lines alone. With these
# three in user.js, both legs drive. tests/test_ci_drive_gate_first_run.py
# ties the copy to the core.
FIRST_RUN = {
"browser.preonboarding.enabled": False,
"termsofuse.acceptedVersion": 4,
"termsofuse.acceptedDate": "1785573000000",
}
HTML = (
"<!doctype html><html><head><title>dt</title></head><body>"
@@ -155,16 +145,12 @@ def _drive(exe: str, url: str, level: str) -> str:
"""One run. `level` is "smoke", "click" or "full". Returns the UA."""
interacts = level in ("click", "full")
full = level == "full"
from playwright.sync_api import sync_playwright
from invisible_playwright import InvisiblePlaywright
# A user.js is read at startup, before the window that would carry the
# modal; a persistent context is the only way to hand Playwright a profile.
profile_dir = Path(tempfile.mkdtemp(prefix="ci-drive-gate-"))
(profile_dir / "user.js").write_bytes(
"".join("user_pref(%s, %s);\n" % (json.dumps(k), json.dumps(v))
for k, v in sorted(FIRST_RUN.items())).encode("utf-8"))
with sync_playwright() as p:
ctx = p.firefox.launch_persistent_context(str(profile_dir), executable_path=exe, headless=True)
# The core declares the first run and sends the session's road before anything else; the seal of the binary is
# INVISIBLE_SEAL_FILE (the job sets it), and `binary_path` is the binary under test.
with InvisiblePlaywright(seed=42, binary_path=exe, headless=True, humanize=False) as browser:
ctx = browser.new_context()
try:
page = ctx.new_page()
resp = page.goto(url, wait_until="load")
@@ -192,7 +178,6 @@ def _drive(exe: str, url: str, level: str) -> str:
inter["plugins"] = page.evaluate("() => navigator.plugins instanceof PluginArray")
finally:
ctx.close()
shutil.rmtree(profile_dir, ignore_errors=True)
# SMOKE asserts (always).
assert "Firefox" in ua, f"unexpected UA (binary not driving correctly): {ua!r}"
+501
View File
@@ -0,0 +1,501 @@
#!/usr/bin/env python3
"""CI verdict - the one judge of the mandatory test suites (stdlib only).
`ci/required-suites.json` lists the suites a round must run, per operating system, with the number of tests each must
collect. A test that is skipped, deselected or never collected is a hole nobody sees, so this script reads the junit
pytest wrote and fails on every one of them.
ci_verdict.py args --required ci/required-suites.json --suite wrapper.e2e.udp --os linux [--with-marker]
prints, one per line, the pytest arguments of the suite (files and node ids); with --with-marker, `-m` and the
suite's marker come first. An error (exit 2) if the suite does not run on that OS or the list is malformed.
ci_verdict.py judge --required ci/required-suites.json --suite wrapper.e2e.udp --os linux
--junit junit.xml --binary PATH [--commit SHA] [--seal gate.seal.json]
[--out result/wrapper.e2e.udp.linux.json]
[--main-required PATH | --main-required PATH --main-has-no-list]
reads the junit, writes the result json (with `verdict`: "green" or "red") and exits 1, printing EVERY problem
with its reason, one per line, when: the junit or the row is missing; the junit is not xunit2 (a testcase with
no `classname`); a test failed, errored or was skipped; fewer tests were collected than `min_tests`, or, when
the row is `exact`, any number other than `min_tests` (a deselected test is not in the junit: `min_tests` goes
up by hand when a test is added, never silently); a required file or node id did not pass; the binary is
missing (--binary is mandatory: without it exit 2) or the commit cannot be known; the --seal is unreadable.
With --main-required (the list of main) the list only grows: a suite of main is gone, its minimum went down,
its `exact` went from true to false, its os or tests lost an element, or its marker changed is red.
What the file of main is can be said only by the gate, which checks main out (a failed download is not
"main has no list"): the file exists -> it is compared; it does not exist and the gate passed
--main-has-no-list (main was checked out and has no such file) -> passed, declared; it does not exist
without --main-has-no-list -> RED, "it is not known what main has".
The commit is --commit SHA or `git rev-parse HEAD` in the current directory (the checkout of the wrapper),
NEVER GITHUB_SHA (in a called workflow it is the commit of the engine's repository). --seal reads the seal of
the gate: the seal that `python -m invisible_core seal` writes, and the release seal, carry NO sha256 of the
engine binary (an asset's `sha256` is the one of the archive, `omni_sha256` the one of omni.ja), so there is
nothing to compare it with: the summary says so and the result records `seal_binary_hash: "absent"`.
ci_verdict.py complete --required ci/required-suites.json --results DIR
DIR holds the result json files `judge` wrote (also in subfolders: one artifact `result-<suite>-<os>` each).
Exit 1, one problem per line, when: a (suite, os) of the list has no result; a result is not green; a result
is of a (suite, os) that is not in the list, or twice; the commit is not the same in every result, or the
binary sha256 is not the same in every result of one OS (or missing).
The list is validated by all three commands (a malformed one is exit 2, with the reason, never green): ids unique; per
row `os` a non-empty subset of {linux, windows}, `tests` a non-empty list of unique strings, `min_tests` an integer > 0,
`exact` a bool, `marker` a string, `needs_root` a bool or a list of the row's OSes.
A required entry of "tests" is a file (at least one test of it must exist and EVERY one collected must pass) or a node
id `tests/x.py::name` (that test must pass; a parametrized test is matched on the name before `[`, and every one of its
parameters must pass).
What the gate must do (it is not done here):
* run pytest as `env -u PYTEST_ADDOPTS python -m pytest ... -p no:rerunfailures -o junit_family=xunit2
--junitxml=junit.xml` (no addopts from outside, no rerun that turns a failure green, a junit that keeps `classname`;
a junit with no `classname`, or with `file`/`line`, is red);
* on the Linux leg of the DoH suite, export INVPW_REQUIRE_TRAP=1 (the resolver trap must run, never be skipped);
* pass --commit or run in the checkout of the wrapper, pass --binary, and check out main before --main-required.
Exit 0 on a green verdict, 1 on a red one, 2 on a wrong use or a malformed list.
"""
from __future__ import annotations
import argparse
import hashlib
import json
import os
import subprocess
import sys
import xml.etree.ElementTree as ET
from pathlib import Path
OSES = ("linux", "windows")
class Usage(Exception):
pass
class BadList(Usage):
"""The required list itself is malformed (exit 2)."""
# --------------------------------------------------------------------------------------------- the required list
def _is_int(value):
return isinstance(value, int) and not isinstance(value, bool)
def validate_list(data):
"""-> the list of reasons why `data` is not a well-formed required list (empty if it is)."""
if not isinstance(data, list):
return ["the required list must be a JSON list of suites"]
if not data:
return ["the required list is empty"]
problems, seen = [], set()
for i, row in enumerate(data):
if not isinstance(row, dict):
problems.append("row %d is not an object" % i)
continue
sid = row.get("id")
where = "row %d" % i
if not isinstance(sid, str) or not sid.strip():
problems.append("%s has no id (a non-empty string)" % where)
else:
where = "row %d (%s)" % (i, sid)
if sid in seen:
problems.append("%s: the id appears more than once" % where)
seen.add(sid)
oses = row.get("os")
oses_ok = (isinstance(oses, list) and oses and all(isinstance(o, str) for o in oses)
and set(oses) <= set(OSES) and len(set(oses)) == len(oses))
if not oses_ok:
problems.append("%s: os must be a non-empty list of distinct values among %s, not %r"
% (where, "/".join(OSES), oses))
tests = row.get("tests")
if not (isinstance(tests, list) and tests and all(isinstance(t, str) and t.strip() for t in tests)):
problems.append("%s: tests must be a non-empty list of non-empty strings" % where)
elif len(set(tests)) != len(tests):
problems.append("%s: tests has duplicates: %s"
% (where, ", ".join(sorted({t for t in tests if tests.count(t) > 1}))))
if not _is_int(row.get("min_tests")) or row.get("min_tests") <= 0:
problems.append("%s: min_tests must be an integer > 0, not %r" % (where, row.get("min_tests")))
if not isinstance(row.get("exact"), bool):
problems.append("%s: exact must be true or false, not %r" % (where, row.get("exact")))
if not isinstance(row.get("marker"), str) or not row.get("marker").strip():
problems.append("%s: marker must be a non-empty string, not %r" % (where, row.get("marker")))
root = row.get("needs_root", False)
if not isinstance(root, bool):
if not (isinstance(root, list) and all(isinstance(o, str) for o in root) and set(root) <= set(OSES)
and (not oses_ok or set(root) <= set(oses))):
problems.append("%s: needs_root must be a bool or a list of the OSes of the row, not %r" % (where, root))
return problems
def _read_json_list(path):
try:
return json.loads(Path(path).read_text(encoding="utf-8"))
except (OSError, ValueError) as exc:
raise Usage("cannot read the required list %s: %s" % (path, exc))
def load_required(path):
data = _read_json_list(path)
problems = validate_list(data)
if problems:
raise BadList("the required list %s is malformed:\n %s" % (path, "\n ".join(problems)))
return data
def find_suite(suites, suite_id, os_name):
if os_name not in OSES:
raise Usage("--os must be one of %s, not %r" % (", ".join(OSES), os_name))
rows = [s for s in suites if isinstance(s, dict) and s.get("id") == suite_id]
if not rows:
raise Usage("no suite %r in the required list" % suite_id)
if len(rows) > 1:
raise Usage("the suite %r appears %d times in the required list" % (suite_id, len(rows)))
row = rows[0]
if os_name not in row.get("os", []):
raise Usage("the suite %r does not run on %s (it runs on: %s)"
% (suite_id, os_name, ", ".join(row.get("os", [])) or "nowhere"))
return row
# ------------------------------------------------------------------------------------------------- the junit
def node_id(classname, name):
"""`tests.test_x` + `test_y[p]` -> `tests/test_x.py::test_y[p]`; a class segment (capitalised) goes after the file."""
parts = [p for p in (classname or "").split(".") if p]
module, klass = [], []
for i, part in enumerate(parts):
if part[:1].isupper() and module:
klass = parts[i:]
break
module.append(part)
if not module:
return name or ""
return "::".join(["/".join(module) + ".py"] + klass + [name or ""])
def parse_junit(path):
"""-> (list of (node id, outcome) with outcome in passed|failed|errors|skipped, names of the testcases that are not
xunit2). Only xunit2 is accepted: a testcase with no `classname` cannot be told which file it is in, and the extra
`file`/`line` attributes are what junit_family=xunit1 writes (pytest 9: it keeps the classname AND adds them)."""
root = ET.parse(path).getroot()
out, no_class = [], []
for case in root.iter("testcase"):
if not (case.get("classname") or "").strip() or case.get("file") is not None or case.get("line") is not None:
no_class.append(case.get("name") or "?")
nid = node_id(case.get("classname"), case.get("name"))
tags = {child.tag for child in case}
if "error" in tags:
outcome = "errors"
elif "failure" in tags:
outcome = "failed"
elif "skipped" in tags:
outcome = "skipped"
else:
outcome = "passed"
out.append((nid, outcome))
return out, no_class
def read_junit(path):
return parse_junit(path)[0]
def _base(nid):
"""The node id without the parameters of its last segment."""
return nid.split("[", 1)[0]
def required_status(entry, cases):
"""-> None if the required entry is satisfied, else why not. EVERY collected test of the entry must have passed."""
if "::" in entry:
mine = [o for n, o in cases if n == entry or _base(n) == entry]
what = "node id"
else:
mine = [o for n, o in cases if n.split("::", 1)[0] == entry]
what = "file"
if not mine:
return "the %s %s did not run (it is not in the junit)" % (what, entry)
bad = sorted({o for o in mine if o != "passed"})
if bad:
return "the %s %s has tests that did not pass (%s)" % (what, entry, ", ".join(bad))
return None
def sha256_of(path):
if not path or not os.path.isfile(path):
return None
h = hashlib.sha256()
with open(path, "rb") as fh:
for chunk in iter(lambda: fh.read(1 << 20), b""):
h.update(chunk)
return h.hexdigest()
def commit_sha(explicit):
"""--commit, else `git rev-parse HEAD` in the current directory. Never GITHUB_SHA (in a called workflow it is the
commit of the engine's repository, not of the wrapper)."""
if explicit:
return explicit.strip() or None
try:
sha = subprocess.run(["git", "rev-parse", "HEAD"], capture_output=True, text=True, timeout=30,
check=True).stdout.strip()
except (OSError, subprocess.SubprocessError):
return None
return sha or None
# ------------------------------------------------------------------------------------------------ against main
def _int(value):
return value if _is_int(value) else 0
def against_main(current, main):
"""The list only grows: every suite of main is still here, with no lower minimum, no exact turned off, no lost
test or OS and the same marker. `main` is read leniently (it may be older than the current format)."""
problems = []
if not isinstance(main, list):
return ["the list of main is not a JSON list: it cannot be compared"]
by_id = {s.get("id"): s for s in current if isinstance(s, dict)}
for old in main:
if not isinstance(old, dict):
continue
sid = old.get("id")
new = by_id.get(sid)
if new is None:
problems.append("the suite %s of main is gone from the list" % sid)
continue
if _int(new.get("min_tests")) < _int(old.get("min_tests")):
problems.append("the minimum of %s went down: %s on main, %s here"
% (sid, old.get("min_tests"), new.get("min_tests")))
if old.get("exact") is True and new.get("exact") is not True:
problems.append("the suite %s is no longer exact, as it is on main" % sid)
lost = [t for t in old.get("tests", []) if t not in new.get("tests", [])]
if lost:
problems.append("the suite %s lost %d required test(s) that main has: %s" % (sid, len(lost), ", ".join(lost)))
lost_os = [o for o in old.get("os", []) if o not in new.get("os", [])]
if lost_os:
problems.append("the suite %s no longer runs on %s, where main runs it" % (sid, ", ".join(lost_os)))
if old.get("marker") != new.get("marker"):
problems.append("the marker of %s changed: %r on main, %r here" % (sid, old.get("marker"), new.get("marker")))
return problems
# ------------------------------------------------------------------------------------------------ the commands
def cmd_args(ns):
row = find_suite(load_required(ns.required), ns.suite, ns.os)
lines = []
if ns.with_marker and row.get("marker"):
lines += ["-m", row["marker"]]
lines += list(row.get("tests", []))
# bytes, so that Windows does not turn the newlines into CRLF (a CR would stay glued to the last argument)
sys.stdout.buffer.write("".join(line + "\n" for line in lines).encode("utf-8"))
sys.stdout.buffer.flush()
return 0
def _seal_problems(path, result):
"""The seal of the gate must be readable. It has no sha256 of the binary to compare (see the docstring)."""
try:
data = json.loads(Path(path).read_text(encoding="utf-8"))
if not isinstance(data, dict):
raise ValueError("not a JSON object")
except (OSError, ValueError) as exc:
result["seal_binary_hash"] = "unreadable"
return ["the seal %s cannot be read: %s" % (path, exc)]
result["seal_binary_hash"] = "absent"
print("note: the seal %s carries no sha256 of the engine binary (an asset's sha256 is the one of the archive): "
"the binary was not compared with it" % path)
return []
def cmd_judge(ns):
problems = []
result = {"suite": ns.suite, "os": ns.os, "commit": commit_sha(ns.commit), "binary_sha256": sha256_of(ns.binary),
"collected": 0, "passed": 0, "failed": 0, "skipped": 0, "errors": 0, "missing_tests": [],
"problems": problems}
code_on_red = 1
try:
suites = load_required(ns.required)
row = find_suite(suites, ns.suite, ns.os)
except BadList as exc:
problems.append(str(exc))
return _finish(ns, result, 2)
except Usage as exc:
problems.append("no result for this row: %s" % exc)
return _finish(ns, result, code_on_red)
if result["commit"] is None:
problems.append("the commit of the wrapper is not known (no --commit and `git rev-parse HEAD` failed here)")
if result["binary_sha256"] is None:
problems.append("the binary %s does not exist: a result with no hash of the engine is not a result" % ns.binary)
if ns.seal:
problems += _seal_problems(ns.seal, result)
counts = {"passed": 0, "failed": 0, "skipped": 0, "errors": 0}
cases = []
if not os.path.isfile(ns.junit):
problems.append("the junit %s is missing: the suite %s did not report on %s" % (ns.junit, ns.suite, ns.os))
else:
try:
cases, no_class = parse_junit(ns.junit)
if no_class:
problems.append("the junit is not xunit2: %d testcase(s) have no classname or carry file/line (e.g. %s); the gate must run "
"pytest with -o junit_family=xunit2" % (len(no_class), no_class[0]))
except (ET.ParseError, OSError) as exc:
problems.append("the junit %s cannot be read: %s" % (ns.junit, exc))
for _n, outcome in cases:
counts[outcome] += 1
collected = len(cases)
if counts["failed"]:
problems.append("%d test(s) failed" % counts["failed"])
if counts["errors"]:
problems.append("%d test(s) ended in error" % counts["errors"])
if counts["skipped"]:
problems.append("%d test(s) were skipped: a required suite allows no skip" % counts["skipped"])
minimum = row.get("min_tests")
if collected < minimum:
problems.append("collected %d test(s), fewer than the minimum %s" % (collected, minimum))
elif row.get("exact") and collected != minimum:
problems.append("collected %d test(s), but the suite is exact: %s, not more (a test was added: raise min_tests "
"by hand)" % (collected, minimum))
missing = []
for entry in row.get("tests", []):
why = required_status(entry, cases)
if why:
missing.append(entry)
problems.append(why)
if ns.main_has_no_list and not ns.main_required:
problems.append("--main-has-no-list without --main-required: it says nothing")
elif ns.main_required:
exists = os.path.isfile(ns.main_required)
if exists and ns.main_has_no_list:
problems.append("the list of main %s exists, but --main-has-no-list says main has none" % ns.main_required)
elif exists:
try:
problems += against_main(suites, _read_json_list(ns.main_required))
except Usage as exc:
problems.append(str(exc))
elif ns.main_has_no_list:
print("the list of main %s does not exist and the gate declares that main was checked out and has none: "
"nothing to compare" % ns.main_required)
else:
problems.append("the list of main %s does not exist and main was not declared to have none "
"(--main-has-no-list): it is not known what main has, so the list cannot be compared"
% ns.main_required)
result.update(counts, collected=collected, missing_tests=missing)
return _finish(ns, result, code_on_red)
def _finish(ns, result, code_on_red):
problems = result["problems"]
result["verdict"] = "red" if problems else "green"
if ns.out:
out = Path(ns.out)
out.parent.mkdir(parents=True, exist_ok=True)
out.write_text(json.dumps(result, indent=2, sort_keys=True) + "\n", encoding="utf-8")
if problems:
for p in problems:
print("VERDICT RED %s/%s: %s" % (ns.suite, ns.os, p))
return code_on_red
print("VERDICT GREEN %s/%s: %d collected, %d passed" % (ns.suite, ns.os, result["collected"], result["passed"]))
return 0
def cmd_complete(ns):
suites = load_required(ns.required)
expected = {(s["id"], o) for s in suites for o in s["os"]}
problems = []
folder = Path(ns.results)
if not folder.is_dir():
problems.append("the results folder %s does not exist: no suite reported" % ns.results)
found = {} # (suite, os) -> (path, data)
for path in sorted(folder.rglob("*.json")) if folder.is_dir() else []:
try:
data = json.loads(path.read_text(encoding="utf-8"))
except (OSError, ValueError) as exc:
problems.append("%s cannot be read as a result: %s" % (path, exc))
continue
if not (isinstance(data, dict) and isinstance(data.get("suite"), str) and isinstance(data.get("os"), str)):
problems.append("%s is not a result of judge (no suite and os)" % path)
continue
key = (data["suite"], data["os"])
if key not in expected:
problems.append("%s is the result of %s/%s, which is not in the required list" % (path, key[0], key[1]))
continue
if key in found:
problems.append("%s/%s has two results: %s and %s" % (key[0], key[1], found[key][0], path))
continue
found[key] = (path, data)
for suite, os_name in sorted(expected - set(found)):
problems.append("%s/%s has no result: the leg did not report" % (suite, os_name))
for key, (path, data) in sorted(found.items()):
if data.get("verdict") != "green":
why = data.get("problems") or ["no verdict in the result"]
problems.append("%s/%s is not green (%s): %s" % (key[0], key[1], data.get("verdict"), "; ".join(map(str, why))))
elif data.get("problems"):
problems.append("%s/%s says green but lists problems: %s" % (key[0], key[1], "; ".join(map(str, data["problems"]))))
commits = {}
shas = {}
for key, (_path, data) in found.items():
commits.setdefault(data.get("commit"), []).append("%s/%s" % key)
shas.setdefault(key[1], {}).setdefault(data.get("binary_sha256"), []).append("%s/%s" % key)
if None in commits:
problems.append("no commit in the result of: %s" % ", ".join(sorted(commits[None])))
if len([c for c in commits if c]) > 1:
problems.append("the legs ran at different commits: %s"
% "; ".join("%s: %s" % (c, ", ".join(sorted(v))) for c, v in sorted(commits.items(), key=str)))
for os_name, by_sha in sorted(shas.items()):
if None in by_sha:
problems.append("no binary sha256 in the result of: %s" % ", ".join(sorted(by_sha[None])))
if len([s for s in by_sha if s]) > 1:
problems.append("the %s legs ran with different binaries: %s" % (
os_name, "; ".join("%s: %s" % (s, ", ".join(sorted(v))) for s, v in sorted(by_sha.items(), key=str))))
if problems:
for p in problems:
print("COMPLETE RED: %s" % p)
return 1
print("COMPLETE GREEN: %d result(s), all green, one commit, one binary per OS" % len(found))
return 0
def main(argv=None):
ap = argparse.ArgumentParser(description=__doc__.split("\n", 1)[0])
sub = ap.add_subparsers(dest="cmd", required=True)
a = sub.add_parser("args", help="print the pytest arguments of a suite")
a.add_argument("--required", required=True)
a.add_argument("--suite", required=True)
a.add_argument("--os", required=True)
a.add_argument("--with-marker", action="store_true", help="print -m and the marker of the suite first")
j = sub.add_parser("judge", help="judge the junit of a suite")
j.add_argument("--required", required=True)
j.add_argument("--suite", required=True)
j.add_argument("--os", required=True)
j.add_argument("--junit", required=True)
j.add_argument("--binary")
j.add_argument("--commit")
j.add_argument("--seal")
j.add_argument("--out")
j.add_argument("--main-required")
j.add_argument("--main-has-no-list", action="store_true",
help="the gate checked main out and the list is not there (a failed checkout is not this)")
c = sub.add_parser("complete", help="check that every (suite, os) reported green at one commit")
c.add_argument("--required", required=True)
c.add_argument("--results", required=True)
ns = ap.parse_args(argv)
try:
if ns.cmd == "judge":
if not ns.binary:
raise Usage("judge needs --binary (the engine the suite ran against: its hash goes in the result)")
return cmd_judge(ns)
if ns.cmd == "complete":
return cmd_complete(ns)
return cmd_args(ns)
except Usage as exc:
print("ci_verdict: %s" % exc, file=sys.stderr)
return 2
if __name__ == "__main__":
sys.exit(main())
-19
View File
@@ -65,25 +65,6 @@ EXPECTED_DIFFERENCES = {
# this line is where to start.
("ElementHandle", "event", "previewUpdated"),
("JSHandle", "event", "previewUpdated"),
# ⛔ `Dialog` FUSED on 2026-08-29: no `__create__`, no channel, no
# `BrowserContext.dialog` wire event - see `_pw/_impl/_dialog.py`. The
# driver still allocates a real channel object for it (parented under
# `Page`, with `type`/`message`/`defaultValue`/`page` in its initializer)
# and announces it with a `dialog` event on `BrowserContext`; this server
# builds the same object directly, on the connection's read-loop thread,
# and hands it straight to the listener through the twin bridge in
# `InProcessTransport.bind_impl_objects`. The three lines below were
# measured EMPTY before this fusion - `capture_protocol.py`'s scripted
# session did not open a dialog at all, so a `PARITY` verdict for this
# type would have been vacuous, not a confirmation. It now clicks a
# button that calls `alert()` and accepts it, so the gap below is a
# measured, argued difference, not an unexercised one.
("Dialog", "initializer", "type"),
("Dialog", "initializer", "message"),
("Dialog", "initializer", "defaultValue"),
("Dialog", "initializer", "page"),
("Dialog", "parent", "Page"),
("BrowserContext", "event", "dialog"),
}
+47 -4
View File
@@ -229,14 +229,48 @@ def render(value: str, badge: Badge) -> bytes:
return "\n".join(lines).encode("utf-8")
def latest(history: dict[str, dict[str, int]], key: str) -> int:
days = [d for d in history if key in history[d]]
if not days:
raise SystemExit(f"no {key} in the history")
return history[max(days)][key]
# The big row at the top of the README is drawn by shields.io from these
# files (its "endpoint" badge), so the numbers stay ours and the look is theirs.
@dataclass(frozen=True)
class Endpoint:
label: str
colour: str
logo: str
file_name: str
key: str
ENDPOINTS = [
Endpoint("browser launches", "FF7139", "firefoxbrowser", "launches.json", "launches_total"),
Endpoint("engine downloads", "2EA44F", "github", "downloads.json", "total_binaries"),
]
def endpoint_json(value: str, e: Endpoint) -> bytes:
if not SAFE_VALUE.match(value):
raise ValueError(f"refusing to publish an unexpected value: {value!r}")
return (json.dumps({
"schemaVersion": 1, "label": e.label, "message": value,
"color": e.colour, "namedLogo": e.logo, "logoColor": "white",
"cacheSeconds": 3600,
}, indent=2) + "\n").encode("utf-8")
def write_badges(directory: Path, history: dict[str, dict[str, int]]) -> None:
directory.mkdir(parents=True, exist_ok=True)
for b in BADGES:
days = [d for d in history if b.key in history[d]]
if not days:
raise SystemExit(f"no {b.key} in the history")
(directory / b.file_name).write_bytes(
render(format_count(history[max(days)][b.key]), b))
render(format_count(latest(history, b.key)), b))
for e in ENDPOINTS:
(directory / e.file_name).write_bytes(
endpoint_json(format_count(latest(history, e.key)), e))
# ── entry point ─────────────────────────────────────────────────────────────
@@ -275,6 +309,15 @@ def selftest() -> int:
append_snapshot(p, "2026-11-08", {"stars": 1})
if append_snapshot(p, "2026-11-08", {"stars": 2}) or read_history(p)["2026-11-08"]["stars"] != 1:
fails.append("idempotent")
# The README's top row reads these two files through shields.io.
h = {"2026-11-11": {"launches_total": 5_319_939, "total_binaries": 232_924, "stars": 2569}}
write_badges(Path(t) / "b", h)
got = json.loads((Path(t) / "b" / "launches.json").read_text(encoding="utf-8"))
if (got.get("schemaVersion"), got.get("label"), got.get("message")) != (1, "browser launches", "5.31M"):
fails.append("endpoint launches")
got = json.loads((Path(t) / "b" / "downloads.json").read_text(encoding="utf-8"))
if got.get("message") != "232.92k":
fails.append("endpoint downloads")
print("selftest:", "OK" if not fails else "FAIL " + ", ".join(fails))
return 1 if fails else 0
+4
View File
@@ -68,6 +68,7 @@ from invisible_core import BINARY_VERSION, FIREFOX_UPSTREAM_VERSION
from invisible_core import GeoTimezoneError, resolve_session_timezone
from invisible_core import ensure_binary, ensure_geoip_mmdb
from .launcher import InvisiblePlaywright
from ._juggler.remote import RemoteServer, launch_server, launch_server_async
# `__version__` describes the CODE that is about to run; the install record is
# a different fact and keeps a name that says so, the way `invisible_core` does.
@@ -79,6 +80,9 @@ from ._version import __install_record_version__, __version__
__all__ = [
"InvisiblePlaywright",
"launch_server",
"launch_server_async",
"RemoteServer",
"ensure_binary",
"ensure_geoip_mmdb",
"get_default_stealth_prefs",
File diff suppressed because it is too large. Load diff
@@ -15,6 +15,7 @@ there has to move.
from __future__ import annotations
import json
import math
import re
from typing import Any, Dict, List, Optional
@@ -135,6 +136,15 @@ def _serialize(value: Any, counter: Optional[Dict] = None) -> Any:
return {"v": "null"}
if isinstance(value, bool):
return {"b": value}
if isinstance(value, float):
# NaN, the infinities and -0 are not JSON numbers: Playwright sends them as a tag
# (`{"v": "NaN"}`), and a bare `{"n": nan}` is refused by a strict wire.
if math.isnan(value):
return {"v": "NaN"}
if math.isinf(value):
return {"v": "Infinity" if value > 0 else "-Infinity"}
if value == 0.0 and math.copysign(1.0, value) < 0:
return {"v": "-0"}
if isinstance(value, (int, float)):
return {"n": value}
if isinstance(value, str):
+138 -40
View File
@@ -33,10 +33,12 @@ from __future__ import annotations
import contextvars
import itertools
import os
import threading
import time
from typing import Any, Callable, Dict, List, Optional
from . import perimeter
from . import perimeter, variants
# One class for a target that is gone, raised here for a disposed object and
# by the connection for a closed pipe. Defined there, the lower layer.
from invisible_core.juggler.connection import TargetClosedError # noqa: F401 - re-exported on purpose
@@ -44,6 +46,43 @@ from invisible_core.juggler.connection import TargetClosedError # noqa: F401 -
#: HOW MANY DISPATCHERS OF ONE BUCKET THE REGISTRY KEEPS, AS PLAYWRIGHT'S SERVER DOES
#: (1.62, `dispatchers/dispatcher.ts` `maxDispatchersForBucket`): a bucket is the object's
#: type - a Frame is 'MainFrame' or 'Frame' - and past its limit the oldest tenth of the
#: bucket is disposed with `__dispose__` {reason: "gc"}, which a client reads as "collected
#: to prevent unbounded heap growth". ONE VALUE PER TYPE, here, so it can be lowered in one
#: place; `INVPW_GC_LIMITS="Request=1000,Response=1000"` lowers some without editing code
#: ("default=N" changes the default).
#:
#: TWO DIFFERENCES FROM PLAYWRIGHT, and the only two. (1) Request, Response and Route are
#: 2000, not 10000: a context that lives through a hundred navigations of real pages
#: (~100 subresources each, ~200 objects per navigation) held 18,000 of them, and with real
#: headers that is 190 MB of process (measured on a real browser, 95 navigations, one
#: context, objects already light) against 70 MB with 2000. A client reads a request in the
#: callback of its event (the Go client keeps none beyond it) and 2000 is ten navigations.
#: (2) An object younger than GC_MIN_AGE_S is never collected, so what a client was just
#: handed is valid for the length of any callback however fast the bucket fills: Playwright
#: collects the oldest tenth whatever its age.
GC_LIMIT_DEFAULT = 10000
GC_LIMITS: Dict[str, int] = {"JSHandle": 100000, "ElementHandle": 100000,
"Request": 2000, "Response": 2000, "Route": 2000}
GC_MIN_AGE_S = 10.0
def gc_limits_from_env(environ: Optional[Dict[str, str]] = None) -> Dict[str, int]:
"""`GC_LIMITS` with the default under "default", and what `INVPW_GC_LIMITS` overrides."""
environ = os.environ if environ is None else environ
limits = dict(GC_LIMITS)
limits["default"] = GC_LIMIT_DEFAULT
for item in (environ.get("INVPW_GC_LIMITS") or "").split(","):
name, _, value = item.partition("=")
try:
limits[name.strip()] = max(1, int(value))
except ValueError:
continue
return limits
class ProtocolException(Exception):
"""A failure the client should see as a protocol error, with its reason.
@@ -120,6 +159,18 @@ class Dispatcher:
server.register(self)
# ⛔ Announced BEFORE anyone can name it. See the module docstring.
server.announce(self)
self.announced()
# And only then, as Playwright does: past the limit of its bucket the oldest are let go.
server.collect_stale(self._gc_bucket)
def announced(self) -> None:
"""The `__create__` has gone: where an object lets go of what only the
announcement needed (a leaf's headers, a POST body). Runs once, from
the constructor."""
def gc_bucket(self) -> str:
"""The bucket this object is counted in (`GC_LIMITS`): its type."""
return self.TYPE
# ── what the protocol needs ─────────────────────────────────────────────
@property
@@ -128,7 +179,11 @@ class Dispatcher:
return {"guid": self.guid}
def emit(self, method: str, params: Optional[Dict] = None) -> None:
"""Fire a protocol event on this object."""
"""Fire a protocol event on this object. One that is already disposed says
nothing: the client has dropped the guid, and naming it is an error there
(Playwright's server ignores it too, outside its own tests)."""
if self.disposed:
return
self.server.send_up({"guid": self.guid, "method": method,
"params": params or {}})
@@ -157,9 +212,17 @@ class Dispatcher:
self.server.send_up({"guid": self.guid, "method": "__dispose__",
"params": params})
self.server.unregister(self)
self.released()
for child in self.server.descendants_of(self):
child.disposed = True
self.server.unregister(child)
child.released()
def released(self) -> None:
"""The object has left the registry, by its own `dispose` or by an
ancestor's cascade (which does not call `dispose` on a descendant):
where it lets go of what OTHER objects hold of it - an index, a list,
a file. Runs once."""
# ── routing ─────────────────────────────────────────────────────────────
def call(self, method: str, params: Dict) -> Any:
@@ -199,6 +262,10 @@ class Server:
#: already in flight behind it.
self._disposed: Dict[str, None] = {}
self._counters: Dict[str, itertools.count] = {}
#: bucket -> the guids of its live objects, oldest first (a dict keeps the order).
self._buckets: Dict[str, Dict[str, None]] = {}
self.gc_limits = gc_limits_from_env()
self.gc_min_age = GC_MIN_AGE_S
self._lock = threading.Lock()
self._transport: Any = None
#: Guid "" is the Root the client creates on its own side. Nothing is
@@ -207,49 +274,11 @@ class Server:
self._on_shutdown: list = []
#: What `shutdown` runs after every hook. See `after_shutdown`.
self._after_shutdown: list = []
#: guid -> the live impl-side object for it, or None until a
#: transport binds it. See `bind_twins`.
self._twins: Optional[Dict[str, Any]] = None
#: The client's `Connection.deliver_event`, or None until bound. See
#: `bind_twins` and `deliver`.
self._deliver_event: Any = None
# ── plumbing ────────────────────────────────────────────────────────────
def attach(self, transport: Any) -> None:
self._transport = transport
def bind_twins(self, objects: Dict[str, Any], deliver_event: Any) -> None:
"""Give this server a live view of the client's guid -> object
registry, and its event-delivery entry point. See
`InProcessTransport.bind_impl_objects`, which calls this - the
docstring for WHY lives there, next to its one caller."""
self._twins = objects
self._deliver_event = deliver_event
def twin(self, guid: str) -> Any:
"""The live impl-side object for a guid this server already created,
or None if nothing is bound yet or the guid is unknown."""
return (self._twins or {}).get(guid)
def deliver(self, fn: Any, *args: Any) -> None:
"""Call `fn(*args)` as an event, under the client's own rules for
what that means (see `Connection.deliver_event`). MUST be called from
the asyncio loop thread - use `call_soon` to get there first."""
self._deliver_event(fn, *args)
def run_blocking(self, fn: Any, *args: Any) -> Any:
"""A fused dispatcher's way to run a blocking call off the loop.
Delegates to the transport, which owns the worker pool; see
`InProcessTransport.run_blocking` for why this exists and what it
guards against."""
return self._transport.run_blocking(fn, *args)
def call_soon(self, fn: Any, *args: Any) -> None:
"""A fused dispatcher's way to hand an EVENT to the asyncio loop from
the connection's read-loop thread. See
`InProcessTransport.call_soon`."""
self._transport.call_soon(fn, *args)
def send_up(self, message: Dict) -> None:
if self._transport is not None:
self._transport.emit_message(message)
@@ -260,8 +289,13 @@ class Server:
return "%s@%d" % (type_name.lower(), next(counter))
def register(self, obj: Dispatcher) -> None:
obj._born = time.monotonic()
bucket = obj._gc_bucket = getattr(obj, "TYPE", "Unknown")
if hasattr(obj, "gc_bucket"):
bucket = obj._gc_bucket = obj.gc_bucket()
with self._lock:
self._objects[obj.guid] = obj
self._buckets.setdefault(bucket, {})[obj.guid] = None
#: How many disposed guids are remembered. Large enough for any burst of
#: in-flight calls, small enough to be free.
@@ -270,6 +304,9 @@ class Server:
def unregister(self, obj: Dispatcher) -> None:
with self._lock:
self._objects.pop(obj.guid, None)
members = self._buckets.get(getattr(obj, "_gc_bucket", None))
if members is not None:
members.pop(obj.guid, None)
self._disposed[obj.guid] = None
while len(self._disposed) > self.DISPOSED_MEMORY:
self._disposed.pop(next(iter(self._disposed)))
@@ -297,6 +334,63 @@ class Server:
walker = walker.parent
return out
def gc_limit(self, bucket: str) -> int:
return self.gc_limits.get(bucket, self.gc_limits["default"])
def collect_stale(self, bucket: str) -> None:
"""Playwright's `maybeDisposeStaleDispatchers`: a bucket past its limit loses its
oldest tenth, each with `__dispose__` {reason: "gc"} and the whole subtree silently
(a client drops the children of a disposed object by itself)."""
limit = self.gc_limit(bucket)
with self._lock:
members = self._buckets.get(bucket)
if not members or len(members) <= limit:
return
oldest = list(itertools.islice(members, max(1, limit // 10)))
young = time.monotonic() - self.gc_min_age
victims = []
for guid in oldest:
obj = self._objects.get(guid)
if obj is None:
continue
if obj._born > young:
break # the bucket is in birth order: the rest are younger
victims.append(obj)
self.dispose_many(victims, "gc")
def dispose_many(self, victims: list, reason: Optional[str]) -> None:
"""Dispose objects and their subtrees with ONE walk of the registry (a walk per
object would be quadratic in a bucket of thousands). A victim under another victim
is dropped by the cascade and says nothing of its own: the client would have no
guid for it."""
ids = {id(v) for v in victims}
params = {"reason": reason} if reason else {}
for victim in victims:
walker, covered = victim.parent, False
while walker is not None:
if id(walker) in ids:
covered = True
break
walker = walker.parent
if covered or victim.disposed:
continue
victim.disposed = True
self.send_up({"guid": victim.guid, "method": "__dispose__", "params": params})
self.unregister(victim)
victim.released()
with self._lock:
everything = list(self._objects.values())
for candidate in everything:
walker, seen = candidate.parent, set()
while walker is not None and id(walker) not in seen:
if id(walker) in ids:
candidate.disposed = True
self.unregister(candidate)
candidate.released()
break
seen.add(id(walker))
walker = walker.parent
def announce(self, obj: Dispatcher) -> None:
"""Emit `__create__` for a new object, parented where the client can
already find it."""
@@ -370,6 +464,10 @@ class Server:
"no object %r to answer %r: it was never created"
% (guid, method))
metadata = message.get("metadata") or {}
# ⛔ THE VERSIONS OF THE PROTOCOL ARE FOLDED HERE, once, before any
# operation reads a parameter: see `variants.py`. A refusal of a
# command this server does not serve is raised from there.
params = variants.to_internal(method, params, metadata)
token = _CURRENT_CALL.set(CallLog(metadata.get("title") or method or ""))
try:
return obj.call(method, params)
@@ -0,0 +1,175 @@
"""What the served browser does about its memory: a trim that is ON, and a probe that is OFF.
THE TRIM. On Linux with glibc the server calls `malloc_trim(0)` after each message of
TRIM_BYTES or more has been sent and after each context close. INVPW_MALLOC_TRIM=0 turns
it off. Elsewhere (not Linux, musl, a libc without the function) it calls nothing and says
nothing: the endpoint asks `trimmer_from_env` once and every hook on the hot path is a
test of the None it gets back. No `mallopt` and no MALLOC_ARENA_MAX here: those are
process-wide and must be set before threads exist, which is the launcher's business
(README: MALLOC_ARENA_MAX=2).
THE PROBE, off unless INVPW_MEM_LOG=<file> (INVPW_MEM_LOG_INTERVAL, default 2 s): one JSON
line every interval and one at each context close, at no cost when it is off.
The line of the probe (`t` is `time.monotonic()`, `event` is "tick" or
"context_closed"):
t, event, uss_mb, rss_mb null where the platform gives neither (psutil is
optional; Linux falls back to /proc/self/statm for rss)
registry_objects, contexts the guid registry, and the BrowserContext among it
clients, outbox_total_bytes, what is queued for sockets and not yet sent: the sum of
outbox_max_messages the texts, and the longest queue of one client
gc_counts {"generations": gc.get_count(), "objects": len(gc.get_objects())}
malloc glibc `mallinfo2` {arena, uordblks, fordblks, hblkhd}, else null
"""
from __future__ import annotations
import gc
import json
import os
import sys
import threading
import time
from typing import Any, Callable, Dict, Optional
#: A message of at least this many bytes is a reply with a body worth giving back to the OS.
#: WHY TRIM AT ALL: in a served browser the pages' contents (1-6 MB each) pass through the
#: process as JSON strings and die young among the long-lived registry objects; glibc keeps
#: the freed memory in its arenas. Measured by slack on a container, runs of 95 navigations:
#: the free memory held by malloc (`fordblks`) went from 13 MB to 177 MB by default. 64 KiB
#: is under any page's content and over any ordinary message.
TRIM_BYTES = 64 * 1024
DEFAULT_INTERVAL = 2.0
def _is_linux() -> bool:
return sys.platform.startswith("linux")
def _load_libc() -> Any:
import ctypes
return ctypes.CDLL("libc.so.6", use_errno=True)
def trimmer_from_env(environ: Optional[Dict[str, str]] = None) -> Optional[Callable[[], None]]:
"""`malloc_trim(0)` as a callable, or None: INVPW_MALLOC_TRIM=0, not Linux, or a libc
that has no such function (musl) - silently, in every one of them."""
environ = os.environ if environ is None else environ
if environ.get("INVPW_MALLOC_TRIM") == "0" or not _is_linux():
return None
try:
libc = _load_libc()
trim = libc.malloc_trim
except (OSError, AttributeError):
return None
return lambda: trim(0)
def _mallinfo() -> Optional[Dict[str, int]]:
if not _is_linux():
return None
try:
import ctypes
libc = _load_libc()
names = ("arena", "ordblks", "smblks", "hblks", "hblkhd",
"usmblks", "fsmblks", "uordblks", "fordblks", "keepcost")
class Info(ctypes.Structure):
_fields_ = [(n, ctypes.c_size_t) for n in names]
libc.mallinfo2.restype = Info
info = libc.mallinfo2()
return {k: int(getattr(info, k)) for k in ("arena", "uordblks", "fordblks", "hblkhd")}
except Exception:
return None
def _memory_mb() -> "tuple[Optional[float], Optional[float]]":
try:
import psutil
info = psutil.Process().memory_full_info()
return round(info.uss / 1048576, 2), round(info.rss / 1048576, 2)
except Exception:
pass
rss = None
if _is_linux():
try:
with open("/proc/self/statm") as statm:
rss = round(int(statm.read().split()[1]) * os.sysconf("SC_PAGE_SIZE") / 1048576, 2)
except Exception:
rss = None
return None, rss
class MemProbe:
"""Writes the lines; `sample` is also what the tests read."""
def __init__(self, endpoint: Any, path: str, interval: float = DEFAULT_INTERVAL) -> None:
self.endpoint = endpoint
self.path = path
self.interval = interval
self._lock = threading.Lock()
self._stop = threading.Event()
self._thread: Optional[threading.Thread] = None
def start(self) -> None:
self._thread = threading.Thread(target=self._run, daemon=True, name="invpw-mem-probe")
self._thread.start()
def stop(self) -> None:
self._stop.set()
def _run(self) -> None:
while not self._stop.is_set():
self.write("tick")
self._stop.wait(self.interval)
@staticmethod
def outbox_of(client: Any) -> "tuple[int, int]":
"""(bytes, messages) queued for one client: read from the queue's own deque, so
sending costs nothing for it. The message the writer holds in `send` is not here."""
try:
queued = list(client._outbox._queue)
except Exception:
return 0, 0
return sum(len(t) for t in queued if t), len(queued)
def sample(self, event: str) -> Dict[str, Any]:
endpoint = self.endpoint
with endpoint._lock:
clients = list(endpoint.clients)
sizes = [self.outbox_of(c) for c in clients]
uss, rss = _memory_mb()
with endpoint.server._lock:
objects = list(endpoint.server._objects.values())
return {
"t": round(time.monotonic(), 3), "event": event,
"uss_mb": uss, "rss_mb": rss,
"registry_objects": len(objects),
"contexts": sum(1 for o in objects if o.TYPE == "BrowserContext"),
"clients": len(clients),
"outbox_total_bytes": sum(b for b, _ in sizes),
"outbox_max_messages": max((m for _, m in sizes), default=0),
"gc_counts": {"generations": list(gc.get_count()), "objects": len(gc.get_objects())},
"malloc": _mallinfo(),
}
def write(self, event: str) -> None:
try:
line = json.dumps(self.sample(event))
with self._lock, open(self.path, "a", encoding="utf-8") as out:
out.write(line + "\n")
except Exception:
pass # a probe never takes the server down
def probe_from_env(endpoint: Any, environ: Optional[Dict[str, str]] = None) -> Optional[MemProbe]:
environ = os.environ if environ is None else environ
path = environ.get("INVPW_MEM_LOG")
if not path:
return None
try:
interval = float(environ.get("INVPW_MEM_LOG_INTERVAL") or DEFAULT_INTERVAL)
except ValueError:
interval = DEFAULT_INTERVAL
return MemProbe(endpoint, path, interval)
@@ -0,0 +1,866 @@
"""The page's pointer, humanised ONCE, on the server.
⛔ WHY IT LIVES HERE AND NOT IN THE CLIENT. Until this module the walk of the
pointer onto an element belonged to the in-process Playwright client
(`_cursor.py` patched `Frame._click`, `Mouse.click`, `Mouse.wheel`, ... and sent
N `mouseMove` to the page before the action). A client that is not ours - a
Go, Node or stock Python Playwright talking to `launch_server` - sends ONE
`Frame.click` and the page saw one `mousemove`: measured with humanize=True on
a served browser. The rule is that a page sees EXACTLY the same through every
client, so the walk is drawn where every client's actions arrive. The in-process
client now sends the plain action and this module does the rest, which is also
why nothing here is asked of a client: there is no copy of it on that side to
get out of step.
WHAT IS HUMANISED, and what is not (this is the list the in-process client
used to answer, carried over unchanged):
* `Frame.click / dblclick / hover / tap / check / uncheck` - the approach to the
element, the landing off its centre, the fidget that fills an idle gap;
* `Mouse.click / dblclick` - the stroke to the point, then the click;
* `Mouse.wheel` - a burst of detents with the hand creeping between them;
* NOT `Mouse.move`: an explicit move is the caller's. (The in-process client
marks its own with `humanise`, see `_cursor._wrap_mouse_move`; a client that
does not say so is answered with exactly the point it named.)
* NOT the actions of an ElementHandle (they name a node, never a selector, and
the in-process client never walked onto them either) and NOT `dragAndDrop`,
whose travel the core's `Actions` already draws.
HOW IT STAYS THE SAME AS THE CLIENT WAS. The stroke generator, the planners
(`_behaviour`) and the discipline events are delivered under (`Pacer`) are the
core's, unchanged; the page's motion seed is `_cursor.page_motion_seed(session
seed, page number)`, the budget is the session's `humanize=` cap. What changed
is only who calls them, and `tests/data/pointer_golden.json` holds what the
engine received from the client-side code of 5d9ad70 for the same seed, page
and targets: this module must reproduce it to the last coordinate and
millisecond.
⛔ NOTHING HERE MAY FAIL AN ACTION THAT WOULD HAVE SUCCEEDED. A probe that finds
the element gone, a planner that raises, a viewport that cannot be read: the
action runs exactly as the caller wrote it. Only a broken install says so, once
per process.
"""
from __future__ import annotations
import random
import time
from dataclasses import dataclass
from typing import Any, Callable, Dict, Iterable, List, Optional, Sequence, Tuple
from invisible_core.juggler import (
DONE, SLEEP, Ev as _Ev, Pacer, PointerPersona, Step,
clamp_to_viewport as _clamp, fine_timer as _fine_timer,
fit_timeline as _fit_timeline, initial_pointer, landing_point,
plan_aimless_move, plan_approach, plan_idle, plan_scroll,
steps_from_waypoints, tail_within,
)
from invisible_core.juggler.connection import ReplyTimeout
from invisible_core.juggler.deadline import Deadline
from invisible_core.juggler.injected import ContextDestroyed, EvaluationError
from invisible_core.seedmix import sub_seed
from .. import _cursor
from .dispatcher import ProtocolException
# Below this much wall clock since the last event we do not fidget at all: two
# actions back to back are one continuous piece of work, and a hand does not
# stop to fiddle between them.
_IDLE_MIN_GAP_MS = 400.0
# ...and above this we stop pretending we know what happened. Half a minute of
# planned idle is plenty to draw a plausible tail from.
_IDLE_MAX_GAP_MS = 45_000.0
# Share of the movement budget an action may spend on the fidget that precedes
# it. The rest belongs to the approach, which is the part that has to work.
_IDLE_BUDGET_FRAC = 0.35
# Used only when the page will not tell us its size.
_FALLBACK_VIEWPORT = (1280.0, 720.0)
# Landing off-centre hands the automation layer a click position we chose. If
# that position turns out not to be actionable we retry with the caller's own
# arguments, so the first attempt is given a bounded slice of the time rather
# than the caller's whole timeout.
_LANDING_ATTEMPT_S = 5.0
_LANDING_MIN_BOX_PX = 12.0
# How far from the centre of a control the landing point may stray, as a
# fraction of the box: sigma of the draw and the hard clip. Tighter than the
# planner's own default because this point is also the click position.
_LANDING_SPREAD = 0.14
_LANDING_KEEP = 0.26
#: What a probe of the page can legitimately answer while we are only AIMING:
#: the element went away, the frame navigated, the page closed.
_PROBE_ERRORS = (ContextDestroyed, EvaluationError, ReplyTimeout,
ProtocolException, TimeoutError)
# ── the clock ───────────────────────────────────────────────────────────────
#
# Injectable so the delivered-vs-planned timing can be asserted without a
# browser and without a test that takes as long as the schedule it checks.
class _RealClock:
__slots__ = ()
@staticmethod
def now() -> float:
return time.perf_counter()
@staticmethod
def sleep(seconds: float) -> None:
time.sleep(seconds)
_CLOCK: Any = _RealClock()
# ── timelines ───────────────────────────────────────────────────────────────
def _timeline(steps: Iterable[Any]) -> List[_Ev]:
"""Turn a ``_behaviour`` Step list (relative delays) into absolute times."""
out: List[_Ev] = []
t = 0.0
for s in steps:
t += max(0.0, float(s.delay_ms))
if s.kind == "wait": # pure elapsed time: nothing to dispatch
continue
out.append(_Ev(t, s.x, s.y, "wheel" if s.kind == "wheel" else "move",
getattr(s, "dx", 0.0), getattr(s, "dy", 0.0)))
return out
def _normalise_waypoints(raw: Iterable[Any], max_seconds: float) -> List[Tuple[float, float, float]]:
"""Reduce whatever the generator returns to ``(x, y, delay_seconds)``.
Three shapes are accepted: a waypoint object carrying ``x`` / ``y`` /
``dt_ms``, an ``(x, y, delay_seconds)`` triple, and a bare ``(x, y)`` pair
whose pacing is then spread evenly over the cap.
The cap from ``humanize=<seconds>`` is applied through
``fit_timeline``, so a tighter cap makes the movement shorter AND coarser
rather than merely denser.
"""
points: List[Tuple[float, float, float]] = []
for p in raw:
x = getattr(p, "x", None)
if x is not None and hasattr(p, "y"):
dt_ms = getattr(p, "dt_ms", None)
delay = float(dt_ms) / 1000.0 if dt_ms is not None else 0.0
points.append((float(x), float(p.y), max(0.0, delay)))
continue
seq = tuple(p)
if len(seq) >= 3:
points.append((float(seq[0]), float(seq[1]), max(0.0, float(seq[2]))))
else:
points.append((float(seq[0]), float(seq[1]), -1.0))
if not points:
return []
if all(d <= 0.0 for _, _, d in points):
# Every waypoint at the same instant is not pacing, it is the absence
# of pacing - and dispatching it would ask for the whole movement in
# one tick. Treated exactly like the bare (x, y) case below.
points = [(x, y, -1.0) for x, y, _ in points]
if points[0][2] < 0: # bare (x, y): no pacing supplied, spread the cap
even = max_seconds / len(points)
points = [(x, y, even) for x, y, _ in points]
evs: List[_Ev] = []
t = 0.0
for x, y, d in points:
t += d * 1000.0
evs.append(_Ev(t, x, y))
evs = _fit_timeline(evs, max_seconds)
out: List[Tuple[float, float, float]] = []
prev = 0.0
for ev in evs:
out.append((ev.x, ev.y, (ev.t_ms - prev) / 1000.0))
prev = ev.t_ms
return out
def _drive(evs: Sequence[_Ev], emit_move: Callable[[float, float], Any],
emit_wheel: Optional[Callable[[float, float], Any]] = None, *,
emit_last: bool = True,
origin: Optional[Tuple[float, float]] = None) -> int:
"""The synchronous driver of `Pacer`. Returns events sent.
The rules it obeys - absolute deadlines from one ``t0``, drop rather than
send late while the drop stays within reach, never two events in one
instant - are the pacer's, the core's, and are the same ones the client's
asynchronous driver obeyed. This supplies a clock, a way of waiting and
where the pointer starts from; it makes no decision the pacer has not made.
"""
if not evs:
return 0
clock = _CLOCK
pacer = Pacer(evs, emit_last=emit_last, origin=origin)
with _fine_timer():
while True:
what, arg = pacer.step(clock.now())
if what == DONE:
break
if what == SLEEP:
clock.sleep(arg)
continue
if arg.is_wheel:
if emit_wheel is None:
pacer.dropped() # nothing here can carry a notch
continue
emit_wheel(arg.dx, arg.dy)
else:
emit_move(arg.x, arg.y)
pacer.emitted(clock.now())
return pacer.delivered
# ── one page's hand ─────────────────────────────────────────────────────────
class _Hand:
"""State of one page's pointer: where it is, and how it likes to move."""
__slots__ = ("seed", "max_seconds", "_profile", "persona", "x", "y",
"busy", "action", "last_event_at", "synced")
def __init__(self, seed: int, max_seconds: float, factory: Callable[..., Any],
synced: Any) -> None:
self.seed = int(seed)
self.max_seconds = float(max_seconds)
self._profile = _cursor._build_profile(factory, self.seed, self.max_seconds)
self.persona = PointerPersona.from_seed(self.seed)
self.x: Optional[float] = None
self.y: Optional[float] = None
self.busy = False
# Counts actions, so every draw that has to differ between two actions
# of one session (the landing point, the fidget) has something to vary
# on while staying reproducible from the seed.
self.action = 0
self.last_event_at: Optional[float] = None
#: The engine-side pointer position (`Actions.position`, the object
#: itself) as this hand last knew it. Anything else moving the pointer
#: - an explicit `mouse.move`, the click an action ends with - replaces
#: it with a new object, and the hand then stands where the pointer
#: really is.
self.synced = synced
def start_point(self, width: Optional[float], height: Optional[float]) -> Tuple[float, float]:
"""Where the pointer is before this page's first movement.
Never the origin, and never a constant: a session whose first movement
departs from (0, 0) is announcing that it had no pointer state at all
before it started, which no real navigation produces.
"""
w, h = width, height
if not w or not h:
_cursor._warn_once(
"no-viewport",
"a page reported no viewport size; the cursor start position "
"falls back to a nominal %dx%d viewport. Coordinates are still "
"seeded, but they are not derived from the real window."
% (int(_FALLBACK_VIEWPORT[0]), int(_FALLBACK_VIEWPORT[1])),
)
w, h = _FALLBACK_VIEWPORT
fn = getattr(self._profile, "start_point", None)
if callable(fn):
try:
px, py = fn(w, h)
return float(px), float(py)
except (TypeError, ValueError, ArithmeticError) as exc:
_cursor._warn_once(
"bad-start-point",
"the motion generator's start_point() failed (%s: %s); "
"using the behaviour planner's instead."
% (type(exc).__name__, exc),
)
return initial_pointer(self.seed, (float(w), float(h)))
def path(self, fx: float, fy: float, tx: float, ty: float) -> List[Tuple[float, float, float]]:
raw = self._profile.path(fx, fy, tx, ty)
return _normalise_waypoints(raw, self.max_seconds)
def renderer(self, bounds: Tuple[float, float]) -> Callable[..., List[Any]]:
"""A ``_behaviour`` renderer backed by the stroke generator.
This is what keeps ONE stroke model in the product: the macro planner
decides that a movement happens and where it goes, and every stroke it
asks for is drawn by the generator.
"""
profile = self._profile
nominal = self.persona.sample_ms
def render(start: Tuple[float, float], end: Tuple[float, float], *,
kind: str, lead_ms: float, bounds: Any = bounds,
target_w: Optional[float] = None) -> List[Any]:
try:
raw = list(profile.path(start[0], start[1], end[0], end[1],
target_w=target_w))
except TypeError:
# A generator predating the target_w argument. Accepting it and
# dropping it is better than refusing to move: pacing degrades
# to the per-seed default, everything else still works.
raw = list(profile.path(start[0], start[1], end[0], end[1]))
if raw and not any(float(getattr(p, "dt_ms", 0.0) or 0.0)
if hasattr(p, "dt_ms") else
(float(p[2]) if len(tuple(p)) > 2 else 0.0)
for p in raw):
# A generator that paces nothing has not said "instantly", it
# has said nothing. Fall back to the session's own sampling
# interval rather than asking for the whole stroke in one tick.
raw = [(float(getattr(p, "x", None) if hasattr(p, "x") else p[0]),
float(getattr(p, "y", None) if hasattr(p, "y") else p[1]),
nominal)
for p in raw]
return steps_from_waypoints(
raw, kind=kind, lead_ms=lead_ms, bounds=bounds
)
return render
def rng(self, tag: str) -> random.Random:
"""A per-(page, action, purpose) stream. Reproducible from the seed."""
return random.Random(
sub_seed(self.seed, "%s:%d" % (tag, self.action))
)
@dataclass
class _Aim:
"""Where this action is going, and how the caller must be adjusted for it.
``override`` is the position the action should run with so that it clicks
the point we walked to rather than the element's centre; None means the
action is left exactly as the caller wrote it.
"""
box: Dict[str, float]
landing: tuple
override: Optional[Dict[str, float]]
@property
def rect(self) -> tuple:
return (self.box["x"], self.box["y"],
self.box["width"], self.box["height"])
def _inside(x: float, y: float, w: Optional[float], h: Optional[float]) -> bool:
if not w or not h:
return True
return 0.0 <= x < float(w) and 0.0 <= y < float(h)
class Pointer:
"""The hand of one page: what an action does with the pointer before it
acts. Inert (`active` False) when the session did not ask for it, which
turns every method into the plain action."""
def __init__(self, actions: Any, injected: Any, number: int,
session_seed: Optional[int], budget_s: Optional[float],
viewport: Callable[[], Any], *, draws: bool = True) -> None:
self.actions = actions
self.injected = injected
self._viewport_of = viewport
self.hand: Optional[_Hand] = None
if not draws or session_seed is None or not budget_s:
return
factory = _cursor._motion_factory()
if factory is None:
return
seed = _cursor.page_motion_seed(session_seed, number)
try:
self.hand = _Hand(seed, budget_s, factory,
getattr(actions, "position", None))
except Exception as exc: # noqa: BLE001 - a broken generator must not break clicking
_cursor._warn_once(
"profile-construction",
"the cursor motion generator could not be constructed (%s: %s); "
"this session will not humanise its pointer. This is a broken "
"install, not a configuration." % (type(exc).__name__, exc),
)
@property
def active(self) -> bool:
return self.hand is not None
# -- geometry ----------------------------------------------------------
def _viewport(self) -> Tuple[Optional[float], Optional[float]]:
size = self._viewport_of()
if isinstance(size, dict):
return size.get("width"), size.get("height")
return None, None
def _bounds(self) -> Tuple[float, float]:
"""Viewport size to plan inside, falling back to a nominal one."""
w, h = self._viewport()
if not w or not h:
return _FALLBACK_VIEWPORT
return float(w) - 1.0, float(h) - 1.0
def _here(self) -> Tuple[float, float]:
"""Current pointer position, placing it first if it has never moved."""
hand = self.hand
now = getattr(self.actions, "position", None)
if now is not hand.synced:
# Something else moved the pointer since we last did.
hand.synced = now
hand.x, hand.y = float(now[0]), float(now[1])
elif hand.x is None or hand.y is None:
w, h = self._viewport()
hand.x, hand.y = hand.start_point(w, h)
return float(hand.x), float(hand.y)
def _emit_move(self, x: float, y: float) -> None:
hand = self.hand
self.actions.move(x, y)
hand.synced = getattr(self.actions, "position", None)
# -- the probes --------------------------------------------------------
def _element_box(self, frame_id: str, selector: str) -> Tuple[Optional[str], Optional[dict]]:
"""Resolve the element and its box, or (None, None). Never raises.
Deliberately non-blocking and deliberately forgiving: this is a hint
used to aim a mouse path, never a correctness step. It resolves the
element if it is already there and gives up otherwise, so it can
neither add a wait to a passing call nor invent an exception on a
failing one - the action itself still does its own waiting and raises
its own errors.
"""
try:
handle = self.injected.query_selector(frame_id, selector)
except _PROBE_ERRORS:
return None, None # gone, navigated, closed, or not a selector we know
if not handle:
return None, None
try:
box = self.injected.bounding_box(frame_id, handle)
except _PROBE_ERRORS:
box = None
if not box:
self._dispose(frame_id, handle)
return None, None
return handle, box
def _dispose(self, frame_id: str, handle: str) -> None:
try:
self.injected.dispose(frame_id, handle)
except _PROBE_ERRORS:
pass # the page or the frame is already gone; nothing to release
def _hits(self, frame_id: str, handle: str, x: float, y: float) -> bool:
"""Does (x, y), in the same main-frame space as the box, land on this
element?
A bounding box is not the element. An inline link that wraps across
two lines, a rotated control, a rounded button: all of them have points
inside their box that belong to something else. The centre is checked
by the automation layer itself; a point we chose has to be checked by
us, or we would be turning working clicks into hit-target failures.
⛔ THE ACTION'S OWN QUESTION (`Actions.hit_target`): the same frame
shift, the same shadow-aware test, so the cursor accepts exactly the
points the action itself would accept.
"""
try:
return self.actions.hit_target(frame_id, handle, (x, y)) == "done"
except _PROBE_ERRORS:
return False
def _choose_landing(self, frame_id: str, selector: str,
position: Optional[dict]) -> Optional[_Aim]:
"""Pick the point on the element this action will land on."""
hand = self.hand
handle, box = self._element_box(frame_id, selector)
if handle is None or box is None:
return None
try:
if isinstance(position, dict) and "x" in position and "y" in position:
# The caller aimed explicitly. Honour it exactly and override
# nothing: choosing our own point here would silently move a
# click the caller had every reason to think was pinned.
return _Aim(box, (box["x"] + float(position["x"]),
box["y"] + float(position["y"])), None)
landing = landing_point(
(box["x"], box["y"], box["width"], box["height"]),
hand.rng("cursor:landing"),
spread=_LANDING_SPREAD, keep=_LANDING_KEEP,
)
if (
_cursor.landing_enabled()
and box["width"] >= _LANDING_MIN_BOX_PX
and box["height"] >= _LANDING_MIN_BOX_PX
and self._hits(frame_id, handle, landing[0], landing[1])
):
return _Aim(box, landing, {"x": landing[0] - box["x"],
"y": landing[1] - box["y"]})
# The off-centre point missed the element (it is not a rectangle,
# or it is too small for the spread to be safe). Fall back to the
# centre and do NOT override: an override naming a point that
# misses would turn a working click into a failing one.
return _Aim(box, (box["x"] + box["width"] / 2.0,
box["y"] + box["height"] / 2.0), None)
finally:
self._dispose(frame_id, handle)
# -- travelling --------------------------------------------------------
def _run_steps(self, steps: Sequence[Any], emit_wheel: Optional[Callable] = None,
*, budget_s: float, emit_last: bool = True) -> None:
"""Dispatch a planned ``_behaviour`` timeline, inside a time budget."""
hand = self.hand
evs = _fit_timeline(_timeline(steps), budget_s)
if not evs:
return
def move(x: float, y: float) -> None:
self._emit_move(x, y)
hand.x, hand.y = x, y
_drive(evs, move, emit_wheel, emit_last=emit_last,
origin=(hand.x, hand.y))
if not emit_last and evs:
hand.x, hand.y = evs[-1].x, evs[-1].y
hand.last_event_at = _CLOCK.now()
def _idle_budget_ms(self) -> float:
"""How much of the movement budget this action may spend on a fidget.
Zero when the previous event was moments ago: two calls back to back
are one piece of work, and inserting a fidget between them would be
both a lie and a delay.
"""
hand = self.hand
if hand.last_event_at is None:
return 0.0
gap_ms = (_CLOCK.now() - hand.last_event_at) * 1000.0
if gap_ms < _IDLE_MIN_GAP_MS:
return 0.0
return min(hand.max_seconds * _IDLE_BUDGET_FRAC * 1000.0, gap_ms * 0.5)
def _plan_fidget(self) -> List[Any]:
"""What the hand did while the caller's script was busy elsewhere.
We cannot dispatch into the past, so the idle period is planned in full
and only its tail is kept (`tail_within`). The alternative, inventing a
short episode from scratch, would have a distribution of its own that no
amount of seeding makes match the planner's.
"""
hand = self.hand
budget = self._idle_budget_ms()
if budget <= 0.0:
return []
gap_ms = min((_CLOCK.now() - (hand.last_event_at or _CLOCK.now())) * 1000.0,
_IDLE_MAX_GAP_MS)
bounds = self._bounds()
here = self._here()
gate = hand.rng("cursor:fidget-gate")
if gate.random() < hand.persona.aimless_rate:
# A movement that ends nowhere in particular. If every movement of
# a session terminates on a control then the SET OF ENDPOINTS is a
# signature on its own, whatever the paths between them look like.
steps = plan_aimless_move(
hand.seed, hand.persona, here, bounds,
nonce=hand.action, render=hand.renderer(bounds),
)
return tail_within(steps, budget, here, bounds)
steps = plan_idle(
hand.seed, hand.persona, here, bounds, gap_ms,
nonce=hand.action, render=hand.renderer(bounds),
)
return tail_within(steps, budget, here, bounds)
def _walk_onto(self, aim: _Aim) -> None:
"""Spend the time budget getting the pointer to ``aim``."""
hand = self.hand
bounds = self._bounds()
budget = hand.max_seconds
fidget = self._plan_fidget()
if fidget:
# The fidget spends its own share of the budget and hands the rest
# to the approach, which is the part that has to work. The floor
# keeps a pathological share from leaving the approach no time.
spent = min(sum(s.delay_ms for s in fidget) / 1000.0,
budget * _IDLE_BUDGET_FRAC)
self._run_steps(fidget, budget_s=spent)
budget = max(budget - spent, 0.2)
steps = plan_approach(
hand.seed, hand.persona, self._here(), aim.rect, bounds,
nonce=hand.action, landing=aim.landing,
render=hand.renderer(bounds),
)
if steps:
# ``emit_last=False``: the final hop onto the landing point is left
# to the action itself. That is the whole hover fix restated - the
# only event inside the hit-target window is the automation layer's
# own move, and it is on target - and it also removes what would
# otherwise be a zero-displacement event immediately before every
# mousedown, since the action moves to the point we just landed on.
self._run_steps(steps, budget_s=budget, emit_last=False)
else:
# Sub-pixel approach: the pointer is already standing on the
# target. Emitting a move to where it already is would be a
# zero-displacement event, so the action's own move is left to do
# the whole of it.
hand.x, hand.y = aim.landing
# -- the entry points --------------------------------------------------
def approach(self, frame_id: str, selector: str, position: Optional[dict],
trial: bool = False) -> Optional[Dict[str, float]]:
"""Walk the pointer onto the element this action is about to touch.
Returns the `position` the action should run with, or None.
⛔ A TRIAL RUN performs the actionability checks without touching
anything, so it must not move the pointer either. It is honoured in
`Actions._retry`, where actionability lives; this only keeps the
pointer still while that happens.
"""
hand = self.hand
if hand is None or hand.busy or trial:
return None
hand.busy = True
hand.action += 1
try:
aim = self._choose_landing(frame_id, selector, position)
if aim is None:
return None
w, h = self._viewport()
if not _inside(aim.landing[0], aim.landing[1], w, h):
# The element is off-screen; the action is about to scroll it
# into view and we would be aiming at where it used to be. Let
# the action place the pointer itself this once.
return None
self._walk_onto(aim)
return aim.override
finally:
hand.busy = False
def act(self, frame_id: str, selector: str, position: Optional[dict],
timeout: Optional[float], run: Callable[[Optional[dict], Optional[float]], Any],
*, trial: bool = False) -> Any:
"""Run a pointer action on an element the way a hand would.
`run(position, timeout)` performs the plain action with those two
arguments. The approach comes first; if it chose a landing point the
action is told to click it, within a bounded slice of the caller's
time, and if that point is not actionable the caller's own call is made
with what is left of its time, so a call that would have succeeded
still does.
"""
override = None
try:
override = self.approach(frame_id, selector, position, trial)
except Exception as exc: # noqa: BLE001 - motion never fails an action
_cursor._warn_once(
"approach-failed",
"the cursor approach raised (%s: %s); the action itself is "
"unaffected and ran normally. Please report this."
% (type(exc).__name__, exc),
)
if not override:
return run(position, timeout)
deadline = Deadline(timeout)
first = (_LANDING_ATTEMPT_S if timeout is None
else min(_LANDING_ATTEMPT_S, timeout))
try:
return run(override, first)
except TimeoutError as exc:
_cursor._warn_once(
"landing-retry",
"an off-centre landing point was not actionable (%s); the "
"action was retried with its own arguments. Set %s=off to "
"disable off-centre landing."
% (type(exc).__name__, _cursor.LANDING_ENV),
)
return run(position,
None if timeout is None else deadline.left(floor=0.05))
def travel(self, x: float, y: float, what: str = "mouse.click") -> None:
"""Emit the intermediate waypoints of one plain stroke to (x, y), the
endpoint itself left to the caller.
Used before `Mouse.click`: the caller named the exact destination and
the macro layer has nothing to add. The endpoint is the caller's to
emit - it has to land on the exact coordinates it was given, unclamped -
so this returns after waiting out the last waypoint's deadline without
sending it.
"""
hand = self.hand
if hand is None or hand.busy:
return
hand.busy = True
hand.action += 1
try:
self._travel(x, y)
except Exception as exc: # noqa: BLE001
_cursor._warn_once(
"move-failed",
"the cursor path raised during %s (%s: %s); the action "
"itself is unaffected. Please report this."
% (what, type(exc).__name__, exc),
)
finally:
hand.busy = False
def _travel(self, to_x: float, to_y: float) -> None:
hand = self.hand
w, h = self._viewport()
hand.x, hand.y = self._here()
try:
waypoints = hand.path(hand.x, hand.y, to_x, to_y)
except Exception as exc: # noqa: BLE001 - never let motion break an action
_cursor._warn_once(
"path-failed",
"the cursor motion generator raised while planning a path "
"(%s: %s); this movement is not humanised. This is a broken "
"install, not a configuration." % (type(exc).__name__, exc),
)
waypoints = []
evs: List[_Ev] = []
t = 0.0
end_key = (round(to_x), round(to_y))
# ⛔ THE FIRST WAYPOINT OF A STROKE IS WHERE IT STARTS. When the engine
# has already been told the pointer is on that pixel (a move that
# stopped there, then a pause), sending it again is a zero-displacement
# `mousemove` that no mouse reports; the stroke begins at its first
# real step. A pointer the engine has never been told about (the
# page's first movement, from the seeded start point) is not "there"
# for the page, so its first waypoint is a real move and goes out.
known = getattr(self.actions, "position", None)
at_start = (None if known is None
else (round(known[0]), round(known[1])))
for px, py, delay in waypoints:
t += delay * 1000.0
cx, cy = _clamp(px, py, w, h)
if (not evs and at_start is not None
and (round(cx), round(cy)) == at_start
and (round(hand.x), round(hand.y)) == at_start):
continue # still standing on the start pixel: nothing moved
# Never pre-empt the endpoint - it is the caller's to emit, once.
#
# Nothing else here filters the stream (the start waypoint above is not
# a repeat of a shape, it is the position itself). Whether two consecutive
# events may share a device pixel is a question about the SHAPE of
# a path, and the shape belongs to the generator: a dispatcher that
# silently removed every repeat would make "the duplicate fraction
# is exactly zero" true no matter what the generator did.
if (round(cx), round(cy)) == end_key:
continue
evs.append(_Ev(t, cx, cy))
# The endpoint closes the schedule so its deadline is waited out even
# though the caller is the one that emits it.
evs.append(_Ev(max(t, evs[-1].t_ms if evs else 0.0), to_x, to_y))
def emit(x: float, y: float) -> None:
self._emit_move(x, y)
hand.x, hand.y = x, y
_drive(evs, emit, emit_last=False, origin=(hand.x, hand.y))
hand.x, hand.y = to_x, to_y
hand.last_event_at = _CLOCK.now()
def click_at(self, x: float, y: float, run: Callable[[], Any]) -> Any:
"""`Mouse.click`: the stroke, then the click `run` makes.
⛔ THE ENDPOINT IS EMITTED ONCE. The stroke stops short of it
(`travel`), and `run` is `Actions.click_at`, whose own approach is the
one `mousemove` onto the exact point before the press. This used to send
the endpoint as a move of its own first (as the client's `Mouse._click`
did), so the engine got two `mousemove` with the same coordinates at the
same instant: no mouse reports that, and a page can count it. A hand
arrives at the button in one last motion and presses; so the last
waypoint is the click's own approach, and nothing else lands on the
point before the press. Every transport comes here (`op_mouse_click`),
so the sequence is one.
"""
if self.hand is None:
return run()
self.travel(x, y)
try:
return run()
finally:
self.hand.synced = getattr(self.actions, "position", None)
def wheel(self, dx: float, dy: float) -> bool:
"""`Mouse.wheel` as a burst of detents with the hand on the mouse.
True when it was done here; False means the caller sends the plain
wheel event."""
hand = self.hand
if hand is None or hand.busy:
return False
try:
hand.busy = True
hand.action += 1
try:
plan = self._scroll_plan(float(dx), float(dy))
if plan:
self._run_steps(plan, self.actions.wheel,
budget_s=hand.max_seconds)
return True
finally:
hand.busy = False
except Exception as exc: # noqa: BLE001
_cursor._warn_once(
"wheel-failed",
"the scroll planner raised (%s: %s); the scroll itself is "
"unaffected. Please report this." % (type(exc).__name__, exc),
)
return False
def _scroll_plan(self, delta_x: float, delta_y: float) -> List[Any]:
"""A wheel burst carrying exactly (delta_x, delta_y), with the hand on it.
One protocol-level wheel event of 900 px is not a scroll a person
performs; a notched wheel produces detents. The number of detents is
bounded by the movement budget, and the deltas are rescaled so the burst
sums EXACTLY to what the caller asked for - a scroll that lands
somewhere else is a broken call, not a subtle one.
"""
hand = self.hand
total = abs(delta_x) + abs(delta_y)
if total < 1.0:
return []
notch = 100.0
max_ticks = max(1, int(hand.max_seconds * 1000.0 / 90.0))
ticks = int(max(1, min(round(total / notch), max_ticks, 24)))
if ticks < 2:
return []
bounds = self._bounds()
steps = plan_scroll(
hand.seed, hand.persona, self._here(), bounds,
ticks=ticks, tick_dy=1.0, nonce=hand.action,
render=hand.renderer(bounds),
)
shares = [s.dy for s in steps if s.kind == "wheel"]
tot = sum(shares)
if not shares or tot <= 0:
return []
out: List[Any] = []
used_x = used_y = 0.0
seen = 0
for s in steps:
if s.kind != "wheel":
out.append(s)
continue
seen += 1
if seen == len(shares): # the last notch absorbs the rounding
dx, dy = delta_x - used_x, delta_y - used_y
else:
frac = s.dy / tot
dx, dy = delta_x * frac, delta_y * frac
used_x += dx
used_y += dy
out.append(Step(x=s.x, y=s.y, delay_ms=s.delay_ms,
kind="wheel", dx=dx, dy=dy))
return out
def move(self, x: float, y: float) -> None:
"""An explicit `Mouse.move` the in-process client asked to be walked.
The endpoint is emitted by the caller, exactly."""
if self.hand is not None:
self.travel(x, y, "mouse.move")
+867
View File
@@ -0,0 +1,867 @@
"""The Playwright server of this package, on a WebSocket: `launch_server()`.
Any standard Playwright client can `connect()` to what this serves, with the
shape of Playwright's own `launchServer` / `connect`: one browser, started
once, and a WebSocket whose messages are the protocol's JSON (`transport.py`
documents the four shapes; `wire.py` is the JSON boundary).
THE DESIGN, AND WHAT IT COSTS.
* ONE BROWSER, ONE REGISTRY, MANY CONNECTIONS. `launch_server()` launches the
browser once (the same launch the in-process client does: seed, persona,
geo, prefs, env, display, all composed by `InvisiblePlaywright`'s own
methods) into a single `JugglerServer` registry, and every WebSocket
connection talks to THAT registry. The alternative - a registry per
connection over the same Juggler connection - was refused: each
`BrowserDispatcher` enables the browser itself and adopts EVERY page
target it hears about, so two of them on one connection would each build a
page for the other's tabs.
* OWNERSHIP IS THE ISOLATION. An object made while answering a call from
client C belongs to C (an object made on a thread of its own - a popup -
belongs to its parent's owner). A message about an object goes only to its
owner; an object with no owner (BrowserType, LocalUtils, the Browser) is
shared and its messages go to every client, unless they name an owned
object, which decides. A client naming an object that is not its own gets
"never created", as if it did not exist.
* A CLIENT LEAVING CLOSES ITS CONTEXTS AND NOT THE BROWSER. So does its
`Browser.close`: the browser belongs to `launch_server()` and ends with
`RemoteServer.close()` (or when the engine dies, see `on_engine_closed`).
* `initialize` IS ANSWERED HERE, not by `JugglerServer.op_initialize`: it
announces BrowserType, LocalUtils, the Browser and the Playwright root with
`preLaunchedBrowser` (the shape of `launchServer`), to that client only.
THE IDENTITY STAYS THE SERVER'S. Seed, persona, prefs and env are composed
once, at launch. The handshake reads `x-playwright-browser`, `?browser=`,
`x-playwright-launch-options`, `?launch-options=` and `x-playwright-proxy`, and
keeps them on the client record (`RemoteClient.handshake`); none of them
changes the launch. There is no version check, no 428 and no limit of ours: any
client is accepted, whatever it says it is. What a client can still choose is
what Playwright lets a client choose per context (`newContext` options); the
server fills the ones it omitted from the session's profile (viewport, screen,
locale, timezone), and `context_options_override=True` makes the server's win.
LIMITS OF THIS FIRST VERSION, said instead of hidden.
* `launchPersistentContext` and `profile_dir` are not served.
* `x-playwright-proxy` (exposeNetwork) is recorded, not honoured.
* Downloads, file choosers and other fused types follow the in-process
client's path and are not carried to a remote client.
* `RemoteServer.process` is the core's handle for the browser process
(`Connection._process`, a private attribute of the core: pid / poll / wait).
* Page numbers (`pageNumber`, which the in-process client reserves) are drawn
here from one counter for the whole browser, for clients that do not send it.
"""
from __future__ import annotations
import asyncio
import collections
import contextvars
import itertools
import json
import queue
import secrets
import sys
import threading
import time
from typing import Any, Callable, Dict, List, Optional
from urllib.parse import parse_qs, urlsplit
from . import memprobe, wire
from .dispatcher import ProtocolException
from .server import (BrowserDispatcher, BrowserTypeDispatcher, JugglerServer,
LocalUtilsDispatcher, RefusingDispatcher)
from .transport import _error_payload
#: The client whose call a worker thread is answering.
CURRENT_CLIENT: "contextvars.ContextVar[Optional[RemoteClient]]" = (
contextvars.ContextVar("invpw_remote_client", default=None))
DEFAULT_HOST = "127.0.0.1"
def _channel_guids(value: Any, depth: int = 4):
"""The guids named inside a message's params (`{"guid": g}` channels)."""
if depth < 0:
return
if isinstance(value, dict):
if set(value) == {"guid"} and isinstance(value["guid"], str):
yield value["guid"]
return
for item in value.values():
yield from _channel_guids(item, depth - 1)
elif isinstance(value, (list, tuple)):
for item in value:
yield from _channel_guids(item, depth - 1)
class RemoteClient:
"""One WebSocket connection."""
def __init__(self, endpoint: "RemoteEndpoint", ws: Any,
loop: asyncio.AbstractEventLoop, handshake: Dict) -> None:
self.endpoint = endpoint
self.ws = ws
self.loop = loop
self.handshake = handshake
self.alive = True
self.initialized = False
self._outbox: "asyncio.Queue" = asyncio.Queue()
def post(self, text: str) -> None:
"""Queue one text for the socket, from any thread. FIFO: the writer
task sends them in the order they were posted, which is what keeps
`__create__` before the reply that names it."""
if not self.alive:
return
try:
self.loop.call_soon_threadsafe(self._outbox.put_nowait, text)
except RuntimeError:
pass # the loop is closed: nobody is left to read it
def post_message(self, message: Dict) -> None:
try:
self.post(wire.dumps(message))
except wire.WireError as problem:
self.endpoint.wire_errors.append(problem)
msg_id = message.get("id") if isinstance(message, dict) else None
if msg_id is not None and "error" not in message:
self.post(json.dumps({"id": msg_id, "error": {"error": {
"name": "Error", "stack": "",
"message": "the reply is not JSON: %s" % problem}}}))
async def pump(self) -> None:
while True:
text = await self._outbox.get()
if text is None:
return
try:
await self.ws.send(text)
except Exception:
return
trim = self.endpoint.trim
if trim is not None and len(text) >= memprobe.TRIM_BYTES:
del text # the reply's text goes back to the allocator first
self._trim(trim)
@staticmethod
def _trim(trim: Callable[[], None]) -> None:
try:
trim()
except Exception:
pass
def stop_pump(self) -> None:
self.alive = False
try:
self.loop.call_soon_threadsafe(self._outbox.put_nowait, None)
except RuntimeError:
pass
class _SharedServer(JugglerServer):
"""The registry of a served browser: it knows who owns what."""
def __init__(self) -> None:
super().__init__()
self.endpoint: Optional["RemoteEndpoint"] = None
def register(self, obj: Any) -> None:
obj._owner = CURRENT_CLIENT.get(None) or getattr(
getattr(obj, "parent", None), "_owner", None)
super().register(obj)
def send_up(self, message: Dict) -> None:
if self.endpoint is not None:
self.endpoint.route(message)
def unregister(self, obj: Any) -> None:
super().unregister(obj)
if obj.TYPE == "BrowserContext" and self.endpoint is not None:
self.endpoint.context_closed()
class SharedBrowserDispatcher(BrowserDispatcher):
"""The browser of a served launch: a client's `close` ends ITS contexts."""
def op_close(self, params: Dict) -> Any:
client = CURRENT_CLIENT.get(None)
for context in list(self.contexts):
if not context.disposed and getattr(context, "_owner", None) is client:
try:
context.op_close({})
except Exception:
pass
return None
class SharedBrowserType(BrowserTypeDispatcher):
browser_class = SharedBrowserDispatcher
class UnservedBrowserType(RefusingDispatcher):
"""chromium and webkit: in the Playwright initializer because the protocol requires every
browser type there (a client's constructor reads all three and does not check for a missing
one), and every call on them refuses with the reason. Only firefox is served."""
TYPE = "BrowserType"
REASON = "this server serves one browser, the firefox engine, and not %s"
def __init__(self, server: Any, name: str) -> None:
super().__init__(server, None, {"executablePath": "", "name": name})
self.REASON = self.REASON % name
class UnservedAndroid(RefusingDispatcher):
"""Required by the 1.62 Playwright initializer; Android is outside what is served."""
TYPE = "Android"
REASON = "Android devices are not served"
def __init__(self, server: Any) -> None:
super().__init__(server, None, {})
class UnservedElectron(RefusingDispatcher):
"""Required by the 1.62 Playwright initializer; Electron is outside what is served."""
TYPE = "Electron"
REASON = "Electron is not served"
def __init__(self, server: Any) -> None:
super().__init__(server, None, {})
class RemoteEndpoint:
"""The WebSocket side: serves an already-launched browser's registry.
Knows nothing of how the browser was launched (`launch_server` does that),
so the unit tests give it a registry with a stand-in Browser.
"""
WORKERS = 8
def __init__(self, server: _SharedServer, browser_type: BrowserTypeDispatcher,
browser: Any, *, host: str = DEFAULT_HOST, port: int = 0,
path: Optional[str] = None,
context_defaults: Optional[Dict] = None,
context_options_override: bool = False) -> None:
self.server = server
self.browser_type = browser_type
self.browser = browser
self.host = host
self.requested_port = port
self.token = path or secrets.token_urlsafe(18)
self.context_defaults = dict(context_defaults or {})
self.context_options_override = context_options_override
self.clients: List[RemoteClient] = []
#: The last few: each one holds its traceback, and a client that keeps
#: asking for what is not JSON must not grow it for the life of the browser.
self.wire_errors: "collections.deque" = collections.deque(maxlen=32)
self.port: Optional[int] = None
self._pages = itertools.count(0)
self._jobs: "queue.Queue" = queue.Queue()
self._workers: List[threading.Thread] = []
self._thread: Optional[threading.Thread] = None
self._loop: Optional[asyncio.AbstractEventLoop] = None
self._stop: Optional[asyncio.Event] = None
self._ready = threading.Event()
self._start_error: Optional[BaseException] = None
self._lock = threading.Lock()
self._closed = False
#: The two opt-in switches (`memprobe.py`): None unless the environment asks.
self.probe = memprobe.probe_from_env(self)
self.trim = memprobe.trimmer_from_env()
#: The rest of what the Playwright initializer must name (spec 1.62: chromium,
#: firefox, webkit, android, electron are all required), created once.
self.chromium = UnservedBrowserType(server, "chromium")
self.webkit = UnservedBrowserType(server, "webkit")
self.android = UnservedAndroid(server)
self.electron = UnservedElectron(server)
server.endpoint = self
# ── where it listens ────────────────────────────────────────────────────
@property
def ws_endpoint(self) -> str:
host = self.host
if host in ("0.0.0.0", "", "::"):
host = "127.0.0.1"
if ":" in host and not host.startswith("["):
host = "[%s]" % host
return "ws://%s:%d/%s" % (host, self.port or 0, self.token)
def start(self) -> None:
for i in range(self.WORKERS):
t = threading.Thread(target=self._work, daemon=True,
name="invpw-remote-%d" % i)
t.start()
self._workers.append(t)
self._thread = threading.Thread(target=self._serve, daemon=True,
name="invpw-remote-ws")
self._thread.start()
self._ready.wait()
if self._start_error is not None:
self.close()
raise self._start_error
if self.probe is not None:
self.probe.start()
def context_closed(self) -> None:
"""A context left the registry: the probe takes a line, the allocator a trim."""
if self.probe is not None:
self.probe.write("context_closed")
if self.trim is not None:
RemoteClient._trim(self.trim)
def _serve(self) -> None:
loop = asyncio.new_event_loop()
self._loop = loop
asyncio.set_event_loop(loop)
try:
loop.run_until_complete(self._main())
except BaseException as failure: # noqa: BLE001
self._start_error = self._start_error or failure
finally:
self._ready.set()
try:
loop.close()
except Exception:
pass
async def _main(self) -> None:
try:
from websockets.asyncio.server import serve
except ImportError as failure: # pragma: no cover
# Spelled by the tool that installed this package, as `_engine.py` does.
from invisible_core.installer import install
from invisible_core.pin import format_command
raise RuntimeError(
"serving a browser needs the `websockets` package: "
+ format_command(install("invisible-playwright", "websockets"))) from failure
self._stop = asyncio.Event()
try:
async with serve(self._handler, self.host, self.requested_port,
process_request=self._process_request,
max_size=None, ping_interval=None,
compression=None) as listener:
self.port = listener.sockets[0].getsockname()[1]
self._ready.set()
await self._stop.wait()
for client in list(self.clients):
try:
await client.ws.close(1001, "the server is closing")
except Exception:
pass
except BaseException as failure: # noqa: BLE001
self._start_error = failure
raise
# ── the handshake ───────────────────────────────────────────────────────
def _process_request(self, connection: Any, request: Any) -> Any:
"""Refuse a wrong path with a readable reason, and read what a client
says about itself. Never raises: a failure is an HTTP answer."""
from http import HTTPStatus
try:
split = urlsplit(request.path)
if split.path.strip("/") != self.token:
return connection.respond(
HTTPStatus.FORBIDDEN,
"this path is not served here: the endpoint is the one "
"launch_server() returned, secret included\n")
query = parse_qs(split.query)
headers = request.headers
handshake: Dict[str, Any] = {
"browser": (headers.get("x-playwright-browser")
or (query.get("browser") or [None])[0]),
"proxy": headers.get("x-playwright-proxy"),
"launch_options": None,
}
raw = (headers.get("x-playwright-launch-options")
or (query.get("launch-options") or [None])[0])
if raw:
try:
handshake["launch_options"] = json.loads(raw)
except ValueError as bad:
return connection.respond(
HTTPStatus.BAD_REQUEST,
"launch-options is not JSON (%s); the server's launch "
"is fixed anyway, so send valid JSON or none\n" % bad)
connection.invpw_handshake = handshake
return None
except Exception as failure: # noqa: BLE001 - never crash a handshake
return connection.respond(
HTTPStatus.INTERNAL_SERVER_ERROR,
"the handshake failed: %s\n" % failure)
# ── one connection ──────────────────────────────────────────────────────
async def _handler(self, ws: Any) -> None:
loop = asyncio.get_running_loop()
client = RemoteClient(self, ws, loop,
getattr(ws, "invpw_handshake", None) or {})
with self._lock:
self.clients.append(client)
pump = asyncio.create_task(client.pump())
try:
async for raw in ws:
try:
text = raw.decode("utf-8") if isinstance(raw, bytes) else raw
message = json.loads(text)
if not isinstance(message, dict):
raise ValueError("a message is a JSON object, got %s"
% type(message).__name__)
except ValueError as bad:
await ws.close(1003, ("not a protocol message: %s" % bad)[:120])
break
self._jobs.put((client, message))
except Exception:
pass
finally:
client.stop_pump()
with self._lock:
if client in self.clients:
self.clients.remove(client)
pump.cancel()
self._jobs.put((client, None)) # the leaving, in the pool
# ── the worker side ─────────────────────────────────────────────────────
def _work(self) -> None:
while True:
item = self._jobs.get()
if item is None:
return
client, message = item
token = CURRENT_CLIENT.set(client)
try:
if message is None:
self._client_gone(client)
else:
self._answer(client, message)
except Exception:
pass
finally:
CURRENT_CLIENT.reset(token)
def _answer(self, client: RemoteClient, message: Dict) -> None:
msg_id = message.get("id")
try:
result = self._dispatch(client, message)
except Exception as failure: # noqa: BLE001
self._reply_error(client, msg_id, failure)
else:
self._reply(client, msg_id, result)
def _dispatch(self, client: RemoteClient, message: Dict) -> Any:
guid = message.get("guid")
method = message.get("method")
if guid == self.server.root_guid and method == "initialize":
return self._initialize(client)
obj = self.server._objects.get(guid)
owner = getattr(obj, "_owner", None)
if obj is not None and owner is not None and owner is not client:
raise ProtocolException(
"no object %r to answer %r: it was never created"
% (guid, method))
return self.server.handle(self._prepared(message))
def _prepared(self, message: Dict) -> Dict:
"""What a standard client does not say and this server needs: the
page's number, and the session's defaults for a context."""
method = message.get("method")
if method not in ("newPage", "newContext"):
return message
params = dict(message.get("params") or {})
if method == "newPage" and "pageNumber" not in params:
params["pageNumber"] = next(self._pages)
if message.get("guid") == self.browser.guid:
for key, value in self.context_defaults.items():
if key in ("viewport", "screen") and params.get("noDefaultViewport"):
continue
if self.context_options_override or key not in params:
params[key] = value
return dict(message, params=params)
def _initialize(self, client: RemoteClient) -> Dict:
"""The announce a launched server makes to a client, to it alone and
in the order that names nothing the client has not seen."""
client.initialized = True
for obj in (self.browser_type, self.chromium, self.webkit, self.android,
self.electron, self._utils(), self.browser):
parent = obj.parent.guid if obj.parent is not None else self.server.root_guid
client.post_message({"guid": parent, "method": "__create__",
"params": {"type": obj.TYPE, "guid": obj.guid,
"initializer": obj.initializer}})
client.post_message({"guid": self.server.root_guid, "method": "__create__",
"params": {"type": "Playwright", "guid": "Playwright",
"initializer": self._playwright_initializer()}})
return {"playwright": {"guid": "Playwright"}}
def _utils(self) -> Any:
for obj in list(self.server._objects.values()):
if isinstance(obj, LocalUtilsDispatcher):
return obj
raise ProtocolException("this server has no LocalUtils")
def _playwright_initializer(self) -> Dict:
return {"chromium": self.chromium.channel,
"firefox": self.browser_type.channel,
"webkit": self.webkit.channel,
"android": self.android.channel,
"electron": self.electron.channel,
"utils": self._utils().channel,
"preLaunchedBrowser": self.browser.channel}
def _reply(self, client: RemoteClient, msg_id: Any, result: Any) -> None:
if msg_id is None:
return
out: Dict[str, Any] = {"id": msg_id}
if result is not None:
out["result"] = result
client.post_message(out)
def _reply_error(self, client: RemoteClient, msg_id: Any,
failure: BaseException) -> None:
if msg_id is None:
return
out: Dict[str, Any] = {"id": msg_id,
"error": {"error": _error_payload(failure)}}
details = getattr(failure, "details", None)
if details is not None:
out["errorDetails"] = details
log = getattr(failure, "log", None)
if log:
out["log"] = list(log)
client.post_message(out)
# ── the server's messages, to whoever they are for ──────────────────────
def route(self, message: Dict) -> None:
for client in self._targets(message):
client.post_message(message)
def _owner_of(self, guid: Any) -> Any:
return getattr(self.server._objects.get(guid), "_owner", None)
def _targets(self, message: Dict) -> List[RemoteClient]:
params = message.get("params") or {}
subjects = [params.get("guid") if message.get("method") in
("__create__", "__adopt__") else None, message.get("guid")]
owner = None
for guid in subjects:
owner = self._owner_of(guid)
if owner is not None:
break
if owner is None:
for guid in _channel_guids(params):
owner = self._owner_of(guid)
if owner is not None:
break
if owner is not None:
return [owner] if owner.alive else []
with self._lock:
return [c for c in self.clients if c.alive and c.initialized]
def _client_gone(self, client: RemoteClient) -> None:
"""A connection ended: its contexts end with it, the browser does not."""
for obj in list(self.server._objects.values()):
if (getattr(obj, "_owner", None) is client
and obj.TYPE == "BrowserContext" and not obj.disposed):
try:
obj.op_close({})
except Exception:
pass
# ── the end ─────────────────────────────────────────────────────────────
def close(self) -> None:
with self._lock:
if self._closed:
return
self._closed = True
if self.probe is not None:
self.probe.stop()
loop, stop = self._loop, self._stop
if loop is not None and stop is not None:
try:
loop.call_soon_threadsafe(stop.set)
except RuntimeError:
pass
if self._thread is not None and self._thread is not threading.current_thread():
self._thread.join(timeout=10)
for _ in self._workers:
self._jobs.put(None)
for t in self._workers:
if t is not threading.current_thread():
t.join(timeout=5)
class RemoteServer:
"""What `launch_server()` returns: the shape of Playwright's BrowserServer
(`ws_endpoint`, `close()`, `process`) plus what the session decided."""
def __init__(self, endpoint: RemoteEndpoint, *, session: Any = None,
browser: Any = None, on_engine_closed: Optional[Callable[[], None]] = None,
notes: Optional[List[str]] = None) -> None:
self._endpoint = endpoint
self._session = session
self._browser = browser
self._on_engine_closed = on_engine_closed
self._closing = threading.Event()
self._closed = False
self._close_lock = threading.Lock()
#: Options that were asked for and could not be honoured, with why.
self.notes: List[str] = list(notes or [])
self._monitor: Optional[threading.Thread] = None
# ── BrowserServer ───────────────────────────────────────────────────────
@property
def ws_endpoint(self) -> str:
return self._endpoint.ws_endpoint
@property
def process(self) -> Any:
"""The browser process (pid / poll / wait), or None for a registry with
no process of its own."""
conn = getattr(self._browser, "conn", None)
return getattr(conn, "_process", None)
@property
def seed(self) -> Optional[int]:
return getattr(self._session, "seed", None)
@property
def exit_ip(self) -> Optional[str]:
"""The egress address measured at launch (through the proxy, if any)."""
return getattr(self._session, "_webrtc_egress_ip", None)
@property
def host(self) -> str:
return self._endpoint.host
@property
def port(self) -> Optional[int]:
return self._endpoint.port
def _watch_engine(self) -> None:
process = self.process
if process is None or self._on_engine_closed is None:
return
def watch() -> None:
while not self._closing.is_set():
try:
dead = process.poll() is not None
except Exception:
dead = True
if dead:
if not self._closing.is_set():
try:
self._on_engine_closed()
except Exception:
pass
return
time.sleep(0.25)
self._monitor = threading.Thread(target=watch, daemon=True,
name="invpw-engine-watch")
self._monitor.start()
def close(self) -> None:
"""Everything: the sockets, the browser and its tree, the hidden
display and the threads. Idempotent."""
with self._close_lock:
if self._closed:
return
self._closed = True
self._closing.set()
self._endpoint.close()
try:
self._endpoint.server.shutdown()
except Exception:
pass
if self._session is not None:
try:
self._session._teardown()
except Exception:
pass
if self._monitor is not None and self._monitor is not threading.current_thread():
self._monitor.join(timeout=5)
kill = close
def __enter__(self) -> "RemoteServer":
return self
def __exit__(self, *exc: Any) -> None:
self.close()
async def aclose(self) -> None:
await asyncio.get_running_loop().run_in_executor(None, self.close)
# ── the launch ──────────────────────────────────────────────────────────────
def _context_defaults(session: Any, downloads: Optional[str]) -> Dict:
"""The session's own defaults for a context, in the protocol's spelling:
what the wrapper's `_default_context_kwargs` gives its in-process users."""
kwargs = session._default_context_kwargs()
out: Dict[str, Any] = {}
for key, value in kwargs.items():
out["timezoneId" if key == "timezone_id" else key] = value
if downloads:
out["acceptDownloads"] = downloads
return out
def _launch_params(session: Any, *, virtual_display: bool, headless: bool,
timeout_ms: Optional[int], notes: List[str]) -> Dict:
"""`InvisiblePlaywright.__enter__` up to the launch, as protocol params.
The same calls in the same order, so the served browser is the one the
wrapper would have launched: geo (egress, timezone, locale), the
hidden display, the prefs, the proxy, the session token and the env."""
from invisible_core import configure_proxy, prepare_session_geo
from invisible_core import make_virtual_display
from invisible_playwright._engine import resolve_executable
from invisible_playwright._reaper import SessionToken
geo = prepare_session_geo(session._timezone, session._proxy,
session._locale_requested)
session._timezone = geo.timezone
session._locale = geo.locale
session._webrtc_egress_ip = geo.egress_ip
executable = resolve_executable(session._binary_path)
pw_headless = bool(headless)
if not headless and virtual_display:
if sys.platform == "win32":
notes.append("virtual_display ignored: Windows has no virtual "
"display in this server (the browser runs on the "
"caller's desktop)")
else:
vd = make_virtual_display()
if vd is None:
notes.append("virtual_display ignored: no display server found")
else:
vd.start()
session._virtual_display = vd
prefs = session._build_prefs()
playwright_proxy = configure_proxy(session._proxy, prefs)
session._session_token = SessionToken.mint()
env = session._build_env(prefs)
params: Dict[str, Any] = {
"executablePath": str(executable),
"headless": pw_headless,
"firefoxUserPrefs": prefs,
"args": list(session._extra_args),
"env": [{"name": k, "value": str(v)} for k, v in env.items()],
}
if playwright_proxy:
params["proxy"] = playwright_proxy
if timeout_ms is not None:
params["timeout"] = timeout_ms
return params
def launch_server(host: str = DEFAULT_HOST, port: int = 0, *,
path: Optional[str] = None,
seed: Optional[int] = None,
pin: Optional[Dict[str, Any]] = None,
proxy: Optional[Dict[str, str]] = None,
headless: bool = False,
virtual_display: bool = True,
humanize: Any = False,
motion_budget_s: Optional[float] = None,
show_cursor: Optional[bool] = None,
locale: str = "auto",
timezone: str = "",
extra_args: Optional[List[str]] = None,
extra_prefs: Optional[Dict[str, Any]] = None,
binary_path: Optional[str] = None,
downloads: Optional[str] = None,
context_options: Optional[Dict[str, Any]] = None,
context_options_override: bool = False,
launch_timeout_ms: Optional[int] = 60000,
on_engine_closed: Optional[Callable[[], None]] = None,
) -> RemoteServer:
"""Launch ONE browser and serve it on a WebSocket; return when it listens
and the browser is ready.
host / port / path where it listens; `127.0.0.1`, a random port and a
random secret path by default. The caller chooses an
external address.
seed None draws a new one; `server.seed` reads it back.
pin fingerprint fields forced (see docs/pinning.md).
proxy `{"server", "username", "password"}`, fixed after the
launch; the egress (exit IP -> timezone, locale
"auto"; the GeoIP database offline from
STEALTHFOX_GEOIP_MMDB) is measured here through it.
headless True = true headless; False = headed.
virtual_display with headless=False: a private virtual display (Xvfb
with its own launch env). Windows: ignored, with the
reason in `server.notes`.
humanize False (default) / True / seconds; `motion_budget_s`
gives the cap in seconds (with the seed it rides in
SESSION_SEED_PREF / MOTION_BUDGET_PREF).
downloads "deny" cancels every download of every context.
context_options protocol-spelled options (`viewport`, `locale`, ...)
applied to every context a client creates, on top of
the profile's geometry, timezone and locale; filled
where the client says nothing, unless
`context_options_override=True`.
on_engine_closed called, from another thread, when the engine dies
(not when `close()` ends it).
The engine is the sealed one (`ensure_binary`, INVISIBLE_PLAYWRIGHT_ENGINE_DIR)
and the launch FAILS if the version it reports is not the seal's.
"""
from invisible_playwright import InvisiblePlaywright
from invisible_playwright._engine import assert_wire_version
if humanize and motion_budget_s:
humanize = float(motion_budget_s)
session = InvisiblePlaywright(
seed, pin=pin, headless=headless, proxy=proxy, extra_args=extra_args,
humanize=humanize, locale=locale, timezone=timezone,
extra_prefs=extra_prefs, binary_path=binary_path,
show_cursor=show_cursor)
notes: List[str] = []
server = _SharedServer()
endpoint: Optional[RemoteEndpoint] = None
try:
params = _launch_params(session, virtual_display=virtual_display,
headless=headless, timeout_ms=launch_timeout_ms,
notes=notes)
browser_type = SharedBrowserType(server)
LocalUtilsDispatcher(server)
browser = server.object(
browser_type.op_launch(params)["browser"]["guid"])
session._bind_process_tree()
class _Reported: # what assert_wire_version reads off a Browser
version = browser.initializer.get("version", "")
assert_wire_version(_Reported)
defaults = _context_defaults(session, downloads)
defaults.update(context_options or {})
endpoint = RemoteEndpoint(
server, browser_type, browser, host=host, port=port, path=path,
context_defaults=defaults,
context_options_override=context_options_override)
endpoint.start()
except BaseException:
if endpoint is not None:
endpoint.close()
try:
server.shutdown()
except Exception:
pass
try:
session._teardown()
except Exception:
pass
raise
result = RemoteServer(endpoint, session=session, browser=browser,
on_engine_closed=on_engine_closed, notes=notes)
result._watch_engine()
return result
async def launch_server_async(*args: Any, **options: Any) -> RemoteServer:
"""`launch_server`, off the loop: the launch blocks for seconds."""
loop = asyncio.get_running_loop()
return await loop.run_in_executor(
None, lambda: launch_server(*args, **options))
+458 -150
View File
@@ -11,8 +11,10 @@ that reading cannot show you.
- `goto`, `click`, `fill`, `title`, `content` and `querySelector` are sent to
the **Frame**, not the Page. The Page owns almost nothing.
- `mouseMove` IS sent to the Page - and in a humanised session it arrives
nineteen times for one click, because the cursor travels.
- `mouseMove` IS sent to the Page. It used to arrive nineteen times for one
click in a humanised session, because the in-process client's cursor
travelled; the walk is the server's now (`pointer.py`), so a click arrives
once, from every client, and the page still sees the walk.
- `BrowserContext` is created with three children already alive - `Debugger`,
`Tracing`, `APIRequestContext` - and each is announced BEFORE the context that
names it, then re-parented with `__adopt__`.
@@ -28,8 +30,10 @@ from __future__ import annotations
import base64
import contextlib
import json
import os
import pathlib
import sys
import tempfile
import threading
import time
@@ -41,6 +45,7 @@ from invisible_core.juggler import connection as juggler
from invisible_core.juggler.actions import Actions
from invisible_core.juggler.deadline import Deadline
from . import dialogs
from .pointer import Pointer
from .dispatcher import (Dispatcher, ExpectNotMet, ProtocolException,
Server, current_call)
from invisible_core.juggler.injected import (ContextDestroyed, EvaluationError,
@@ -218,6 +223,20 @@ SESSION_SEED_PREF = "invisible.server.session_seed"
#: a cap of its own would be a second answer to a question the caller answered,
#: and would show up as a drag that ignores a budget every click obeys.
MOTION_BUDGET_PREF = "invisible.server.motion_budget_ms"
#: WHETHER THIS SERVER DRAWS THE POINTER'S WALK (`pointer.py`): true when the
#: launcher chose the Python generator (`_cursor.resolve_cursor_engine`). It
#: travels like the seed, for the same reason: the choice is made once, by the
#: caller's `humanize=` and the environment, and this server answering it by
#: itself would be a second answer. False with a seed present is a session whose
#: pointer is the engine's own (`binary`) or nobody's (`off`): drawing a path
#: here as well would humanise twice.
POINTER_PREF = "invisible.server.pointer"
#: Set by the launcher's `build_prefs` on every pref dict it composes, and taken
#: out here like the three above: the profile a launch writes is a composed
#: session, or the server composes one (`session_for_launch`).
COMPOSED_PREF = "invisible.server.composed"
#: The persona's keyboards, as Windows writes its input profiles (LANGID:KLID
#: joined by semicolons, the language's first), decided by the core from the
#: session's language AND country (`keyboard.profiles_for`). Server-only, like
@@ -243,11 +262,55 @@ def take_session_motion(prefs: Dict) -> tuple:
rest = dict(prefs)
seed = rest.pop(SESSION_SEED_PREF, None)
budget_ms = rest.pop(MOTION_BUDGET_PREF, None)
rest.pop(POINTER_PREF, None)
rest.pop(COMPOSED_PREF, None)
return (rest,
(None if seed is None else int(seed)),
(None if budget_ms is None else int(budget_ms) / 1000.0))
def session_for_launch(prefs: Dict, executable: str, proxy: Optional[Dict] = None) -> tuple:
"""What a launch writes into its profile and adds to its environment: always a
composed session. Returns (prefs, session_env).
⛔ A LAUNCH THAT NAMES NO SESSION IS FIREFOX READING THE HOST. The launcher
(`InvisiblePlaywright`, `launch_server`) composes the session, marks its prefs
(COMPOSED_PREF) and sends the environment it composed; a bare
`BrowserType.launch` from any other client of this server named only the
prefs it chose, usually none, and `user.js` held nothing of the core's. That
browser was the engine with Mozilla's defaults: no persona, every value a page
reads taken from the machine, and on Linux the first-run policy tab of
TelemetryReportingPolicy (the Terms of Use not accepted), a second tab in the
first window that `Browser.newPage` refuses with "Unexpected number of tabs in
the new window: 2". Measured 2026-11-11 on firefox-61 and on the firefox-62
candidate, 15 of 15 bare launches.
And the PREFS ARE HALF OF IT. The engine reads its font list at startup from
the manifest an environment variable names (`build_env`); without it the
engine lists the fonts of the machine. So an unmarked launch gets the session
`InvisiblePlaywright()` composes with the server's defaults (a new seed,
humanize off as in `launch_server`): its prefs, with the caller's on top, and
the variables of its environment, which `op_launch` adds wherever the caller
named none of the same name. A marked launch comes with both already.
`proxy` is the launch's own (`launch(proxy=...)`): the session is composed
through it as `InvisiblePlaywright(proxy=...)` composes, so the egress it
measures there (timezone, locale) and the network it declares are the proxy's,
not this machine's. The engine is told the proxy by `op_launch`, as before.
"""
if COMPOSED_PREF in prefs:
return dict(prefs), {}
from invisible_playwright._session import default_session
session_prefs, session_env = default_session(executable, proxy)
return dict(session_prefs, **prefs), dict(session_env)
def session_draws_pointer(prefs: Dict) -> bool:
"""Did the launcher ask this server to draw the pointer's walk? Read from
the prefs BEFORE `take_session_motion` takes the key out."""
return bool(prefs.get(POINTER_PREF))
def _launch_environment(named) -> Dict[str, str]:
"""The environment a launched browser gets, from what the caller named.
@@ -323,6 +386,30 @@ def _remote_value(remote: Dict) -> Any:
#: Calls what the caller's script produced with the receivers, then the
#: argument: Playwright's utility script calls `result(...args)` on what
#: `eval` produced.
# The names a page and a caller use for a permission (`grant_permissions(["geolocation"])`, the ones of
# `navigator.permissions`) are not the names the engine keeps them under (`geo`, `desktop-notification`): the
# engine's permission manager knows a grant only by its own name, and a name it does not know is stored as
# nothing, so the page is still asked, or refused, as if nothing had been granted. This is the table of the
# Playwright client for this browser (playwright-core `ffBrowser.js`, `doGrantPermissions`), and a name outside
# it is an error there as it is here: a grant that does nothing, in silence, is worse than a refusal.
_WEB_PERMISSION_TO_ENGINE = {
"geolocation": "geo",
"persistent-storage": "persistent-storage",
"push": "push",
"notifications": "desktop-notification",
"screen-wake-lock": "screen-wake-lock",
}
def _engine_permissions(permissions) -> List[str]:
engine_names = []
for permission in permissions:
if permission not in _WEB_PERMISSION_TO_ENGINE:
raise ProtocolException("Unknown permission: %s" % (permission,))
engine_names.append(_WEB_PERMISSION_TO_ENGINE[permission])
return engine_names
_CALL = "(f, ...a) => f(...a)"
#: Reads a caller's object by value, from the reference that holds it.
_READ = "o => o"
@@ -545,9 +632,11 @@ class ElementHandleDispatcher(Dispatcher):
def op_check_hit_target(self, params: Dict) -> Any:
"""Would an event at this MAIN-FRAME point land on this element?
⛔ NOT A PLAYWRIGHT METHOD: the humanised cursor (`_cursor._hits`) is
its only caller, asking about the off-centre point it is about to aim
at. The point is in the space `boundingBox` answers in, and the answer
⛔ NOT A PLAYWRIGHT METHOD, and the product no longer calls it: the
server's own pointer (`pointer.py`) asks `Actions.hit_target` directly
about the off-centre point it is about to aim at. It stays for whoever
wants to ask the same question of a handle, and for the tests that pin
the answer. The point is in the space `boundingBox` answers in, and the answer
is the one the action's own check gives (`Actions.hit_target`): the
same frame shift, the same shadow-aware test. A second hit test here
would be a second definition of where a click lands.
@@ -568,9 +657,10 @@ class ElementHandleDispatcher(Dispatcher):
is the sane way to write a probe - simply took the wrong branch in
silence.
⛔ THE COST, MEASURED. The humanised cursor asks the element whether an
off-centre point actually lands on it (`_cursor._hits`, which passes
`{x, y}` as exactly this argument). With `arg` dropped the check threw
⛔ THE COST, MEASURED. The humanised cursor (then the client's, asking
through `_hits`; the server's pointer asks the action's own hit test
now) asked the element whether an off-centre point actually lands on
it, passing `{x, y}` as exactly this argument. With `arg` dropped the check threw
every single time, was caught, and answered False - so the landing
override was never applied and EVERY click fell on the exact geometric
centre of its element. That is the tell `_landing_override`'s own
@@ -868,6 +958,28 @@ class FrameDispatcher(Dispatcher):
"addStyleTag": "op_add_style_tag",
}
#: ⛔ A FRAME THAT LEFT THE PAGE STAYS HERE, and answers every call with Playwright's own error. The driver never
#: disposes a Frame when it detaches (it disposes the Page, the contexts, the handles; the frames go with the page,
#: or are collected when their bucket is full): a call on a detached frame reaches its dispatcher and is refused
#: "Frame was detached". Disposing it on detach, as this class did, made the same call a call on a guid that no
#: longer exists, and the client read it as `Target page, context or browser has been closed`: the page is not
#: closed, and a script that handles "detached" (an iframe a framework removed) never saw it.
detached = False
def detach(self) -> None:
"""The frame left the page: its handles go (their frame is no more), the frame itself stays and refuses."""
self.detached = True
self.server.dispose_many(self.server.descendants_of(self), None)
def call(self, method: str, params: Dict) -> Any:
if self.detached:
raise ProtocolException("Frame was detached")
return super().call(method, params)
def gc_bucket(self) -> str:
"""Playwright counts the main frame and the others apart (`frameDispatcher.ts`)."""
return "MainFrame" if getattr(self, "parent_frame", None) is None else "Frame"
def __init__(self, server, page: "PageDispatcher", frame_id: str,
url: str = "about:blank", name: str = "",
load_states: Optional[List[str]] = None,
@@ -1244,12 +1356,32 @@ class FrameDispatcher(Dispatcher):
lifecycle.wait_for_action_signals(main, since, deadline.left(floor=0.05))
return result
def _by_hand(self, params: Dict, frame_id: str, selector: str,
run: Callable[[Any, Any], Any]) -> Any:
"""Run a pointer action with the hand of the session in front of it.
⛔ THE WALK ONTO THE ELEMENT IS DRAWN HERE, once, for every client: it
used to be the in-process client's, so a client that was not ours sent
one `Frame.click` and the page saw one `mousemove` (`pointer.py`).
`run(position, timeout)` is the plain action; with no hand (humanising
off, the engine's own expansion) it is all that happens, with the
caller's own arguments.
"""
hand = self.page.pointer
if hand is None or not hand.active:
return run(self._position(params), self._timeout(params))
return hand.act(frame_id, selector, self._position(params),
self._timeout(params), run,
trial=self._act_opts(params)["trial"])
def op_click(self, params: Dict) -> Any:
frame_id, selector = self.enter_frames(params["selector"])
self._waiting_after(params, lambda: self.actions.click(
selector, timeout=self._timeout(params), frame_id=frame_id,
**self._act_opts(params), position=self._position(params),
**self._pointer(params)))
self._waiting_after(params, lambda: self._by_hand(
params, frame_id, selector,
lambda position, timeout: self.actions.click(
selector, timeout=timeout, frame_id=frame_id,
**self._act_opts(params), position=position,
**self._pointer(params))))
return None
def op_dblclick(self, params: Dict) -> Any:
@@ -1257,16 +1389,19 @@ class FrameDispatcher(Dispatcher):
pointer = self._pointer(params)
# dblclick sets its own clickCount; the caller's is not a second one.
pointer.pop("clicks", None)
self.actions.dblclick(selector, timeout=self._timeout(params),
frame_id=frame_id, **self._act_opts(params),
position=self._position(params), **pointer)
self._by_hand(params, frame_id, selector,
lambda position, timeout: self.actions.dblclick(
selector, timeout=timeout, frame_id=frame_id,
**self._act_opts(params), position=position,
**pointer))
return None
def op_hover(self, params: Dict) -> Any:
frame_id, selector = self.enter_frames(params["selector"])
self.actions.hover(selector, timeout=self._timeout(params),
frame_id=frame_id, **self._act_opts(params),
position=self._position(params))
self._by_hand(params, frame_id, selector,
lambda position, timeout: self.actions.hover(
selector, timeout=timeout, frame_id=frame_id,
**self._act_opts(params), position=position))
return None
def op_fill(self, params: Dict) -> Any:
@@ -1278,16 +1413,18 @@ class FrameDispatcher(Dispatcher):
def op_check(self, params: Dict) -> Any:
frame_id, selector = self.enter_frames(params["selector"])
self.actions.check(selector, timeout=self._timeout(params),
frame_id=frame_id, **self._act_opts(params),
position=self._position(params))
self._by_hand(params, frame_id, selector,
lambda position, timeout: self.actions.check(
selector, timeout=timeout, frame_id=frame_id,
**self._act_opts(params), position=position))
return None
def op_uncheck(self, params: Dict) -> Any:
frame_id, selector = self.enter_frames(params["selector"])
self.actions.uncheck(selector, timeout=self._timeout(params),
frame_id=frame_id, **self._act_opts(params),
position=self._position(params))
self._by_hand(params, frame_id, selector,
lambda position, timeout: self.actions.uncheck(
selector, timeout=timeout, frame_id=frame_id,
**self._act_opts(params), position=position))
return None
def op_focus(self, params: Dict) -> Any:
@@ -1349,9 +1486,10 @@ class FrameDispatcher(Dispatcher):
def op_tap(self, params: Dict) -> Any:
frame_id, selector = self.enter_frames(params["selector"])
self.actions.tap(selector, timeout=self._timeout(params),
frame_id=frame_id, **self._act_opts(params),
position=self._position(params))
self._by_hand(params, frame_id, selector,
lambda position, timeout: self.actions.tap(
selector, timeout=timeout, frame_id=frame_id,
**self._act_opts(params), position=position))
return None
def op_dispatch_event(self, params: Dict) -> Any:
@@ -1970,16 +2108,88 @@ class FrameDispatcher(Dispatcher):
return {"handle": self._handle_from_caller(remote).channel}
# ⛔ `DialogDispatcher` LIVED HERE AND IS GONE, fused into `_pw._impl._dialog`
# on 2026-08-29 - the first type fused into its impl class rather than merely
# simplified in place. There is no `__create__` for a dialog any more: see
# `PageDispatcher._on_juggler_event`'s `Page.dialogOpened` branch below, which
# constructs the fused object directly and hands it across the thread boundary
# with `call_soon_threadsafe`, and `_pw/_impl/_dialog.py` for the object
# itself, including the auto-answer safety net this docstring used to
# describe.
class DialogDispatcher(Dispatcher):
"""One open dialog, waiting for the caller to answer it.
⛔ A DIALOG THAT IS NEVER ANSWERED HANGS THE PAGE, and silently: the content
process sits inside `window.alert` and the next command times out naming
something unrelated (measured as `Runtime.callFunction: no response in
30s`). The client answers on its own when nobody listens (see
`BrowserContext._on_dialog`), which only works if this object reaches it:
it is announced with `__create__` and then carried by the `dialog` event
of the context, in that order, from `PageDispatcher._on_juggler_event`.
⛔ THE PAUSE IS HERE, in the worker that answers: `Page.answer_dialog`
waits what the reader of the seed still needs, then sends. A call runs on
the transport's worker pool, so the sleep holds up neither the loop nor
the reader thread."""
TYPE = "Dialog"
METHODS = {"accept": "op_accept", "dismiss": "op_dismiss"}
def __init__(self, server, page: "PageDispatcher", dialog_id: str,
kind: str, message: str, default_value: str) -> None:
self.page = page
self.dialog_id = dialog_id
super().__init__(server, page, {
"type": kind,
"message": message,
"defaultValue": default_value,
"page": page.channel,
})
def op_accept(self, params: Dict) -> Any:
answer = {"dialogId": self.dialog_id, "accept": True}
if params.get("promptText") is not None:
answer["promptText"] = params["promptText"]
self.page.answer_dialog("Page.handleDialog", answer)
return None
def op_dismiss(self, params: Dict) -> Any:
self.page.answer_dialog(
"Page.handleDialog", {"dialogId": self.dialog_id, "accept": False})
return None
def _pack_headers(entries: List[Dict[str, str]]) -> tuple:
"""Headers kept as a tuple of (name, value) pairs, names and short values interned.
⛔ A LIST OF DICTS PER MESSAGE WAS 3.6 KB PER REQUEST AND 4.9 KB PER RESPONSE (measured
on a real browser, ten headers each): a dict costs more than the two strings it holds,
and every response of a site repeats the same names and most of the same values. The
registry keeps a request and its response for as long as the context lives, so a
session of a hundred navigations held them by the thousand. The list of dicts the
protocol wants is rebuilt when it is asked for (`_unpack_headers`)."""
out = []
for entry in entries:
name, value = entry["name"], entry["value"]
out.append((sys.intern(name),
sys.intern(value) if len(value) <= 256 else value))
return tuple(out)
def _unpack_headers(pairs: tuple) -> List[Dict[str, str]]:
return [{"name": name, "value": value} for name, value in pairs]
#: Certificates as the engine reports them, one object per distinct certificate: every
#: response of a host carries the same chain, a few KB, and each kept its own copy.
_DETAILS: Dict[str, Any] = {}
def _shared_details(details: Any) -> Any:
if not details:
return None
try:
key = json.dumps(details, sort_keys=True)
except (TypeError, ValueError):
return details
shared = _DETAILS.get(key)
if shared is None:
if len(_DETAILS) >= 256:
_DETAILS.pop(next(iter(_DETAILS)))
shared = _DETAILS[key] = details
return shared
class RequestDispatcher(Dispatcher):
@@ -2004,7 +2214,7 @@ class RequestDispatcher(Dispatcher):
#: sends it on somewhere else (`continued_at`). Its response is that
#: URL's, as Playwright's server has it.
self.url = params.get("url") or ""
self.raw_headers = _headers_array(params.get("headers"))
self._headers = _pack_headers(_headers_array(params.get("headers")))
self.response: Optional["ResponseDispatcher"] = None
#: Filled by `Network.requestFailed`. ⛔ None until it fails: an
#: empty string would say "failed for no reason", which is a different
@@ -2014,7 +2224,7 @@ class RequestDispatcher(Dispatcher):
super().__init__(server, page, {
"url": self.url,
"method": params.get("method") or "GET",
"headers": self.raw_headers,
"headers": _unpack_headers(self._headers),
# ⛔ OMITTED WHEN ABSENT, never sent as null. The client reads
# `initializer.get("postData")` and base64-decodes anything that is
# not None, so a null is harmless today and a raw string would be
@@ -2037,6 +2247,22 @@ class RequestDispatcher(Dispatcher):
"frame": page.frame_for(frame_id).channel,
})
@property
def raw_headers(self) -> List[Dict[str, str]]:
return _unpack_headers(self._headers)
def announced(self) -> None:
"""⛔ THE ANNOUNCEMENT CARRIED THEM AND NOTHING READS THEM AGAIN: the client takes
a request's headers and POST body (up to 10 MB) from the `__create__`, and the
server answers `rawRequestHeaders` from `_headers`. A NEW dict, not a pop: the
message that went up may still be waiting in a queue, and it holds the old one."""
self.initializer = {k: v for k, v in self.initializer.items()
if k not in ("headers", "postData")}
def released(self) -> None:
self._headers = ()
self.response = None
def continued_at(self, url: str) -> None:
"""A route sent this request on to `url`.
@@ -2080,13 +2306,13 @@ class ResponseDispatcher(Dispatcher):
def __init__(self, server, request: RequestDispatcher,
params: Dict) -> None:
self.request = request
self.raw_headers = _headers_array(params.get("headers"))
self._headers = _pack_headers(_headers_array(params.get("headers")))
self.protocol_version = params.get("protocolVersion") or ""
self.remote = {"ipAddress": params.get("remoteIPAddress") or "",
"port": params.get("remotePort") or 0}
self._remote = (sys.intern(params.get("remoteIPAddress") or ""),
params.get("remotePort") or 0)
# The certificate the engine read off the channel, or None for a
# response that did not come over TLS.
self.security_details = params.get("securityDetails") or None
self.security_details = _shared_details(params.get("securityDetails"))
# ⛔ The parent is the REQUEST, which is where the driver puts it.
# Unlike the ElementHandle case this one is not load-bearing today -
# `_network.py` reads its request from the INITIALIZER, not from the
@@ -2097,7 +2323,7 @@ class ResponseDispatcher(Dispatcher):
"url": request.url,
"status": params.get("status") or 0,
"statusText": params.get("statusText") or "",
"headers": self.raw_headers,
"headers": _unpack_headers(self._headers),
"request": request.channel,
"fromServiceWorker": bool(params.get("fromServiceWorker")),
# ⛔ EVERY timing field is mandatory and -1 means "did not happen".
@@ -2109,6 +2335,24 @@ class ResponseDispatcher(Dispatcher):
"requestStart": -1, "responseStart": -1},
})
@property
def raw_headers(self) -> List[Dict[str, str]]:
return _unpack_headers(self._headers)
@property
def remote(self) -> Dict[str, Any]:
return {"ipAddress": self._remote[0], "port": self._remote[1]}
def announced(self) -> None:
"""The client took the headers and the timing from the `__create__` (a new dict,
not a pop: see `RequestDispatcher.announced`)."""
self.initializer = {k: v for k, v in self.initializer.items()
if k not in ("headers", "timing")}
def released(self) -> None:
self._headers = ()
self.security_details = None
def op_body(self, params: Dict) -> Any:
"""The response body, base64, straight from the engine.
@@ -2233,7 +2477,21 @@ class RouteDispatcher(Dispatcher):
# session they came back "Handler for does not implement method", the
# held request was never released and the page hung on its first
# request. Every route that ever reached a handler failed this way.
result = self.request.page.send(command, params)
# ⛔ THE ANSWER TO A REQUEST THE BROWSER HAS ALREADY CLOSED IS NOT AN ERROR. The page cancels requests while a route is
# deciding (a fetch aborted, an image replaced, an iframe removed, a beacon with its document): the engine takes
# the request out of its held set at once, and the late `continue`/`abort`/`fulfill` meets "Cannot find request".
# Stock Playwright sends these commands as may-fail and tells the client nothing (`sendMayFail`). Ours passed the
# error up; the client kept it as the error of the whole connection and raised it on the NEXT route command,
# which was never sent: its request stayed held in the engine, its handler failed too, and so on down the page
# (measured on a real news page: six held requests in a row, one a beacon, networkidle never).
try:
result = self.request.page.send(command, params)
except juggler.ProtocolError as exc:
if "Cannot find request" not in str(exc):
raise
result = None
except juggler.TargetClosedError:
result = None # the page went away: nothing is held any more
self.dispose()
return result
@@ -2292,7 +2550,11 @@ class RouteDispatcher(Dispatcher):
# ── page ────────────────────────────────────────────────────────────────────
class PageDispatcher(Dispatcher):
TYPE = "Page"
#: No hand until `_build` gives it one: a page without it acts as the
#: caller wrote.
pointer: Optional[Pointer] = None
METHODS = {
"screencastFrameAck": "op_noop",
"mouseMove": "op_mouse_move",
"mouseDown": "op_mouse_down",
"mouseUp": "op_mouse_up",
@@ -2413,6 +2675,18 @@ class PageDispatcher(Dispatcher):
self.injected.install()
self.actions = context.browser.actions_for_page(
session, self.lifecycle, self.injected, self.number)
#: The viewport as the client was told it (the initializer's, then
#: `setViewportSize`): the hand plans inside it.
self.viewport_size = context.options.get("viewport") or {
"width": 1280, "height": 720}
#: ⛔ THE HAND, built where the page's number and the session's seed
#: meet: one stream per page, the seed the client's cursor drew from
#: (`_cursor.page_motion_seed`). See `pointer.py`.
self.pointer = Pointer(
self.actions, self.injected, self.number,
context.browser.session_seed, context.browser.motion_budget_s,
lambda: self.viewport_size,
draws=context.browser.pointer_draws)
# ⛔ THE EVENTS THIS PAGE ALREADY MISSED, handed over now that the two
# things that need them exist. `Page.frameAttached` and the
# `Runtime.executionContextCreated` pair are sent by the browser BEFORE
@@ -2449,7 +2723,7 @@ class PageDispatcher(Dispatcher):
#: must not exhaust the process driving it.
self._request_log: List[Any] = []
#: Dialogs still open, by id: when they opened (monotonic seconds),
#: their rank on this page and their text. `send_async` reads them
#: their rank on this page and their text. `answer_dialog` reads them
#: to answer after a reader's pause, see `dialogs.plan_answer_ms`.
self._dialogs_open: Dict[str, Any] = {}
self._dialogs_seen = 0
@@ -2457,11 +2731,11 @@ class PageDispatcher(Dispatcher):
# ⛔ The Frame is created BEFORE the Page and adopted after: the Page
# initializer has to name a mainFrame the client can already resolve.
self.frame = FrameDispatcher(server, self, self.main_frame_id)
viewport = context.options.get("viewport") or {"width": 1280,
"height": 720}
# `pageNumber` is ours, not Playwright's: the cursor reads it
# (`_cursor._cursor_for_page`), so client and server draw one page's
# rhythms under one number.
viewport = self.viewport_size
# `pageNumber` is ours, not Playwright's: the number the page's
# rhythms are drawn under (`pointer.py` and the actions' nonce read it
# from `self.number`), told to the client so that it can name the page
# the way the server does.
initializer = {"mainFrame": self.frame.channel,
"viewportSize": viewport, "isClosed": False,
"pageNumber": self.number}
@@ -2571,7 +2845,7 @@ class PageDispatcher(Dispatcher):
child = self._frames.pop(frame_id, None)
if child is not None:
self.emit("frameDetached", {"frame": child.channel})
child.dispose()
child.detach()
return
if what == "frameAttached":
# Never the main frame: the lifecycle announces an id it sees for
@@ -2754,10 +3028,14 @@ class PageDispatcher(Dispatcher):
self._dialogs_open[params["dialogId"]] = (
time.monotonic(), self._dialogs_seen,
params.get("message") or "")
self._emit_fused_dialog(params["dialogId"],
params.get("type") or "alert",
params.get("message") or "",
params.get("defaultValue") or "")
# ⛔ THE OBJECT IS ANNOUNCED BEFORE THE EVENT THAT CARRIES IT:
# `__create__` happens in the constructor, `dialog` after it, from
# this one thread.
dialog = DialogDispatcher(self.server, self, params["dialogId"],
params.get("type") or "alert",
params.get("message") or "",
params.get("defaultValue") or "")
self.context.emit("dialog", {"dialog": dialog.channel})
elif method == "Page.fileChooserOpened":
# ⛔ OFF THIS THREAD, and it is a deadlock rather than a slowdown.
# `_on_juggler_event` runs INSIDE the connection's read loop, and
@@ -2809,14 +3087,15 @@ class PageDispatcher(Dispatcher):
self._offer_route(request)
elif method == "Network.responseReceived":
request = self._requests.get(params.get("requestId"))
if request is not None:
# A request the registry already collected (`GC_LIMITS`) is not named again.
if request is not None and not request.disposed:
response = ResponseDispatcher(self.server, request, params)
request.response = response
self.context.emit("response", {"response": response.channel,
"page": self.channel})
elif method == "Network.requestFinished":
request = self._requests.pop(params.get("requestId"), None)
if request is not None:
if request is not None and not request.disposed:
if request.response is not None:
request.response.protocol_version = (
params.get("protocolVersion") or "")
@@ -2829,7 +3108,7 @@ class PageDispatcher(Dispatcher):
})
elif method == "Network.requestFailed":
request = self._requests.pop(params.get("requestId"), None)
if request is not None:
if request is not None and not request.disposed:
request.failure = params.get("errorCode") or "failed"
self.context.emit("requestFailed", {
"request": request.channel,
@@ -2959,7 +3238,7 @@ class PageDispatcher(Dispatcher):
if frame_id == self.frame.frame_id:
return self.frame
existing = self._frames.get(frame_id)
if existing is not None:
if existing is not None and not existing.disposed:
return existing
frame = self.lifecycle.frame(frame_id)
parent_id = getattr(frame, "parent", None)
@@ -3047,29 +3326,7 @@ class PageDispatcher(Dispatcher):
return self.conn.send(command, params, session=self.session,
timeout=timeout)
async def send_async(self, command: str, params: Dict) -> Any:
"""`send`, off the loop and awaitable.
⛔ THE PRIMITIVE A FUSED TYPE NEEDS. A fused object's own methods are
`async def` - the public API promises that - but the Juggler call
underneath still BLOCKS. This hands it to the transport's worker pool
via `Server.run_blocking` and awaits the result, instead of a fused
type reaching for the pool on its own and reinventing the translation
`run_blocking` already does. Dialog is the first caller, 2026-08-29.
⛔ A DIALOG IS ANSWERED AFTER A READER'S PAUSE (2026-11-07). Until
then `Page.handleDialog` left in the same millisecond the dialog
opened, whoever answered it: the auto-dismiss with no handler, or a
handler's `accept()`. The pause is drawn from the session's seed and
the dialog's text (`dialogs.plan_answer_ms`); only the remainder is
waited, and it is waited here, in the worker, not on the loop.
"""
if command == "Page.handleDialog":
return await self.server.run_blocking(
self._answer_dialog, command, params)
return await self.server.run_blocking(self.send, command, params)
def _answer_dialog(self, command: str, params: Dict) -> Any:
def answer_dialog(self, command: str, params: Dict) -> Any:
"""The pause, then the answer. ⛔ THE ANSWER ALWAYS GOES OUT: a dialog
left open blocks the page's script for good (every evaluate on it
times out), so whatever goes wrong in planning the pause is a warning,
@@ -3091,51 +3348,6 @@ class PageDispatcher(Dispatcher):
time.sleep(wait / 1000.0)
return self.send(command, params)
def _emit_fused_dialog(self, dialog_id: str, kind: str, message: str,
default_value: str) -> None:
"""A dialog just opened: build the fused object and hand it to the
impl-side `BrowserContext` directly, no `__create__`, no guid, no
channel.
⛔ THIS RUNS ON THE CONNECTION'S READ LOOP, not the asyncio loop -
`_on_juggler_event` always does, see the comment on `_history` /
`Page.fileChooserOpened` above for the same fact stated once already.
`_on_dialog` and the auto-answer path it may take
(`asyncio.create_task(...)`) both require the ASYNCIO loop, so the
hand-off is `Server.call_soon`, the exact mechanism every other event
already crosses this same boundary with - just carrying a real object
instead of a wire message this time.
⛔ AND CREATING THE OBJECT IS NOT NOTIFYING ANYONE, same as when this
was two objects: forgetting the hand-off is a HANG, not a leak - the
content process sits inside `window.alert` and the next command times
out naming something unrelated. Measured on 2026-08-28, before the
fusion, as `Runtime.callFunction: no response in 30s`.
"""
from invisible_playwright._pw._impl._dialog import Dialog as ImplDialog
impl_page = self.server.twin(self.guid)
if impl_page is None:
# The client never learned about this page - can happen only if
# a dialog fires in the gap between the engine creating the page
# and `__create__` reaching the client, which today's ordering
# guarantee is not supposed to allow. Refusing to guess who to
# notify is safer than guessing wrong.
return
dialog = ImplDialog(self, impl_page, dialog_id, kind, message,
default_value)
browser_context = impl_page._browser_context
# ⛔ TWO HOPS, NOT ONE: `call_soon` gets to the loop thread from here
# (the connection's read loop); `server.deliver` then runs the target
# under the client's own event-delivery rules once there (the
# `EventGreenlet` wrapping `dispatch` gives every wire event, see
# `Connection.deliver_event`). Calling `_on_dialog` bare through
# `call_soon` skips that wrapping entirely, and a sync-mode
# `dialog.accept()` called from the "dialog" handler hangs with no
# exception - found live, 2026-08-29, not by the unit suite.
self.server.call_soon(
lambda: self.server.deliver(browser_context._on_dialog, dialog))
# ── history ─────────────────────────────────────────────────────────────
def _history(self, command: str, params: Dict) -> Any:
"""⛔ goBack / goForward / reload are sent to the PAGE, not the Frame.
@@ -3183,8 +3395,15 @@ class PageDispatcher(Dispatcher):
# ── pointer and keyboard ──────────────────────────────────────────
def op_mouse_move(self, params: Dict) -> Any:
self.actions.move(params["x"], params["y"],
steps=params.get("steps") or 1)
# ⛔ AN EXPLICIT MOVE IS THE CALLER'S: it is walked only when the
# in-process client says so (`humanise`, see `_cursor._wrap_mouse_move`),
# which is how it has always moved its own pointer. A client that does
# not say so - a Go, Node or stock Python Playwright - gets exactly the
# point it named, and the server adds nothing to it.
steps = params.get("steps") or 1
if params.get("humanise") is True and steps <= 1 and self.pointer:
self.pointer.move(params["x"], params["y"])
self.actions.move(params["x"], params["y"], steps=steps)
return None
def op_mouse_down(self, params: Dict) -> Any:
@@ -3198,12 +3417,24 @@ class PageDispatcher(Dispatcher):
return None
def op_mouse_click(self, params: Dict) -> Any:
self.actions.click_at(params["x"], params["y"],
button=_button(params.get("button")),
clicks=params.get("clickCount") or 1)
# The stroke to the point, then the click: the walk is the hand's
# (`Pointer.click_at`), as `Mouse._click` used to make it on the client.
def click() -> Any:
return self.actions.click_at(
params["x"], params["y"],
button=_button(params.get("button")),
clicks=params.get("clickCount") or 1)
if self.pointer is None:
click()
else:
self.pointer.click_at(params["x"], params["y"], click)
return None
def op_mouse_wheel(self, params: Dict) -> Any:
if self.pointer is not None and self.pointer.wheel(
params["deltaX"], params["deltaY"]):
return None
self.actions.wheel(params["deltaX"], params["deltaY"])
return None
@@ -3238,6 +3469,8 @@ class PageDispatcher(Dispatcher):
def op_set_viewport_size(self, params: Dict) -> Any:
self.send("Page.setViewportSize", only_set(
{"viewportSize": params.get("viewportSize")}))
if params.get("viewportSize"):
self.viewport_size = params["viewportSize"]
return None
def op_emulate_media(self, params: Dict) -> Any:
@@ -3249,15 +3482,29 @@ class PageDispatcher(Dispatcher):
raising anything.
"""
out: Dict[str, Any] = {}
reset = False
for ours, theirs in (("colorScheme", "colorScheme"),
("reducedMotion", "reducedMotion"),
("forcedColors", "forcedColors"),
("contrast", "contrast"),
("media", "type")):
value = params.get(ours)
if value is not None:
out[theirs] = value
if not out:
if value is None:
continue
# ⛔ "no-override" IS THE CALLER TAKING A FEATURE BACK, NOT A VALUE.
# Playwright's `emulateMedia({colorScheme: null})` arrives so, and
# the engine's enum has no such member: it refuses it by name. What
# it means is "nothing imposed", which for the engine is the field
# left out (the call replaces the page's whole emulation) or, for
# the medium, the empty type. The scheme then goes back to what the
# persona declared, never to the host.
if value == NO_OVERRIDE:
reset = True
if ours == "media":
out[theirs] = ""
continue
out[theirs] = value
if not out and not reset:
return None
self.send("Page.setEmulatedMedia", out)
return None
@@ -3329,8 +3576,10 @@ class PageDispatcher(Dispatcher):
"""⛔ `Heap.collectGarbage` really does collect, and it is SLOW - it was
once used as a "bare command" to measure transport latency and reported
26,8 ms of browser work as if it were ours. It is the right command
here, and the wrong one to benchmark with."""
self.conn.send("Heap.collectGarbage", {}, timeout=None)
here, and the wrong one to benchmark with. Sent with this page's session
(`self.send`): Juggler answers it from its PAGE handler, and the browser-level
connection (`self.conn`) gets 'Handler for does not implement method'."""
self.send("Heap.collectGarbage", {}, timeout=None)
return None
def op_add_script_tag(self, params: Dict) -> Any:
@@ -3710,12 +3959,13 @@ class StreamDispatcher(Dispatcher):
self._file.close()
return None
def dispose(self, reason: Optional[str] = None) -> None:
def released(self) -> None:
"""⛔ ALSO WHEN A PARENT'S DISPOSE FORGETS IT (`Dispatcher.dispose`
does not call `dispose` on a descendant): the file stayed open."""
try:
self._file.close()
except Exception:
pass
super().dispose(reason)
class ArtifactDispatcher(Dispatcher):
@@ -3750,6 +4000,12 @@ class ArtifactDispatcher(Dispatcher):
self.error = error
self.finished.set()
def released(self) -> None:
"""⛔ THE BROWSER'S INDEX BY UUID LET GO TOO: it kept every download of
every context for the life of the browser, the path and the Event
with it."""
self.parent.browser._artifacts.pop(self.uuid, None)
def _wait(self) -> None:
while not self.finished.wait(0.2):
if self.disposed:
@@ -3847,6 +4103,14 @@ class BrowserContextDispatcher(Dispatcher):
})
for child in (debugger, request_context, tracing):
self.emit("__adopt__", {"guid": child.guid})
# ⛔ ADOPTED ON THE WIRE, AND ADOPTED HERE TOO. They were announced
# under the browser (the client needs a parent it already knows) and
# adopted by the context, and `dispose` forgets a subtree by walking
# `parent`: left at the browser, the three outlived every context
# that made them, three registry entries per context for the life of
# the browser (measured at 500 contexts: 1,500). The page does the
# same with its main frame. The wire does not change.
child.parent = self
self.pages: List[PageDispatcher] = []
self.intercepting = False
#: The caller's context-level init scripts, in order. The engine's
@@ -3857,6 +4121,15 @@ class BrowserContextDispatcher(Dispatcher):
def conn(self) -> "juggler.Connection":
return self.browser.conn
def released(self) -> None:
"""⛔ THE BROWSER'S LIST LET GO TOO. Every way a context ends passes
here, and `browser.contexts` kept each one - with its options, its
owner (the connection that made it, and through it the socket) and
its init scripts - for the life of the browser."""
try:
self.browser.contexts.remove(self)
except ValueError:
pass
def op_context_init_script(self, params: Dict) -> Any:
"""The same, for every page of this context - present and future.
@@ -3936,6 +4209,12 @@ class BrowserContextDispatcher(Dispatcher):
self.browser.require_interception("context.route()")
self._browser_send("Browser.setRequestInterception",
{"enabled": wanted})
# ⛔ THE CACHE GOES OFF WITH THE FIRST ROUTE AND BACK ON WITH THE LAST,
# as upstream does: `ffBrowser.ts` `doUpdateRequestInterception` sends
# `Browser.setCacheDisabled` with the same flag, for the same context.
# Without it a routed session fills the engine's cache2 on disk.
self._browser_send("Browser.setCacheDisabled",
{"cacheDisabled": wanted})
self.intercepting = wanted
return None
@@ -4030,8 +4309,8 @@ class BrowserContextDispatcher(Dispatcher):
def op_grant_permissions(self, params: Dict) -> Any:
self._browser_send("Browser.grantPermissions",
{"origin": params.get("origin") or "",
"permissions": params.get("permissions") or []})
{"origin": params.get("origin") or "*",
"permissions": _engine_permissions(params.get("permissions") or [])})
return None
def op_clear_permissions(self, params: Dict) -> Any:
@@ -4111,6 +4390,12 @@ class BrowserContextDispatcher(Dispatcher):
return None
# The value Playwright's client sends for "this option is not overridden".
NO_OVERRIDE = "no-override"
# The context options whose enum the engine does not extend with it.
NO_OVERRIDE_OPTIONS = ("colorScheme", "reducedMotion", "forcedColors")
class BrowserDispatcher(Dispatcher):
TYPE = "Browser"
METHODS = {"newContext": "op_new_context", "close": "op_close",
@@ -4120,8 +4405,12 @@ class BrowserDispatcher(Dispatcher):
conn: Any, version: str, session_seed: Any = None,
motion_budget_s: Any = None,
service_workers_enabled: bool = True,
layout: str = "us") -> None:
layout: str = "us", pointer_draws: bool = False) -> None:
self.conn = conn
#: Whether this browser's pages walk the pointer onto their targets
#: (`pointer.py`): the launcher chose the Python generator. Off for a
#: browser built without saying so, which acts as the caller wrote.
self.pointer_draws = pointer_draws
#: The keyboards the persona types on, from the session's language
#: (`keyboard.profiles_for`, LANGID:KLID joined by semicolons): one set per
#: session, whatever a context later says its language is.
@@ -4684,6 +4973,17 @@ class BrowserDispatcher(Dispatcher):
value = params.get(name)
if value in (None, ""):
continue
# ⛔ "no-override" IS NOT A SCHEME, A MOTION OR A COLOUR MODE. The Go
# client (and `new_context(color_scheme=None)` in the Python one)
# sends it for a context that asks for nothing, and Playwright's own
# server reads it as "no override". Passing it on made the engine
# refuse the whole context (`Expected <root>.colorScheme to be one
# of [dark, light, no-preference]`). Nothing is sent: the context
# keeps the persona's declaration (`ui.systemUsesDarkTheme`), which
# is what a context with no override is for. An explicit "dark",
# "light" or "no-preference" still goes out, as before.
if name in NO_OVERRIDE_OPTIONS and value == NO_OVERRIDE:
continue
if name == "locale":
# ⛔ THE ENGINE TAKES A LANGUAGE LIST, NOT A TAG. The context's
# locale becomes the BrowsingContext's LanguageOverride, which
@@ -4770,7 +5070,7 @@ class BrowserDispatcher(Dispatcher):
# accident that works until somebody tightens that condition.
self._context_send("Browser.grantPermissions",
{"browserContextId": context_id, "origin": "*",
"permissions": permissions})
"permissions": _engine_permissions(permissions)})
viewport = params.get("viewport")
if viewport:
# ⛔ `screen` is a SEPARATE option from `viewport` and rides in
@@ -4915,6 +5215,10 @@ class BrowserDispatcher(Dispatcher):
class BrowserTypeDispatcher(Dispatcher):
TYPE = "BrowserType"
#: The class `launch` builds; None means `BrowserDispatcher`. A subclass
#: names its own: `remote.py` serves ONE browser to many clients, and its
#: `close` must not end the browser.
browser_class: Any = None
METHODS = {"launch": "op_launch",
"launchPersistentContext": "op_launch_persistent",
}
@@ -5002,8 +5306,12 @@ class BrowserTypeDispatcher(Dispatcher):
# raise, and until B223 the removal was registered only after both, so
# those sessions kept their profile. `after_shutdown` runs once
# `conn.close` has waited for the browser to exit.
files = SessionFiles(params.get("userDataDir"),
_launch_environment(params.get("env")))
launch_prefs, session_env = session_for_launch(
params.get("firefoxUserPrefs") or {}, executable, params.get("proxy"))
environment = _launch_environment(params.get("env"))
named = {e["name"] for e in params.get("env") or []}
environment.update({k: v for k, v in session_env.items() if k not in named})
files = SessionFiles(params.get("userDataDir"), environment)
self.server.after_shutdown(files.remove)
env, profile = files.env, files.profile
# ⛔ THE TYPING SEED TRAVELS IN THE PREFS AND IS TAKEN OUT AGAIN HERE,
@@ -5019,8 +5327,8 @@ class BrowserTypeDispatcher(Dispatcher):
# means "the patched binary reads this", and a reader who found a
# typing key under it would go looking in C++ for something that is
# answered in Python.
prefs, session_seed, motion_budget_s = take_session_motion(
params.get("firefoxUserPrefs") or {})
pointer_draws = session_draws_pointer(launch_prefs)
prefs, session_seed, motion_budget_s = take_session_motion(launch_prefs)
# The keyboard the session decided, out of the prefs before the
# profile sees them; without it, the language alone decides.
keyboard_layout = prefs.pop(KEYBOARD_LAYOUT_PREF, None) or profiles_pref(
@@ -5057,8 +5365,8 @@ class BrowserTypeDispatcher(Dispatcher):
# ⛔ THE PROXY IS SET BY THE CORE'S `launch`, before any page exists,
# and a proxy the engine refuses closes the browser there: the driver
# once accepted `proxy=` and dropped it, and a page went out on the
# host address while the session's timezone, locale and WebRTC
# candidate had been resolved THROUGH the proxy (2026-08-30). Until
# host address while the session's timezone and locale
# had been resolved THROUGH the proxy (2026-08-30). Until
# 0.34.0 this method sent the command itself, as Selenium's and
# Puppeteer's launch did, each with the same fixed 10 s.
conn = juggler.launch(executable, profile,
@@ -5071,7 +5379,7 @@ class BrowserTypeDispatcher(Dispatcher):
# nobody will close before the server shuts down.
try:
version = read_version(executable)
browser = BrowserDispatcher(
browser = (self.browser_class or BrowserDispatcher)(
self.server, self, conn, version, session_seed=session_seed,
motion_budget_s=motion_budget_s,
service_workers_enabled=prefs.get(
@@ -5079,7 +5387,7 @@ class BrowserTypeDispatcher(Dispatcher):
# The persona's keyboard: the one a Windows install gives the
# session's language in its country (German in Switzerland
# types on the Swiss keyboard).
layout=keyboard_layout)
layout=keyboard_layout, pointer_draws=pointer_draws)
except BaseException:
conn.close()
raise
+44 -99
View File
@@ -53,6 +53,8 @@ from typing import Any, Dict, Optional
from invisible_playwright._pw._impl._helper import parse_error
from invisible_playwright._pw._impl._transport import Transport
from . import wire
def _error_payload(failure: BaseException) -> Dict[str, str]:
"""The `{name, message, stack}` shape both an error REPLY and a
@@ -84,19 +86,6 @@ def _translate_exception(failure: BaseException) -> BaseException:
return parse_error(_error_payload(failure))
def _settle_result(future: asyncio.Future, result: Any) -> None:
"""⛔ Guarded: a future the caller already cancelled must not be resolved
again - `asyncio.Future.set_result` on a cancelled future raises, and this
runs on the loop where that exception would have nowhere useful to go."""
if not future.done():
future.set_result(result)
def _settle_exception(future: asyncio.Future, failure: BaseException) -> None:
if not future.done():
future.set_exception(failure)
class InProcessTransport(Transport):
"""A `Transport` whose other end is a Python object, not a subprocess."""
@@ -114,85 +103,6 @@ class InProcessTransport(Transport):
self._threads: list = []
server.attach(self)
# ── the fused-type escape hatch ──────────────────────────────────────────
def bind_impl_objects(self, objects: Dict[str, Any],
deliver_event: Any) -> None:
"""Give the server a live view of the CLIENT's guid registry, and its
way to deliver an event under the correct execution context.
⛔ THE ONLY BRIDGE BETWEEN THE TWO GRAPHS. `objects` is a REFERENCE,
not a copy: the client mutates it in place as it creates and disposes
things, so this always sees the CURRENT state with nothing to go
stale. It exists because a FUSED type - one with no `__create__` and no
guid of its own - still needs to reach the live impl-side object a
SIBLING guid corresponds to (a Dialog needs its Page's twin, to find
the BrowserContext to notify).
⛔ AND `deliver_event` IS NOT OPTIONAL EITHER, found by an actual
dialog hanging rather than by the unit suite. `Connection.dispatch`
wraps every wire event in an `EventGreenlet` under the sync facade, so
a handler that calls an async method (`dialog.accept()`) can suspend
into it and resume. A fused type delivers its event directly, never
through `dispatch`, so without this it never gets that wrapping - and
the handler hangs with no exception, because it suspended into a fiber
with nobody on the other end of the switch. Dialog is the first user
of both, 2026-08-29.
"""
self._server.bind_twins(objects, deliver_event)
def run_blocking(self, fn: Any, *args: Any) -> asyncio.Future:
"""Run `fn(*args)` on this transport's OWN worker pool; return an
awaitable that resolves on the LOOP once it is done.
⛔ THE SAME POOL AS EVERY CHANNEL MESSAGE, on purpose: a fused type's
blocking call and a channel-routed call must never be able to starve
each other by running on separate pools with separate limits. `_work`
below accepts a plain callable exactly as it accepts a message dict,
from the SAME queue, serviced by the SAME four threads.
⛔ AND THE EXCEPTION IS TRANSLATED, not passed through raw. `fn` runs
`_juggler` code and can raise `_juggler.dispatcher.TargetClosedError` -
a DIFFERENT CLASS than `_pw._impl._errors.TargetClosedError` with the
SAME NAME. A fused type's own exception handling
(`is_target_closed_error`) checks the FORK's class by `isinstance`, so
a raw `_juggler` exception reaching it would look like an ordinary
error and never be swallowed - reproducing, through this new path, the
exact regression fixed on 2026-08-29 in `Page.close()`. The
translation below goes through `parse_error`, the same one the
message-envelope path already uses: not a second way of doing it, the
one way, reused.
"""
future: asyncio.Future = self._loop.create_future()
def job() -> None:
try:
result = fn(*args)
except Exception as failure:
translated = _translate_exception(failure)
self._loop.call_soon_threadsafe(_settle_exception, future,
translated)
else:
self._loop.call_soon_threadsafe(_settle_result, future, result)
self._queue.put(job)
return future
def call_soon(self, fn: Any, *args: Any) -> None:
"""Hand a call to the LOOP thread, fire-and-forget - the
construction half of what `run_blocking` does for a call whose
RESULT matters. A fused type's incoming EVENT (a dialog that just
opened, built on the connection's read-loop thread) needs this to
reach the code that must run on the asyncio loop, exactly like every
message this transport already delivers via `emit_message` below -
just carrying a real object instead of a wire message.
"""
if self._stopped.is_set():
return
try:
self._loop.call_soon_threadsafe(fn, *args)
except RuntimeError:
pass # the loop is already closed; nobody is left to receive it
# ── the five methods the seam declares ──────────────────────────────────
async def connect(self) -> None:
for i in range(self.WORKERS):
@@ -241,13 +151,6 @@ class InProcessTransport(Transport):
item = self._queue.get()
if item is None:
return
# ⛔ A PLAIN CALLABLE IS A JOB FROM `run_blocking`, and a dict is a
# channel message: the same queue, the same four threads, told
# apart by shape rather than by a second queue that would split
# the pool in two.
if callable(item):
item()
continue
message = item
try:
result = self._server.handle(message)
@@ -302,6 +205,43 @@ class InProcessTransport(Transport):
out["log"] = list(log)
self.emit_message(out)
class JsonWireTransport(InProcessTransport):
"""`InProcessTransport` with the wire between the two ends: every message crosses as the
JSON text a socket would carry, in both directions.
⛔ THIS IS THE CHECK, NOT THE SOCKET. The remote transport (`remote.py`) sends the same
text over a WebSocket; this class sends it between two Python objects, so the whole
existing suite can run on it with no network and no second process, and any value that
JSON would change or lose (`wire.py`) fails here, at the line that built it, naming the
path inside the message.
A client message that is not JSON raises from `send` to its caller. A server REPLY that
is not JSON becomes an error reply for the same id (so the call that caused it fails
with the path in its message); a server EVENT that is not JSON cannot be answered, so it
is dropped and recorded in `wire_errors`, which a test asserts empty.
"""
def __init__(self, loop: asyncio.AbstractEventLoop, server: Any) -> None:
super().__init__(loop, server)
self.wire_errors: list = []
def send(self, message: Dict) -> None:
super().send(wire.round_trip(message))
def emit_message(self, message: Dict) -> None:
try:
carried = wire.round_trip(message)
except wire.WireError as problem:
self.wire_errors.append(problem)
msg_id = message.get("id") if isinstance(message, dict) else None
if msg_id is not None and "error" not in message:
super().emit_message({"id": msg_id, "error": {"error": {
"name": "Error", "message": "the reply is not JSON: %s" % problem,
"stack": ""}}})
return
super().emit_message(carried)
# ── choosing one ────────────────────────────────────────────────────────────
#
# ⛔ THIS WAS A MODULE OF ITS OWN UNTIL 2026-08-29, and what it chose between
@@ -320,6 +260,9 @@ class InProcessTransport(Transport):
# shell, and "unknown transport" would tell them nothing about what happened.
CHOICE_ENV = "INVPW_TRANSPORT"
#: `json` puts the wire between the client and the server (`JsonWireTransport`), as it is
#: for a remote client. Off by default: local use passes the dicts as it always did.
WIRE_ENV = "INVPW_WIRE"
DRIVER = "driver"
JUGGLER = "juggler"
@@ -342,4 +285,6 @@ def make_transport(loop: asyncio.AbstractEventLoop) -> "InProcessTransport":
"INVPW_DRIVER_TREE at it. Both `judge_both_transports.py` and "
"`diff_protocol.py` read that variable." % CHOICE_ENV)
from .server import JugglerServer
if (os.environ.get(WIRE_ENV) or "").strip().lower() == "json":
return JsonWireTransport(loop, JugglerServer())
return InProcessTransport(loop, JugglerServer())
@@ -0,0 +1,97 @@
"""The shapes a message takes across Playwright's protocol versions, brought to
the one this server reads.
⛔ ONE PLACE, AT THE ENTRANCE. The client is whatever version the caller has
installed, and the protocol moved between versions: in 1.62 the `timeout` left
the parameters of nearly every command and went to the call's metadata, and a
few commands and optional fields were added. Reading each variant where the
operation uses it would put a second spelling of every timeout in a hundred
places; folding them here means `server.py` reads one shape, `_caller_timeout`
reads `params["timeout"]` as it always did, and a new version is a change to
this file.
⛔ NO VERSION IS ASKED FOR, AND NONE IS REFUSED. The two forms do not conflict
- a message carries its timeout in the parameters or in the metadata, never
meaningfully in both - so the message is read by what it contains: a timeout in
the parameters wins, one in the metadata fills the gap, and a field this
server does not know is carried along unread, as the protocol's own optional
fields are.
What each 1.62 addition becomes here:
* `metadata.timeout` (milliseconds, `0` = no limit, as in the parameters):
read into `params["timeout"]` when the parameters carry none.
* `scroll` ("auto" | "none") on click, dblclick, hover, tap, check, uncheck,
dragAndDrop: IGNORED ON PURPOSE. Every pointer action here scrolls the
target into view first, which is `auto`; `none` asks to act on the element
where it is, and honouring it needs an action path that does not scroll,
which does not exist. The action still happens, scrolled.
* `noGlobal` on exposeBinding: moot, `exposeBinding` is refused as a whole.
* `type` "webp" on screenshot: REFUSED. The engine captures PNG and JPEG, and
answering a webp request with PNG bytes would hand the caller a file that
is not the format it asked for.
* `selector` / `strict` on waitForFunction (the predicate runs against an
element): REFUSED when a selector is given. Running the predicate without
the element would answer a different question.
* `credentials` (virtual WebAuthn credentials) in storageState,
setStorageState and a context's `storageState`: REFUSED when asked for or
given; WebAuthn is outside the perimeter (see `perimeter.py`). `False`,
`None` and an empty list are not a request and pass.
* `Page.screencastFrameAck`: ACCEPTED AND DOES NOTHING (`PageDispatcher`
answers it with `op_noop`). This server acknowledges a frame to the engine
itself as soon as it has relayed it, so there is no frame held back for the
client to release; a client that acknowledges every frame, as 1.62's does,
must not be failed for that.
* `Frame.drop`: already answered by `FrameDispatcher.op_drop`, which refuses
it with its own reason (the engine has no command for it).
"""
from __future__ import annotations
from typing import Any, Dict, Optional
def _metadata_timeout(metadata: Dict) -> Optional[float]:
wanted = metadata.get("timeout")
if isinstance(wanted, bool) or not isinstance(wanted, (int, float)):
return None
return float(wanted) if wanted >= 0 else None
def _refuse(reason: str):
# Imported here: `dispatcher.py` imports this module.
from .dispatcher import ProtocolException
raise ProtocolException(reason)
def _present(value: Any) -> bool:
"""A request for something, as opposed to false, null or an empty list."""
return bool(value)
def to_internal(method: Optional[str], params: Dict, metadata: Dict) -> Dict:
"""`params` in the shape the operations read, or a refusal naming why this
one command is not served. `params` itself is never changed."""
out = dict(params)
if out.get("timeout") is None:
out.pop("timeout", None)
wanted = _metadata_timeout(metadata or {})
if wanted is not None:
out["timeout"] = wanted
if method in ("screenshot", "expectScreenshot") and out.get("type") == "webp":
_refuse("a webp screenshot is not available: the engine captures PNG "
"and JPEG only, and a PNG sent as webp would be a file that is "
"not the format asked for")
if method == "waitForFunction" and out.get("selector"):
_refuse("wait_for_function() on an element (a selector) is not "
"available: the predicate would run without the element it "
"was written for")
if method in ("storageState", "setStorageState", "newContext",
"launchPersistentContext"):
state = out.get("storageState")
if _present(out.get("credentials")) or (
isinstance(state, dict) and _present(state.get("credentials"))):
_refuse("virtual credentials in a storage state are not available: "
"WebAuthn is outside the perimeter this package covers")
return out
+86
View File
@@ -0,0 +1,86 @@
"""The wire form of a protocol message: JSON, and nothing a socket cannot carry.
Today the client and the server of this package pass each other Python dicts in the
same process (`transport.InProcessTransport`). That is why nothing has ever checked that
a message is JSON: a `bytes`, a tuple of objects, a NaN or an impl object can sit in one
and travel without a word. A message that goes through a WebSocket (`remote.py`) is a
string, so the first such value is a failure that shows up far from the line that put it
there.
`dumps` therefore refuses what JSON would change or lose, and names WHERE it is
(`$.params.payloads[0].buffer`), which is the one thing a bare `TypeError: Object of type
bytes is not JSON serializable` does not say:
- `bytes`, `bytearray`, sets and any object that is not a plain value;
- a key that is not a string (`json` would turn 1 into "1" and the reader would look
up the wrong key);
- NaN and the infinities (not JSON; Playwright's own protocol sends them as
`{"v": "NaN"}` inside serialised values, never as a bare number).
A tuple is accepted: it is a JSON array and reads back as a list, which is what a client
on the other end of a socket would see anyway.
Playwright's own protocol carries binary as a base64 string, so a server that wants to
send bytes encodes them where it builds the message; it is never this module's job to
guess that.
"""
from __future__ import annotations
import json
import math
from typing import Any, Optional
class WireError(TypeError):
"""A value in a message that JSON would change or lose. `path` says where."""
def __init__(self, path: str, reason: str) -> None:
super().__init__("%s: %s" % (path, reason))
self.path = path
self.reason = reason
def first_problem(value: Any, path: str = "$") -> Optional[WireError]:
"""The first value under `value` that is not plain JSON, or None."""
if value is None or isinstance(value, (bool, str)):
return None
if isinstance(value, int):
return None
if isinstance(value, float):
if math.isnan(value) or math.isinf(value):
return WireError(path, "%r is not JSON" % value)
return None
if isinstance(value, dict):
for key, item in value.items():
if not isinstance(key, str):
return WireError("%s[%r]" % (path, key),
"a key must be a string, not %s" % type(key).__name__)
problem = first_problem(item, "%s.%s" % (path, key))
if problem:
return problem
return None
if isinstance(value, (list, tuple)):
for index, item in enumerate(value):
problem = first_problem(item, "%s[%d]" % (path, index))
if problem:
return problem
return None
return WireError(path, "%s is not a JSON value" % type(value).__name__)
def dumps(message: Any) -> str:
"""The message as the text that crosses the wire. Raises `WireError`."""
problem = first_problem(message)
if problem:
raise problem
return json.dumps(message, separators=(",", ":"), allow_nan=False)
def loads(text: "str | bytes") -> Any:
"""The message a text carries."""
return json.loads(text)
def round_trip(message: Any) -> Any:
"""What the other end of a socket would read: `loads(dumps(message))`."""
return loads(dumps(message))
+1 -2
View File
@@ -23,10 +23,9 @@ also where the repository's English gate reads it.
|---|---|
| `_impl/_browser.py` | the numbers of the pages the script asks for, 0, 1, 2, in the order of the calls, reserved before the first `await`; the only counter of them |
| `_impl/_browser_context.py` | each page the script asks for carries its number in the session, reserved on the client at the moment of the call, where the order of the calls exists |
| `_impl/_connection.py` | the execution-context guarantee is extracted out of `dispatch`, so a fused type (`Dialog`) gets it too: without it a sync `dialog.accept()` inside the `dialog` callback hangs |
| `_impl/_playwright.py` | asking for `chromium` or `webkit` raises a `ValueError` that says they were removed, not disabled |
| `sync_api/_generated.py`, `async_api/_generated.py` | the `chromium` and `webkit` properties raise `NotImplementedError` with the same explanation, instead of an `AttributeError` |
| `sync_api/_context_manager.py`, `async_api/_context_manager.py` | the transport comes from `make_transport` (the in-process server), and the impl-side objects are bound for the fused types |
| `sync_api/_context_manager.py`, `async_api/_context_manager.py` | the transport comes from `make_transport` (the in-process server) |
Everything else is upstream, byte for byte.
@@ -214,16 +214,10 @@ class BrowserContext(ChannelOwner):
lambda event: self._on_console_message(event),
)
# ⛔ NO "dialog" CHANNEL LISTENER HERE SINCE 2026-08-29, and its absence
# is the point. `Dialog` was fused (see `_dialog.py`): it has no guid,
# no `__create__`, and nothing on either side ever emits a wire
# "dialog" event any more, so this registration could not fire. It was
# left behind by the fusion commit, which cleaned up the matching dead
# branch in `_object_factory.py` and missed this one.
# The sole delivery path is now `PageDispatcher._emit_fused_dialog` in
# `_juggler/server.py`, which calls `_on_dialog` below directly across
# the thread boundary. `scripts/diff_protocol.py` records the wire-level
# consequence permanently, as an argued entry in EXPECTED_DIFFERENCES.
self._channel.on(
"dialog",
lambda params: self._on_dialog(from_channel(params["dialog"])),
)
self._channel.on(
"pageError",
lambda params: self._on_page_error(
@@ -738,20 +732,14 @@ class BrowserContext(ChannelOwner):
if page:
has_listeners = page.emit(Page.Events.Dialog, dialog) or has_listeners
if not has_listeners:
# ⛔ THIS IS THE ONLY AUTO-ANSWER IN THE PRODUCT, and the reason it
# exists is not the one upstream wrote here. Upstream's comment
# said this guarded a race between a) the client unsubscribing
# from "dialog" and b) the server sending one anyway - a race that
# cannot happen since the 2026-08-29 fusion, because there is no
# subscription and no wire event left to race with.
#
# It stays because `_juggler` has NO server-side auto-answer of
# its own: upstream's note that "we do similar handling on the
# server side" was true of the Node driver and is false here.
# An unanswered dialog leaves the content process sitting inside
# `window.alert`, and the failure surfaces as an unrelated command
# timing out - measured 2026-08-28 as `Runtime.callFunction: no
# response in 30s`. Deleting this is a hang, not a leak.
# ⛔ THIS IS THE ONLY AUTO-ANSWER IN THE PRODUCT. `_juggler` has NO
# server-side auto-answer of its own (upstream's note that "we do
# similar handling on the server side" was true of the Node driver
# and is false here). An unanswered dialog leaves the content
# process sitting inside `window.alert`, and the failure surfaces
# as an unrelated command timing out - measured 2026-08-28 as
# `Runtime.callFunction: no response in 30s`. Deleting this is a
# hang, not a leak.
if dialog.type == "beforeunload":
asyncio.create_task(dialog.accept())
else:
@@ -463,57 +463,35 @@ class Connection(EventEmitter):
object = self._objects[guid]
should_replace_guids_with_channels = "jsonPipe@" not in guid
try:
transformed_params = (
self._replace_guids_with_channels(params)
if should_replace_guids_with_channels else params
)
if self._is_sync:
for listener in object._channel.listeners(method):
self.deliver_event(listener, transformed_params)
# Event handlers like route/locatorHandlerTriggered require us to perform async work.
# In order to report their potential errors to the user, we need to catch it and store it in the connection
def _done_callback(future: asyncio.Future) -> None:
exc = future.exception()
if exc:
self._on_event_listener_error(exc)
def _listener_with_error_handler_attached(params: Any) -> None:
potential_future = listener(params)
if asyncio.isfuture(potential_future):
potential_future.add_done_callback(_done_callback)
# Each event handler is a potentilly blocking context, create a fiber for each
# and switch to them in order, until they block inside and pass control to each
# other and then eventually back to dispatcher as listener functions return.
g = EventGreenlet(_listener_with_error_handler_attached)
if should_replace_guids_with_channels:
g.switch(self._replace_guids_with_channels(params))
else:
g.switch(params)
else:
object._channel.emit(method, transformed_params)
except BaseException as exc:
self._on_event_listener_error(exc)
def deliver_event(self, fn: Callable[..., Any], *args: Any) -> None:
"""Call `fn(*args)` the same way a wire event calls a listener:
wrapped in its own `EventGreenlet` under the sync facade, so a
handler that calls an async method (`dialog.accept()`) can properly
suspend into it and resume; called directly under the async facade
otherwise.
# MODIFIED by invisible_playwright: extracted out of `dispatch`'s own
# sync branch above, which used to inline this. A FUSED type (Dialog,
# 2026-08-29) delivers its own events directly - it never goes through
# `dispatch` at all, since there is no `__create__`/guid for it to
# arrive under - but it still needs the SAME execution-context
# guarantee: without it, a sync-mode `dialog.accept()` called from
# inside the "dialog" callback hangs. It suspends into a fiber
# expecting the dispatcher fiber on the other end of the switch, and a
# bare `call_soon_threadsafe` callback is not that fiber - found live,
# not by the unit suite, which stubs this whole path out. One
# definition now serves both the wire path and the fused path,
# instead of the fused path copying it and the two silently drifting.
"""
try:
if self._is_sync:
def _done_callback(future: asyncio.Future) -> None:
exc = future.exception()
if exc:
self._on_event_listener_error(exc)
def _with_error_handler_attached(*a: Any) -> None:
potential_future = fn(*a)
if asyncio.isfuture(potential_future):
potential_future.add_done_callback(_done_callback)
# Each event handler is a potentially blocking context, create
# a fiber for it and switch, until it blocks inside and passes
# control back to the dispatcher as the listener returns.
g = EventGreenlet(_with_error_handler_attached)
g.switch(*args)
else:
fn(*args)
if should_replace_guids_with_channels:
object._channel.emit(
method, self._replace_guids_with_channels(params)
)
else:
object._channel.emit(method, params)
except BaseException as exc:
self._on_event_listener_error(exc)
+18 -87
View File
@@ -12,120 +12,51 @@
# See the License for the specific language governing permissions and
# limitations under the License.
"""⛔ FUSED, 2026-08-29: no `__create__`, no guid, no channel.
Until this date `Dialog` was a `ChannelOwner`, built by `_object_factory.py`
from a `{parent, type, guid, initializer}` the server announced over the
wire, and `accept`/`dismiss` sent a message back the same way. That round
trip earned its keep when the other end was a real process; it no longer
does when the other end is `_juggler`, in the same process.
⛔ IT IS STILL A PLAIN CLASS AND NOT A `ChannelOwner` on purpose, not by
omission: nothing in this codebase ever passes a `Dialog` back INTO a Juggler
call as a parameter (checked against the 2026-08-29 channel-call inventory of
all 351 sites in `_impl`), and `ImplToApiMapping.from_maybe_impl` wraps by
Python TYPE, not by `ChannelOwner`-ness - `mapping.register(Dialog,
sync_api.Dialog)` keeps working unchanged as long as this stays importable
from here under the same name.
⛔ THERE IS NOW EXACTLY ONE WAY THIS GETS CONSTRUCTED.
`_juggler/server.py`'s `PageDispatcher._emit_fused_dialog` builds one on the
connection's read-loop thread. `_object_factory.py` has no `Dialog` case in
its if/elif chain at all any more - the branch was deleted outright, and a
comment marking its absence is the only trace, kept so nobody re-adds the old
four-argument `(parent, type, guid, initializer)` call out of habit. That
signature no longer matches this class's constructor, so a revived branch
would fail in a way that points nowhere near the real cause.
⛔ AND DELIVERING IT IS TWO HOPS, NOT ONE, found by an actual dialog hanging
with no exception. `Server.call_soon` gets to the asyncio loop thread from
the read loop; once there, `Server.deliver` (not a bare call) runs
`BrowserContext._on_dialog` under `Connection.deliver_event`'s rules - which
wraps it in its own `EventGreenlet` under the sync facade, exactly as
`dispatch` wraps every wire event. Skipping that second hop is invisible
right up until a handler calls an async method (`dialog.accept()`): it
suspends into a fiber with nobody on the other end of the switch.
`accept`/`dismiss` cross back into `_juggler` through
`PageDispatcher.send_async`, which runs the call on the SAME worker pool
every other Juggler operation blocks on, and translates a `_juggler`-side
exception into this fork's own exception classes before it reaches
`is_target_closed_error` below - skipping that translation would silently
un-fix the exact regression closed in `Page.close()` earlier the same day.
"""
from typing import TYPE_CHECKING, Optional
from typing import TYPE_CHECKING, Dict, Optional
from invisible_playwright._pw._impl._connection import ChannelOwner, from_nullable_channel
from invisible_playwright._pw._impl._errors import is_target_closed_error
from invisible_playwright._pw._impl._helper import locals_to_params
if TYPE_CHECKING: # pragma: no cover
from invisible_playwright._pw._impl._page import Page
from invisible_playwright._juggler.server import PageDispatcher
class Dialog:
def __init__(self, page_dispatcher: "PageDispatcher", page: "Page",
dialog_id: str, kind: str, message: str,
default_value: str) -> None:
self._page_dispatcher = page_dispatcher
#: ⛔ RESOLVED ONCE, AT CONSTRUCTION, not looked up again on every
#: `.page` access. The caller (`_emit_fused_dialog`) already has it in
#: hand - it is how it found where to deliver this dialog in the
#: first place - so asking the twin registry a second time would be
#: the reach-through chain this refactor spent the day removing,
#: reintroduced in the one file it just added.
self._page = page
#: ⛔ NOT OPTIONAL, AND NOT OBVIOUS FROM THE PUBLIC API THIS CLASS
#: OFFERS: `SyncBase.__init__`/`AsyncBase.__init__` - the generated
#: `sync_api`/`async_api` wrapper this object is handed to on its way
#: to a listener - read `impl_obj._loop` unconditionally, and the sync
#: side also reads `impl_obj._dispatcher_fiber` to know which greenlet
#: to switch back to. A `ChannelOwner` gets both from its PARENT
#: (`self._loop = parent._loop`, in `_connection.py`); Dialog's old
#: parent was always its Page, so copying them from the same `page`
#: reproduces exactly the value a `ChannelOwner`-based Dialog would
#: have had. Missing this is not a slow failure: the very first
#: `page.on("dialog", ...)` callback raises `AttributeError` while
#: wrapping the object, before user code ever runs - found by an
#: actual dialog, not by the unit suite, which stubs this path out
#: entirely.
self._loop = page._loop
self._dispatcher_fiber = page._dispatcher_fiber
self._dialog_id = dialog_id
self._type = kind
self._message = message
self._default_value = default_value or ""
class Dialog(ChannelOwner):
def __init__(
self, parent: ChannelOwner, type: str, guid: str, initializer: Dict
) -> None:
super().__init__(parent, type, guid, initializer)
self._page: Optional["Page"] = from_nullable_channel(initializer.get("page"))
def __repr__(self) -> str:
return (f"<Dialog type={self.type} message={self.message} "
f"default_value={self.default_value}>")
return f"<Dialog type={self.type} message={self.message} default_value={self.default_value}>"
@property
def type(self) -> str:
return self._type
return self._initializer["type"]
@property
def message(self) -> str:
return self._message
return self._initializer["message"]
@property
def default_value(self) -> str:
return self._default_value
return self._initializer["defaultValue"]
@property
def page(self) -> Optional["Page"]:
return self._page
async def accept(self, promptText: str = None) -> None:
params = {"dialogId": self._dialog_id, "accept": True}
if promptText is not None:
params["promptText"] = promptText
await self._page_dispatcher.send_async("Page.handleDialog", params)
await self._channel.send("accept", None, locals_to_params(locals()))
async def dismiss(self) -> None:
try:
await self._page_dispatcher.send_async(
"Page.handleDialog",
{"dialogId": self._dialog_id, "accept": False})
await self._channel.send(
"dismiss",
None,
)
except Exception as e:
if is_target_closed_error(e):
return
@@ -21,6 +21,7 @@ from invisible_playwright._pw._impl._browser_type import BrowserType
from invisible_playwright._pw._impl._cdp_session import CDPSession
from invisible_playwright._pw._impl._connection import ChannelOwner
from invisible_playwright._pw._impl._debugger import Debugger
from invisible_playwright._pw._impl._dialog import Dialog
from invisible_playwright._pw._impl._disposable import Disposable
from invisible_playwright._pw._impl._element_handle import ElementHandle
from invisible_playwright._pw._impl._fetch import APIRequestContext
@@ -67,12 +68,8 @@ def create_remote_object(
return CDPSession(parent, type, guid, initializer)
if type == "Debugger":
return Debugger(parent, type, guid, initializer)
# ⛔ NO "Dialog" BRANCH HERE SINCE 2026-08-29, ON PURPOSE. `Dialog` fused
# into a plain class with a different constructor signature (see
# `_dialog.py`); no `__create__` for a dialog is ever sent any more, so
# this factory is never asked to build one. A branch calling the OLD
# four-argument form would be a landmine - reachable only if something
# regressed, and wrong in a way that points nowhere near the real cause.
if type == "Dialog":
return Dialog(parent, type, guid, initializer)
if type == "Disposable":
return Disposable(parent, type, guid, initializer)
if type == "ElementHandle":
@@ -39,12 +39,6 @@ class PlaywrightContextManager:
transport,
loop,
)
# MODIFIED by invisible_playwright: the one bridge between the two
# object graphs. See the sync entry point's `_context_manager.py` for
# why - this is the same line, needed for the same reason, on the
# other facade.
transport.bind_impl_objects(self._connection._objects,
self._connection.deliver_event)
loop.create_task(self._connection.run())
playwright_future = self._connection.playwright_future
@@ -68,15 +68,6 @@ Please use the Async API instead."""
transport,
self._loop,
)
# MODIFIED by invisible_playwright: the one bridge between the two
# object graphs. A FUSED type (Dialog, 2026-08-29) has no guid and no
# `__create__` of its own, and still needs to reach the live impl-side
# object a sibling guid corresponds to - see
# `InProcessTransport.bind_impl_objects` for why. `_connection._objects`
# is a reference, not a snapshot: it always reflects what has been
# created so far, including everything created after this line runs.
transport.bind_impl_objects(self._connection._objects,
self._connection.deliver_event)
g_self = greenlet.getcurrent()
+61 -27
View File
@@ -26,7 +26,7 @@ from ._cursor import (ENGINE_BINARY,
enable_for as _enable_cursor_engine,
max_seconds_for as _cursor_max_seconds)
from ._engine import resolve_executable
from ._juggler.server import MOTION_BUDGET_PREF, SESSION_SEED_PREF
from ._juggler.server import COMPOSED_PREF, MOTION_BUDGET_PREF, POINTER_PREF, SESSION_SEED_PREF
from typing import Any, Dict, Optional
from invisible_core import compose_session_prefs, context_geometry, make_virtual_display
@@ -65,6 +65,39 @@ __all__ = ["build_prefs", "true_headless_requested", "TRUE_HEADLESS_ENV",
TRUE_HEADLESS_ENV = "INVPW_TRUE_HEADLESS"
def session_geo(timezone: str, proxy: Optional[Dict[str, str]], locale: Any):
"""`invisible_core.prepare_session_geo`, the one network step of composing a
session (the egress IP). One name, so a hermetic test replaces it alone."""
from invisible_core import prepare_session_geo
return prepare_session_geo(timezone, proxy, locale)
def default_session(executable: Optional[str] = None,
proxy: Optional[Dict[str, str]] = None) -> "tuple[Dict[str, Any], Dict[str, str]]":
"""The session `InvisiblePlaywright()` composes with the server's defaults (a new
seed, the launch's proxy, locale "auto", humanize off: the default of `launch_server`, the
other entry that is a server), as (prefs, the variables of its environment).
The variables are what `build_env` adds to an environment, composed onto an
empty one: the font manifest, the WebRTC declaration, the display backend.
What `server.session_for_launch` gives a launch that names no session."""
from .launcher import InvisiblePlaywright
session = InvisiblePlaywright(binary_path=executable, humanize=False, proxy=proxy or None)
geo = session_geo(session._timezone, session._proxy, session._locale_requested)
session._timezone, session._locale = geo.timezone, geo.locale
prefs = session._build_prefs()
env = build_env(network_declared=declared_network(session), profile=session._profile,
executable=executable, base_env={})
return prefs, env
def declared_network(session: Any) -> str:
"""The host network this session declares to the engine (the value of
STEALTHFOX_WEBRTC_NETWORK), drawn from its seed, with or without a proxy."""
from invisible_core import network_to_declare
return network_to_declare(session.seed)
def true_headless_requested(env: Optional[Dict[str, str]] = None) -> bool:
return (env if env is not None else os.environ).get(TRUE_HEADLESS_ENV) == "1"
@@ -73,13 +106,9 @@ def true_headless_requested(env: Optional[Dict[str, str]] = None) -> bool:
#: lives. It was duplicated here byte-for-byte - ten entries, including the
def build_env(
*,
#: The address to DECLARE as srflx, or None to declare nothing and let the
#: real one through. ⛔ This is NOT the egress IP: it is a DECISION the
#: core makes in a single place, looking at the capabilities of the egress
#: (`SessionGeo.srflx_to_declare`). The old name, `egress_ip`, said
#: something else and made the rule look like "there's a proxy -> declare
#: it", which is the wrong question.
srflx_declared: Optional[str],
#: The host network the engine reads (STEALTHFOX_WEBRTC_NETWORK), drawn from
#: the session seed (`declared_network`); None declares nothing.
network_declared: Optional[str],
profile: Any = None,
executable: Optional[str] = None,
base_env: Optional[Dict[str, str]] = None,
@@ -140,7 +169,7 @@ def build_env(
f"(e.g. {missing[:3]}). Engine: {executable}. The metrics "
f"would describe fonts that are not there.")
manifest_path = cached_font_manifest_path(manifest)
return build_launch_env({}, srflx_declared=srflx_declared,
return build_launch_env({}, network_declared=network_declared,
manifest_path=manifest_path, base_env=base_env,
display_env=display_env)
@@ -217,24 +246,31 @@ def build_prefs(
# It follows `humanize`, like the cursor: a caller who turned human motion
# off asked for a machine, and giving them a hand on the keyboard anyway
# would be a second answer to a question they already answered.
# ⛔ AND THE MOTION BUDGET RIDES WITH IT, under exactly the same condition,
# for the one pointer movement the client cannot wrap: the travel of a drag,
# which happens with the button already down and whose far end is only
# resolved after the press. That movement is generated inside the server,
# so without this the caller's `humanize=<n>` would cap every click and be
# ignored by every drag.
# ⛔ AND THE MOTION BUDGET RIDES WITH IT, under exactly the same condition:
# it caps the walk the server draws before every pointer action
# (`_juggler/pointer.py`) and the travel of a drag, which happens with the
# button already down and whose far end is only resolved after the press.
# Both are generated inside the server, so the caller's `humanize=<n>` caps
# every click and every drag, whichever client sent them.
#
# The condition is shared and not merely similar: the server draws a path
# only when it has the seed, so a budget without one would cap a movement
# nobody is making.
#
# ⛔ AND WHO DRAWS THE WALK TRAVELS TOO (`POINTER_PREF`): with the seed
# alone the server could not tell the Python generator from the engine's own
# expansion or from `INVPW_CURSOR_ENGINE=off`, and a walk drawn on top of
# either would humanise twice.
#
# Milliseconds, and an int: Gecko has no float pref type, and `1.0` written
# as a number arrives with the right value and the wrong type - the defect
# `ui.textScaleFactor` had.
# The persona's keyboards are in the prefs already: the core declares them
# with the language and country (invisible_core.prefs._apply_locale).
prefs[COMPOSED_PREF] = True
if session_seed is not None and humanize:
prefs[SESSION_SEED_PREF] = int(session_seed)
prefs[POINTER_PREF] = cursor_engine == ENGINE_PYTHON
prefs[MOTION_BUDGET_PREF] = int(round(
_cursor_max_seconds(humanize) * 1000.0))
return prefs
@@ -246,16 +282,14 @@ class ProxyEgressDrifted(RuntimeError):
This is not a condition the product can recover from, and it is deliberate
that it is an error instead of a silent update.
The IP we declare to the engine for the WebRTC srflx candidate is
discovered ONCE, at launch. If the egress changes afterwards, the page
exits from one address and WebRTC announces another: it is exactly the
comparison detectors make ("WebRTC IP doesn't match your Remote IP"), and
no Firefox on a real connection produces it.
The timezone and the locale are decided ONCE, at launch, from the egress
country. If the egress moves afterwards, the page exits from one place
while the timezone and the language still describe another: a mismatch no
real connection produces.
Updating the value on the fly would be worse, not better: the site would
see the WebRTC IP change before its own eyes mid-session, which is just as
unnatural a signal. If the egress does not hold for the duration of the
session, that proxy is not sticky and is not usable for this purpose.
Updating them on the fly would be just as unnatural (the site would see
them change mid-session). If the egress does not hold for the duration of
the session, that proxy is not sticky and is not usable for this purpose.
Measured on 2026-08-25: the two providers tried both declare sessions
sticky by TIME (60 minutes at most for one, a sliding timeout for the
@@ -351,7 +385,7 @@ class CommonLaunch:
`_cursor_engine`, `_extra_prefs`, `_headless`, `_humanize`,
`_lifetime_guard`, `_locale` (the core's SessionLocale, None until
`__enter__` decides it), `_profile`, `_session_token`, `_show_cursor`,
`_srflx_declared`, `_timezone` and `_virtual_display` in their own
`_network_declared`, `_timezone` and `_virtual_display` in their own
`__init__`. They already did, identically, which is why this works at all.
"""
@@ -416,7 +450,7 @@ class CommonLaunch:
"""Env for the Firefox subprocess, then stamped with this session's token.
The body is `build_env`, shared with the async class - it was
written twice, identically, and the WebRTC pair is a contract with the
written twice, identically, and the WebRTC declaration is a contract with the
binary, so two landing sites meant two chances to miss a change.
The token stamp stays here because it is the only genuinely per-session
@@ -425,7 +459,7 @@ class CommonLaunch:
"""
vd = self._virtual_display
return self._session_token.stamp(
build_env(srflx_declared=self._srflx_declared,
build_env(network_declared=self._network_declared,
profile=self._profile,
executable=resolve_executable(self._binary_path),
display_env=vd.launch_env() if vd is not None else None))
+14 -27
View File
@@ -88,13 +88,11 @@ class InvisiblePlaywright(_session.CommonLaunch):
# otherwise. Nothing was red because no test enters this context manager.
self._session_token = SessionToken()
self._lifetime_guard = guard_for()
# Proxy egress IP (WebRTC srflx override); discovered in __aenter__.
# Proxy egress IP, discovered in __aenter__: the guard against drift
# compares it with the egress now. None without a proxy.
self._webrtc_egress_ip: Optional[str] = None
#: The DECISION about the srflx, distinct from the fact above.
#: Starts as None like it: `_build_env` can be called before
#: the geo path has resolved, and in that case nothing is
#: declared.
self._srflx_declared: Optional[str] = None
#: The host network the engine reads, drawn from the seed.
self._network_declared: str = _session.declared_network(self)
#: See the twin in `launcher.py`: starts at 0 because the first
#: context must be able to check right away.
self._ultimo_controllo_uscita: float = 0.0
@@ -116,17 +114,6 @@ class InvisiblePlaywright(_session.CommonLaunch):
self._timezone = _geo.timezone
self._locale = _geo.locale
self._webrtc_egress_ip = _geo.egress_ip
# ⛔ TWO DIFFERENT THINGS, and they used to be a single field.
# `_webrtc_egress_ip` is the FACT: where we exit from. It feeds
# the guard against drift, which compares the current egress
# against the one at launch.
# `_srflx_declared` is the DECISION: what the engine must
# announce. It is None when the egress has proven, consistent
# UDP, because there the real srflx is already correct and
# declaring one would add a candidate with no matching
# allocation - the signal a detector running its own TURN reads.
# The core takes it in a single spot.
self._srflx_declared = _geo.srflx_to_declare()
# binary_path= never reaches ensure_binary(), so the engine check lives
# on the resolved executable rather than inside the fetcher.
executable = resolve_executable(self._binary_path)
@@ -191,7 +178,7 @@ class InvisiblePlaywright(_session.CommonLaunch):
#: session gets rejected. One alone would be too strict - a timeout
#: happens - but unlimited would be declared blindness: after three
#: silent checks at 120 s each, that is six minutes in which nothing
#: is confirming the address the engine announces on every page.
#: is confirming that the timezone and the locale still match the egress.
_MAX_USCITE_NON_MISURABILI = 3
async def _assert_uscita_invariata(self) -> None:
@@ -210,19 +197,19 @@ class InvisiblePlaywright(_session.CommonLaunch):
if outcome == _session.USCITA_DERIVATA:
raise _session.ProxyEgressDrifted(
"the proxy's egress IP changed during the session: "
"at launch it was %s, now it is %s. The WebRTC srflx "
"candidate still declares the first one, so from this "
"moment the page exits from one address and WebRTC "
"announces another - the disagreement detectors look "
"for. This proxy does not hold the session sticky for "
"at launch it was %s, now it is %s. The timezone and the "
"locale still describe the first one, so from this moment "
"the page exits from one place and they say another. "
"This proxy does not hold the session sticky for "
"the required duration: use one that guarantees it, or "
"shorten the session."
% (self._webrtc_egress_ip, current))
if outcome == _session.USCITA_NON_MISURABILE:
# This is NOT "holds", which is why there are three outcomes. A
# probe that fails ONCE is the network; one that always fails is
# blindness: from that moment the engine keeps declaring an
# address on every page that nobody is confirming anymore. It is
# blindness: from that moment the timezone and the locale stay
# declared on every page with nobody confirming them against the
# egress anymore. It is
# counted, instead of ignored, and rejected only if it repeats.
self._uscite_non_misurabili += 1
if self._uscite_non_misurabili >= self._MAX_USCITE_NON_MISURABILI:
@@ -230,8 +217,8 @@ class InvisiblePlaywright(_session.CommonLaunch):
"the egress IP could not be verified for %d checks in "
"a row. It is not drift - the probe did not respond at "
"all - but it is not agreement either: from here on "
"the engine would be declaring an address on every "
"page that nobody confirms anymore. Check that the "
"the timezone and the locale go unconfirmed on every "
"page. Check that the "
"proxy is reachable, then relaunch the session."
% self._uscite_non_misurabili)
return
+23 -42
View File
@@ -235,14 +235,11 @@ class InvisiblePlaywright(_session.CommonLaunch):
# before __enter__ has got anywhere - always finds them.
self._session_token = SessionToken()
self._lifetime_guard = guard_for()
# Proxy egress IP, discovered at launch (see __enter__). Feeds the
# WebRTC srflx override so the candidate matches the proxy IP, not the
# real host IP. None when no proxy is set.
# Proxy egress IP, discovered at launch (see __enter__): the guard
# against drift compares it with the egress now. None without a proxy.
self._webrtc_egress_ip: Optional[str] = None
#: The DECISION about the srflx, distinct from the fact above.
#: Starts at None like it: `_build_env` can be called before the
#: geo path has resolved, and in that case nothing is declared.
self._srflx_declared: Optional[str] = None
#: The host network the engine reads, drawn from the seed.
self._network_declared: str = _session.declared_network(self)
#: When the egress was last rechecked. Starts at 0 rather than at
#: `time.monotonic()`: the first context must be able to check
#: right away, because time may already have passed between launch
@@ -264,17 +261,6 @@ class InvisiblePlaywright(_session.CommonLaunch):
self._timezone = _geo.timezone
self._locale = _geo.locale
self._webrtc_egress_ip = _geo.egress_ip
# ⛔ TWO DIFFERENT THINGS, and before they were a single field.
# `_webrtc_egress_ip` is the FACT: where we exit from. It serves the
# guard against drift, which compares now's egress against the one
# at launch.
# `_srflx_declared` is the DECISION: what the engine must
# announce. It is None when the egress has proven, consistent UDP,
# because there the real srflx is already born correct and
# declaring one would add a candidate with no matching
# allocation - the signal a detector running its own TURN reads.
# The core reads it in one place only.
self._srflx_declared = _geo.srflx_to_declare()
# binary_path= never reaches ensure_binary(), so the engine check lives
# on the resolved executable rather than inside the fetcher.
executable = resolve_executable(self._binary_path)
@@ -409,20 +395,18 @@ class InvisiblePlaywright(_session.CommonLaunch):
#: session gets refused. Just one would be too strict - a timeout
#: happens - but unlimited would be declared blindness: after three
#: silent checks at 120s each, that is six minutes in which nobody is
#: confirming the address the engine announces on every page.
#: confirming that the timezone and the locale still match the egress.
_MAX_USCITE_NON_MISURABILI = 3
def _assert_uscita_invariata(self) -> None:
"""Refuses if the egress IP has changed since launch.
A change mid-session cannot be recovered from: the IP we declare to
the engine for the srflx was photographed at launch, so from that
moment the page exits from one address and WebRTC announces
another - the disagreement detectors look for. Updating it on the
fly would not help: it would make the WebRTC IP change under the
site's eyes, which is just as unnatural. If the egress does not
hold for the session's duration, that proxy is not sticky and is
not fit for this purpose.
A change mid-session cannot be recovered from: the timezone and the locale were decided from the egress at launch, so
from that moment the page exits from one place while they describe
another. Updating them on the fly would not help: the site would see
them change, which is just as unnatural. If the egress does not hold
for the session's duration, that proxy is not sticky and is not fit
for this purpose.
"""
if not self._proxy or not self._webrtc_egress_ip:
return
@@ -435,10 +419,9 @@ class InvisiblePlaywright(_session.CommonLaunch):
if outcome == _session.USCITA_DERIVATA:
raise _session.ProxyEgressDrifted(
"the proxy's egress IP changed during the session: "
"it was %s at launch, now it is %s. The WebRTC srflx "
"candidate still declares the first one, so from this "
"moment the page exits from one address and WebRTC "
"announces another - the disagreement detectors look for. "
"it was %s at launch, now it is %s. The timezone and the "
"locale still describe the first one, so from this moment "
"the page exits from one place and they say another. "
"This proxy does not hold the session sticky for the "
"required duration: use one that guarantees it, or "
"shorten the session."
@@ -446,18 +429,18 @@ class InvisiblePlaywright(_session.CommonLaunch):
if outcome == _session.USCITA_NON_MISURABILE:
# It is NOT "holding", and that is why there are three outcomes.
# A probe that fails ONCE is the network; one that always fails
# is blindness: from that moment the engine keeps declaring an
# address on every page that nobody is confirming anymore. It
# is counted, instead of ignored, and refused only if it
# is blindness: from that moment the timezone and the locale
# stay declared on every page with nobody confirming them against
# the egress anymore. It is counted, instead of ignored, and refused only if it
# repeats.
self._uscite_non_misurabili += 1
if self._uscite_non_misurabili >= self._MAX_USCITE_NON_MISURABILI:
raise _session.ProxyEgressNonVerificabile(
"the egress IP was not verifiable for %d checks in a "
"row. It is not drift - the probe did not respond at "
"all - but it is not parity either: from here on the "
"engine would keep declaring an address on every page "
"that nobody confirms anymore. Check that the proxy is "
"all - but it is not parity either: from here on "
"the timezone and the locale go unconfirmed on every "
"page. Check that the proxy is "
"reachable, then relaunch the session."
% self._uscite_non_misurabili)
return
@@ -516,11 +499,9 @@ class InvisiblePlaywright(_session.CommonLaunch):
# then on.
#
# Measured 2026-08-25 in a manual session: at launch the egress
# was `82.40.95.144` and that is what landed in the srflx; nine
# tabs later the page was exiting from `130.12.17.118`, and the
# two showed up together on screen - `PUBLIC IP` against
# `WEBRTC CLIENT SIDE IP OFFER`. The guard existed, it was
# correct, and it was never asked.
# was `203.0.113.10`, which the timezone was decided from; nine
# tabs later the page was exiting from `203.0.113.20`. The guard
# existed, it was correct, and it was never asked.
#
# The cost stays the same as before: `_assert_uscita_invariata`
# limits itself to one check every `_INTERVALLO_CONTROLLO_USCITA_S`,
+115
View File
@@ -0,0 +1,115 @@
"""What the canvas text e2e tests share: the persona pin, the bundled fonts and the server.
tests/test_canvas_text_is_windows_e2e.py (black text, 342 cases) and
tests/test_canvas_text_colors_and_cleartype_is_windows_e2e.py (coloured text and the
ClearType keys) both compare the RGBA bytes of a canvas drawn by the engine with the ones
retail Firefox 159.0 on Windows drew, for pages served on localhost with the engine's own
bundled font files. This module holds what the two do the same way.
"""
from __future__ import annotations
import hashlib
import http.server
import json
import threading
from pathlib import Path
DATA = Path(__file__).parent / "data" / "canvas_text_ref"
#: What the reference's ``cleartype`` field says the retail machine had: FontSmoothing 2 with
#: FontSmoothingType 2 is ClearType (system text quality 5). The other tuning values are an
#: untuned Windows machine's (gamma 1.8, contrast 1.0, level 1.0), which refs.json does not
#: record.
UNTUNED = {"font.cleartype_gamma": 1800, "font.cleartype_contrast": 100,
"font.cleartype_level": 100}
def pin(refs):
"""The prefs that make the engine the machine ``refs["cleartype"]`` describes."""
ct = refs["cleartype"]
smoothing, kind = str(ct["FontSmoothing"]), str(ct["FontSmoothingType"])
if smoothing == "2" and kind in ("2", "0x2"):
quality = 5
elif smoothing == "2":
quality = 4
else:
quality = 0
return {"screen.dpr": 1.0, "font.system_text_quality": quality, **UNTUNED}
def bundle_font(fonts_dir, entry):
"""The bundled file a reference entry names."""
return Path(fonts_dir) / entry["bundle_file"]
def wrong_fonts(fonts_dir, entries):
"""One line for each reference font whose bundled file is not the one measured."""
wrong = []
for e in entries:
f = bundle_font(fonts_dir, e)
got = hashlib.sha256(f.read_bytes()).hexdigest() if f.is_file() else None
if got != e["sha256"]:
wrong.append("%s: the engine's %s has sha256 %s, the reference was made with %s"
% (e["family"], f.name, got, e["sha256"]))
return wrong
def serve(fonts_dir, entries, pages):
"""``pages`` (url path -> HTML bytes) and, under /bundle/<name>, the engine's bundled
font files. Returns the running server; the caller shuts it down."""
by_url = {"/bundle/" + e["bundle_file"]: bundle_font(fonts_dir, e) for e in entries}
class _H(http.server.BaseHTTPRequestHandler):
def do_GET(self):
path = self.path.split("?")[0]
if path in pages:
body, kind = pages[path], "text/html"
elif path in by_url and by_url[path].is_file():
body, kind = by_url[path].read_bytes(), "font/ttf"
else:
self.send_error(404)
return
self.send_response(200)
self.send_header("Content-Type", kind)
self.send_header("Content-Length", str(len(body)))
self.end_headers()
self.wfile.write(body)
def log_message(self, *args):
pass
server = http.server.ThreadingHTTPServer(("127.0.0.1", 0), _H)
threading.Thread(target=server.serve_forever, daemon=True).start()
return server
_SPECS_LOOP = " window.R = {};\n for (const sp of SPECS) {"
def only_cases(html, ids):
"""canvas_text_ref/index.html as text, drawing only the cases ``ids``.
The page draws all 342 cases (the 400 px ones take minutes); a test that wants a few of
them serves this. The drawing code is untouched, so a case gives the bytes it gives in
the whole page."""
if _SPECS_LOOP not in html:
raise AssertionError("canvas_text_ref/index.html no longer has the loop over SPECS "
"that only_cases() narrows: update the helper")
return html.replace(
_SPECS_LOOP,
" window.R = {};\n const ONLY = new Set(%s);\n"
" for (const sp of SPECS.filter(s => ONLY.has(s.id))) {" % json.dumps(sorted(ids)))
def diff_lines(want, got, label=""):
"""One line for each case of ``want`` (id -> sha256) that ``got`` does not draw as
expected: its name, the hash retail gave, the hash the engine gave (or "not drawn")."""
lines = []
for cid in sorted(want):
have = got.get(cid)
if have != want[cid]:
lines.append("%s%s: expected %s, got %s"
% (label, cid, want[cid], have if have is not None else "not drawn"))
lines += ["%s%s: drawn but not in the reference" % (label, cid)
for cid in sorted(set(got) - set(want))]
return lines
+609
View File
@@ -0,0 +1,609 @@
"""A DNS-over-HTTPS server and a SOCKS5 gateway that carries the DoH road, for tests that need a real wire.
Hermetic: loopback only, no DNS, no internet. Nothing here knows about the product.
What the core declares (core-19), for every session, is the DoH of Firefox at
``https://mozilla.cloudflare-dns.com/dns-query``, found with no DNS at the address ``network.trr.bootstrapAddr``
(162.159.61.4). A test does NOT impersonate that host: Firefox refuses a certificate override for an HSTS-preloaded or
pinned host (``mozilla.cloudflare-dns.com`` is one), so a self-signed certificate for it can never be accepted, whatever
``ignore_https_errors`` says. The test declares its own provider instead, through the core's ``extra_prefs`` overlay:
``network.trr.uri`` = ``https://doh.gateway.test/dns-query`` (a ``.test`` name, never preloaded) and
``network.trr.bootstrapAddr`` = ``192.0.2.53`` (TEST-NET-1, so nothing real is addressed). With a proxy the engine turns it on (``network.trr.mode`` 3, derived from the proxies it receives, never
written by the core), so every name the browser resolves goes to it; the DoH request is a channel like any other, so it
leaves THROUGH the proxy of the context of the lookup. A test of that needs three things this file builds:
* :class:`FakeDoh` - the DoH server. RFC 8484 (POST ``application/dns-message`` and GET ``?dns=base64url``) over TLS
with a certificate for ``doh.gateway.test`` and ``127.0.0.1``, written by hand: the question is parsed from
its labels and the answer is built byte by byte (header, the question copied, one A record, TTL 30). It answers
HTTP/2 when the ``h2`` package is importable and ALPN selects it (Firefox's TRR speaks h2), HTTP/1.1 otherwise.
Every query is recorded as ``(name, qtype, via)``.
* :class:`DohGateway` - a SOCKS5 gateway (the ``Gateway`` of ``_socks_servers``) whose CONNECT to the DoH address
(``192.0.2.53:443``, or ``doh.gateway.test:443`` by name) is handed to the FakeDoh of the test, with the
gateway's name as ``via``; every other CONNECT to a loopback address is relayed for real. It never resolves a name
itself and never reaches a non-loopback address: a CONNECT that asks for one is refused and recorded, so a test run
cannot leak anything and cannot be mistaken for leaking.
* the DNS codec (:func:`parse_query`, :func:`build_response`), which the resolver trap of ``_leaks`` reuses.
``via`` answers "by which road did this query arrive": the name of the gateway that carried the CONNECT, or
``"direct"`` for a client that connected to the FakeDoh's own port.
"""
from __future__ import annotations
import base64
import datetime
import ipaddress
import socket
import ssl
import struct
import tempfile
import threading
import time
from pathlib import Path
from typing import Callable, Dict, List, NamedTuple, Optional, Set, Tuple
from urllib.parse import parse_qs, urlsplit
from _socks_servers import EXIT, Gateway, WEB_NAME, WHOAMI4, WHOAMI6
try: # the HTTP/2 side needs it; a test that wants h2 says pytest.importorskip("h2")
import h2.config
import h2.connection
import h2.events
import h2.exceptions
H2_AVAILABLE = True
except ImportError: # pragma: no cover - depends on the environment
H2_AVAILABLE = False
#: The host name of the DoH the TEST declares (``network.trr.uri``) and the address it is found at without DNS
#: (``network.trr.bootstrapAddr``). Not the core's default provider: that host is HSTS-preloaded/pinned, so Firefox
#: refuses any certificate override for it and a fake could never be accepted. A ``.test`` name is on no preload list;
#: 192.0.2.0/24 is TEST-NET-1 (RFC 5737), reserved for documentation, so the address cannot reach anything real.
DOH_HOST = "doh.gateway.test"
DOH_BOOTSTRAP = "192.0.2.53"
DOH_PORT = 443
DOH_PATH = "/dns-query"
#: The two prefs that make a session use the FakeDoh as its provider (applied with ``extra_prefs``).
DOH_PROVIDER_PREFS = {"network.trr.uri": "https://%s%s" % (DOH_HOST, DOH_PATH),
"network.trr.bootstrapAddr": DOH_BOOTSTRAP}
#: Every CONNECT target the gateways hand to the FakeDoh.
DOH_TARGETS = frozenset({(DOH_BOOTSTRAP, DOH_PORT), (DOH_HOST, DOH_PORT)})
QTYPE_A, QTYPE_AAAA = 1, 28
RCODE_OK, RCODE_NXDOMAIN, RCODE_REFUSED = 0, 3, 5
DOH_TTL = 30
# --------------------------------------------------------------------------------------------------------- DNS codec
class Query(NamedTuple):
ident: int
flags: int
name: str # lower case, no trailing dot
qtype: int
qclass: int
question: bytes # the question section as it came, to be copied into the answer
def parse_query(msg: bytes) -> Query:
"""The first (and only) question of a DNS message. Raises ``ValueError`` on anything that is not one."""
try:
ident, flags, qdcount, _an, _ns, _ar = struct.unpack("!6H", msg[:12])
if qdcount != 1:
raise ValueError("expected one question, got %d" % qdcount)
i, labels = 12, []
while True:
length = msg[i]
i += 1
if length == 0:
break
if length & 0xC0:
raise ValueError("a compressed name in the question")
labels.append(msg[i:i + length].decode("ascii"))
i += length
qtype, qclass = struct.unpack("!HH", msg[i:i + 4]) # struct.error when truncated
i += 4
except (IndexError, struct.error, UnicodeDecodeError) as exc:
raise ValueError("not a DNS query: %s" % exc) from None
return Query(ident, flags, ".".join(labels).lower(), qtype, qclass, msg[12:i])
def build_response(query: Query, rcode: int = RCODE_OK, answers: Tuple[Tuple[int, bytes], ...] = ()) -> bytes:
"""A response to ``query``: QR+RA, the RD bit copied, ``rcode``, the question copied, one record per
``(type, rdata)`` with the name as a pointer to the question and TTL 30."""
flags = 0x8000 | (query.flags & 0x0100) | 0x0080 | (rcode & 0xF)
out = struct.pack("!6H", query.ident, flags, 1, len(answers), 0, 0) + query.question
for rtype, rdata in answers:
out += struct.pack("!HHHIH", 0xC00C, rtype, 1, DOH_TTL, len(rdata)) + rdata
return out
def encode_query(name: str, qtype: int = QTYPE_A, ident: int = 0) -> bytes:
"""A query message (RD set), the way a client builds it."""
labels = b"".join(bytes([len(p)]) + p.encode("ascii") for p in name.rstrip(".").split(".") if p)
return struct.pack("!6H", ident, 0x0100, 1, 0, 0, 0) + labels + b"\x00" + struct.pack("!HH", qtype, 1)
def answer_for(names: Dict[str, str], query: Query) -> bytes:
"""The response a zone made of ``names`` (name -> address) gives: A for an IPv4 value, AAAA for an IPv6 one,
NOERROR with no answer for any other type of a known name, NXDOMAIN for an unknown name."""
value = names.get(query.name)
if value is None:
return build_response(query, RCODE_NXDOMAIN)
address = ipaddress.ip_address(value)
if query.qtype == QTYPE_A and address.version == 4:
return build_response(query, RCODE_OK, ((QTYPE_A, address.packed),))
if query.qtype == QTYPE_AAAA and address.version == 6:
return build_response(query, RCODE_OK, ((QTYPE_AAAA, address.packed),))
return build_response(query, RCODE_OK)
def wait_until(predicate: Callable[[], object], timeout: float, step: float = 0.05) -> bool:
"""True as soon as ``predicate()`` is truthy, False after ``timeout`` seconds."""
deadline = time.monotonic() + timeout
while True:
if predicate():
return True
if time.monotonic() >= deadline:
return False
time.sleep(step)
# ------------------------------------------------------------------------------------------------------ certificate
def make_certificate(directory: Path, dns_names: Tuple[str, ...] = (DOH_HOST,),
ip_addresses: Tuple[str, ...] = ("127.0.0.1",)) -> Tuple[Path, Path]:
"""A self-signed certificate (EC P-256, 30 days) whose SAN covers ``dns_names`` and ``ip_addresses``.
Returns (certificate path, key path), both PEM."""
from cryptography import x509
from cryptography.hazmat.primitives import hashes, serialization
from cryptography.hazmat.primitives.asymmetric import ec
from cryptography.x509.oid import NameOID
key = ec.generate_private_key(ec.SECP256R1())
name = x509.Name([x509.NameAttribute(NameOID.COMMON_NAME, dns_names[0] if dns_names else ip_addresses[0])])
now = datetime.datetime.now(datetime.timezone.utc)
san = [x509.DNSName(n) for n in dns_names] + [x509.IPAddress(ipaddress.ip_address(a)) for a in ip_addresses]
cert = (x509.CertificateBuilder().subject_name(name).issuer_name(name).public_key(key.public_key())
.serial_number(x509.random_serial_number()).not_valid_before(now - datetime.timedelta(days=1))
.not_valid_after(now + datetime.timedelta(days=30))
.add_extension(x509.SubjectAlternativeName(san), critical=False)
.sign(key, hashes.SHA256()))
cert_path, key_path = directory / "doh-cert.pem", directory / "doh-key.pem"
cert_path.write_bytes(cert.public_bytes(serialization.Encoding.PEM))
key_path.write_bytes(key.private_bytes(serialization.Encoding.PEM, serialization.PrivateFormat.PKCS8,
serialization.NoEncryption()))
return cert_path, key_path
_REASONS = {200: "OK", 400: "Bad Request", 404: "Not Found", 405: "Method Not Allowed",
415: "Unsupported Media Type"}
class DohQuery(NamedTuple):
name: str
qtype: int
via: str
class FakeDoh:
"""A DoH server on 127.0.0.1 (its own port, ``via`` ``"direct"``) that also serves any socket a gateway hands it.
``names`` maps a name to the address it resolves to; it can be changed while the server runs. ``h2=False`` makes
it offer HTTP/1.1 only (the way to test that a client falls back), ``h2=True`` is the default when the ``h2``
package is importable.
"""
def __init__(self, names: Optional[Dict[str, str]] = None, *, h2: Optional[bool] = None):
self.names: Dict[str, str] = {k.lower(): v for k, v in (names or {}).items()}
self.offers_h2 = H2_AVAILABLE if h2 is None else (h2 and H2_AVAILABLE)
#: Every query, in order.
self.queries: List[DohQuery] = []
#: Every TLS connection served: (via, negotiated protocol).
self.connections: List[Tuple[str, str]] = []
#: The TLS handshakes that did not complete (a client that refused the certificate): (via, error).
self.tls_failures: List[Tuple[str, str]] = []
#: Every HTTP request that was not a well-formed DoH query: (via, method, target, status).
self.bad_requests: List[Tuple[str, str, str, int]] = []
self._lock = threading.Lock()
self._open: List[Tuple[str, ssl.SSLSocket]] = []
self._dir = tempfile.TemporaryDirectory()
self.certificate_path, self._key_path = make_certificate(Path(self._dir.name))
self._context = ssl.SSLContext(ssl.PROTOCOL_TLS_SERVER)
self._context.load_cert_chain(str(self.certificate_path), str(self._key_path))
self._context.set_alpn_protocols(["h2", "http/1.1"] if self.offers_h2 else ["http/1.1"])
self._listener = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
self._listener.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
self._listener.bind(("127.0.0.1", 0))
self._listener.listen(32)
self.port: int = self._listener.getsockname()[1]
self._closed = False
threading.Thread(target=self._accept, daemon=True).start()
# --- what a test reads ------------------------------------------------------------------------------------
def queries_for(self, name: str, qtype: Optional[int] = None) -> List[DohQuery]:
name = name.lower().rstrip(".")
with self._lock:
return [q for q in self.queries if q.name == name and (qtype is None or q.qtype == qtype)]
def vias_of(self, name: str, qtype: Optional[int] = None) -> Set[str]:
"""The set of roads (gateway names) a name was asked by."""
return {q.via for q in self.queries_for(name, qtype)}
def seen_names(self) -> List[str]:
with self._lock:
return sorted({q.name for q in self.queries})
def alpn_of(self, via: str) -> Set[str]:
with self._lock:
return {proto for v, proto in self.connections if v == via}
# --- serving ----------------------------------------------------------------------------------------------
def _accept(self) -> None:
while not self._closed:
try:
conn, _ = self._listener.accept()
except OSError:
return
threading.Thread(target=self.serve, args=(conn, "direct"), daemon=True).start()
def serve(self, sock: socket.socket, via: str) -> None:
"""Serve one connection (TLS first) that arrived by ``via``. Blocks until it ends, and closes ``sock``."""
try:
sock.settimeout(60)
tls = self._context.wrap_socket(sock, server_side=True)
except (ssl.SSLError, OSError) as exc:
with self._lock:
self.tls_failures.append((via, "%s: %s" % (type(exc).__name__, exc)))
try:
sock.close()
except OSError:
pass
return
protocol = tls.selected_alpn_protocol() or "http/1.1"
with self._lock:
self.connections.append((via, protocol))
self._open.append((via, tls))
try:
if protocol == "h2":
self._serve_h2(tls, via)
else:
self._serve_h1(tls, via)
except (OSError, ssl.SSLError, ValueError, KeyError):
pass
except Exception as exc: # noqa: BLE001 - an h2 protocol error ends the connection like a reset
if not (H2_AVAILABLE and isinstance(exc, h2.exceptions.H2Error)):
raise
finally:
with self._lock:
self._open = [(v, s) for v, s in self._open if s is not tls]
try:
tls.close()
except OSError:
pass
def drop(self, via: Optional[str] = None) -> int:
"""Close every open connection that arrived by ``via`` (all of them when None). Returns how many."""
with self._lock:
victims = [s for v, s in self._open if via is None or v == via]
for s in victims:
for action in (lambda: s.shutdown(socket.SHUT_RDWR), s.close):
try:
action()
except OSError:
pass
return len(victims)
def _answer(self, via: str, method: str, target: str, content_type: str,
body: bytes) -> Tuple[int, bytes, str]:
"""(status, body, content type) of one HTTP request, recording the DNS query it carries."""
def bad(status: int) -> Tuple[int, bytes, str]:
with self._lock:
self.bad_requests.append((via, method, target, status))
return status, b"", "text/plain"
split = urlsplit(target)
if split.path != DOH_PATH:
return bad(404)
if method == "POST":
if content_type.split(";")[0].strip().lower() != "application/dns-message":
return bad(415)
message = body
elif method == "GET":
values = parse_qs(split.query).get("dns")
if not values:
return bad(400)
try:
message = base64.urlsafe_b64decode(values[0] + "=" * (-len(values[0]) % 4))
except ValueError:
return bad(400)
else:
return bad(405)
try:
query = parse_query(message)
except ValueError:
return bad(400)
with self._lock:
self.queries.append(DohQuery(query.name, query.qtype, via))
names = dict(self.names)
return 200, answer_for(names, query), "application/dns-message"
def _serve_h1(self, tls: ssl.SSLSocket, via: str) -> None:
buffer = b""
while True:
while b"\r\n\r\n" not in buffer:
chunk = tls.recv(65536)
if not chunk:
return
buffer += chunk
head, _, buffer = buffer.partition(b"\r\n\r\n")
lines = head.decode("latin-1").split("\r\n")
method, target, _version = lines[0].split(" ", 2)
headers = {}
for line in lines[1:]:
key, _, value = line.partition(":")
headers[key.strip().lower()] = value.strip()
length = int(headers.get("content-length", "0"))
while len(buffer) < length:
chunk = tls.recv(65536)
if not chunk:
return
buffer += chunk
body, buffer = buffer[:length], buffer[length:]
status, payload, content_type = self._answer(via, method, target, headers.get("content-type", ""), body)
close = headers.get("connection", "").lower() == "close"
tls.sendall(("HTTP/1.1 %d %s\r\nContent-Type: %s\r\nContent-Length: %d\r\nCache-Control: max-age=%d\r\n"
"%s\r\n" % (status, _REASONS.get(status, "Status"), content_type, len(payload), DOH_TTL,
"Connection: close\r\n" if close else "")).encode("latin-1") + payload)
if close:
return
def _serve_h2(self, tls: ssl.SSLSocket, via: str) -> None:
connection = h2.connection.H2Connection(
config=h2.config.H2Configuration(client_side=False, header_encoding="utf-8"))
connection.initiate_connection()
tls.sendall(connection.data_to_send())
streams: Dict[int, dict] = {}
while True:
data = tls.recv(65536)
if not data:
return
for event in connection.receive_data(data):
if isinstance(event, h2.events.RequestReceived):
streams[event.stream_id] = {"headers": dict(event.headers), "body": b""}
elif isinstance(event, h2.events.DataReceived):
streams[event.stream_id]["body"] += event.data
connection.acknowledge_received_data(event.flow_controlled_length, event.stream_id)
elif isinstance(event, h2.events.StreamEnded):
request = streams.pop(event.stream_id)
headers = request["headers"]
status, payload, content_type = self._answer(
via, headers.get(":method", ""), headers.get(":path", ""),
headers.get("content-type", ""), request["body"])
connection.send_headers(event.stream_id, [
(":status", str(status)), ("content-type", content_type),
("content-length", str(len(payload))), ("cache-control", "max-age=%d" % DOH_TTL)])
connection.send_data(event.stream_id, payload, end_stream=True)
elif isinstance(event, h2.events.StreamReset):
streams.pop(event.stream_id, None)
elif isinstance(event, h2.events.ConnectionTerminated):
return
pending = connection.data_to_send()
if pending:
tls.sendall(pending)
def close(self) -> None:
self._closed = True
try:
self._listener.close()
except OSError:
pass
self.drop()
try:
self._dir.cleanup()
except OSError:
pass
def __enter__(self) -> "FakeDoh":
return self
def __exit__(self, *exc) -> None:
self.close()
# --------------------------------------------------------------------------------------------------------- relaying
def pump(source: socket.socket, sink: socket.socket, delay: float = 0.0) -> None:
"""Copy bytes from ``source`` to ``sink`` until either ends, then shut both. ``delay`` seconds wait before each
chunk is forwarded (a gateway that is far away)."""
try:
while True:
data = source.recv(65536)
if not data:
break
if delay:
time.sleep(delay)
sink.sendall(data)
except OSError:
pass
finally:
for s in (source, sink):
try:
s.shutdown(socket.SHUT_RDWR)
except OSError:
pass
def relay(a: socket.socket, b: socket.socket, delay: float = 0.0) -> None:
"""Carry bytes both ways between two connected sockets until one ends. Blocks."""
a.settimeout(None)
b.settimeout(None)
thread = threading.Thread(target=pump, args=(b, a, delay), daemon=True)
thread.start()
pump(a, b, delay)
thread.join(timeout=2)
def is_loopback(host: str) -> bool:
"""True for a loopback ADDRESS. A name is never loopback here: nothing in these helpers resolves a name."""
try:
return ipaddress.ip_address(host).is_loopback
except ValueError:
return False
class DohGateway(Gateway):
"""A SOCKS5 gateway of ``_socks_servers`` that carries the DoH road to a :class:`FakeDoh`.
* CONNECT to ``DOH_TARGETS`` is served by ``doh`` with ``via=name``;
* CONNECT to a loopback address is relayed for real (the pages and the echo servers of a test);
* the egress endpoints of the base class (``api.ipify.org:80``) keep working;
* any other CONNECT is refused (reply 2 "not allowed", for an address; 4 "host unreachable", for a name) and
listed in :attr:`refused`: the gateway never resolves a name and never reaches past the loopback.
:attr:`connects` (inherited) lists EVERY CONNECT target in order, so ``("page-a.test", 80)`` in it means the
browser sent a name where it should have sent an address. :attr:`credentials_seen` lists every
username/password offered, ``first_connection_delay`` holds the first accepted connection that many seconds
before it is answered (a gateway that is slow to say hello), and :meth:`kill` makes the gateway dead: the port
refuses, and every open tunnel is closed.
"""
def __init__(self, name: str, doh: FakeDoh, *, user: Optional[str] = None, password: Optional[str] = None,
first_connection_delay: float = 0.0, **gateway: object):
# ``gateway`` goes to the base Gateway as it is (``udp="relay"``, ``relay_host``, ``rtt_ms``, ``exit_host``,
# ``tcp_exit``, ``udp_exit``, ``tcp_data_delay``): a road with UDP is this same class, not another gateway.
# State first: the base constructor starts the accept thread.
self.name = name
self.doh = doh
self.first_connection_delay = first_connection_delay
#: Every (username, password) a client offered.
self.credentials_seen: List[Tuple[str, str]] = []
#: Every CONNECT that was refused: (host, port).
self.refused: List[Tuple[str, int]] = []
#: How many connections were accepted, and the monotonic time of each.
self.accepted_at: List[float] = []
self.killed = False
self._live: List[socket.socket] = []
self._live_lock = threading.Lock()
options = dict(udp="refuse", tcp_exit=EXIT, udp_exit=EXIT)
options.update(gateway)
super().__init__(user=user, password=password, **options)
# --- accepting, and the slow first hello ---------------------------------------------------------------------
def _handle(self, c: socket.socket) -> None:
with self._live_lock:
self.accepted_at.append(time.monotonic())
first = len(self.accepted_at) == 1
self._live.append(c)
if first and self.first_connection_delay:
time.sleep(self.first_connection_delay)
super()._handle(c)
def _greet(self, c: socket.socket) -> bool:
"""The base negotiation, recording the credentials a client sent."""
ver, n = _recv_exact(c, 2)
methods = _recv_exact(c, n)
if ver != 5:
return False
if self.user is not None:
if 2 not in methods:
self._send(c, b"\x05\xff")
return False
self._send(c, b"\x05\x02")
_recv_exact(c, 1)
offered = (_recv_exact(c, _recv_exact(c, 1)[0]).decode("utf-8", "replace"),
_recv_exact(c, _recv_exact(c, 1)[0]).decode("utf-8", "replace"))
self.credentials_seen.append(offered)
ok = offered == (self.user, self.password)
self._send(c, b"\x01" + (b"\x00" if ok else b"\x01"))
return ok
self._send(c, b"\x05\x00" if 0 in methods else b"\x05\x02")
if 0 not in methods: # a client that only offers user/password: accept any
_recv_exact(c, 1)
offered = (_recv_exact(c, _recv_exact(c, 1)[0]).decode("utf-8", "replace"),
_recv_exact(c, _recv_exact(c, 1)[0]).decode("utf-8", "replace"))
self.credentials_seen.append(offered)
self._send(c, b"\x01\x00")
return True
# --- CONNECT ---------------------------------------------------------------------------------------------------
def _connect(self, c: socket.socket, host: str, port: int) -> None:
if (host, port) in DOH_TARGETS:
self.connects.append((host, port))
self._send(c, self._reply(0))
if self.tcp_data_delay and self.rtt: # a far gateway: every chunk of the tunnel waits half the round trip
near, far = socket.socketpair()
threading.Thread(target=self.doh.serve, args=(far, self.name), daemon=True).start()
try:
relay(c, near, self.rtt / 2)
finally:
near.close()
return
self.doh.serve(c, self.name)
return
if (host, port) in (WHOAMI4, WHOAMI6, (WEB_NAME, 80)):
super()._connect(c, host, port)
return
if not is_loopback(host):
self.connects.append((host, port))
self.refused.append((host, port))
self._send(c, self._reply(2 if _is_address(host) else 4))
return
self.connects.append((host, port))
try:
upstream = socket.create_connection((host, port), timeout=10)
except OSError:
self._send(c, self._reply(5))
return
with self._live_lock:
self._live.append(upstream)
self._send(c, self._reply(0))
try:
relay(c, upstream, self.rtt / 2 if self.tcp_data_delay else 0.0)
finally:
upstream.close()
# --- the DoH road, by CONNECT target --------------------------------------------------------------------------
def doh_connects(self) -> List[Tuple[str, int]]:
return [t for t in self.connects if t in DOH_TARGETS]
def kill(self) -> None:
"""Dead proxy: the port refuses new connections and every tunnel that was open is closed."""
self.killed = True
# shutdown() first: on Linux, close() alone leaves a listening socket open (and accepting) while another
# thread is blocked in accept() on it, so the "dead" proxy would still take connections.
try:
self._listener.shutdown(socket.SHUT_RDWR)
except OSError:
pass
self.close()
self.doh.drop(self.name)
with self._live_lock:
sockets, self._live = self._live, []
for s in sockets:
for action in (lambda: s.shutdown(socket.SHUT_RDWR), s.close):
try:
action()
except OSError:
pass
def _is_address(host: str) -> bool:
try:
ipaddress.ip_address(host)
return True
except ValueError:
return False
def _recv_exact(s: socket.socket, n: int) -> bytes:
data = b""
while len(data) < n:
chunk = s.recv(n - len(data))
if not chunk:
raise ConnectionError("closed")
data += chunk
return data
__all__ = [
"DOH_BOOTSTRAP", "DOH_HOST", "DOH_PATH", "DOH_PORT", "DOH_PROVIDER_PREFS", "DOH_TARGETS", "DOH_TTL", "H2_AVAILABLE", "QTYPE_A",
"QTYPE_AAAA", "RCODE_NXDOMAIN", "RCODE_OK", "RCODE_REFUSED", "DohGateway", "DohQuery", "FakeDoh", "Query",
"answer_for", "build_response", "encode_query", "is_loopback", "make_certificate", "parse_query", "pump",
"relay", "wait_until",
]
+158
View File
@@ -0,0 +1,158 @@
"""A local HTTPS server that speaks HTTP/3 as well, reached by its address.
The same port answers TCP (TLS, HTTP/1.1, with an `Alt-Svc: h3` header) and UDP (QUIC, HTTP/3, aioquic), with a self-signed
certificate for the address it is given. It records, for every QUIC connection, the address the packets came from: a
connection that comes from anywhere but the relay of a gateway on this host (127.0.0.1) did not go through the proxy.
Needs `aioquic` (pip install aioquic); a test that wants it imports it with `pytest.importorskip`.
"""
from __future__ import annotations
import asyncio
import datetime
import http.server
import ipaddress
import socket
import ssl
import tempfile
import threading
from pathlib import Path
from typing import List
def _certificate(address: str, directory: Path):
from cryptography import x509
from cryptography.hazmat.primitives import hashes, serialization
from cryptography.hazmat.primitives.asymmetric import ec
from cryptography.x509.oid import NameOID
key = ec.generate_private_key(ec.SECP256R1())
name = x509.Name([x509.NameAttribute(NameOID.COMMON_NAME, address)])
now = datetime.datetime.now(datetime.timezone.utc)
cert = (x509.CertificateBuilder().subject_name(name).issuer_name(name).public_key(key.public_key())
.serial_number(x509.random_serial_number()).not_valid_before(now - datetime.timedelta(days=1))
.not_valid_after(now + datetime.timedelta(days=30))
.add_extension(x509.SubjectAlternativeName([x509.IPAddress(ipaddress.ip_address(address))]), critical=False)
.sign(key, hashes.SHA256()))
cert_path, key_path = directory / "cert.pem", directory / "key.pem"
cert_path.write_bytes(cert.public_bytes(serialization.Encoding.PEM))
key_path.write_bytes(key.private_bytes(serialization.Encoding.PEM, serialization.PrivateFormat.PKCS8,
serialization.NoEncryption()))
return cert_path, key_path
class H3Server:
"""TCP+TLS and QUIC on one port of `address`."""
def __init__(self, address: str):
from aioquic.asyncio import serve
from aioquic.asyncio.protocol import QuicConnectionProtocol
from aioquic.h3.connection import H3_ALPN, H3Connection
from aioquic.h3.events import HeadersReceived
from aioquic.quic.configuration import QuicConfiguration
from aioquic.quic.events import ProtocolNegotiated
self.address = address
#: The address each QUIC connection came from.
self.quic_peers: List[str] = []
#: The paths of the requests that were answered over HTTP/3, and over TCP.
self.h3_requests: List[str] = []
self.tcp_requests: List[str] = []
self._dir = tempfile.TemporaryDirectory()
cert, key = _certificate(address, Path(self._dir.name))
server = self
class Handler(http.server.BaseHTTPRequestHandler):
protocol_version = "HTTP/1.1"
timeout = 5
def do_GET(self):
server.tcp_requests.append(self.path)
body = b"tcp ok"
self.send_response(200)
self.send_header("Content-Type", "text/plain")
self.send_header("Content-Length", str(len(body)))
self.send_header("Alt-Svc", 'h3=":%d"; ma=3600' % server.port)
self.send_header("Access-Control-Allow-Origin", "*")
self.end_headers()
self.wfile.write(body)
def log_message(self, *args):
pass
# One port for both: the TCP port first, then the same number for UDP.
for _ in range(50):
tcp = http.server.ThreadingHTTPServer((address, 0), Handler)
port = tcp.server_address[1]
probe = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
try:
probe.bind((address, port))
probe.close()
break
except OSError:
probe.close()
tcp.server_close()
else:
raise RuntimeError("no port free for both TCP and UDP")
self.port = port
context = ssl.SSLContext(ssl.PROTOCOL_TLS_SERVER)
context.load_cert_chain(str(cert), str(key))
context.set_alpn_protocols(["http/1.1"])
tcp.socket = context.wrap_socket(tcp.socket, server_side=True)
tcp.daemon_threads = True
self._tcp = tcp
threading.Thread(target=tcp.serve_forever, daemon=True).start()
class Protocol(QuicConnectionProtocol):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self._http = None
def quic_event_received(self, event):
if isinstance(event, ProtocolNegotiated):
self._http = H3Connection(self._quic)
server.quic_peers.append(self._quic._network_paths[0].addr[0])
if self._http is not None:
for http_event in self._http.handle_event(event):
if isinstance(http_event, HeadersReceived):
headers = dict(http_event.headers)
server.h3_requests.append(headers.get(b":path", b"").decode())
self._http.send_headers(http_event.stream_id, [
(b":status", b"200"), (b"content-type", b"text/plain"),
(b"access-control-allow-origin", b"*")])
self._http.send_data(http_event.stream_id, b"h3 ok", end_stream=True)
self.transmit()
configuration = QuicConfiguration(is_client=False, alpn_protocols=H3_ALPN)
configuration.load_cert_chain(str(cert), str(key))
self._loop = asyncio.new_event_loop()
started = threading.Event()
def run():
asyncio.set_event_loop(self._loop)
self._quic = self._loop.run_until_complete(
serve(address, port, configuration=configuration, create_protocol=Protocol))
started.set()
self._loop.run_forever()
threading.Thread(target=run, daemon=True).start()
if not started.wait(10):
raise RuntimeError("the QUIC server did not start")
@property
def url(self) -> str:
return "https://%s:%d/" % (self.address, self.port)
def close(self) -> None:
self._tcp.shutdown()
self._tcp.server_close()
self._quic.close()
self._loop.call_soon_threadsafe(self._loop.stop)
self._dir.cleanup()
def __enter__(self) -> "H3Server":
return self
def __exit__(self, *exc) -> None:
self.close()
+234
View File
@@ -0,0 +1,234 @@
"""An HTTP proxy on 127.0.0.1 that asks for credentials, and carries the DoH road to a :class:`FakeDoh`.
The counterpart of :class:`_doh_servers.DohGateway` for the ``http`` scheme:
* a request without a valid ``Proxy-Authorization: Basic`` gets ``407`` with ``Proxy-Authenticate: Basic`` (the
connection is closed, as many real proxies do); the right credentials get through;
* ``CONNECT`` to the DoH address (``192.0.2.53:443`` or ``doh.gateway.test:443``) is answered ``200``
and handed to the FakeDoh with ``via=name``; ``CONNECT`` to a loopback address is relayed for real; any other
CONNECT is refused (``403``) and recorded;
* a plain ``GET http://host:port/path`` (the form a browser sends to an HTTP proxy for an ``http`` page: the NAME
travels to the proxy, the proxy is the one that resolves it) is forwarded for real to a loopback address. The
proxy "resolves" the name with the zone of the FakeDoh (``doh.names``) and never asks any other resolver; a name
that is not in the zone answers ``502``. That is the exit's own resolution, and it is why a page behind an HTTP
proxy does NOT make the browser ask DoH for its name: something else must (an ICE server name does);
* every request is recorded in :attr:`seen` with the ``Proxy-Authorization`` header it carried and the status given.
Hermetic: nothing leaves the loopback and no name is resolved by the operating system.
"""
from __future__ import annotations
import base64
import socket
import threading
from typing import Dict, List, NamedTuple, Optional, Tuple
from urllib.parse import urlsplit
from _doh_servers import DOH_TARGETS, FakeDoh, is_loopback, relay
_REASONS = {200: "Connection Established", 403: "Forbidden", 405: "Method Not Allowed",
407: "Proxy Authentication Required", 502: "Bad Gateway"}
def basic(user: str, password: str) -> str:
"""The ``Proxy-Authorization`` value of Basic credentials (UTF-8, RFC 7617)."""
return "Basic " + base64.b64encode(("%s:%s" % (user, password)).encode("utf-8")).decode("ascii")
class Seen(NamedTuple):
method: str
host: str
port: int
#: The Proxy-Authorization header as it came, None when the request had none.
authorization: Optional[str]
status: int
class HttpProxy:
"""See the module docstring. ``user=None`` means no authentication is asked."""
def __init__(self, name: str, doh: FakeDoh, *, user: Optional[str] = None, password: Optional[str] = None):
self.name = name
self.doh = doh
self.user, self.password = user, password
#: Every request, in order.
self.seen: List[Seen] = []
self._lock = threading.Lock()
self._listener = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
self._listener.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
self._listener.bind(("127.0.0.1", 0))
self._listener.listen(32)
self.port: int = self._listener.getsockname()[1]
self._closed = False
threading.Thread(target=self._accept, daemon=True).start()
# --- what the test hands to the product ---------------------------------------------------------------------
@property
def server(self) -> str:
return "http://127.0.0.1:%d" % self.port
@property
def proxy(self) -> dict:
"""The endpoint dict the core takes: ``{"server": ..., [username, password]}``."""
out = {"server": self.server}
if self.user is not None:
out.update(username=self.user, password=self.password)
return out
@property
def expected_authorization(self) -> Optional[str]:
return basic(self.user, self.password) if self.user is not None else None
# --- what the test reads ------------------------------------------------------------------------------------
@property
def connects(self) -> List[Tuple[str, int]]:
"""The targets of the CONNECTs that were accepted, in order."""
with self._lock:
return [(s.host, s.port) for s in self.seen if s.method == "CONNECT" and s.status == 200]
@property
def refused_for_credentials(self) -> List[Seen]:
with self._lock:
return [s for s in self.seen if s.status == 407]
def authorizations_for(self, host: str, port: int) -> List[Optional[str]]:
"""The Proxy-Authorization of every CONNECT to ``host:port`` (the DoH address, for instance)."""
with self._lock:
return [s.authorization for s in self.seen if s.method == "CONNECT" and (s.host, s.port) == (host, port)]
def doh_authorizations(self) -> List[Optional[str]]:
with self._lock:
return [s.authorization for s in self.seen if s.method == "CONNECT" and (s.host, s.port) in DOH_TARGETS]
def doh_connects(self) -> List[Tuple[str, int]]:
return [t for t in self.connects if t in DOH_TARGETS]
# --- serving ------------------------------------------------------------------------------------------------
def close(self) -> None:
self._closed = True
try:
self._listener.close()
except OSError:
pass
def __enter__(self) -> "HttpProxy":
return self
def __exit__(self, *exc) -> None:
self.close()
def _accept(self) -> None:
while not self._closed:
try:
conn, _ = self._listener.accept()
except OSError:
return
threading.Thread(target=self._handle, args=(conn,), daemon=True).start()
@staticmethod
def _answer(conn: socket.socket, status: int, extra: str = "") -> None:
conn.sendall(("HTTP/1.1 %d %s\r\n%sContent-Length: 0\r\n%s\r\n" % (
status, _REASONS.get(status, "Status"), extra,
"Connection: close\r\n" if status != 200 else "")).encode("latin-1"))
def _record(self, method: str, host: str, port: int, authorization: Optional[str], status: int) -> None:
with self._lock:
self.seen.append(Seen(method, host, port, authorization, status))
def _handle(self, conn: socket.socket) -> None:
try:
conn.settimeout(30)
data = b""
while b"\r\n\r\n" not in data:
chunk = conn.recv(65536)
if not chunk:
return
data += chunk
head, _, rest = data.partition(b"\r\n\r\n")
lines = head.decode("latin-1").split("\r\n")
method, target, _version = lines[0].split(" ", 2)
headers: Dict[str, str] = {}
for line in lines[1:]:
key, _, value = line.partition(":")
headers[key.strip().lower()] = value.strip()
authorization = headers.get("proxy-authorization")
if method == "CONNECT":
host, _, port_text = target.rpartition(":")
host, port = host.strip("[]"), int(port_text)
else:
split = urlsplit(target)
host, port = split.hostname or "", split.port or 80
if self.user is not None and authorization != self.expected_authorization:
self._record(method, host, port, authorization, 407)
self._answer(conn, 407, 'Proxy-Authenticate: Basic realm="invisible"\r\n')
return
if method == "CONNECT":
self._connect(conn, host, port, authorization)
elif method == "GET":
self._forward(conn, host, port, authorization, split, headers, rest)
else:
self._record(method, host, port, authorization, 405)
self._answer(conn, 405)
except (OSError, ValueError):
pass
finally:
try:
conn.close()
except OSError:
pass
def _connect(self, conn: socket.socket, host: str, port: int, authorization: Optional[str]) -> None:
if (host, port) in DOH_TARGETS:
self._record("CONNECT", host, port, authorization, 200)
self._answer(conn, 200)
self.doh.serve(conn, self.name)
return
if not is_loopback(host):
self._record("CONNECT", host, port, authorization, 403)
self._answer(conn, 403)
return
try:
upstream = socket.create_connection((host, port), timeout=10)
except OSError:
self._record("CONNECT", host, port, authorization, 502)
self._answer(conn, 502)
return
self._record("CONNECT", host, port, authorization, 200)
self._answer(conn, 200)
try:
relay(conn, upstream)
finally:
upstream.close()
def _forward(self, conn: socket.socket, host: str, port: int, authorization: Optional[str], split,
headers: Dict[str, str], rest: bytes) -> None:
"""A plain GET, in the absolute form: resolved by the zone of the FakeDoh, then fetched for real."""
address = host if is_loopback(host) else self.doh.names.get(host.lower(), "")
if not address or not is_loopback(address):
self._record("GET", host, port, authorization, 502)
self._answer(conn, 502)
return
try:
upstream = socket.create_connection((address, port), timeout=10)
except OSError:
self._record("GET", host, port, authorization, 502)
self._answer(conn, 502)
return
self._record("GET", host, port, authorization, 200)
try:
path = (split.path or "/") + ("?" + split.query if split.query else "")
passed = "".join("%s: %s\r\n" % (k, v) for k, v in headers.items()
if not k.startswith("proxy-") and k not in ("connection", "keep-alive"))
upstream.sendall(("GET %s HTTP/1.1\r\n%sConnection: close\r\n\r\n" % (path, passed)).encode("latin-1"))
conn.settimeout(None)
upstream.settimeout(None)
while True:
data = upstream.recv(65536)
if not data:
break
conn.sendall(data)
finally:
upstream.close()
__all__ = ["HttpProxy", "Seen", "basic"]
+340
View File
@@ -0,0 +1,340 @@
"""Two traps for what a browser does that it should not: a connection that does not go through the gateway, and a
question put to the resolver of the machine.
* :class:`Watcher` samples, from before a launch until it is stopped, the network connections of every process that
is a DESCENDANT of this test process and whose executable name contains a given word (``firefox`` by default).
An inet connection - TCP in any state, SYN_SENT included, or a connected UDP socket - whose remote address is not
loopback is a DIRECT connection: the browser did not go through the proxy (the proxy of a test is on 127.0.0.1).
It also lists the names of every descendant it saw, which is how a test shows that no helper process
(crash reporter, updater...) was ever started. Descendants of THIS process only, so parallel workers do not see
each other's browsers.
* :class:`ResolverTrap` listens on 127.0.0.1:53 (UDP and TCP, and ::1 when it can) and points ``/etc/resolv.conf``
at it for as long as it runs, restoring the file byte for byte at the end, so every question that reaches the
resolver of the machine is counted as ``(name, qtype)``. It needs Linux, root and a writable resolv.conf:
``ResolverTrap.available`` says so and ``ResolverTrap.reason`` says why not. The trap answers from ``answers``
(name -> IPv4) and REFUSES everything else at once, so nothing waits for it. Anything on the machine that resolves
a name while it runs is counted too, the test process included: a test must not resolve names itself.
``ResolverTrap(port=0, rewrite_resolv_conf=False)`` is the same trap on a free port with no file touched, for the
unit tests of the trap itself and for a client that is told where to ask.
"""
from __future__ import annotations
import ipaddress
import os
import socket
import struct
import sys
import threading
import time
from pathlib import Path
from typing import Dict, Iterable, List, NamedTuple, Optional, Set, Tuple
from _doh_servers import RCODE_REFUSED, DohQuery, answer_for, build_response, parse_query
RESOLV_CONF = Path("/etc/resolv.conf")
# --------------------------------------------------------------------------------------------------------- Watcher
class DirectConnection(NamedTuple):
pid: int
process: str # the name of the process
protocol: str # "tcp" or "udp"
local: str
remote: str # "ip:port"
status: str
def _is_loopback(ip: str) -> bool:
try:
address = ipaddress.ip_address(ip.split("%")[0])
except ValueError:
return False
if address.version == 6 and address.ipv4_mapped is not None:
address = address.ipv4_mapped
return address.is_loopback
def _connections_of(process) -> list:
getter = getattr(process, "net_connections", None) or process.connections
return getter(kind="inet")
class Watcher:
"""Samples every ``interval`` seconds. Use as a context manager, or ``start()`` and ``stop()``.
``match`` is a word (or several) searched, case-insensitively, in the name of a process: only the connections of
the descendants whose name contains one of them are judged. Every descendant, matching or not, is listed in
:attr:`process_names`.
"""
def __init__(self, *, interval: float = 0.02, match: Iterable[str] | str = "firefox", root_pid: Optional[int] = None):
self.interval = interval
self.match = tuple(m.lower() for m in ([match] if isinstance(match, str) else match))
self.root_pid = root_pid if root_pid is not None else os.getpid()
#: Every direct connection seen, once per (pid, remote, status).
self.direct: List[DirectConnection] = []
#: Names of the descendants seen, in the order they were first seen (one entry per name).
self.process_names: List[str] = []
#: pids of the matching descendants seen.
self.watched_pids: Set[int] = set()
self.samples = 0
self._seen_keys: Set[tuple] = set()
self._stop = threading.Event()
self._thread: Optional[threading.Thread] = None
# --- control -------------------------------------------------------------------------------------------------
def start(self) -> "Watcher":
if self._thread is None:
self._thread = threading.Thread(target=self._run, daemon=True, name="leak-watcher")
self._thread.start()
return self
def stop(self) -> "Watcher":
self._stop.set()
if self._thread is not None:
self._thread.join(timeout=5)
self._thread = None
return self
def __enter__(self) -> "Watcher":
return self.start()
def __exit__(self, *exc) -> None:
self.stop()
# --- what a test asks ----------------------------------------------------------------------------------------
def describe(self) -> str:
return "; ".join("%s(pid %d) %s %s -> %s %s" % (c.process, c.pid, c.protocol, c.local, c.remote, c.status)
for c in self.direct) or "nothing"
def helpers_seen(self, forbidden: Iterable[str]) -> List[str]:
"""The process names whose stem (the name without its extension) contains one of ``forbidden``."""
words = [w.lower() for w in forbidden]
return [n for n in self.process_names if any(w in os.path.splitext(n)[0].lower() for w in words)]
# --- the sampling --------------------------------------------------------------------------------------------
def _run(self) -> None:
import psutil
root = None
while not self._stop.is_set():
started = time.monotonic()
try:
root = root or psutil.Process(self.root_pid)
children = root.children(recursive=True)
except psutil.Error:
children = []
for child in children:
try:
name = child.name()
except psutil.Error:
continue
if name not in self.process_names:
self.process_names.append(name)
if not any(m in name.lower() for m in self.match):
continue
self.watched_pids.add(child.pid)
try:
connections = _connections_of(child)
except (psutil.Error, OSError):
continue
for c in connections:
if not c.raddr or _is_loopback(c.raddr.ip):
continue
protocol = "udp" if c.type == socket.SOCK_DGRAM else "tcp"
key = (child.pid, protocol, c.raddr.ip, c.raddr.port, c.status)
if key in self._seen_keys:
continue
self._seen_keys.add(key)
self.direct.append(DirectConnection(
child.pid, name, protocol, "%s:%s" % (c.laddr.ip, c.laddr.port) if c.laddr else "",
"%s:%s" % (c.raddr.ip, c.raddr.port), c.status))
self.samples += 1
self._stop.wait(max(0.0, self.interval - (time.monotonic() - started)))
# ---------------------------------------------------------------------------------------------------- ResolverTrap
def _trap_capability() -> Tuple[bool, str]:
if not sys.platform.startswith("linux"):
return False, "the resolver trap needs Linux (it points /etc/resolv.conf at itself)"
if os.geteuid() != 0:
return False, "the resolver trap needs root (port 53 and /etc/resolv.conf)"
if not os.access(RESOLV_CONF, os.W_OK):
return False, "/etc/resolv.conf is not writable"
return True, ""
class ResolverTrap:
"""A resolver on loopback that counts what it is asked. See the module docstring."""
available, reason = _trap_capability()
def __init__(self, answers: Optional[Dict[str, str]] = None, *, port: int = 53,
rewrite_resolv_conf: bool = True):
self.answers = {k.lower(): v for k, v in (answers or {}).items()}
self.port = port
self.rewrite_resolv_conf = rewrite_resolv_conf
#: Every question: (name, qtype, "udp"|"tcp").
self.queries: List[DohQuery] = []
self._lock = threading.Lock()
self._sockets: List[socket.socket] = []
self._original: Optional[bytes] = None
self._running = False
# --- what a test reads ---------------------------------------------------------------------------------------
def names(self) -> List[str]:
with self._lock:
return sorted({q.name for q in self.queries})
def asked(self, name: str, qtype: Optional[int] = None) -> List[DohQuery]:
name = name.lower().rstrip(".")
with self._lock:
return [q for q in self.queries if q.name == name and (qtype is None or q.qtype == qtype)]
def describe(self) -> str:
with self._lock:
return ", ".join("%s/%d (%s)" % q for q in self.queries) or "nothing"
# --- control -------------------------------------------------------------------------------------------------
def __enter__(self) -> "ResolverTrap":
if self.rewrite_resolv_conf and not self.available:
raise RuntimeError(self.reason)
try:
self._bind()
if self.rewrite_resolv_conf:
self._original = RESOLV_CONF.read_bytes()
# In place, not by rename: in a container the file is often a bind mount.
with open(RESOLV_CONF, "wb") as f:
f.write(b"nameserver 127.0.0.1\noptions timeout:1 attempts:1\n")
except BaseException:
self._restore()
raise
self._running = True
return self
def __exit__(self, *exc) -> None:
self._running = False
self._restore()
def _restore(self) -> None:
if self._original is not None:
with open(RESOLV_CONF, "wb") as f:
f.write(self._original)
self._original = None
for s in self._sockets:
try:
s.close()
except OSError:
pass
self._sockets = []
def _bind(self) -> None:
"""UDP and TCP on 127.0.0.1 (required) and on ::1 (when it can): the same port for all of them."""
discarded: List[socket.socket] = [] # closed at the end, so a failed attempt's port is not handed out again
made: List[socket.socket] = []
try:
for attempt in range(200):
made = self._bind_once(discarded)
if made:
break
if self.port != 0:
break
if not made:
raise OSError("the resolver trap found no port it could bind for TCP and UDP")
finally:
for s in discarded:
s.close()
self._sockets += made
for s in made:
target = self._serve_udp if s.type == socket.SOCK_DGRAM else self._serve_tcp
threading.Thread(target=target, args=(s,), daemon=True).start()
def _bind_once(self, discarded: List[socket.socket]) -> List[socket.socket]:
"""One attempt: the sockets bound, or [] after putting what it opened in ``discarded``."""
made: List[socket.socket] = []
port = self.port
for family, host, required in ((socket.AF_INET, "127.0.0.1", True), (socket.AF_INET6, "::1", False)):
pair: List[socket.socket] = [] # this family's TCP and UDP, kept or dropped together
try:
# TCP first: Windows keeps big excluded ranges and hands out ephemeral ports in sequence, so a
# UDP-first pick can land in a range TCP may not bind, again and again.
tcp = socket.socket(family, socket.SOCK_STREAM)
pair.append(tcp)
if sys.platform != "win32": # on Windows SO_REUSEADDR is "share the port": it breaks bind
tcp.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
tcp.bind((host, port))
if port == 0:
port = tcp.getsockname()[1]
tcp.listen(16)
udp = socket.socket(family, socket.SOCK_DGRAM)
pair.append(udp)
udp.bind((host, port))
except OSError:
discarded += pair
if required:
discarded += made
return []
continue
made += pair
self.port = port
return made
# --- answering -----------------------------------------------------------------------------------------------
def _respond(self, message: bytes, protocol: str) -> Optional[bytes]:
try:
query = parse_query(message)
except ValueError:
return None
with self._lock:
self.queries.append(DohQuery(query.name, query.qtype, protocol))
if query.name in self.answers:
return answer_for(self.answers, query)
return build_response(query, RCODE_REFUSED)
def _serve_udp(self, sock: socket.socket) -> None:
while True:
try:
data, peer = sock.recvfrom(4096)
except OSError:
return
response = self._respond(data, "udp")
if response is not None:
try:
sock.sendto(response, peer)
except OSError:
pass
def _serve_tcp(self, listener: socket.socket) -> None:
while True:
try:
conn, _ = listener.accept()
except OSError:
return
threading.Thread(target=self._tcp_conversation, args=(conn,), daemon=True).start()
def _tcp_conversation(self, conn: socket.socket) -> None:
try:
conn.settimeout(5)
while True:
head = conn.recv(2)
if len(head) < 2:
return
size = struct.unpack("!H", head)[0]
message = b""
while len(message) < size:
chunk = conn.recv(size - len(message))
if not chunk:
return
message += chunk
response = self._respond(message, "tcp")
if response is None:
return
conn.sendall(struct.pack("!H", len(response)) + response)
except OSError:
pass
finally:
conn.close()
__all__ = ["DirectConnection", "ResolverTrap", "Watcher"]
+103
View File
@@ -0,0 +1,103 @@
"""Stand-ins for what the server's pointer talks to: the page's engine side
(`Actions`), the page's script (`InjectedScript`) and a clock.
Nothing launches a browser. `make_pointer` builds a real `Pointer` over them, the
way `PageDispatcher._build` does, and the page records what the engine would
receive.
"""
from __future__ import annotations
from invisible_playwright._juggler import pointer as pointer_mod
from invisible_playwright._juggler.pointer import Pointer
# A 100x40 control at (400, 300): centre exactly (450, 320).
BOX = {"x": 400.0, "y": 300.0, "width": 100.0, "height": 40.0}
class VirtualClock:
"""A clock that only advances when something sleeps.
Plumbing assertions must not be at the mercy of what the machine running
them was doing at the time. The dispatcher drops waypoints it cannot
deliver on time; against a clock that never falls behind nothing is dropped
and the behaviour is exactly reproducible."""
def __init__(self) -> None:
self.t = 0.0
def now(self) -> float:
return self.t
def sleep(self, seconds: float) -> None:
self.t += max(0.0, seconds)
class LateClock(VirtualClock):
"""A platform that always oversleeps by a fixed amount: Windows with its
default 15.6 ms timer tick, in a form that can be asserted on exactly."""
def __init__(self, overshoot: float = 0.006) -> None:
super().__init__()
self.overshoot = overshoot
def sleep(self, seconds: float) -> None:
self.t += max(0.0, seconds) + self.overshoot
class FakeActions:
def __init__(self, page) -> None:
self._page = page
self.position = (0.0, 0.0)
def move(self, x, y, steps=1):
self._page.moves.append((round(x, 4), round(y, 4)))
self.position = (x, y)
def wheel(self, dx, dy):
self._page.wheels.append((dx, dy))
def hit_target(self, frame_id, element, point):
self._page.hit_asked.append((frame_id, element, point))
return "done" if self._page.hits else "other"
class FakeInjected:
def __init__(self, page) -> None:
self._page = page
def query_selector(self, frame_id, selector, strict=False):
self._page.queried.append((frame_id, selector))
return "el" if self._page.box is not None else None
def bounding_box(self, frame_id, element):
return dict(self._page.box) if self._page.box else None
def dispose(self, frame_id, element):
self._page.disposed.append(element)
class FakePage:
def __init__(self, width=1280, height=720, box=BOX, hits=True) -> None:
self.viewport_size = {"width": width, "height": height}
self.box = box
self.hits = hits
self.moves = []
self.wheels = []
self.hit_asked = []
self.queried = []
self.disposed = []
self.actions = FakeActions(self)
self.injected = FakeInjected(self)
def make_pointer(seed=4242, max_seconds=1.5, *, number=0, width=1280,
height=720, box=BOX, hits=True, draws=True):
"""A real `Pointer` on a fake page. Returns `(page, pointer)`."""
page = FakePage(width, height, box, hits)
pointer = Pointer(page.actions, page.injected, number, seed, max_seconds,
lambda: page.viewport_size, draws=draws)
return page, pointer
def use_clock(monkeypatch, clock) -> None:
monkeypatch.setattr(pointer_mod, "_CLOCK", clock)
+443
View File
@@ -0,0 +1,443 @@
"""Three local SOCKS5 gateways on 127.0.0.1, for tests that need a real wire.
Reusable: nothing here knows about the core. A test (or the wrapper's system
test) starts one with ``with coherent() as gw:`` and points the product at
``gw.server`` (``socks5://127.0.0.1:<port>``), with ``gw.credentials`` when the
gateway asks for a user and password.
The three gateways are the three things a real one can be:
* :func:`coherent` - TCP CONNECT works, UDP ASSOCIATE is granted, and the relay
carries a STUN binding request to a fake STUN server that answers with the
SAME address the TCP side reports as the exit. This is the gateway whose UDP
can be trusted.
* :func:`tcp_only` - TCP CONNECT works, UDP ASSOCIATE is refused with reply code
7 ("command not supported"), the way a residential gateway does.
* :func:`mismatched` - UDP ASSOCIATE is granted and STUN answers, but with an
address DIFFERENT from the TCP exit: the disagreement a detector looks for.
Everything is on loopback, so the "exit address" is made observable and
controllable instead of real: the TCP exit is what the gateway's fake "what is
my address" endpoint (``api.ipify.org:80``, the one the product asks) answers,
and the UDP exit is what the fake STUN server puts in its XOR-MAPPED-ADDRESS.
Both are chosen by the test (``tcp_exit`` and ``udp_exit`` arguments).
Any other CONNECT is really forwarded, and any other UDP datagram is really
forwarded to its destination and the reply wrapped back, so a page, or an echo
server on 127.0.0.1, can be reached through the gateway and the test can
observe which road its bytes took (:attr:`Gateway.connects`,
:attr:`Gateway.datagrams`).
This is the ONE SOCKS5 gateway of the test suite. A road that needs more than the three above (a TURN server, a resolver,
a page, by NAME: ``tests/_turn_chain.py``) subclasses :class:`Gateway` and overrides the small hooks (:meth:`Gateway._route`,
:meth:`Gateway._target`, :attr:`Gateway.whoami_names`) instead of re-implementing the greeting, the authentication, the
ASSOCIATE, the relay or the round trip.
"""
from __future__ import annotations
import os
import socket
import struct
import threading
import time
from typing import List, Optional, Tuple
#: The name the product's STUN probe sends through the relay. The relay maps it
#: to the fake STUN server; every other destination is forwarded for real.
STUN_NAME = "stun.l.google.com"
STUN_PORT = 19302
#: The same STUN server by NUMBER. A page cannot resolve a name behind the session (the engine forbids local
#: resolution), so the wrapper's system test hands the page this address; like the name it is a documentation
#: address (RFC 5737, TEST-NET-2), unroutable: the only road to it is the relay, which maps it to the fake STUN
#: server. (A copy of invisible_core's tests/_socks_servers.py with this one addition.)
STUN_NUMBER = "198.51.100.5"
#: A page the gateway serves itself, for a test that loads one through the proxy (a name nothing else resolves).
WEB_NAME = "page.test"
#: The echo endpoints the product asks for its TCP exit.
WHOAMI4 = ("api.ipify.org", 80)
WHOAMI6 = ("api6.ipify.org", 80)
_MAGIC = b"\x21\x12\xa4\x42"
def _recv_exact(s: socket.socket, n: int) -> bytes:
data = b""
while len(data) < n:
chunk = s.recv(n - len(data))
if not chunk:
raise ConnectionError("closed")
data += chunk
return data
class FakeStun:
"""A UDP STUN server that answers every binding request with ``mapped_ip``."""
def __init__(self, mapped_ip: str, mapped_port: int = 40000):
self.mapped_ip = mapped_ip
self.mapped_port = mapped_port
self.requests = 0
self._sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
self._sock.bind(("127.0.0.1", 0))
self.address: Tuple[str, int] = self._sock.getsockname()
self._thread = threading.Thread(target=self._serve, daemon=True)
self._thread.start()
def _serve(self) -> None:
while True:
try:
data, peer = self._sock.recvfrom(2048)
except OSError:
return
if len(data) < 20 or data[0:2] != b"\x00\x01":
continue
self.requests += 1
txid = data[8:20]
xport = struct.pack("!H", self.mapped_port ^ 0x2112)
xaddr = bytes(a ^ b for a, b in zip(socket.inet_aton(self.mapped_ip), _MAGIC))
attr = struct.pack("!HH", 0x0020, 8) + b"\x00\x01" + xport + xaddr
resp = b"\x01\x01" + struct.pack("!H", len(attr)) + _MAGIC + txid + attr
try:
self._sock.sendto(resp, peer)
except OSError:
return
def close(self) -> None:
self._sock.close()
class Gateway:
"""A SOCKS5 server. ``udp`` is ``"relay"`` or ``"refuse"`` (reply code 7)."""
def __init__(self, *, udp: str, tcp_exit: str, udp_exit: str,
user: Optional[str] = None, password: Optional[str] = None,
relay_host: str = "127.0.0.1", rtt_ms: int = 0,
exit_host: str = "127.0.0.1", tcp_data_delay: bool = False):
assert udp in ("relay", "refuse")
self.udp = udp
#: The round trip to this gateway, in seconds: every answer on the control connection waits for it, and each
#: datagram the relay carries waits half of it each way. A real gateway is not on loopback.
self.rtt = rtt_ms / 1000.0
#: The address of the UDP relay, the BND.ADDR of the association. A real gateway's is a routable address; the
#: loopback default only suits a client whose UDP socket is not bound to an interface (an engine's ICE
#: sockets are, and Windows does not send from an interface address to loopback).
self.relay_host = relay_host
#: The local address the relay's datagrams leave from (the source a server behind the gateway sees). Another
#: loopback address makes a client that sent direct (from 127.0.0.1) tell apart from one that used the relay.
self.exit_host = exit_host
#: Whether each chunk of a forwarded TCP stream also waits half the round trip (a far gateway), as the datagrams do.
self.tcp_data_delay = tcp_data_delay
self.tcp_exit = tcp_exit
self.user, self.password = user, password
self.stun = FakeStun(udp_exit)
#: Every CONNECT, as (host, port), in order.
self.connects: List[Tuple[str, int]] = []
#: Every UDP ASSOCIATE request, answered or refused.
self.associates = 0
#: When the gateway started: the origin of the times below.
self.t0 = time.monotonic()
#: Every UDP ASSOCIATE that was granted, as [start, end] seconds from t0; end is None until it was answered.
self.associations: List[List[Optional[float]]] = []
#: Every datagram the relay carried out, as (host as sent, port, address type, seconds from t0).
self.datagram_log: List[Tuple[str, int, int, float]] = []
#: Every datagram the relay carried out, as (host, port, payload).
self.datagrams: List[Tuple[str, int, bytes]] = []
self._listener = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
self._listener.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
self._listener.bind(("127.0.0.1", 0))
self._listener.listen(32)
self.port: int = self._listener.getsockname()[1]
self._closed = False
threading.Thread(target=self._accept, daemon=True).start()
# --- what the test hands to the product ---------------------------------
@property
def server(self) -> str:
return "socks5://127.0.0.1:%d" % self.port
@property
def credentials(self) -> dict:
return ({"username": self.user, "password": self.password}
if self.user is not None else {})
@property
def proxy(self) -> dict:
"""The endpoint dict the core takes: ``{"server": ..., [credentials]}``."""
return dict({"server": self.server}, **self.credentials)
def close(self) -> None:
self._closed = True
for s in (self._listener,):
try:
s.close()
except OSError:
pass
self.stun.close()
def __enter__(self) -> "Gateway":
return self
def __exit__(self, *exc) -> None:
self.close()
# --- the TCP side --------------------------------------------------------
def _send(self, c: socket.socket, data: bytes) -> None:
if self.rtt:
time.sleep(self.rtt)
c.sendall(data)
def _accept(self) -> None:
while not self._closed:
try:
conn, _ = self._listener.accept()
except OSError:
return
threading.Thread(target=self._handle, args=(conn,), daemon=True).start()
def _greet(self, c: socket.socket) -> bool:
ver, n = _recv_exact(c, 2)
methods = _recv_exact(c, n)
if ver != 5:
return False
if self.user is not None:
if 2 not in methods:
self._send(c, b"\x05\xff")
return False
self._send(c, b"\x05\x02")
_recv_exact(c, 1)
u = _recv_exact(c, _recv_exact(c, 1)[0]).decode()
p = _recv_exact(c, _recv_exact(c, 1)[0]).decode()
ok = (u, p) == (self.user, self.password)
self._send(c, b"\x01" + (b"\x00" if ok else b"\x01"))
return ok
self._send(c, b"\x05\x00" if 0 in methods else b"\x05\x02")
if 0 not in methods: # a client that only offers user/password: accept any
_recv_exact(c, 1)
_recv_exact(c, _recv_exact(c, 1)[0])
_recv_exact(c, _recv_exact(c, 1)[0])
self._send(c, b"\x01\x00")
return True
@staticmethod
def _read_address(c: socket.socket) -> Tuple[str, int]:
atyp = _recv_exact(c, 1)[0]
if atyp == 1:
host = socket.inet_ntoa(_recv_exact(c, 4))
elif atyp == 3:
host = _recv_exact(c, _recv_exact(c, 1)[0]).decode()
else:
host = socket.inet_ntop(socket.AF_INET6, _recv_exact(c, 16))
return host, struct.unpack("!H", _recv_exact(c, 2))[0]
@staticmethod
def _reply(rep: int, host: str = "0.0.0.0", port: int = 0) -> bytes:
return b"\x05" + bytes([rep]) + b"\x00\x01" + socket.inet_aton(host) + struct.pack("!H", port)
def _handle(self, c: socket.socket) -> None:
try:
c.settimeout(30)
if not self._greet(c):
return
ver, cmd, _rsv = _recv_exact(c, 3)
host, port = self._read_address(c)
if cmd == 1:
self._connect(c, host, port)
elif cmd == 3:
self._associate(c)
else:
self._send(c, self._reply(7))
except (OSError, ConnectionError):
pass
finally:
try:
c.close()
except OSError:
pass
#: The names the product asks "what is my address" of (on port 80); each is answered with ``tcp_exit``.
whoami_names: Tuple[str, ...] = (WHOAMI4[0],)
def _target(self, host: str, port: int) -> Tuple[str, int]:
"""Where a CONNECT that is not a special one really goes. A subclass maps a name to a local server."""
return host, port
def _connect(self, c: socket.socket, host: str, port: int) -> None:
self.connects.append((host, port))
if host.lower() in self.whoami_names and port == WHOAMI4[1]:
self._send(c, self._reply(0))
_ = c.recv(4096)
body = self.tcp_exit.encode()
self._send(c, b"HTTP/1.1 200 OK\r\nContent-Type: text/plain\r\nContent-Length: %d\r\n"
b"Connection: close\r\n\r\n%s" % (len(body), body))
return
if (host, port) == WHOAMI6:
self._send(c, self._reply(4)) # no IPv6 exit
return
if (host, port) == (WEB_NAME, 80): # a page that only the gateway can reach
self._send(c, self._reply(0))
_ = c.recv(4096)
body = b"<html><body>behind the gateway</body></html>"
self._send(c, b"HTTP/1.1 200 OK\r\nContent-Type: text/html\r\nContent-Length: %d\r\n"
b"Connection: close\r\n\r\n%s" % (len(body), body))
return
try:
up = socket.create_connection(self._target(host, port), timeout=10)
except OSError:
self._send(c, self._reply(5))
return
self._send(c, self._reply(0))
c.settimeout(None)
up.settimeout(None)
def pump(a: socket.socket, b: socket.socket) -> None:
try:
while True:
d = a.recv(65536)
if not d:
break
if self.tcp_data_delay and self.rtt:
time.sleep(self.rtt / 2)
b.sendall(d)
except OSError:
pass
finally:
for s in (a, b):
try:
s.shutdown(socket.SHUT_RDWR)
except OSError:
pass
t = threading.Thread(target=pump, args=(up, c), daemon=True)
t.start()
pump(c, up)
t.join(timeout=2)
up.close()
# --- the UDP side --------------------------------------------------------
def _later(self, fn) -> None:
"""Run ``fn`` after half the round trip (at once on loopback), ignoring a socket that is already closed."""
def run() -> None:
try:
fn()
except OSError:
pass
threading.Timer(self.rtt / 2, run).start() if self.rtt else run()
def _deliver(self, relay: socket.socket, to: Tuple[str, int], host: str, port: int, payload: bytes) -> None:
"""Wrap ``payload`` as coming from ``host``:``port`` (an IPv4 literal) and send it back to the client."""
data = b"\x00\x00\x00\x01" + socket.inet_aton(host) + struct.pack("!H", port) + payload
self._later(lambda: relay.sendto(data, to))
def _route(self, host: str, dport: int, atyp: int, payload: bytes, out_port: int,
answer) -> Optional[Tuple[Tuple[str, int], Optional[Tuple[str, int]]]]:
"""Where one datagram of the client goes: ``(target, reported_as)``, or None when it is dropped.
``target`` is the real address the datagram is sent to from the exit socket (``out_port`` is that socket's port);
``reported_as`` is the address the client is told the reply came from (None: the real source). A subclass may also
answer by itself with ``answer(host, port, data)``. By default the fake STUN server, by name or by number, is
mapped and everything else is forwarded for real."""
if (host, dport) in ((STUN_NAME, STUN_PORT), (STUN_NUMBER, STUN_PORT)):
# A real server answers from the address it was asked at; the fake STUN server is mapped, so its reply is
# reported as from the asked address (only when that was a literal: a name has no address to report).
return self.stun.address, ((host, dport) if atyp == 1 else None)
return (host, dport), None
def _associate(self, c: socket.socket) -> None:
self.associates += 1
if self.udp == "refuse":
self._send(c, self._reply(7))
return
record: List[Optional[float]] = [time.monotonic() - self.t0, None]
self.associations.append(record)
relay = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
relay.bind((self.relay_host, 0))
out = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
out.bind((self.exit_host, 0))
client: List[Optional[Tuple[str, int]]] = [None]
#: Where a mapped destination really is -> the address the client is told it answered from.
asked_at: dict = {}
self._send(c, self._reply(0, self.relay_host, relay.getsockname()[1]))
record[1] = time.monotonic() - self.t0
def answer(host: str, port: int, data: bytes) -> None:
self._deliver(relay, client[0], host, port, data)
def inbound() -> None: # client -> world
while True:
try:
d, peer = relay.recvfrom(65536)
except OSError:
return
if len(d) < 10 or d[2] != 0:
continue
client[0] = peer
atyp, i = d[3], 4
if atyp == 1:
host, i = socket.inet_ntoa(d[i:i + 4]), i + 4
elif atyp == 3:
n = d[i]
host, i = d[i + 1:i + 1 + n].decode(), i + 1 + n
else:
host, i = socket.inet_ntop(socket.AF_INET6, d[i:i + 16]), i + 16
dport = struct.unpack("!H", d[i:i + 2])[0]
payload = d[i + 2:]
self.datagrams.append((host, dport, payload))
self.datagram_log.append((host, dport, atyp, time.monotonic() - self.t0))
routed = self._route(host, dport, atyp, payload, out.getsockname()[1], answer)
if routed is None:
continue
target, reported = routed
if reported is not None:
asked_at[target] = reported
self._later(lambda p=payload, t=target: out.sendto(p, t))
def outbound() -> None: # world -> client
while True:
try:
d, src = out.recvfrom(65536)
except OSError:
return
if client[0] is None:
continue
host, port = asked_at.get(src, src)
self._deliver(relay, client[0], host, port, d)
threading.Thread(target=inbound, daemon=True).start()
threading.Thread(target=outbound, daemon=True).start()
try: # the association lives as long as the control connection
c.settimeout(None)
while c.recv(1024):
pass
except OSError:
pass
finally:
relay.close()
out.close()
#: Documentation addresses (RFC 5737): never a real host, so nothing in a test
#: can be mistaken for the machine's own address.
EXIT = "203.0.113.7"
OTHER_EXIT = "198.51.100.4"
def coherent(*, exit_ip: str = EXIT, user: Optional[str] = None,
password: Optional[str] = None, relay_host: str = "127.0.0.1", rtt_ms: int = 0) -> Gateway:
"""TCP and UDP both work, and both leave from ``exit_ip``."""
return Gateway(udp="relay", tcp_exit=exit_ip, udp_exit=exit_ip,
user=user, password=password, relay_host=relay_host, rtt_ms=rtt_ms)
def tcp_only(*, exit_ip: str = EXIT, user: Optional[str] = None,
password: Optional[str] = None) -> Gateway:
"""TCP works; UDP ASSOCIATE is refused with reply code 7."""
return Gateway(udp="refuse", tcp_exit=exit_ip, udp_exit=exit_ip,
user=user, password=password)
def mismatched(*, tcp_exit: str = EXIT, udp_exit: str = OTHER_EXIT,
user: Optional[str] = None, password: Optional[str] = None) -> Gateway:
"""UDP is granted and STUN answers, with an address that is not the TCP exit."""
assert udp_exit != tcp_exit
return Gateway(udp="relay", tcp_exit=tcp_exit, udp_exit=udp_exit,
user=user, password=password)
+26
View File
@@ -0,0 +1,26 @@
"""When the resolver trap is mandatory (the gate's Linux leg of the DoH suite) a trap that cannot run is a failure.
`INVPW_REQUIRE_TRAP=1` is set by the gate on the leg where the trap can run (Linux, root). With it, an unavailable
trap or a port 53 that cannot be bound fails the test with the reason, instead of letting the assertions on the
machine's resolver be skipped in silence. Without it (a developer's machine) the old behaviour stays.
"""
from __future__ import annotations
import os
ENV = "INVPW_REQUIRE_TRAP"
def required(environ=None) -> bool:
return (os.environ if environ is None else environ).get(ENV) == "1"
def failure(environ, available: bool, reason: str = "", bind_error=None):
"""-> the message to fail with, or None when the test may go on (with or without a trap)."""
if not required(environ):
return None
if not available:
return "%s=1 but the resolver trap cannot run here: %s" % (ENV, reason or "no reason given")
if bind_error is not None:
return "%s=1 but the resolver trap could not bind its port: %s" % (ENV, bind_error)
return None
+333
View File
@@ -0,0 +1,333 @@
"""A whole, hermetic road for a page that asks for a TURN allocation BY NAME behind a SOCKS5 gateway that carries UDP.
Nothing here is a real server of anybody: everything is on loopback, and the only way to anything is the gateway.
The design this road keeps: a browser behind a proxy resolves every name with the DoH of Firefox, THROUGH the proxy
(``network.trr.mode`` 3, ``https://mozilla.cloudflare-dns.com/dns-query``, found with no DNS at 162.159.61.4). So the name of the
TURN server is a DoH question, carried by a SOCKS5 CONNECT; the answer is an ADDRESS, and the datagrams of the allocation go to
that address, by SOCKS5 address type 1, through the UDP relay. The gateway resolves nothing and answers no DNS query.
* :class:`TurnServer` - a TURN server (RFC 5766, the part a browser uses): Allocate answered 401 with a realm and a nonce, then
answered with the relayed and the mapped address under a long-term credential, checked and signed (MESSAGE-INTEGRITY), so
the browser's ICE agent accepts it as it accepts a real one. It records the SOURCE it saw for every datagram: that is the
address a real TURN server would report as the browser's, and the one the verdict compares with.
* :class:`Chain` - the SOCKS5 gateway of the tests (``_socks_servers.Gateway``, with the DoH road of
``_doh_servers.DohGateway``: greeting, ASSOCIATE, relay and the round trip of a gateway that is far away, ``rtt_ms``, for the
control connection, the datagrams and the TCP tunnels, are all there, not here). Told where this world's roads go: a CONNECT
to the DoH goes to the :class:`_doh_servers.FakeDoh` of the chain, whose zone is the TURN name and the page name; a CONNECT
to a loopback address (the page, once its name is resolved) is relayed; a datagram to the TURN's documentation address goes
to the TURN server; a STUN binding request to anything else is answered with the exit. A datagram that carries a NAME or
goes to port 53 is dropped and recorded (the roads the product must not use). Datagrams leave from ``EXIT_HOST`` (another
loopback address), so the TURN server sees a source that is not the browser's own: if it sees the browser's, the road was
not the gateway's.
* :class:`Page` - the page and the verdict, with the shape of a leak test's logic: a tick of 2 seconds after the page starts that
marks TIMEOUT, cleared only after a POST made when a server-reflexive candidate arrives; the server compares the address
of that candidate with the source the TURN saw.
The names and the addresses are RFC 2606 / RFC 5737: nothing in a test can be mistaken for a real host.
"""
from __future__ import annotations
import hashlib
import hmac
import json
import socket
import struct
import threading
import time
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
from typing import Dict, List, Optional, Tuple
from _doh_servers import DohGateway, FakeDoh
from _socks_servers import WHOAMI4, Gateway
TURN_NAME = "turn.relay-only.test"
PAGE_NAME = "page.relay-only.test"
#: RFC 5737 TEST-NET-2: unroutable, so the only road to it is the gateway, which maps it to the TURN server.
TURN_IP = "198.51.100.7"
TURN_PORT = 3478
RELAYED = ("198.51.100.7", 50000)
#: Where the gateway's datagrams come from. A browser that sends direct comes from 127.0.0.1.
EXIT_HOST = "127.0.0.2"
MAGIC = 0x2112A442
PASSWORD = "qwerty"
REALM = "hermetic"
NONCE = "6e6f6e6365"
def this_host_address() -> str:
"""The address of this host that a socket bound to an interface can send from: the relay's BND.ADDR (a loopback relay
only suits a client whose UDP socket is not bound to an interface, and an engine's ICE sockets are)."""
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
try:
s.connect(("192.0.2.1", 9))
return s.getsockname()[0]
finally:
s.close()
# ── STUN / TURN wire ───────────────────────────────────────────────────────────
def _attrs(data: bytes) -> Dict[int, bytes]:
out: Dict[int, bytes] = {}
i = 20
while i + 4 <= len(data):
t, n = struct.unpack("!HH", data[i:i + 4])
out[t] = data[i + 4:i + 4 + n]
i += 4 + ((n + 3) & ~3)
return out
def _attr(t: int, v: bytes) -> bytes:
return struct.pack("!HH", t, len(v)) + v + b"\x00" * (-len(v) % 4)
def _xor_addr(ip: str, port: int) -> bytes:
xp = port ^ (MAGIC >> 16)
xa = struct.unpack("!I", socket.inet_aton(ip))[0] ^ MAGIC
return b"\x00\x01" + struct.pack("!HI", xp, xa)
def _message(mtype: int, tid: bytes, attrs: bytes, key: Optional[bytes] = None) -> bytes:
if key is None:
return struct.pack("!HHI", mtype, len(attrs), MAGIC) + tid + attrs
head = struct.pack("!HHI", mtype, len(attrs) + 24, MAGIC) + tid
mac = hmac.new(key, head + attrs, hashlib.sha1).digest()
return head + attrs + _attr(0x0008, mac)
class TurnServer:
"""UDP TURN server on 127.0.0.1. ``seen`` is every datagram as (source ip, source port, STUN type), in order;
``allocations`` the successful Allocates as (source ip, source port, username, time)."""
def __init__(self) -> None:
self.sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
self.sock.bind(("127.0.0.1", 0))
self.address: Tuple[str, int] = self.sock.getsockname()
self.seen: List[Tuple[str, int, int]] = []
self.allocations: List[Tuple[str, int, str, float]] = []
self._closed = False
threading.Thread(target=self._serve, daemon=True).start()
def close(self) -> None:
self._closed = True
self.sock.close()
def _serve(self) -> None:
while not self._closed:
try:
data, src = self.sock.recvfrom(65536)
except OSError:
return
if len(data) < 20 or struct.unpack("!I", data[4:8])[0] != MAGIC:
continue
mtype, tid = struct.unpack("!H", data[:2])[0], data[8:20]
self.seen.append((src[0], src[1], mtype))
attrs = _attrs(data)
if mtype == 0x0003: # Allocate
if 0x0008 not in attrs or 0x0006 not in attrs: # no credentials: 401 with a realm and a nonce
err = _attr(0x0009, b"\x00\x00\x04\x01Unauthorized") + _attr(0x0014, REALM.encode()) + _attr(0x0015, NONCE.encode())
self.sock.sendto(_message(0x0113, tid, err), src)
continue
user = attrs[0x0006].decode(errors="replace")
key = hashlib.md5(("%s:%s:%s" % (user, REALM, PASSWORD)).encode()).digest()
body = (_attr(0x0016, _xor_addr(*RELAYED)) + _attr(0x0020, _xor_addr(src[0], src[1])) +
_attr(0x000D, struct.pack("!I", 600)))
self.allocations.append((src[0], src[1], user, time.monotonic()))
self.sock.sendto(_message(0x0103, tid, body, key), src)
elif mtype in (0x0004, 0x0008, 0x0009): # Refresh, CreatePermission, ChannelBind
user = attrs.get(0x0006, b"").decode(errors="replace")
key = hashlib.md5(("%s:%s:%s" % (user, REALM, PASSWORD)).encode()).digest()
body = _attr(0x000D, struct.pack("!I", 600)) if mtype == 0x0004 else b""
self.sock.sendto(_message(mtype | 0x0100, tid, body, key), src)
# ── the gateway ────────────────────────────────────────────────────────────────
class Chain(DohGateway):
"""The one SOCKS5 gateway of the tests (``_socks_servers.Gateway`` through ``_doh_servers.DohGateway``), with UDP, the
DoH, the TURN server and the page behind it. A context manager.
What it does, and nothing else (it never resolves a name and never answers a DNS query):
* a CONNECT to the DoH (``162.159.61.4:443`` or ``mozilla.cloudflare-dns.com:443``) is handed to :attr:`doh`, whose zone
is the TURN name and the page name; a CONNECT to a loopback ADDRESS (the page, once its name is resolved) is relayed;
a CONNECT that carries any other name or address is refused and listed in :attr:`refused`;
* a datagram to ``TURN_IP:3478`` (address type 1) goes to the TURN server, which hears it from ``EXIT_HOST``; a STUN
binding request to anyone else is answered with the exit; everything else is dropped. A datagram that carries a NAME
(address type 3) or goes to port 53 is dropped and recorded: those are roads the product must not use.
"""
#: What the product asks "what is my address" of: answered with the exit.
whoami_names = ("api.ipify.org", "ifconfig.me", "icanhazip.com")
def __init__(self, *, rtt_ms: int = 130, relay_host: Optional[str] = None) -> None:
self.turn = TurnServer()
self.doh = FakeDoh({TURN_NAME: TURN_IP, PAGE_NAME: "127.0.0.1"})
self.page = Page(self)
super().__init__("chain", self.doh, udp="relay", tcp_exit=EXIT_HOST, udp_exit=EXIT_HOST,
relay_host=relay_host or this_host_address(), rtt_ms=rtt_ms,
exit_host=EXIT_HOST, tcp_data_delay=True)
def close(self) -> None:
super().close()
self.turn.close()
self.doh.close()
self.page.close()
def _connect(self, c, host, port) -> None:
if host.lower() in self.whoami_names and port == WHOAMI4[1]:
Gateway._connect(self, c, host, port) # the answer of "what is my address"
return
super()._connect(c, host, port)
def _route(self, host, dport, atyp, payload, out_port, answer):
if atyp == 1 and host == TURN_IP and dport == TURN_PORT:
return self.turn.address, (host, dport) # the TURN server answers as from the address it was asked at
if (atyp == 1 and dport != 53 and len(payload) >= 20 and payload[:2] == b"\x00\x01"
and struct.unpack("!I", payload[4:8])[0] == MAGIC):
# a STUN binding request to anyone else: answered by the gateway, with the exit as the mapped address
answer(host, dport, _message(0x0101, payload[8:20], _attr(0x0020, _xor_addr(EXIT_HOST, out_port))))
return None # a name, port 53, anything else: dropped (and in datagram_log)
# --- what a failed test says ----------------------------------------------
def explain(self, result: dict) -> str:
"""The road, as the DoH, the gateway, the TURN server and the page saw it, and the sentence that says where it stopped."""
turn_heard = list(self.turn.seen)
turn_asked = [q for q in self.doh.queries if q.name == TURN_NAME]
names_on_relay = [(h, p) for h, p, a, _t in self.datagram_log if a == 3]
dns_on_relay = [(h, p) for h, p, _a, _t in self.datagram_log if p == 53]
to_turn = [1 for h, p, a, _t in self.datagram_log if a == 1 and h == TURN_IP and p == TURN_PORT]
doh_connects = self.doh_connects()
lines = ["", "THE ROAD, as each server saw it:"]
lines.append(" DoH (reached only through the gateway): %d connection(s) %s, %d TLS failure(s) %s" % (
len(self.doh.connections), self.doh.connections[:4], len(self.doh.tls_failures), self.doh.tls_failures[:2]))
lines.append(" DoH queries (name, type, road): %s" % ([tuple(q) for q in self.doh.queries][:12] or "none"))
lines.append(" gateway: CONNECTs %s; refused %s; the DoH ones: %d" % (self.connects[:12], self.refused[:6], len(doh_connects)))
lines.append(" gateway: %d UDP ASSOCIATE (start -> answered, seconds): %s" % (
len(self.associations), ", ".join("%.2f->%s" % (a, "%.2f" % b if b is not None else "-") for a, b in self.associations) or "none"))
lines.append(" gateway: datagrams carried: %d (to %s:%d by address: %d; carrying a NAME, dropped: %s; to port 53, dropped: %s)" % (
len(self.datagram_log), TURN_IP, TURN_PORT, len(to_turn), names_on_relay[:4] or "none", dns_on_relay[:4] or "none"))
lines.append(" TURN server heard %d datagram(s) %s; allocations: %s" % (
len(turn_heard), [("%s:%d" % (s[0], s[1]), hex(s[2])) for s in turn_heard][:6],
[("%s:%d" % (a[0], a[1])) for a in self.turn.allocations]))
lines.append(" page server: asked for %s; verdicts: %s" % (
self.page.hits[:4] or "nothing", self.page.verdicts or "none: no server-reflexive candidate came before the tick, or the POST did not finish"))
lines.append(" page: %s" % json.dumps({k: result.get(k) for k in ("status", "timeline", "errors", "srflx", "candidates")}, default=str)[:900])
if not turn_asked:
if names_on_relay or dns_on_relay:
why = ("the name %r went along the UDP relay (%s) instead of being asked to the DoH: the gateway resolves nothing, so "
"no allocation could be asked for" % (TURN_NAME, names_on_relay or dns_on_relay))
elif self.doh.tls_failures:
why = "the browser reached the DoH but refused its certificate (%s): the context must accept it (ignore_https_errors)" % (self.doh.tls_failures[:1],)
elif not doh_connects:
why = ("the browser never asked the DoH: no CONNECT to the DoH reached the gateway (%s), so the name %r was not "
"resolved through the proxy and the browser never tried to reach the TURN server; the only "
"server-reflexive candidate the page can have is one the engine made up"
% (self.connects[:6] or "no CONNECT at all", TURN_NAME))
else:
why = ("the DoH was reached (%d connection(s)) but never asked for %r (it was asked %s): the lookup of the ICE "
"server name did not go to the DoH" % (len(self.doh.connections), TURN_NAME, self.doh.seen_names()))
elif "direct" in {q.via for q in turn_asked}:
why = "the name %r reached the DoH without the proxy (road 'direct')" % TURN_NAME
elif not turn_heard:
why = ("the name %r was resolved by the DoH (%s) but no datagram reached the TURN server: %s" % (
TURN_NAME, sorted({q.via for q in turn_asked}),
("the browser sent none to %s:%d by address through the relay (%d association(s), datagrams %s)" % (
TURN_IP, TURN_PORT, len(self.associations), [(h, p, a) for h, p, a, _t in self.datagram_log][:4]))
if not to_turn else "the answer did not come back"))
elif not self.turn.allocations:
why = "the TURN server heard the browser but no Allocate was answered with credentials: the 401 round trip did not finish"
elif result.get("status") == "TIMEOUT":
ends = [e for _s, e in self.associations if e is not None]
why = ("the allocation succeeded but too late for the tick of 2000 ms: the association handshakes alone ended at %s s"
% ", ".join("%.2f" % e for e in ends))
else:
why = "the srflx of the page is not the address the TURN server saw (%s)" % [("%s:%d" % (a[0], a[1])) for a in self.turn.allocations]
lines.append("WHY: " + why)
return "\n".join(lines)
# ── the page and the verdict ───────────────────────────────────────────────────
PAGE_HTML = """<!doctype html><meta charset=utf-8><title>relay-only</title><script>
const t0 = performance.now(), mark = (k) => (window.__result.timeline[k] = Math.round(performance.now() - t0));
window.__result = {status: 'PENDING', timeline: {}, errors: [], candidates: [], srflx: null};
let status = 'PENDING';
const finish = (s) => { status = s; window.__result.status = s; window.__done = true; };
document.addEventListener('DOMContentLoaded', () => {
mark('dom');
// the tick of a leak test: 2 seconds after the page starts. It is cleared only after the POST made on a srflx.
const tick = setInterval(() => { if (status === 'PENDING') { mark('tick'); finish('TIMEOUT'); } clearInterval(tick); }, 2000);
const pc = new RTCPeerConnection({iceServers: [{urls: ['turn:%(turn)s:%(port)d?transport=udp'], username: 'challenge-' + Date.now(), credential: '%(password)s'}]});
pc.createDataChannel('x');
mark('pc');
pc.onicegatheringstatechange = () => mark('gathering_' + pc.iceGatheringState);
pc.onicecandidateerror = (e) => window.__result.errors.push([e.errorCode, e.url]);
pc.onicecandidate = async (e) => {
if (!e.candidate) return;
window.__result.candidates.push(e.candidate.candidate);
if (e.candidate.candidate.indexOf(' typ srflx ') < 0 || status !== 'PENDING') return;
mark('srflx');
window.__result.srflx = e.candidate.candidate;
const r = await fetch('/verdict', {method: 'POST', body: JSON.stringify({srflx: e.candidate.candidate})});
mark('posted');
if (status !== 'PENDING') return;
clearInterval(tick);
finish((await r.json()).ok ? 'DONE' : 'REFUSED');
};
pc.createOffer().then((o) => pc.setLocalDescription(o));
});
</script>"""
class Page:
"""The page server (the browser asks the DoH for its NAME, then reaches the ADDRESS through the gateway) and the verdict."""
def __init__(self, chain: "Chain") -> None:
outer = self
self.verdicts: List[dict] = []
#: Every GET the page server answered: the Host header and the path.
self.hits: List[Tuple[str, str]] = []
class Handler(BaseHTTPRequestHandler):
timeout = 5
def log_message(self, *a):
pass
def do_GET(self):
outer.hits.append((self.headers.get("Host", ""), self.path))
body = (PAGE_HTML % {"turn": TURN_NAME, "port": TURN_PORT, "password": PASSWORD}).encode()
self.send_response(200)
self.send_header("Content-Type", "text/html; charset=utf-8")
self.send_header("Content-Length", str(len(body)))
self.end_headers()
self.wfile.write(body)
def do_POST(self):
n = int(self.headers.get("Content-Length") or 0)
cand = json.loads(self.rfile.read(n) or b"{}").get("srflx", "")
parts = cand.split()
ip, port = (parts[4], int(parts[5])) if len(parts) > 5 else ("", 0)
seen = [(a[0], a[1]) for a in chain.turn.allocations]
ok = bool(seen) and (ip, port) in seen and ip == EXIT_HOST
outer.verdicts.append({"srflx": "%s:%d" % (ip, port), "seen_by_the_turn": ["%s:%d" % s for s in seen], "ok": ok})
body = json.dumps({"ok": ok}).encode()
self.send_response(200)
self.send_header("Content-Type", "application/json")
self.send_header("Content-Length", str(len(body)))
self.end_headers()
self.wfile.write(body)
self.httpd = ThreadingHTTPServer(("127.0.0.1", 0), Handler)
self.httpd.daemon_threads = True
self.port: int = self.httpd.server_address[1]
threading.Thread(target=self.httpd.serve_forever, daemon=True).start()
@property
def url(self) -> str:
return "http://%s:%d/" % (PAGE_NAME, self.port)
def close(self) -> None:
self.httpd.shutdown()
+34 -3
View File
@@ -69,6 +69,12 @@ def _watchdog_open():
return _watchdog_handle
def pytest_configure(config):
# The run stops at the first refusal of the engine (tests/engine_refusal.py).
from engine_refusal import StopAtTheFirstRefusal
config.pluginmanager.register(StopAtTheFirstRefusal(config), "engine-refusal-stop")
def pytest_runtest_setup(item):
if item.get_closest_marker("e2e") is None:
return
@@ -120,6 +126,24 @@ def _require_package():
f"venv; any other test needs `pip install -e .`")
@pytest.fixture(autouse=True)
def _offline_session_geo(request, monkeypatch):
"""Outside the e2e, the one network step of composing a session (the egress
IP, `_session.session_geo`) answers a fixed geo: New York, en-US. A launch
that names no session composes one on the server (`session_for_launch`),
and a unit test that drives `op_launch` must not ask the network who it is."""
if request.node.get_closest_marker("e2e") is not None:
return
try:
from invisible_playwright import _session
from invisible_core import decide_session_locale
from invisible_core._geo import SessionGeo
except Exception: # the package is absent: the tests that need it say so
return
geo = SessionGeo("America/New_York", None, locale=decide_session_locale("en-US"))
monkeypatch.setattr(_session, "session_geo", lambda *_a, **_k: geo)
@pytest.fixture
def deterministic_rng():
"""Seeded RNG for reproducible tests."""
@@ -188,8 +212,8 @@ def firefox_binary():
# so a property only the newer engine promises must not run on the older one.
#
# The engine is read from the seal the process runs under, the same one that
# checks the launch: `active_seal().tag`. Only the number counts: `firefox-60`
# and `firefox-60-candidate` are both 60. A tag with no number (`local`, or
# checks the launch: `active_seal().tag`. Only the number counts: `firefox-64`
# and `firefox-64-candidate` are both 64. A tag with no number (`local`, or
# anything else) does not say which engine it is, so the test does not skip and
# does not run: it fails and says why. A candidate is sealed as
# `firefox-N-candidate` by the gate.
@@ -220,7 +244,7 @@ def _skip_unless_engine_at_least(minimum, tag):
@pytest.fixture(scope="session")
def engine_at_least():
"""``engine_at_least("firefox-60")``: skip the test unless the engine in
"""``engine_at_least("firefox-64")``: skip the test unless the engine in
use is that release or a later one (see above for how it is read). A seal
whose tag has no number (``local``, anything but firefox-N or
firefox-N-candidate) makes the test FAIL, saying so: it neither skips nor
@@ -234,6 +258,13 @@ def engine_at_least():
return check
@pytest.fixture
def the_udp_line(engine_at_least):
"""The UDP line (the declared network, the DoH through the proxy, the SOCKS5 UDP layer, HTTP/3 through it) is the engine
firefox-63: a test of it skips on an older engine (the published one that main's e2e fetches) and runs on the candidate."""
engine_at_least("firefox-63")
# ---------------------------------------------------------------------------
# Local HTTP fixture server - service workers need a real http(s) origin
# (data: and about:blank are opaque-origin, no SW registration possible).
@@ -0,0 +1,41 @@
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>canvas text colours ref</title>
<style>@font-face{font-family:"Arial";src:url("bundle/arial7_04.ttf") format("truetype")}</style>
</head>
<body>
<script>
// Canvas 2D coloured text reference page. Seven colour pairs (text, background) by two sizes:
// each case fills a 420 x 160 canvas with the background, draws TEXT in the text colour with
// fillText, reads the pixels back with getImageData and hashes the RGBA bytes with SHA-256.
// The case id is "<name>|<size>". The drawing code is the one retail Firefox 159.0 on Windows
// ran to write refs.json, so the hashes compare.
const COLORS = [["black", "#000000", "#ffffff"], ["teal", "#006699", "#ffffff"],
["limealpha", "rgba(102,204,0,0.2)", "#ffffff"], ["grey", "#888888", "#ffffff"],
["white_on_black", "#ffffff", "#000000"], ["red", "#ff0000", "#ffffff"],
["white_on_blue", "#ffffff", "#0000ff"]];
const SIZES = [16, 33];
(async () => {
try {
await document.fonts.load('16px "Arial"');
window.R = {};
for (const [name, fg, bg] of COLORS) for (const S of SIZES) {
const W = 420, H = 160, c = document.createElement("canvas");
c.width = W; c.height = H;
const ctx = c.getContext("2d", {willReadFrequently: true});
ctx.fillStyle = bg; ctx.fillRect(0, 0, W, H);
ctx.fillStyle = fg; ctx.font = S + 'px "Arial"'; ctx.textBaseline = "alphabetic";
ctx.fillText("Hamburgefonstiv 0123", 20, 90);
const img = ctx.getImageData(0, 0, W, H);
const id = name + "|" + S;
const d = await crypto.subtle.digest("SHA-256", img.data.buffer);
window.R[id] = {sha256: [...new Uint8Array(d)].map(b => b.toString(16).padStart(2, "0")).join("")};
}
window.DONE = true;
} catch (e) { window.ERR = String(e); }
})();
</script>
</body>
</html>
+929
View File
@@ -0,0 +1,929 @@
{
"test_page": "index.html",
"black_page": "../canvas_text_ref/index.html",
"text": "Hamburgefonstiv 0123",
"firefox": {
"version": "159.0",
"buildid": "20261022150525",
"browser_version_capability": "159.0",
"exe_sha256": "d8b5ed82fcd9c0f159dc86dc1c4526ceae981c4d9651f21908b6de90d0a56d85",
"os": "Windows_NT",
"os_version": "10.0"
},
"canvas": {
"gfx.canvas.accelerated": false,
"pref_read_back": false
},
"cleartype": {
"FontSmoothing": "2",
"FontSmoothingType": "0x2"
},
"fonts": [
{
"family": "Arial",
"bundle_file": "arial7_04.ttf",
"sha256": "05c7da5fe195e04d76bbe4f22b7829ebc142f957066449f68d59afbb2d446b33",
"version": "Version 7.04",
"psname": "ArialMT",
"names": {
"1": "Arial",
"2": "Normal",
"4": "Arial",
"5": "Version 7.04",
"6": "ArialMT"
},
"list_entry": "f|arial7_04.ttf|0|400|400|100|100|normal|ArialMT|2048|1854|434|67|1062|1467|-217|150|530|102"
}
],
"capture": {
"date": "2026-11-09",
"origin": "retail Firefox 159.0 (build 20261022150525, firefox.exe sha256 d8b5ed82fcd9c0f159dc86dc1c4526ceae981c4d9651f21908b6de90d0a56d85) on Windows, headless, canvases read back with getImageData; bytes saved by the measuring harness: colors/retail (the 14 coloured cases) and keys/<gamma>_<contrast>/retail (39 cases per key) of the win-asset analysis of 2026-11-09",
"colors_prefs": {
"gfx.canvas.accelerated": false
},
"keys_prefs": {
"gfx.canvas.accelerated": false,
"gfx.font_rendering.cleartype_params.gamma": "<gamma>",
"gfx.font_rendering.cleartype_params.enhanced_contrast": "<contrast>",
"gfx.font_rendering.cleartype_params.cleartype_level": 100,
"gfx.font_rendering.cleartype_params.pixel_structure": 1,
"gfx.font_rendering.cleartype_params.rendering_mode": 0
}
},
"colors": {
"count": 14,
"cases": {
"black|16": {
"id": "black|16",
"name": "black",
"fg": "#000000",
"bg": "#ffffff",
"size": 16,
"width": 420,
"height": 160,
"sha256": "938b7381139ef4f5d5bd0ca3f12d58f11224981f494afa869e92a2f22d7e7181"
},
"black|33": {
"id": "black|33",
"name": "black",
"fg": "#000000",
"bg": "#ffffff",
"size": 33,
"width": 420,
"height": 160,
"sha256": "d201f011ff0da51760a7dbd6f8b1a415173b278dd861edd19f1e240273661d21"
},
"teal|16": {
"id": "teal|16",
"name": "teal",
"fg": "#006699",
"bg": "#ffffff",
"size": 16,
"width": 420,
"height": 160,
"sha256": "8746ee921e50c0b8b08d8448faaa2bdc6c71e9268621bd71c0fcf24fd5495ae7"
},
"teal|33": {
"id": "teal|33",
"name": "teal",
"fg": "#006699",
"bg": "#ffffff",
"size": 33,
"width": 420,
"height": 160,
"sha256": "2b3df9671621de69a4e8415db76825bb2e18ddd122778521a8ddbc79e899dd71"
},
"limealpha|16": {
"id": "limealpha|16",
"name": "limealpha",
"fg": "rgba(102,204,0,0.2)",
"bg": "#ffffff",
"size": 16,
"width": 420,
"height": 160,
"sha256": "2f3cac50d2b3cfdda020841414a171c06b9d42c671b1688e744ccda1587ae74e"
},
"limealpha|33": {
"id": "limealpha|33",
"name": "limealpha",
"fg": "rgba(102,204,0,0.2)",
"bg": "#ffffff",
"size": 33,
"width": 420,
"height": 160,
"sha256": "4de189802d53988a14c12696b7304b5c46c43b77478b43c5174011b547e3cd71"
},
"grey|16": {
"id": "grey|16",
"name": "grey",
"fg": "#888888",
"bg": "#ffffff",
"size": 16,
"width": 420,
"height": 160,
"sha256": "117520b0392502751ddab388c91e9713153a58a71c2df5ca948e78b3471c3f0d"
},
"grey|33": {
"id": "grey|33",
"name": "grey",
"fg": "#888888",
"bg": "#ffffff",
"size": 33,
"width": 420,
"height": 160,
"sha256": "a20325721477839253b47e912d6ca2faca57b678dfd0684a53d2039c71b18f7d"
},
"white_on_black|16": {
"id": "white_on_black|16",
"name": "white_on_black",
"fg": "#ffffff",
"bg": "#000000",
"size": 16,
"width": 420,
"height": 160,
"sha256": "72e1b06edb977634bd70fcd9edd921a4332b526097ebb51e876eceb429cf5194"
},
"white_on_black|33": {
"id": "white_on_black|33",
"name": "white_on_black",
"fg": "#ffffff",
"bg": "#000000",
"size": 33,
"width": 420,
"height": 160,
"sha256": "5b84dd2f3a04210bb86a375e0c0d531fc1c7d90e0d50e97d19940981bee77dfc"
},
"red|16": {
"id": "red|16",
"name": "red",
"fg": "#ff0000",
"bg": "#ffffff",
"size": 16,
"width": 420,
"height": 160,
"sha256": "ac0c3b25f7d973e6c77251b100130e5d2df749def5502a84c98c28645540c594"
},
"red|33": {
"id": "red|33",
"name": "red",
"fg": "#ff0000",
"bg": "#ffffff",
"size": 33,
"width": 420,
"height": 160,
"sha256": "8a0a7f5461dccf8b1e87bf37c0b58333995a61ea73464c11575f40d3750e8d7e"
},
"white_on_blue|16": {
"id": "white_on_blue|16",
"name": "white_on_blue",
"fg": "#ffffff",
"bg": "#0000ff",
"size": 16,
"width": 420,
"height": 160,
"sha256": "7d3fc588aec100214021ced202515a3c51799a75540e507b1c68eadbdf5ebb80"
},
"white_on_blue|33": {
"id": "white_on_blue|33",
"name": "white_on_blue",
"fg": "#ffffff",
"bg": "#0000ff",
"size": 33,
"width": 420,
"height": 160,
"sha256": "9b90b082b3ec5a6242f60f89d198017d0dc84d4082b26f6de7fa01b9b8929436"
}
}
},
"keys": {
"1800_100": {
"gamma": 1800,
"contrast": 100,
"count": 39,
"black": {
"Arial|12.5|none|normal|normal|fill": {
"id": "Arial|12.5|none|normal|normal|fill",
"width": 319,
"height": 183,
"sha256": "ee3a8e3dfea9159a8497979695e096057fa49f2577fe6bf638e41d1fecec67ea"
},
"Arial|16|none|normal|normal|fill": {
"id": "Arial|16|none|normal|normal|fill",
"width": 386,
"height": 212,
"sha256": "98cd2b38609078580d7cb7eda232967ee28ad53ba6159ae59298cf1c7137c164"
},
"Arial|16|none|normal|normal|stroke": {
"id": "Arial|16|none|normal|normal|stroke",
"width": 386,
"height": 212,
"sha256": "1e6571d8a74938a478548455619639476ac1d5fe556361aa227059f9a5383cc8"
},
"Arial|33|none|normal|normal|fill": {
"id": "Arial|33|none|normal|normal|fill",
"width": 711,
"height": 352,
"sha256": "77d3ad98366467e10e0a7a30ec89615435d500684bd6ae14e077be083e0fd1b4"
},
"Arial|33|rot15-scale1.5x2|normal|normal|fill": {
"id": "Arial|33|rot15-scale1.5x2|normal|normal|fill",
"width": 711,
"height": 352,
"sha256": "268661170dbf65b4087095d6572a9e5eb47df3aba92de4497ab9305ddc25969a"
},
"Arial|33|rot15-scale1.5x2|normal|normal|fill|alpha=false": {
"id": "Arial|33|rot15-scale1.5x2|normal|normal|fill|alpha=false",
"width": 711,
"height": 352,
"sha256": "56bdb525c665af5aed8eb887d5fef9bc2cf96dc04c580f847e3ac2d7adb7facf"
},
"Arial|72|none|normal|normal|fill": {
"id": "Arial|72|none|normal|normal|fill",
"width": 1456,
"height": 673,
"sha256": "cde0d587e27ae735ab3f4d48ab9db9e4ab67b428a47725e80889b05fc585cb19"
},
"Arial|72|none|normal|normal|fill|alpha=false": {
"id": "Arial|72|none|normal|normal|fill|alpha=false",
"width": 1456,
"height": 673,
"sha256": "8f3002ed06eb19f56b436404bf270b89ef1f773c403a682d0197bb8c86193b09"
},
"Arial|72|none|normal|normal|stroke": {
"id": "Arial|72|none|normal|normal|stroke",
"width": 1456,
"height": 673,
"sha256": "dcfd4e18ea49e2939fc9ed4b0125d3537129ef9db16a307bbace4ee0e404db3e"
},
"Arial|9|none|normal|normal|fill": {
"id": "Arial|9|none|normal|normal|fill",
"width": 252,
"height": 155,
"sha256": "3e7800055997f8c1a66b8e6743079abc1f8861a7805097be20910e23d2a94f96"
},
"Calibri|12.5|none|normal|normal|fill": {
"id": "Calibri|12.5|none|normal|normal|fill",
"width": 302,
"height": 179,
"sha256": "d2ffbf661f27e331c065dfaa75d9ac211e422cdd33ec7100ad440e880d9609ea"
},
"Calibri|16|none|normal|normal|fill": {
"id": "Calibri|16|none|normal|normal|fill",
"width": 364,
"height": 206,
"sha256": "e92b7be795a3f9c6fff81923bd19332ed197e0d4c9a435eec3007503277731f4"
},
"Calibri|33|none|normal|normal|fill": {
"id": "Calibri|33|none|normal|normal|fill",
"width": 666,
"height": 340,
"sha256": "51da20ad1f3cff06c7e3f03112f697c430cafe5b0ec1a02d7b81d73226389fa8"
},
"Calibri|9|none|normal|normal|fill": {
"id": "Calibri|9|none|normal|normal|fill",
"width": 240,
"height": 151,
"sha256": "196f471dd173d75c7eda41f9d87caa3a6321d43b2df3cf176581f82257169aad"
},
"Consolas|12.5|none|normal|normal|fill": {
"id": "Consolas|12.5|none|normal|normal|fill",
"width": 338,
"height": 188,
"sha256": "94e60dca493f234bea874e7a962855d2a708f00cc35f4e266c0d5f98f998b905"
},
"Consolas|16|none|normal|normal|fill": {
"id": "Consolas|16|none|normal|normal|fill",
"width": 410,
"height": 218,
"sha256": "50e756f75be97db95df3cb2d46511ec95a1afa2ba5d9cdb2cd73123a65bcb0e4"
},
"Consolas|33|none|normal|normal|fill": {
"id": "Consolas|33|none|normal|normal|fill",
"width": 760,
"height": 365,
"sha256": "f0ab5cc32841bb964b06cad8cc960a6ce7b2ff1f893b61d40f2ade0fa1a3da57"
},
"Consolas|9|none|normal|normal|fill": {
"id": "Consolas|9|none|normal|normal|fill",
"width": 266,
"height": 158,
"sha256": "fe35c05a55d67fa9be55edc4a3c26ec1b02ae0554c3927df65d63d7f314ba5cb"
},
"Segoe UI|12.5|none|normal|normal|fill": {
"id": "Segoe UI|12.5|none|normal|normal|fill",
"width": 319,
"height": 183,
"sha256": "2b0e2121a7cecb95627884b225686516823ecf907cdac3d16de2c9d9448e7cb4"
},
"Segoe UI|16|none|normal|normal|fill": {
"id": "Segoe UI|16|none|normal|normal|fill",
"width": 386,
"height": 212,
"sha256": "e2da2ca50b4a3714b344fc909f06cc21d8e70985c87fba10d02105302b050f03"
},
"Segoe UI|33|none|normal|normal|fill": {
"id": "Segoe UI|33|none|normal|normal|fill",
"width": 711,
"height": 352,
"sha256": "051b495e0c4c7c29ded7b83f54aaa0eca0d072c0f3b299c8429828394a614499"
},
"Segoe UI|9|none|normal|normal|fill": {
"id": "Segoe UI|9|none|normal|normal|fill",
"width": 253,
"height": 155,
"sha256": "498ab34b34191205b46cce4edbd08c539c07734be633f17998dc4cc3e613360c"
},
"Times New Roman|16|none|normal|normal|fill": {
"id": "Times New Roman|16|none|normal|normal|fill",
"width": 365,
"height": 207,
"sha256": "3060970fff10250556c1dedda06e0602ba74f8cd62319cc4c07d79c764d0d198"
},
"Twemoji Mozilla|33|none|normal|normal|fill|alpha=false|text=emoji": {
"id": "Twemoji Mozilla|33|none|normal|normal|fill|alpha=false|text=emoji",
"width": 338,
"height": 254,
"sha256": "b17a096d51b6b7226984188e54627a496863aeab998bb9f1adc9e816c8b6a64b"
},
"Twemoji Mozilla|33|none|normal|normal|fill|text=emoji": {
"id": "Twemoji Mozilla|33|none|normal|normal|fill|text=emoji",
"width": 338,
"height": 254,
"sha256": "b17a096d51b6b7226984188e54627a496863aeab998bb9f1adc9e816c8b6a64b"
}
},
"colors": {
"black|16": {
"id": "black|16",
"width": 420,
"height": 160,
"sha256": "938b7381139ef4f5d5bd0ca3f12d58f11224981f494afa869e92a2f22d7e7181"
},
"black|33": {
"id": "black|33",
"width": 420,
"height": 160,
"sha256": "d201f011ff0da51760a7dbd6f8b1a415173b278dd861edd19f1e240273661d21"
},
"teal|16": {
"id": "teal|16",
"width": 420,
"height": 160,
"sha256": "8746ee921e50c0b8b08d8448faaa2bdc6c71e9268621bd71c0fcf24fd5495ae7"
},
"teal|33": {
"id": "teal|33",
"width": 420,
"height": 160,
"sha256": "2b3df9671621de69a4e8415db76825bb2e18ddd122778521a8ddbc79e899dd71"
},
"limealpha|16": {
"id": "limealpha|16",
"width": 420,
"height": 160,
"sha256": "2f3cac50d2b3cfdda020841414a171c06b9d42c671b1688e744ccda1587ae74e"
},
"limealpha|33": {
"id": "limealpha|33",
"width": 420,
"height": 160,
"sha256": "4de189802d53988a14c12696b7304b5c46c43b77478b43c5174011b547e3cd71"
},
"grey|16": {
"id": "grey|16",
"width": 420,
"height": 160,
"sha256": "117520b0392502751ddab388c91e9713153a58a71c2df5ca948e78b3471c3f0d"
},
"grey|33": {
"id": "grey|33",
"width": 420,
"height": 160,
"sha256": "a20325721477839253b47e912d6ca2faca57b678dfd0684a53d2039c71b18f7d"
},
"white_on_black|16": {
"id": "white_on_black|16",
"width": 420,
"height": 160,
"sha256": "72e1b06edb977634bd70fcd9edd921a4332b526097ebb51e876eceb429cf5194"
},
"white_on_black|33": {
"id": "white_on_black|33",
"width": 420,
"height": 160,
"sha256": "5b84dd2f3a04210bb86a375e0c0d531fc1c7d90e0d50e97d19940981bee77dfc"
},
"red|16": {
"id": "red|16",
"width": 420,
"height": 160,
"sha256": "ac0c3b25f7d973e6c77251b100130e5d2df749def5502a84c98c28645540c594"
},
"red|33": {
"id": "red|33",
"width": 420,
"height": 160,
"sha256": "8a0a7f5461dccf8b1e87bf37c0b58333995a61ea73464c11575f40d3750e8d7e"
},
"white_on_blue|16": {
"id": "white_on_blue|16",
"width": 420,
"height": 160,
"sha256": "7d3fc588aec100214021ced202515a3c51799a75540e507b1c68eadbdf5ebb80"
},
"white_on_blue|33": {
"id": "white_on_blue|33",
"width": 420,
"height": 160,
"sha256": "9b90b082b3ec5a6242f60f89d198017d0dc84d4082b26f6de7fa01b9b8929436"
}
}
},
"1400_50": {
"gamma": 1400,
"contrast": 50,
"count": 39,
"black": {
"Arial|12.5|none|normal|normal|fill": {
"id": "Arial|12.5|none|normal|normal|fill",
"width": 319,
"height": 183,
"sha256": "14c99d061e0f4a4c53418e9364cfbebb263637ff271eb88ce0174ec7f580a8d1"
},
"Arial|16|none|normal|normal|fill": {
"id": "Arial|16|none|normal|normal|fill",
"width": 386,
"height": 212,
"sha256": "460090856e361a9d1c8b8e508f1389bb18d6ed4bcbcb54de0a41def27df66c60"
},
"Arial|16|none|normal|normal|stroke": {
"id": "Arial|16|none|normal|normal|stroke",
"width": 386,
"height": 212,
"sha256": "d430dc9d241cbcf3163cf3c84819e296695b271ce5e4c0cbb81ff5e52fb7f888"
},
"Arial|33|none|normal|normal|fill": {
"id": "Arial|33|none|normal|normal|fill",
"width": 711,
"height": 352,
"sha256": "133696ab25926088783d52f37a1e0b38b6c05d89b5f8be9ba526a6d40b3ac9cc"
},
"Arial|33|rot15-scale1.5x2|normal|normal|fill": {
"id": "Arial|33|rot15-scale1.5x2|normal|normal|fill",
"width": 711,
"height": 352,
"sha256": "60be668ad5c98d4f6c1a882c991ac2bf716c370e7ddad2fc33727382729540e1"
},
"Arial|33|rot15-scale1.5x2|normal|normal|fill|alpha=false": {
"id": "Arial|33|rot15-scale1.5x2|normal|normal|fill|alpha=false",
"width": 711,
"height": 352,
"sha256": "a6d3ed8f876b2549de27d495a18275a8d1d57aabb12b366a5ea010f64ff2a487"
},
"Arial|72|none|normal|normal|fill": {
"id": "Arial|72|none|normal|normal|fill",
"width": 1456,
"height": 673,
"sha256": "e94fec8095a60639e7f032a83010c67d2cb903c564963a7502736424b031cfd1"
},
"Arial|72|none|normal|normal|fill|alpha=false": {
"id": "Arial|72|none|normal|normal|fill|alpha=false",
"width": 1456,
"height": 673,
"sha256": "7e99bff1907801acadcbac04269a7d12ffb3bd7f51866dfc530160150b323042"
},
"Arial|72|none|normal|normal|stroke": {
"id": "Arial|72|none|normal|normal|stroke",
"width": 1456,
"height": 673,
"sha256": "2f6e77afccf808b8093d8401eff74063579e20878aa92b9dee79e9772bb9557a"
},
"Arial|9|none|normal|normal|fill": {
"id": "Arial|9|none|normal|normal|fill",
"width": 252,
"height": 155,
"sha256": "f6f0f83c38699bac16c911ffb08bb4d65bcd2eb310af96999c86ed1a3849b1c1"
},
"Calibri|12.5|none|normal|normal|fill": {
"id": "Calibri|12.5|none|normal|normal|fill",
"width": 302,
"height": 179,
"sha256": "9245eea21c147ff68d9939442dd706a543c5d330aac23bf8b3d98763c6b4be49"
},
"Calibri|16|none|normal|normal|fill": {
"id": "Calibri|16|none|normal|normal|fill",
"width": 364,
"height": 206,
"sha256": "99267623a24e50c9b8780c9164466c3e87eeba0f1121e3a967388b2270c1f4e0"
},
"Calibri|33|none|normal|normal|fill": {
"id": "Calibri|33|none|normal|normal|fill",
"width": 666,
"height": 340,
"sha256": "015bb14578ca98863179cf6cf8f081141895919caa5b40bbbeb5850d6daf1dd6"
},
"Calibri|9|none|normal|normal|fill": {
"id": "Calibri|9|none|normal|normal|fill",
"width": 240,
"height": 151,
"sha256": "3032e62b1f242f40a929515e8c7c0795df490ee8689b7ff8edb5576cb281039f"
},
"Consolas|12.5|none|normal|normal|fill": {
"id": "Consolas|12.5|none|normal|normal|fill",
"width": 338,
"height": 188,
"sha256": "940e7b60291c65c0478370523b110ba443a154bb9adbfeb6a8f2f05aa5bf64f9"
},
"Consolas|16|none|normal|normal|fill": {
"id": "Consolas|16|none|normal|normal|fill",
"width": 410,
"height": 218,
"sha256": "627d72ba3944f9f7d75f7656022c3e2721d40c7c58bb54066231ed87be12997c"
},
"Consolas|33|none|normal|normal|fill": {
"id": "Consolas|33|none|normal|normal|fill",
"width": 760,
"height": 365,
"sha256": "75658b28d60aa33498c7beab0672416a0e1aa1e90ea1a5baec103b687725552a"
},
"Consolas|9|none|normal|normal|fill": {
"id": "Consolas|9|none|normal|normal|fill",
"width": 266,
"height": 158,
"sha256": "5a9fa9c242e44227bbb68d45b58324c7e16d3a4b36c7e97a0113b945c72147d9"
},
"Segoe UI|12.5|none|normal|normal|fill": {
"id": "Segoe UI|12.5|none|normal|normal|fill",
"width": 319,
"height": 183,
"sha256": "659a72b345f342f4bd4d4a7cdd444f68e802302d199ac59ba619441414a3cf5a"
},
"Segoe UI|16|none|normal|normal|fill": {
"id": "Segoe UI|16|none|normal|normal|fill",
"width": 386,
"height": 212,
"sha256": "7ed00e70c9ad30aa78faa09a0781197a4fe511af65f72e14b6b65ec8081d8ffd"
},
"Segoe UI|33|none|normal|normal|fill": {
"id": "Segoe UI|33|none|normal|normal|fill",
"width": 711,
"height": 352,
"sha256": "85598e54157f9c74091a92cd86653e6f4b10956c47aa63791ea4f799a41e0cda"
},
"Segoe UI|9|none|normal|normal|fill": {
"id": "Segoe UI|9|none|normal|normal|fill",
"width": 253,
"height": 155,
"sha256": "ba4e8c10825da7b2ca987a159345da51bd15892465a7e4102cd8ea28cf6861a1"
},
"Times New Roman|16|none|normal|normal|fill": {
"id": "Times New Roman|16|none|normal|normal|fill",
"width": 365,
"height": 207,
"sha256": "05f8cc92764a333044b3ea5ff03f8cfc52616670c2ac89b351a1a94bd0ac3316"
},
"Twemoji Mozilla|33|none|normal|normal|fill|alpha=false|text=emoji": {
"id": "Twemoji Mozilla|33|none|normal|normal|fill|alpha=false|text=emoji",
"width": 338,
"height": 254,
"sha256": "09d0464c8a0da0cdde22392a6e02df35f02ba67c7e89ff415f37302630b076df"
},
"Twemoji Mozilla|33|none|normal|normal|fill|text=emoji": {
"id": "Twemoji Mozilla|33|none|normal|normal|fill|text=emoji",
"width": 338,
"height": 254,
"sha256": "09d0464c8a0da0cdde22392a6e02df35f02ba67c7e89ff415f37302630b076df"
}
},
"colors": {
"black|16": {
"id": "black|16",
"width": 420,
"height": 160,
"sha256": "52ad1861583860289040685f6d12360e17707b94a0e518c5484cffd4e022e4bb"
},
"black|33": {
"id": "black|33",
"width": 420,
"height": 160,
"sha256": "980ea0631ee5813905f894ebfbca8ce859402b3eeb11cc3069c265d594610f84"
},
"teal|16": {
"id": "teal|16",
"width": 420,
"height": 160,
"sha256": "019ef31ba5e38bba0e0ed00c1f7872d1f752d4faef964220728b703689b8e0ea"
},
"teal|33": {
"id": "teal|33",
"width": 420,
"height": 160,
"sha256": "3a46c08e48f0adb86e68d95a211eb61ac2f9dcc9a6279913b1d9698f50a33fb1"
},
"limealpha|16": {
"id": "limealpha|16",
"width": 420,
"height": 160,
"sha256": "10e296a606b3c506a4d9046dfc593d901d49e6eaaa5803d18ff51d8e49dd10ac"
},
"limealpha|33": {
"id": "limealpha|33",
"width": 420,
"height": 160,
"sha256": "40e733728a6aae4ab7e78993ad2e2eb8689b8761f3698dc1054bf6d0615da30f"
},
"grey|16": {
"id": "grey|16",
"width": 420,
"height": 160,
"sha256": "a6b24c09f8364adf1190ae3c33d6c8b575d179cc6c2de98a342cd321c82dffe7"
},
"grey|33": {
"id": "grey|33",
"width": 420,
"height": 160,
"sha256": "fd6f0d41ebb37ceff9ae9d476f297293be36279bed196d66a13708298322d3ff"
},
"white_on_black|16": {
"id": "white_on_black|16",
"width": 420,
"height": 160,
"sha256": "acc160da81e8cddd293c5bce6a0d24f382cb778c4df90488ad21e3cc0177099c"
},
"white_on_black|33": {
"id": "white_on_black|33",
"width": 420,
"height": 160,
"sha256": "2b457056b9add984d1f09f3194b116399d6f1313cb7b5c006adb59662d8011c1"
},
"red|16": {
"id": "red|16",
"width": 420,
"height": 160,
"sha256": "bbafe01fa867809ef60b23de34292b6130e018f06cecb5dc4036fde01ad8524c"
},
"red|33": {
"id": "red|33",
"width": 420,
"height": 160,
"sha256": "00c7c3b8114a536a2e305b9c995456501553c158a572288a6382c7addcd6ab9f"
},
"white_on_blue|16": {
"id": "white_on_blue|16",
"width": 420,
"height": 160,
"sha256": "2114b54a0da2799c310357e1f3e88255228bd6b10277b5bb4c28be9dd0e8309f"
},
"white_on_blue|33": {
"id": "white_on_blue|33",
"width": 420,
"height": 160,
"sha256": "42df0d6244b32216364af6dbfaba48a44ef3689a28786529715372688e1da443"
}
}
},
"2200_0": {
"gamma": 2200,
"contrast": 0,
"count": 39,
"black": {
"Arial|12.5|none|normal|normal|fill": {
"id": "Arial|12.5|none|normal|normal|fill",
"width": 319,
"height": 183,
"sha256": "bc41b0f4665d48690f6acaf86575e90045da6eeeb1e21c1d71cee9eb0fdadf97"
},
"Arial|16|none|normal|normal|fill": {
"id": "Arial|16|none|normal|normal|fill",
"width": 386,
"height": 212,
"sha256": "494f8937cfabe6df194df5942b4a1a7dc11de5e891784bd743467714cc905bb2"
},
"Arial|16|none|normal|normal|stroke": {
"id": "Arial|16|none|normal|normal|stroke",
"width": 386,
"height": 212,
"sha256": "c59f1864698754e5f010baa4b2af1c65e9e74d6bdf6d84cafada9bae1fbeeb6f"
},
"Arial|33|none|normal|normal|fill": {
"id": "Arial|33|none|normal|normal|fill",
"width": 711,
"height": 352,
"sha256": "46753d78e39d6d7d472e805e46b062256705d2622ad1a0441b34b622e20fbe30"
},
"Arial|33|rot15-scale1.5x2|normal|normal|fill": {
"id": "Arial|33|rot15-scale1.5x2|normal|normal|fill",
"width": 711,
"height": 352,
"sha256": "dc2d1220bfc481f561e0ee1c1093f9a2e7484a137e1fa4a7054e88a8cde8efee"
},
"Arial|33|rot15-scale1.5x2|normal|normal|fill|alpha=false": {
"id": "Arial|33|rot15-scale1.5x2|normal|normal|fill|alpha=false",
"width": 711,
"height": 352,
"sha256": "d766613d927d0402f64875a3f84d730c05e8334f04d538550669eb60a6f7c90b"
},
"Arial|72|none|normal|normal|fill": {
"id": "Arial|72|none|normal|normal|fill",
"width": 1456,
"height": 673,
"sha256": "bff75224bc88dad497d360779bd999a2c327651e68a29df0332a025f27414b60"
},
"Arial|72|none|normal|normal|fill|alpha=false": {
"id": "Arial|72|none|normal|normal|fill|alpha=false",
"width": 1456,
"height": 673,
"sha256": "3b1d63436b498024c8fa5dd191aaec66a720920f4f5cbebcec4fb10cafbad543"
},
"Arial|72|none|normal|normal|stroke": {
"id": "Arial|72|none|normal|normal|stroke",
"width": 1456,
"height": 673,
"sha256": "44fd511bb9097a9344524a9ce88a2832767b93310274790de08ca68a76da971d"
},
"Arial|9|none|normal|normal|fill": {
"id": "Arial|9|none|normal|normal|fill",
"width": 252,
"height": 155,
"sha256": "7f1c0a53a28d5d1928788db178742643435c6576e0df291b6d68688d306ebeb1"
},
"Calibri|12.5|none|normal|normal|fill": {
"id": "Calibri|12.5|none|normal|normal|fill",
"width": 302,
"height": 179,
"sha256": "c6834082d739490f9486ff17e13b07d97c47bf823e14864d18ae752db88193ed"
},
"Calibri|16|none|normal|normal|fill": {
"id": "Calibri|16|none|normal|normal|fill",
"width": 364,
"height": 206,
"sha256": "48d1d575a8e73c17c89b57bcadaf94a21d66956ab3406c81d0462a3d5f1e7f42"
},
"Calibri|33|none|normal|normal|fill": {
"id": "Calibri|33|none|normal|normal|fill",
"width": 666,
"height": 340,
"sha256": "823a7c1037ba76cee297b77e26de62d698bd8f8055fbdde556949248c01eb5c4"
},
"Calibri|9|none|normal|normal|fill": {
"id": "Calibri|9|none|normal|normal|fill",
"width": 240,
"height": 151,
"sha256": "d22432b47834f0426de5e2bcfa199e39f54db75e5cd503aa7175fa125f52a9c4"
},
"Consolas|12.5|none|normal|normal|fill": {
"id": "Consolas|12.5|none|normal|normal|fill",
"width": 338,
"height": 188,
"sha256": "2038306771f3c80c528cceca6a5045367dfb2789e0fac6c3b063a1979262ff82"
},
"Consolas|16|none|normal|normal|fill": {
"id": "Consolas|16|none|normal|normal|fill",
"width": 410,
"height": 218,
"sha256": "8e4d6ffa72d864c811647613554a9e9f044c949688566e84847be8d544b0c57b"
},
"Consolas|33|none|normal|normal|fill": {
"id": "Consolas|33|none|normal|normal|fill",
"width": 760,
"height": 365,
"sha256": "d79a5a9f2134bbbeb509fac67eaedddbba88a71a901ebc498c9e3c2b0f42178b"
},
"Consolas|9|none|normal|normal|fill": {
"id": "Consolas|9|none|normal|normal|fill",
"width": 266,
"height": 158,
"sha256": "9d76f6b720d844f961d74c8779849f701a10b6b088cb8f6b73d1ac181a01179e"
},
"Segoe UI|12.5|none|normal|normal|fill": {
"id": "Segoe UI|12.5|none|normal|normal|fill",
"width": 319,
"height": 183,
"sha256": "6f05277c4eea92d7d1ca86471bcf47f42172d9ab43d11e784c14650b86b7f744"
},
"Segoe UI|16|none|normal|normal|fill": {
"id": "Segoe UI|16|none|normal|normal|fill",
"width": 386,
"height": 212,
"sha256": "7fed78964672e26bfc878ab65910c9c59abf57af85f8d01af330f0d8e6a890e4"
},
"Segoe UI|33|none|normal|normal|fill": {
"id": "Segoe UI|33|none|normal|normal|fill",
"width": 711,
"height": 352,
"sha256": "af8d02cec31673a205a5a389f478e8270474bd025936cd11fd01478a706da04b"
},
"Segoe UI|9|none|normal|normal|fill": {
"id": "Segoe UI|9|none|normal|normal|fill",
"width": 253,
"height": 155,
"sha256": "5bc7924b646811c83d2a6f31bb02236ccae08abdc39c98f574c41c6211ee0413"
},
"Times New Roman|16|none|normal|normal|fill": {
"id": "Times New Roman|16|none|normal|normal|fill",
"width": 365,
"height": 207,
"sha256": "cfff39b7d31293c20e44353c76ed717424e375ad59f98a74b800f24c5934316b"
},
"Twemoji Mozilla|33|none|normal|normal|fill|alpha=false|text=emoji": {
"id": "Twemoji Mozilla|33|none|normal|normal|fill|alpha=false|text=emoji",
"width": 338,
"height": 254,
"sha256": "4aac8af7051ea57f30eeb0a18bc56e1f73d74c1751df3a45a78c874eb0a4a5f2"
},
"Twemoji Mozilla|33|none|normal|normal|fill|text=emoji": {
"id": "Twemoji Mozilla|33|none|normal|normal|fill|text=emoji",
"width": 338,
"height": 254,
"sha256": "4aac8af7051ea57f30eeb0a18bc56e1f73d74c1751df3a45a78c874eb0a4a5f2"
}
},
"colors": {
"black|16": {
"id": "black|16",
"width": 420,
"height": 160,
"sha256": "77d5557ee05bc85c9ecd875517422c0516ac9d979933fc4c50a00c2a85c4a8a1"
},
"black|33": {
"id": "black|33",
"width": 420,
"height": 160,
"sha256": "580a367613617a17978fe64bc2514e0c34414fbbfdbfea4a81f6f41a9048fd02"
},
"teal|16": {
"id": "teal|16",
"width": 420,
"height": 160,
"sha256": "226470fa83fe2039c31e073cb620c1aadd4c0c615be2e40b53905c2132554ef5"
},
"teal|33": {
"id": "teal|33",
"width": 420,
"height": 160,
"sha256": "20ee0972b2582b55c1532bbc98fd00550ae6af110bc92ac65f09ae7a5e4c1ae0"
},
"limealpha|16": {
"id": "limealpha|16",
"width": 420,
"height": 160,
"sha256": "8674bbefa9ce1106172929a986f6a98b37a1394d13c537c4d4388a7600816ef7"
},
"limealpha|33": {
"id": "limealpha|33",
"width": 420,
"height": 160,
"sha256": "643b28b21d276d940d892b5fb393f845e3bb74a87b388b609d057d5901fe9469"
},
"grey|16": {
"id": "grey|16",
"width": 420,
"height": 160,
"sha256": "022631fc03d1610531248ef4a927231ec6e23194e1e1f4afa89c4c3948cd0629"
},
"grey|33": {
"id": "grey|33",
"width": 420,
"height": 160,
"sha256": "df655c2f29a1dc0c478fe57f9bbc5201f465d56b77de99504cb775bc519df987"
},
"white_on_black|16": {
"id": "white_on_black|16",
"width": 420,
"height": 160,
"sha256": "5b80cc5864ab3e7b53fae364eaf9328938f2170312201ec0e27a0c42bfd02bd9"
},
"white_on_black|33": {
"id": "white_on_black|33",
"width": 420,
"height": 160,
"sha256": "7abbe06b0ae934fde081a8e9e7abdba2c74268a4703b3fd14ec91165ba9e0643"
},
"red|16": {
"id": "red|16",
"width": 420,
"height": 160,
"sha256": "11d2b4bbd971feb10b866a8aed895b944c68c3094eab90f4fbe1c4e75cdbfe84"
},
"red|33": {
"id": "red|33",
"width": 420,
"height": 160,
"sha256": "b4ff984d6faf7c7a7c17c5bd347dfd243196fbcd55ce2754b05b684b775edaed"
},
"white_on_blue|16": {
"id": "white_on_blue|16",
"width": 420,
"height": 160,
"sha256": "806b730875ad3b0223aa3acb435fbc5490a7240e5e4e0f1df4d9422001232ae5"
},
"white_on_blue|33": {
"id": "white_on_blue|33",
"width": 420,
"height": 160,
"sha256": "46035656360248005c49c9bd0e9db1ac47223689b96993ccb2370c82e7f726f2"
}
}
}
}
}
+685
View File
@@ -0,0 +1,685 @@
{
"_origin": {"what": "Page.dispatchMouseEvent / dispatchWheelEvent messages the ENGINE received (t: seconds on a virtual clock) from the in-process client's humanised pointer, through a real invisible_core Actions whose connection only records", "commit": "5d9ad70 (invisible_playwright, the client-side wrappers of _cursor.py: _approach, _wrap_mouse_move, _wrap_mouse_click, _wrap_mouse_wheel)", "generator": "tests/data/pointer_golden_origin.py, run against that commit with the core below", "core": "invisible_core 58.56.0", "date": "2026-11-09", "revisions": [{"what": "explicit_pointer: the Mouse.click no longer repeats its mousemove on the click point", "why": "Pointer.click_at sent the endpoint as a move and Actions.click_at moved onto it again before the press; the server now lets click_at make the one move", "change": "one mousemove fewer (same x, y, t as its twin); the other sessions are untouched", "generator": "tests/data/pointer_golden_origin.py --revise-mouse-click, run against feat/rt-dblmove"}, {"what": "explicit_pointer: a stroke from standstill no longer opens with a mousemove on the point it stands on", "why": "the first waypoint of a stroke is its start; Pointer._travel sent it although the engine had already been told the pointer was on that pixel (a zero-displacement move no mouse reports)", "change": "one mousemove fewer (the repeat of (800, 500) after the wait); t, x, y and type of every other event are unchanged, the latency draws follow the event ordinal; the other three sessions are identical event for event", "generator": "tests/data/pointer_golden_origin.py --revise-standstill, run against feat/rt-dblmove"}]},
"scenarios": {
"session_a": {
"spec": {"seed": 4242, "number": 0, "budget": 1.5, "ops": [["click", "#b"], ["wait", 0.1], ["hover", "#c"], ["wait", 3.0], ["dblclick", "#b"], ["wait", 2.0], ["tap", "#c"], ["wait", 0.05], ["click", "#c", {"position": {"x": 10.0, "y": 5.0}}], ["wait", 7.5], ["check", "#b"], ["click", "#tiny"]]},
"engine_events": [
{"t": 0.011566453, "m": "Page.dispatchMouseEvent", "type": "mousemove", "x": 599.6397925456525, "y": 132.3656956667507, "button": 0, "buttons": 0, "modifiers": 0, "latency": 9.31},
{"t": 0.026710884, "m": "Page.dispatchMouseEvent", "type": "mousemove", "x": 598.4287327325028, "y": 134.0073389822865, "button": 0, "buttons": 0, "modifiers": 0, "latency": 5.73},
{"t": 0.039505459, "m": "Page.dispatchMouseEvent", "type": "mousemove", "x": 596.5304747185694, "y": 136.53793817332306, "button": 0, "buttons": 0, "modifiers": 0, "latency": 7.24},
{"t": 0.056994669, "m": "Page.dispatchMouseEvent", "type": "mousemove", "x": 592.6676004291593, "y": 141.65428079587366, "button": 0, "buttons": 0, "modifiers": 0, "latency": 9.95},
{"t": 0.072912782, "m": "Page.dispatchMouseEvent", "type": "mousemove", "x": 587.7187415492641, "y": 147.681127761503, "button": 0, "buttons": 0, "modifiers": 0, "latency": 7.28},
{"t": 0.092055402, "m": "Page.dispatchMouseEvent", "type": "mousemove", "x": 580.4223465343077, "y": 157.57618066006802, "button": 0, "buttons": 0, "modifiers": 0, "latency": 6.48},
{"t": 0.102395649, "m": "Page.dispatchMouseEvent", "type": "mousemove", "x": 575.4216915722751, "y": 163.22088981568183, "button": 0, "buttons": 0, "modifiers": 0, "latency": 9.09},
{"t": 0.112403647, "m": "Page.dispatchMouseEvent", "type": "mousemove", "x": 570.5967843546083, "y": 169.51419986686378, "button": 0, "buttons": 0, "modifiers": 0, "latency": 16.65},
{"t": 0.123677344, "m": "Page.dispatchMouseEvent", "type": "mousemove", "x": 564.9181221972894, "y": 177.17625501337156, "button": 0, "buttons": 0, "modifiers": 0, "latency": 11.42},
{"t": 0.131829921, "m": "Page.dispatchMouseEvent", "type": "mousemove", "x": 560.4179637852559, "y": 183.16152650465855, "button": 0, "buttons": 0, "modifiers": 0, "latency": 4.55},
{"t": 0.145018977, "m": "Page.dispatchMouseEvent", "type": "mousemove", "x": 552.4536044583945, "y": 192.70196073087777, "button": 0, "buttons": 0, "modifiers": 0, "latency": 12.46},
{"t": 0.153034485, "m": "Page.dispatchMouseEvent", "type": "mousemove", "x": 548.1615285875071, "y": 199.16780789718683, "button": 0, "buttons": 0, "modifiers": 0, "latency": 14.35},
{"t": 0.167421582, "m": "Page.dispatchMouseEvent", "type": "mousemove", "x": 539.0741147543215, "y": 210.54829976477697, "button": 0, "buttons": 0, "modifiers": 0, "latency": 8.27},
{"t": 0.182095049, "m": "Page.dispatchMouseEvent", "type": "mousemove", "x": 530.1339047901081, "y": 222.3181379706062, "button": 0, "buttons": 0, "modifiers": 0, "latency": 9.69},
{"t": 0.192647886, "m": "Page.dispatchMouseEvent", "type": "mousemove", "x": 523.3686547842664, "y": 231.07836633289108, "button": 0, "buttons": 0, "modifiers": 0, "latency": 13.75},
{"t": 0.202985135, "m": "Page.dispatchMouseEvent", "type": "mousemove", "x": 516.8293491273616, "y": 239.80023090403708, "button": 0, "buttons": 0, "modifiers": 0, "latency": 14.18},
{"t": 0.21534481, "m": "Page.dispatchMouseEvent", "type": "mousemove", "x": 508.9608255968454, "y": 249.48250239569143, "button": 0, "buttons": 0, "modifiers": 0, "latency": 12.86},
{"t": 0.224440586, "m": "Page.dispatchMouseEvent", "type": "mousemove", "x": 503.4944327139185, "y": 257.2374920540273, "button": 0, "buttons": 0, "modifiers": 0, "latency": 8.19},
{"t": 0.235875121, "m": "Page.dispatchMouseEvent", "type": "mousemove", "x": 496.4482196250297, "y": 265.88545944339, "button": 0, "buttons": 0, "modifiers": 0, "latency": 7.57},
{"t": 0.249745901, "m": "Page.dispatchMouseEvent", "type": "mousemove", "x": 489.0874052314377, "y": 276.27825486906846, "button": 0, "buttons": 0, "modifiers": 0, "latency": 7.3},
{"t": 0.263301747, "m": "Page.dispatchMouseEvent", "type": "mousemove", "x": 481.29148219841875, "y": 285.3336199278234, "button": 0, "buttons": 0, "modifiers": 0, "latency": 7.67},
{"t": 0.27518005, "m": "Page.dispatchMouseEvent", "type": "mousemove", "x": 475.55957638041303, "y": 293.3723249531305, "button": 0, "buttons": 0, "modifiers": 0, "latency": 8.07},
{"t": 0.291162263, "m": "Page.dispatchMouseEvent", "type": "mousemove", "x": 468.4246471712217, "y": 302.41063212739476, "button": 0, "buttons": 0, "modifiers": 0, "latency": 8.32},
{"t": 0.30461305, "m": "Page.dispatchMouseEvent", "type": "mousemove", "x": 463.237206678957, "y": 309.54873293239143, "button": 0, "buttons": 0, "modifiers": 0, "latency": 7.2},
{"t": 0.318943261, "m": "Page.dispatchMouseEvent", "type": "mousemove", "x": 458.66843747078667, "y": 315.55250174164183, "button": 0, "buttons": 0, "modifiers": 0, "latency": 3.98},
{"t": 0.344446359, "m": "Page.dispatchMouseEvent", "type": "mousemove", "x": 452.6964766953205, "y": 323.11331545589877, "button": 0, "buttons": 0, "modifiers": 0, "latency": 15.67},
{"t": 0.352643357, "m": "Page.dispatchMouseEvent", "type": "mousemove", "x": 451.70631986681036, "y": 324.73776445953723, "button": 0, "buttons": 0, "modifiers": 0, "latency": 9.66},
{"t": 0.364501786, "m": "Page.dispatchMouseEvent", "type": "mousemove", "x": 450.4894122550681, "y": 326.26428969530946, "button": 0, "buttons": 0, "modifiers": 0, "latency": 15.52},
{"t": 0.382302941, "m": "Page.dispatchMouseEvent", "type": "mousemove", "x": 449.9510251050417, "y": 326.9471418422686, "button": 0, "buttons": 0, "modifiers": 0, "latency": 11.01},
{"t": 0.454731911, "m": "Page.dispatchMouseEvent", "type": "mousedown", "x": 449.9510251050417, "y": 326.9471418422686, "button": 0, "buttons": 1, "modifiers": 0, "clickCount": 1, "latency": 6.15},
{"t": 0.6668294, "m": "Page.dispatchMouseEvent", "type": "mouseup", "x": 449.9510251050417, "y": 326.9471418422686, "button": 0, "buttons": 0, "modifiers": 0, "clickCount": 1, "latency": 10.4},
{"t": 0.777125423, "m": "Page.dispatchMouseEvent", "type": "mousemove", "x": 449.9903772576359, "y": 326.96398439750294, "button": 0, "buttons": 0, "modifiers": 0, "latency": 8.12},
{"t": 0.79104543, "m": "Page.dispatchMouseEvent", "type": "mousemove", "x": 450.61892906910174, "y": 326.8288788980842, "button": 0, "buttons": 0, "modifiers": 0, "latency": 4.22},
{"t": 0.806053177, "m": "Page.dispatchMouseEvent", "type": "mousemove", "x": 452.4414291696958, "y": 326.1225570924564, "button": 0, "buttons": 0, "modifiers": 0, "latency": 9.1},
{"t": 0.820994402, "m": "Page.dispatchMouseEvent", "type": "mousemove", "x": 456.1747812877343, "y": 324.5765034912608, "button": 0, "buttons": 0, "modifiers": 0, "latency": 12.19},
{"t": 0.830844933, "m": "Page.dispatchMouseEvent", "type": "mousemove", "x": 460.3441506155217, "y": 323.3832122458064, "button": 0, "buttons": 0, "modifiers": 0, "latency": 10.96},
{"t": 0.84346077, "m": "Page.dispatchMouseEvent", "type": "mousemove", "x": 467.6519261789863, "y": 320.9524111712255, "button": 0, "buttons": 0, "modifiers": 0, "latency": 3.39},
{"t": 0.856805673, "m": "Page.dispatchMouseEvent", "type": "mousemove", "x": 477.8711105655968, "y": 317.07371384866815, "button": 0, "buttons": 0, "modifiers": 0, "latency": 4.93},
{"t": 0.87735848, "m": "Page.dispatchMouseEvent", "type": "mousemove", "x": 499.56109166874666, "y": 309.2540830078914, "button": 0, "buttons": 0, "modifiers": 0, "latency": 10.94},
{"t": 0.890197375, "m": "Page.dispatchMouseEvent", "type": "mousemove", "x": 516.2082355478852, "y": 302.5553135813689, "button": 0, "buttons": 0, "modifiers": 0, "latency": 10.97},
{"t": 0.902691967, "m": "Page.dispatchMouseEvent", "type": "mousemove", "x": 535.3708964905439, "y": 295.29528966211893, "button": 0, "buttons": 0, "modifiers": 0, "latency": 8.1},
{"t": 0.916381983, "m": "Page.dispatchMouseEvent", "type": "mousemove", "x": 559.4097484572497, "y": 287.0417860162389, "button": 0, "buttons": 0, "modifiers": 0, "latency": 8.62},
{"t": 0.930162437, "m": "Page.dispatchMouseEvent", "type": "mousemove", "x": 585.7123831601225, "y": 275.89499894072003, "button": 0, "buttons": 0, "modifiers": 0, "latency": 9.22},
{"t": 0.94165225, "m": "Page.dispatchMouseEvent", "type": "mousemove", "x": 609.3187279168321, "y": 266.0391006259531, "button": 0, "buttons": 0, "modifiers": 0, "latency": 7.28},
{"t": 0.95448841, "m": "Page.dispatchMouseEvent", "type": "mousemove", "x": 637.5748890112362, "y": 255.2809119464663, "button": 0, "buttons": 0, "modifiers": 0, "latency": 5.7},
{"t": 0.969263624, "m": "Page.dispatchMouseEvent", "type": "mousemove", "x": 671.8296604294167, "y": 241.15813595432797, "button": 0, "buttons": 0, "modifiers": 0, "latency": 7.46},
{"t": 0.98328677, "m": "Page.dispatchMouseEvent", "type": "mousemove", "x": 705.2737623667869, "y": 226.85413746072797, "button": 0, "buttons": 0, "modifiers": 0, "latency": 10.37},
{"t": 0.993324975, "m": "Page.dispatchMouseEvent", "type": "mousemove", "x": 729.6604322918951, "y": 216.93449276620282, "button": 0, "buttons": 0, "modifiers": 0, "latency": 9.83},
{"t": 1.006044102, "m": "Page.dispatchMouseEvent", "type": "mousemove", "x": 760.4154510067955, "y": 204.04960970221256, "button": 0, "buttons": 0, "modifiers": 0, "latency": 6.32},
{"t": 1.015806724, "m": "Page.dispatchMouseEvent", "type": "mousemove", "x": 783.8923252205215, "y": 194.11561004033254, "button": 0, "buttons": 0, "modifiers": 0, "latency": 4.72},
{"t": 1.02686378, "m": "Page.dispatchMouseEvent", "type": "mousemove", "x": 809.8121666804968, "y": 183.54943138173712, "button": 0, "buttons": 0, "modifiers": 0, "latency": 8.36},
{"t": 1.039826782, "m": "Page.dispatchMouseEvent", "type": "mousemove", "x": 838.7411620195135, "y": 170.60206626216768, "button": 0, "buttons": 0, "modifiers": 0, "latency": 4.6},
{"t": 1.056772994, "m": "Page.dispatchMouseEvent", "type": "mousemove", "x": 875.0059304465872, "y": 155.45882092537914, "button": 0, "buttons": 0, "modifiers": 0, "latency": 10.07},
{"t": 1.067629527, "m": "Page.dispatchMouseEvent", "type": "mousemove", "x": 896.1323604084212, "y": 146.44060543299273, "button": 0, "buttons": 0, "modifiers": 0, "latency": 15.45},
{"t": 1.078006684, "m": "Page.dispatchMouseEvent", "type": "mousemove", "x": 914.863849247156, "y": 138.4456656983462, "button": 0, "buttons": 0, "modifiers": 0, "latency": 7.3},
{"t": 1.088905467, "m": "Page.dispatchMouseEvent", "type": "mousemove", "x": 932.4738637269053, "y": 130.5773651466717, "button": 0, "buttons": 0, "modifiers": 0, "latency": 9.82},
{"t": 1.101888192, "m": "Page.dispatchMouseEvent", "type": "mousemove", "x": 950.8951049243782, "y": 122.47637234977951, "button": 0, "buttons": 0, "modifiers": 0, "latency": 7.3},
{"t": 1.112047251, "m": "Page.dispatchMouseEvent", "type": "mousemove", "x": 963.3375690272486, "y": 117.21820863826676, "button": 0, "buttons": 0, "modifiers": 0, "latency": 8.08},
{"t": 1.123368446, "m": "Page.dispatchMouseEvent", "type": "mousemove", "x": 974.8007418062095, "y": 112.14076160593999, "button": 0, "buttons": 0, "modifiers": 0, "latency": 9.54},
{"t": 1.133898595, "m": "Page.dispatchMouseEvent", "type": "mousemove", "x": 983.4767101564369, "y": 108.42892581425679, "button": 0, "buttons": 0, "modifiers": 0, "latency": 10.82},
{"t": 1.144258803, "m": "Page.dispatchMouseEvent", "type": "mousemove", "x": 990.1616972202877, "y": 105.50503044737079, "button": 0, "buttons": 0, "modifiers": 0, "latency": 14.61},
{"t": 1.156935118, "m": "Page.dispatchMouseEvent", "type": "mousemove", "x": 995.9313723502289, "y": 102.97462240575769, "button": 0, "buttons": 0, "modifiers": 0, "latency": 12.63},
{"t": 1.173751917, "m": "Page.dispatchMouseEvent", "type": "mousemove", "x": 1000.1202186026343, "y": 101.3341612435477, "button": 0, "buttons": 0, "modifiers": 0, "latency": 13.19},
{"t": 1.198899897, "m": "Page.dispatchMouseEvent", "type": "mousemove", "x": 1001.4460085417488, "y": 100.66456875999546, "button": 0, "buttons": 0, "modifiers": 0, "latency": 9.41},
{"t": 1.361961414, "m": "Page.dispatchMouseEvent", "type": "mousemove", "x": 1000.3519858711072, "y": 102.09739932635948, "button": 0, "buttons": 0, "modifiers": 0, "latency": 13.8},
{"t": 1.375335185, "m": "Page.dispatchMouseEvent", "type": "mousemove", "x": 998.8705505568213, "y": 104.43052936438836, "button": 0, "buttons": 0, "modifiers": 0, "latency": 6.94},
{"t": 1.387735296, "m": "Page.dispatchMouseEvent", "type": "mousemove", "x": 996.6318214387924, "y": 107.1781923502572, "button": 0, "buttons": 0, "modifiers": 0, "latency": 8.64},
{"t": 1.4047784, "m": "Page.dispatchMouseEvent", "type": "mousemove", "x": 992.5241039469886, "y": 112.3693547589102, "button": 0, "buttons": 0, "modifiers": 0, "latency": 10.31},
{"t": 1.416578054, "m": "Page.dispatchMouseEvent", "type": "mousemove", "x": 989.1257637635148, "y": 116.3826372242187, "button": 0, "buttons": 0, "modifiers": 0, "latency": 6.52},
{"t": 1.428516212, "m": "Page.dispatchMouseEvent", "type": "mousemove", "x": 985.5514640766315, "y": 120.51669882649212, "button": 0, "buttons": 0, "modifiers": 0, "latency": 11.66},
{"t": 1.43997673, "m": "Page.dispatchMouseEvent", "type": "mousemove", "x": 981.9384841300042, "y": 124.68403378102751, "button": 0, "buttons": 0, "modifiers": 0, "latency": 5.57},
{"t": 1.45470597, "m": "Page.dispatchMouseEvent", "type": "mousemove", "x": 977.8843697965355, "y": 129.38710808340434, "button": 0, "buttons": 0, "modifiers": 0, "latency": 11.23},
{"t": 1.468262574, "m": "Page.dispatchMouseEvent", "type": "mousemove", "x": 974.7646887837992, "y": 133.12069309029013, "button": 0, "buttons": 0, "modifiers": 0, "latency": 5.86},
{"t": 1.481104208, "m": "Page.dispatchMouseEvent", "type": "mousemove", "x": 972.6403556166764, "y": 135.54194446133508, "button": 0, "buttons": 0, "modifiers": 0, "latency": 17.19},
{"t": 1.493200998, "m": "Page.dispatchMouseEvent", "type": "mousemove", "x": 971.0273855080054, "y": 136.95808612137617, "button": 0, "buttons": 0, "modifiers": 0, "latency": 10.19},
{"t": 1.519500083, "m": "Page.dispatchMouseEvent", "type": "mousemove", "x": 970.5468999612265, "y": 137.82363032657804, "button": 0, "buttons": 0, "modifiers": 0, "latency": 5.65},
{"t": 4.532334223, "m": "Page.dispatchMouseEvent", "type": "mousemove", "x": 970.0932860486631, "y": 138.05983832271284, "button": 0, "buttons": 0, "modifiers": 0, "latency": 9.9},
{"t": 4.542800638, "m": "Page.dispatchMouseEvent", "type": "mousemove", "x": 968.4385112469628, "y": 138.70211219461336, "button": 0, "buttons": 0, "modifiers": 0, "latency": 6.85},
{"t": 4.554931991, "m": "Page.dispatchMouseEvent", "type": "mousemove", "x": 963.9607165473954, "y": 140.2546319560043, "button": 0, "buttons": 0, "modifiers": 0, "latency": 14.61},
{"t": 4.567529968, "m": "Page.dispatchMouseEvent", "type": "mousemove", "x": 956.0112293382675, "y": 143.21281578360754, "button": 0, "buttons": 0, "modifiers": 0, "latency": 9.44},
{"t": 4.576956598, "m": "Page.dispatchMouseEvent", "type": "mousemove", "x": 947.3793519533989, "y": 146.53915364465323, "button": 0, "buttons": 0, "modifiers": 0, "latency": 10.15},
{"t": 4.591279018, "m": "Page.dispatchMouseEvent", "type": "mousemove", "x": 930.3002553639586, "y": 153.29008390801252, "button": 0, "buttons": 0, "modifiers": 0, "latency": 8.57},
{"t": 4.604909482, "m": "Page.dispatchMouseEvent", "type": "mousemove", "x": 908.8276132450959, "y": 161.41876400419528, "button": 0, "buttons": 0, "modifiers": 0, "latency": 4.8},
{"t": 4.615752597, "m": "Page.dispatchMouseEvent", "type": "mousemove", "x": 888.1414426858373, "y": 169.283080124344, "button": 0, "buttons": 0, "modifiers": 0, "latency": 6.46},
{"t": 4.627414402, "m": "Page.dispatchMouseEvent", "type": "mousemove", "x": 863.4448143866307, "y": 178.9758313311239, "button": 0, "buttons": 0, "modifiers": 0, "latency": 8.18},
{"t": 4.64117936, "m": "Page.dispatchMouseEvent", "type": "mousemove", "x": 830.3531562111232, "y": 191.16730284469196, "button": 0, "buttons": 0, "modifiers": 0, "latency": 9.39},
{"t": 4.654143666, "m": "Page.dispatchMouseEvent", "type": "mousemove", "x": 795.5831264573138, "y": 203.95979001777312, "button": 0, "buttons": 0, "modifiers": 0, "latency": 8.54},
{"t": 4.666945591, "m": "Page.dispatchMouseEvent", "type": "mousemove", "x": 759.7518023106865, "y": 217.2883200813578, "button": 0, "buttons": 0, "modifiers": 0, "latency": 8.26},
{"t": 4.678244147, "m": "Page.dispatchMouseEvent", "type": "mousemove", "x": 726.8309602278209, "y": 229.47950415386364, "button": 0, "buttons": 0, "modifiers": 0, "latency": 11.23},
{"t": 4.688522529, "m": "Page.dispatchMouseEvent", "type": "mousemove", "x": 696.5651865557472, "y": 240.5685533985882, "button": 0, "buttons": 0, "modifiers": 0, "latency": 7.1},
{"t": 4.701687639, "m": "Page.dispatchMouseEvent", "type": "mousemove", "x": 657.8638221792376, "y": 254.9252932912933, "button": 0, "buttons": 0, "modifiers": 0, "latency": 5.69},
{"t": 4.71791598, "m": "Page.dispatchMouseEvent", "type": "mousemove", "x": 611.8063150903466, "y": 272.1545420268071, "button": 0, "buttons": 0, "modifiers": 0, "latency": 9.2},
{"t": 4.731296036, "m": "Page.dispatchMouseEvent", "type": "mousemove", "x": 576.0658984145527, "y": 285.06882952479026, "button": 0, "buttons": 0, "modifiers": 0, "latency": 11.77},
{"t": 4.747093466, "m": "Page.dispatchMouseEvent", "type": "mousemove", "x": 538.5270388201852, "y": 298.98780213408395, "button": 0, "buttons": 0, "modifiers": 0, "latency": 8.64},
{"t": 4.756862511, "m": "Page.dispatchMouseEvent", "type": "mousemove", "x": 518.065650263867, "y": 306.36613098220846, "button": 0, "buttons": 0, "modifiers": 0, "latency": 10.26},
{"t": 4.769116828, "m": "Page.dispatchMouseEvent", "type": "mousemove", "x": 496.3529478390738, "y": 315.1647196087386, "button": 0, "buttons": 0, "modifiers": 0, "latency": 12.84},
{"t": 4.779698471, "m": "Page.dispatchMouseEvent", "type": "mousemove", "x": 480.9725330214225, "y": 320.4209910068782, "button": 0, "buttons": 0, "modifiers": 0, "latency": 10.92},
{"t": 4.798569221, "m": "Page.dispatchMouseEvent", "type": "mousemove", "x": 462.9250798297371, "y": 326.9423102601787, "button": 0, "buttons": 0, "modifiers": 0, "latency": 6.04},
{"t": 4.814090698, "m": "Page.dispatchMouseEvent", "type": "mousemove", "x": 456.4083976291475, "y": 329.41044133065486, "button": 0, "buttons": 0, "modifiers": 0, "latency": 6.38},
{"t": 4.825512596, "m": "Page.dispatchMouseEvent", "type": "mousemove", "x": 455.35141338254977, "y": 329.78711882532434, "button": 0, "buttons": 0, "modifiers": 0, "latency": 4.96},
{"t": 4.98901089, "m": "Page.dispatchMouseEvent", "type": "mousemove", "x": 455.35833046424807, "y": 329.7269088106554, "button": 0, "buttons": 0, "modifiers": 0, "latency": 13.8},
{"t": 5.013729796, "m": "Page.dispatchMouseEvent", "type": "mousemove", "x": 455.92590183952683, "y": 329.62367947731457, "button": 0, "buttons": 0, "modifiers": 0, "latency": 5.91},
{"t": 5.027550665, "m": "Page.dispatchMouseEvent", "type": "mousemove", "x": 456.88036094973484, "y": 329.45701199063853, "button": 0, "buttons": 0, "modifiers": 0, "latency": 5.35},
{"t": 5.041541572, "m": "Page.dispatchMouseEvent", "type": "mousemove", "x": 458.2617852588681, "y": 328.6856452531197, "button": 0, "buttons": 0, "modifiers": 0, "latency": 12.49},
{"t": 5.0554129, "m": "Page.dispatchMouseEvent", "type": "mousemove", "x": 459.95620941324347, "y": 328.3769147397998, "button": 0, "buttons": 0, "modifiers": 0, "latency": 16.12},
{"t": 5.064448544, "m": "Page.dispatchMouseEvent", "type": "mousemove", "x": 461.34182199098717, "y": 328.0088470937991, "button": 0, "buttons": 0, "modifiers": 0, "latency": 15.05},
{"t": 5.085402115, "m": "Page.dispatchMouseEvent", "type": "mousemove", "x": 465.0638428031812, "y": 326.69898852914594, "button": 0, "buttons": 0, "modifiers": 0, "latency": 12.92},
{"t": 5.099228687, "m": "Page.dispatchMouseEvent", "type": "mousemove", "x": 467.49268518223255, "y": 325.64931441749883, "button": 0, "buttons": 0, "modifiers": 0, "latency": 12.03},
{"t": 5.118542234, "m": "Page.dispatchMouseEvent", "type": "mousemove", "x": 470.7699592637019, "y": 324.5394619082194, "button": 0, "buttons": 0, "modifiers": 0, "latency": 7.67},
{"t": 5.129480305, "m": "Page.dispatchMouseEvent", "type": "mousemove", "x": 472.25375232690584, "y": 323.7717437904422, "button": 0, "buttons": 0, "modifiers": 0, "latency": 7.16},
{"t": 5.140404835, "m": "Page.dispatchMouseEvent", "type": "mousemove", "x": 473.72646105662096, "y": 323.227567120323, "button": 0, "buttons": 0, "modifiers": 0, "latency": 10.46},
{"t": 5.149165654, "m": "Page.dispatchMouseEvent", "type": "mousemove", "x": 474.77407908247096, "y": 322.80427932901785, "button": 0, "buttons": 0, "modifiers": 0, "latency": 8.85},
{"t": 5.167943903, "m": "Page.dispatchMouseEvent", "type": "mousemove", "x": 476.02409484183335, "y": 322.2918132977939, "button": 0, "buttons": 0, "modifiers": 0, "latency": 12.47},
{"t": 5.192016594, "m": "Page.dispatchMouseEvent", "type": "mousemove", "x": 476.0, "y": 322.25214545083213, "button": 0, "buttons": 0, "modifiers": 0, "latency": 5.6},
{"t": 5.300300879, "m": "Page.dispatchMouseEvent", "type": "mousedown", "x": 476.0, "y": 322.25214545083213, "button": 0, "buttons": 1, "modifiers": 0, "clickCount": 1, "latency": 4.84},
{"t": 5.366501525, "m": "Page.dispatchMouseEvent", "type": "mouseup", "x": 476.0, "y": 322.25214545083213, "button": 0, "buttons": 0, "modifiers": 0, "clickCount": 1, "latency": 6.96},
{"t": 5.497191056, "m": "Page.dispatchMouseEvent", "type": "mousedown", "x": 476.0, "y": 322.25214545083213, "button": 0, "buttons": 1, "modifiers": 0, "clickCount": 2, "latency": 6.62},
{"t": 5.593952594, "m": "Page.dispatchMouseEvent", "type": "mouseup", "x": 476.0, "y": 322.25214545083213, "button": 0, "buttons": 0, "modifiers": 0, "clickCount": 2, "latency": 7.14},
{"t": 7.606694822, "m": "Page.dispatchMouseEvent", "type": "mousemove", "x": 477.77927489271946, "y": 322.60059441938324, "button": 0, "buttons": 0, "modifiers": 0, "latency": 8.27},
{"t": 7.618568478, "m": "Page.dispatchMouseEvent", "type": "mousemove", "x": 480.9436413229587, "y": 323.1335789453738, "button": 0, "buttons": 0, "modifiers": 0, "latency": 5.58},
{"t": 7.630365959, "m": "Page.dispatchMouseEvent", "type": "mousemove", "x": 485.1284533475551, "y": 323.6460956236181, "button": 0, "buttons": 0, "modifiers": 0, "latency": 5.19},
{"t": 7.643917119, "m": "Page.dispatchMouseEvent", "type": "mousemove", "x": 491.56226430156875, "y": 325.33491401927654, "button": 0, "buttons": 0, "modifiers": 0, "latency": 7.09},
{"t": 7.657432355, "m": "Page.dispatchMouseEvent", "type": "mousemove", "x": 499.4104891001676, "y": 326.62708911036964, "button": 0, "buttons": 0, "modifiers": 0, "latency": 6.78},
{"t": 7.673696069, "m": "Page.dispatchMouseEvent", "type": "mousemove", "x": 510.32650191155614, "y": 327.82970042029586, "button": 0, "buttons": 0, "modifiers": 0, "latency": 8.5},
{"t": 7.686079233, "m": "Page.dispatchMouseEvent", "type": "mousemove", "x": 519.4369448918778, "y": 330.00334783678767, "button": 0, "buttons": 0, "modifiers": 0, "latency": 9.16},
{"t": 7.699366366, "m": "Page.dispatchMouseEvent", "type": "mousemove", "x": 529.8574044753514, "y": 331.5435502648876, "button": 0, "buttons": 0, "modifiers": 0, "latency": 10.38},
{"t": 7.712070975, "m": "Page.dispatchMouseEvent", "type": "mousemove", "x": 539.832019515514, "y": 332.96989876213934, "button": 0, "buttons": 0, "modifiers": 0, "latency": 5.49},
{"t": 7.721918671, "m": "Page.dispatchMouseEvent", "type": "mousemove", "x": 547.6340372467073, "y": 333.7141280196961, "button": 0, "buttons": 0, "modifiers": 0, "latency": 10.23},
{"t": 7.73672888, "m": "Page.dispatchMouseEvent", "type": "mousemove", "x": 559.0483109296379, "y": 335.4183035739646, "button": 0, "buttons": 0, "modifiers": 0, "latency": 12.09},
{"t": 7.749195609, "m": "Page.dispatchMouseEvent", "type": "mousemove", "x": 568.2673629863705, "y": 336.9293705204073, "button": 0, "buttons": 0, "modifiers": 0, "latency": 14.3},
{"t": 7.763096268, "m": "Page.dispatchMouseEvent", "type": "mousemove", "x": 578.2304139755397, "y": 339.0295108893585, "button": 0, "buttons": 0, "modifiers": 0, "latency": 7.72},
{"t": 7.773573573, "m": "Page.dispatchMouseEvent", "type": "mousemove", "x": 585.2613319376826, "y": 340.82218022386974, "button": 0, "buttons": 0, "modifiers": 0, "latency": 10.32},
{"t": 7.783345347, "m": "Page.dispatchMouseEvent", "type": "mousemove", "x": 591.5130352199208, "y": 342.227952683785, "button": 0, "buttons": 0, "modifiers": 0, "latency": 9.38},
{"t": 7.793155895, "m": "Page.dispatchMouseEvent", "type": "mousemove", "x": 596.5656909307299, "y": 343.63407617094254, "button": 0, "buttons": 0, "modifiers": 0, "latency": 7.59},
{"t": 7.805187434, "m": "Page.dispatchMouseEvent", "type": "mousemove", "x": 601.4100065254825, "y": 344.6750992613015, "button": 0, "buttons": 0, "modifiers": 0, "latency": 7.08},
{"t": 7.818111681, "m": "Page.dispatchMouseEvent", "type": "mousemove", "x": 604.8342948118411, "y": 345.0959473747656, "button": 0, "buttons": 0, "modifiers": 0, "latency": 16.04},
{"t": 7.832793167, "m": "Page.dispatchMouseEvent", "type": "mousemove", "x": 606.6938041684248, "y": 344.64127547114464, "button": 0, "buttons": 0, "modifiers": 0, "latency": 9.15},
{"t": 7.844792971, "m": "Page.dispatchMouseEvent", "type": "mousemove", "x": 606.5264308415603, "y": 343.8044896203082, "button": 0, "buttons": 0, "modifiers": 0, "latency": 4.0},
{"t": 7.857546545, "m": "Page.dispatchMouseEvent", "type": "mousemove", "x": 605.2447938111029, "y": 342.2897283998135, "button": 0, "buttons": 0, "modifiers": 0, "latency": 4.59},
{"t": 7.868695922, "m": "Page.dispatchMouseEvent", "type": "mousemove", "x": 605.3217826374415, "y": 342.14308460405266, "button": 0, "buttons": 0, "modifiers": 0, "latency": 19.16},
{"t": 7.883371093, "m": "Page.dispatchMouseEvent", "type": "mousemove", "x": 606.5706620798605, "y": 341.5116347224792, "button": 0, "buttons": 0, "modifiers": 0, "latency": 7.94},
{"t": 7.896614426, "m": "Page.dispatchMouseEvent", "type": "mousemove", "x": 609.6408310700469, "y": 339.65969606685337, "button": 0, "buttons": 0, "modifiers": 0, "latency": 9.77},
{"t": 7.908826194, "m": "Page.dispatchMouseEvent", "type": "mousemove", "x": 614.8738805324843, "y": 336.67603122469336, "button": 0, "buttons": 0, "modifiers": 0, "latency": 11.96},
{"t": 7.921229448, "m": "Page.dispatchMouseEvent", "type": "mousemove", "x": 622.890892902876, "y": 332.58157904119975, "button": 0, "buttons": 0, "modifiers": 0, "latency": 10.69},
{"t": 7.931840185, "m": "Page.dispatchMouseEvent", "type": "mousemove", "x": 631.5239488564799, "y": 327.1872571608006, "button": 0, "buttons": 0, "modifiers": 0, "latency": 11.44},
{"t": 7.944956806, "m": "Page.dispatchMouseEvent", "type": "mousemove", "x": 645.2876840086453, "y": 318.8999735640071, "button": 0, "buttons": 0, "modifiers": 0, "latency": 5.6},
{"t": 7.953880483, "m": "Page.dispatchMouseEvent", "type": "mousemove", "x": 656.6613059858267, "y": 312.629950822328, "button": 0, "buttons": 0, "modifiers": 0, "latency": 13.07},
{"t": 7.96338371, "m": "Page.dispatchMouseEvent", "type": "mousemove", "x": 669.894616526193, "y": 304.39719121620556, "button": 0, "buttons": 0, "modifiers": 0, "latency": 4.58},
{"t": 7.975021439, "m": "Page.dispatchMouseEvent", "type": "mousemove", "x": 687.7423613848551, "y": 293.82739523408515, "button": 0, "buttons": 0, "modifiers": 0, "latency": 12.79},
{"t": 7.989761551, "m": "Page.dispatchMouseEvent", "type": "mousemove", "x": 713.2111036488658, "y": 278.7707854681554, "button": 0, "buttons": 0, "modifiers": 0, "latency": 6.1},
{"t": 8.003167056, "m": "Page.dispatchMouseEvent", "type": "mousemove", "x": 738.0765899156423, "y": 263.8103515246826, "button": 0, "buttons": 0, "modifiers": 0, "latency": 7.54},
{"t": 8.01430411, "m": "Page.dispatchMouseEvent", "type": "mousemove", "x": 759.1753741758123, "y": 250.5766599563955, "button": 0, "buttons": 0, "modifiers": 0, "latency": 7.62},
{"t": 8.028780244, "m": "Page.dispatchMouseEvent", "type": "mousemove", "x": 787.4242133850586, "y": 233.74007957572522, "button": 0, "buttons": 0, "modifiers": 0, "latency": 8.64},
{"t": 8.045795618, "m": "Page.dispatchMouseEvent", "type": "mousemove", "x": 819.9279054816885, "y": 213.94517183021918, "button": 0, "buttons": 0, "modifiers": 0, "latency": 5.36},
{"t": 8.057509824, "m": "Page.dispatchMouseEvent", "type": "mousemove", "x": 841.1531748827509, "y": 200.98490740667438, "button": 0, "buttons": 0, "modifiers": 0, "latency": 7.53},
{"t": 8.068436713, "m": "Page.dispatchMouseEvent", "type": "mousemove", "x": 859.5403920325616, "y": 189.48791636623923, "button": 0, "buttons": 0, "modifiers": 0, "latency": 6.68},
{"t": 8.080763141, "m": "Page.dispatchMouseEvent", "type": "mousemove", "x": 878.5684919360394, "y": 177.71070475136716, "button": 0, "buttons": 0, "modifiers": 0, "latency": 4.71},
{"t": 8.094414275, "m": "Page.dispatchMouseEvent", "type": "mousemove", "x": 897.0617130020582, "y": 166.36471741609773, "button": 0, "buttons": 0, "modifiers": 0, "latency": 5.63},
{"t": 8.108158002, "m": "Page.dispatchMouseEvent", "type": "mousemove", "x": 912.2862129629133, "y": 156.78376772956614, "button": 0, "buttons": 0, "modifiers": 0, "latency": 8.74},
{"t": 8.124038188, "m": "Page.dispatchMouseEvent", "type": "mousemove", "x": 925.8294610270041, "y": 148.79004191611858, "button": 0, "buttons": 0, "modifiers": 0, "latency": 12.46},
{"t": 8.135894528, "m": "Page.dispatchMouseEvent", "type": "mousemove", "x": 932.853427455016, "y": 144.31684158384897, "button": 0, "buttons": 0, "modifiers": 0, "latency": 10.07},
{"t": 8.148597113, "m": "Page.dispatchMouseEvent", "type": "mousemove", "x": 937.8864605458238, "y": 141.44391222246753, "button": 0, "buttons": 0, "modifiers": 0, "latency": 8.41},
{"t": 8.161568411, "m": "Page.dispatchMouseEvent", "type": "mousemove", "x": 940.5554268605911, "y": 139.9115462931803, "button": 0, "buttons": 0, "modifiers": 0, "latency": 7.11},
{"t": 8.183892723, "m": "Page.dispatchMouseEvent", "type": "mousemove", "x": 941.4699862079036, "y": 139.1623036406111, "button": 0, "buttons": 0, "modifiers": 0, "latency": 10.98},
{"t": 8.343707123, "m": "Page.dispatchMouseEvent", "type": "mousemove", "x": 941.5295133537178, "y": 139.11913786737495, "button": 0, "buttons": 0, "modifiers": 0, "latency": 12.12},
{"t": 8.374820078, "m": "Page.dispatchMouseEvent", "type": "mousemove", "x": 942.5262960622367, "y": 138.5398746153685, "button": 0, "buttons": 0, "modifiers": 0, "latency": 14.02},
{"t": 8.389812955, "m": "Page.dispatchMouseEvent", "type": "mousemove", "x": 943.36677544725, "y": 138.11599079171032, "button": 0, "buttons": 0, "modifiers": 0, "latency": 6.63},
{"t": 8.405358681, "m": "Page.dispatchMouseEvent", "type": "mousemove", "x": 944.3193893010618, "y": 137.61931942823497, "button": 0, "buttons": 0, "modifiers": 0, "latency": 8.68},
{"t": 8.417817247, "m": "Page.dispatchMouseEvent", "type": "mousemove", "x": 945.0624341332028, "y": 137.1490906443726, "button": 0, "buttons": 0, "modifiers": 0, "latency": 8.11},
{"t": 8.430951168, "m": "Page.dispatchMouseEvent", "type": "mousemove", "x": 945.7108136242649, "y": 136.64706604798755, "button": 0, "buttons": 0, "modifiers": 0, "latency": 9.18},
{"t": 8.444965925, "m": "Page.dispatchMouseEvent", "type": "mousemove", "x": 946.3203332581336, "y": 136.21050511803833, "button": 0, "buttons": 0, "modifiers": 0, "latency": 4.57},
{"t": 8.456863168, "m": "Page.dispatchMouseEvent", "type": "mousemove", "x": 946.7558282288504, "y": 136.03745673003317, "button": 0, "buttons": 0, "modifiers": 0, "latency": 3.51},
{"t": 8.484408673, "m": "Page.dispatchTapEvent", "x": 947.0274551036065, "y": 135.80480881127883, "modifiers": 0},
{"t": 8.562140502, "m": "Page.dispatchMouseEvent", "type": "mousemove", "x": 944.2814693266105, "y": 135.72789332865057, "button": 0, "buttons": 0, "modifiers": 0, "latency": 7.56},
{"t": 8.573405551, "m": "Page.dispatchMouseEvent", "type": "mousemove", "x": 940.8461578302006, "y": 135.51107529649104, "button": 0, "buttons": 0, "modifiers": 0, "latency": 5.0},
{"t": 8.586309034, "m": "Page.dispatchMouseEvent", "type": "mousemove", "x": 935.6809269394015, "y": 134.97383785363473, "button": 0, "buttons": 0, "modifiers": 0, "latency": 5.08},
{"t": 8.595842494, "m": "Page.dispatchMouseEvent", "type": "mousemove", "x": 930.949851129302, "y": 134.15991238382406, "button": 0, "buttons": 0, "modifiers": 0, "latency": 9.09},
{"t": 8.611334402, "m": "Page.dispatchMouseEvent", "type": "mousemove", "x": 922.5097067477308, "y": 132.6116889781748, "button": 0, "buttons": 0, "modifiers": 0, "latency": 10.57},
{"t": 8.624488383, "m": "Page.dispatchMouseEvent", "type": "mousemove", "x": 915.0917508158183, "y": 131.05812340234718, "button": 0, "buttons": 0, "modifiers": 0, "latency": 9.91},
{"t": 8.635740458, "m": "Page.dispatchMouseEvent", "type": "mousemove", "x": 909.1921692618356, "y": 129.8582787959228, "button": 0, "buttons": 0, "modifiers": 0, "latency": 16.21},
{"t": 8.650358825, "m": "Page.dispatchMouseEvent", "type": "mousemove", "x": 902.0017016452372, "y": 127.98999733387146, "button": 0, "buttons": 0, "modifiers": 0, "latency": 9.06},
{"t": 8.662630943, "m": "Page.dispatchMouseEvent", "type": "mousemove", "x": 897.1689147236439, "y": 126.88309828623606, "button": 0, "buttons": 0, "modifiers": 0, "latency": 5.94},
{"t": 8.672504884, "m": "Page.dispatchMouseEvent", "type": "mousemove", "x": 894.3553998859359, "y": 126.27042132902083, "button": 0, "buttons": 0, "modifiers": 0, "latency": 10.17},
{"t": 8.68652296, "m": "Page.dispatchMouseEvent", "type": "mousemove", "x": 891.6999774195993, "y": 125.62334149241345, "button": 0, "buttons": 0, "modifiers": 0, "latency": 10.66},
{"t": 8.698780716, "m": "Page.dispatchMouseEvent", "type": "mousemove", "x": 890.6883828696162, "y": 125.31691690879914, "button": 0, "buttons": 0, "modifiers": 0, "latency": 9.22},
{"t": 8.709047613, "m": "Page.dispatchMouseEvent", "type": "mousemove", "x": 890.5, "y": 125.25, "button": 0, "buttons": 0, "modifiers": 0, "latency": 6.02},
{"t": 8.853785204, "m": "Page.dispatchMouseEvent", "type": "mousedown", "x": 890.5, "y": 125.25, "button": 0, "buttons": 1, "modifiers": 0, "clickCount": 1, "latency": 11.32},
{"t": 8.938771468, "m": "Page.dispatchMouseEvent", "type": "mouseup", "x": 890.5, "y": 125.25, "button": 0, "buttons": 0, "modifiers": 0, "clickCount": 1, "latency": 8.78},
{"t": 16.454456552, "m": "Page.dispatchMouseEvent", "type": "mousemove", "x": 891.5, "y": 125.25, "button": 0, "buttons": 0, "modifiers": 0, "latency": 8.13},
{"t": 16.467661693, "m": "Page.dispatchMouseEvent", "type": "mousemove", "x": 891.7921258428407, "y": 132.46214953890643, "button": 0, "buttons": 0, "modifiers": 0, "latency": 7.67},
{"t": 16.481781321, "m": "Page.dispatchMouseEvent", "type": "mousemove", "x": 891.472949232665, "y": 145.82053495853324, "button": 0, "buttons": 0, "modifiers": 0, "latency": 7.4},
{"t": 16.493688227, "m": "Page.dispatchMouseEvent", "type": "mousemove", "x": 892.0857050037708, "y": 161.23810492948405, "button": 0, "buttons": 0, "modifiers": 0, "latency": 8.64},
{"t": 16.507136428, "m": "Page.dispatchMouseEvent", "type": "mousemove", "x": 892.8407166808627, "y": 182.871869185266, "button": 0, "buttons": 0, "modifiers": 0, "latency": 11.19},
{"t": 16.524910587, "m": "Page.dispatchMouseEvent", "type": "mousemove", "x": 895.0151455799665, "y": 216.31914995601807, "button": 0, "buttons": 0, "modifiers": 0, "latency": 9.76},
{"t": 16.534881305, "m": "Page.dispatchMouseEvent", "type": "mousemove", "x": 896.7234411186804, "y": 237.3976008416875, "button": 0, "buttons": 0, "modifiers": 0, "latency": 10.8},
{"t": 16.549649327, "m": "Page.dispatchMouseEvent", "type": "mousemove", "x": 898.5755317930278, "y": 268.9680951767716, "button": 0, "buttons": 0, "modifiers": 0, "latency": 6.14},
{"t": 16.565336316, "m": "Page.dispatchMouseEvent", "type": "mousemove", "x": 901.9736265806414, "y": 302.75043307118995, "button": 0, "buttons": 0, "modifiers": 0, "latency": 6.15},
{"t": 16.577574438, "m": "Page.dispatchMouseEvent", "type": "mousemove", "x": 904.0733905482601, "y": 327.5500120335353, "button": 0, "buttons": 0, "modifiers": 0, "latency": 9.8},
{"t": 16.589691735, "m": "Page.dispatchMouseEvent", "type": "mousemove", "x": 906.4411685031145, "y": 350.4058234850788, "button": 0, "buttons": 0, "modifiers": 0, "latency": 7.22},
{"t": 16.604721785, "m": "Page.dispatchMouseEvent", "type": "mousemove", "x": 908.525037920876, "y": 375.19488510285566, "button": 0, "buttons": 0, "modifiers": 0, "latency": 5.51},
{"t": 16.616906426, "m": "Page.dispatchMouseEvent", "type": "mousemove", "x": 909.8845421026746, "y": 390.80943990433633, "button": 0, "buttons": 0, "modifiers": 0, "latency": 7.63},
{"t": 16.626565624, "m": "Page.dispatchMouseEvent", "type": "mousemove", "x": 911.0328370007763, "y": 400.52865595531375, "button": 0, "buttons": 0, "modifiers": 0, "latency": 12.2},
{"t": 16.638229956, "m": "Page.dispatchMouseEvent", "type": "mousemove", "x": 911.6979362300177, "y": 408.8223329409037, "button": 0, "buttons": 0, "modifiers": 0, "latency": 12.46},
{"t": 16.646686292, "m": "Page.dispatchMouseEvent", "type": "mousemove", "x": 912.208864341333, "y": 411.92379437606235, "button": 0, "buttons": 0, "modifiers": 0, "latency": 7.5},
{"t": 16.658952173, "m": "Page.dispatchMouseEvent", "type": "mousemove", "x": 912.2902333015486, "y": 413.50647899070987, "button": 0, "buttons": 0, "modifiers": 0, "latency": 9.46},
{"t": 16.672894878, "m": "Page.dispatchMouseEvent", "type": "mousemove", "x": 911.1310109865708, "y": 413.43919820140763, "button": 0, "buttons": 0, "modifiers": 0, "latency": 6.3},
{"t": 16.68605622, "m": "Page.dispatchMouseEvent", "type": "mousemove", "x": 907.0652163395553, "y": 412.82567342104784, "button": 0, "buttons": 0, "modifiers": 0, "latency": 8.09},
{"t": 16.696525302, "m": "Page.dispatchMouseEvent", "type": "mousemove", "x": 900.9129145654533, "y": 411.88849760356095, "button": 0, "buttons": 0, "modifiers": 0, "latency": 9.68},
{"t": 16.70775172, "m": "Page.dispatchMouseEvent", "type": "mousemove", "x": 891.7563993542835, "y": 410.4834676326232, "button": 0, "buttons": 0, "modifiers": 0, "latency": 10.33},
{"t": 16.716798443, "m": "Page.dispatchMouseEvent", "type": "mousemove", "x": 882.2114367250028, "y": 408.80634700358655, "button": 0, "buttons": 0, "modifiers": 0, "latency": 6.21},
{"t": 16.725996729, "m": "Page.dispatchMouseEvent", "type": "mousemove", "x": 870.454688980436, "y": 406.74968008999497, "button": 0, "buttons": 0, "modifiers": 0, "latency": 5.51},
{"t": 16.736805967, "m": "Page.dispatchMouseEvent", "type": "mousemove", "x": 854.6045264964619, "y": 403.3243030722024, "button": 0, "buttons": 0, "modifiers": 0, "latency": 14.82},
{"t": 16.752218501, "m": "Page.dispatchMouseEvent", "type": "mousemove", "x": 827.6082027285674, "y": 396.7078915148092, "button": 0, "buttons": 0, "modifiers": 0, "latency": 5.53},
{"t": 16.764757246, "m": "Page.dispatchMouseEvent", "type": "mousemove", "x": 802.9207255472676, "y": 390.8486274006831, "button": 0, "buttons": 0, "modifiers": 0, "latency": 4.96},
{"t": 16.774048968, "m": "Page.dispatchMouseEvent", "type": "mousemove", "x": 783.2428567648902, "y": 385.87097772968184, "button": 0, "buttons": 0, "modifiers": 0, "latency": 4.81},
{"t": 16.78748322, "m": "Page.dispatchMouseEvent", "type": "mousemove", "x": 752.7294247336173, "y": 377.42115223625603, "button": 0, "buttons": 0, "modifiers": 0, "latency": 6.01},
{"t": 16.796530846, "m": "Page.dispatchMouseEvent", "type": "mousemove", "x": 731.5912541448862, "y": 371.25750591560035, "button": 0, "buttons": 0, "modifiers": 0, "latency": 5.57},
{"t": 16.809618242, "m": "Page.dispatchMouseEvent", "type": "mousemove", "x": 699.8705750267488, "y": 362.3738624409237, "button": 0, "buttons": 0, "modifiers": 0, "latency": 23.42},
{"t": 16.819648295, "m": "Page.dispatchMouseEvent", "type": "mousemove", "x": 675.2147180410539, "y": 355.10313454573804, "button": 0, "buttons": 0, "modifiers": 0, "latency": 12.59},
{"t": 16.83231045, "m": "Page.dispatchMouseEvent", "type": "mousemove", "x": 644.3450795030313, "y": 346.2755654859782, "button": 0, "buttons": 0, "modifiers": 0, "latency": 10.5},
{"t": 16.845577036, "m": "Page.dispatchMouseEvent", "type": "mousemove", "x": 612.8051804886838, "y": 335.5912701081006, "button": 0, "buttons": 0, "modifiers": 0, "latency": 8.09},
{"t": 16.860694656, "m": "Page.dispatchMouseEvent", "type": "mousemove", "x": 578.193674123766, "y": 325.3417461778036, "button": 0, "buttons": 0, "modifiers": 0, "latency": 8.59},
{"t": 16.874461466, "m": "Page.dispatchMouseEvent", "type": "mousemove", "x": 541.9820956185026, "y": 310.9559082979217, "button": 0, "buttons": 0, "modifiers": 0, "latency": 8.94},
{"t": 16.889001179, "m": "Page.dispatchMouseEvent", "type": "mousemove", "x": 508.00897799157525, "y": 297.4485592667214, "button": 0, "buttons": 0, "modifiers": 0, "latency": 9.75},
{"t": 16.908004598, "m": "Page.dispatchMouseEvent", "type": "mousemove", "x": 471.42828095131995, "y": 283.51768753031405, "button": 0, "buttons": 0, "modifiers": 0, "latency": 5.55},
{"t": 16.922948022, "m": "Page.dispatchMouseEvent", "type": "mousemove", "x": 449.7201125839018, "y": 275.6643720363795, "button": 0, "buttons": 0, "modifiers": 0, "latency": 11.89},
{"t": 16.936750859, "m": "Page.dispatchMouseEvent", "type": "mousemove", "x": 435.9324152028672, "y": 271.5924248753518, "button": 0, "buttons": 0, "modifiers": 0, "latency": 10.01},
{"t": 16.951878435, "m": "Page.dispatchMouseEvent", "type": "mousemove", "x": 427.8998731127827, "y": 269.9144953879536, "button": 0, "buttons": 0, "modifiers": 0, "latency": 6.91},
{"t": 16.96232973, "m": "Page.dispatchMouseEvent", "type": "mousemove", "x": 426.14859936735326, "y": 270.6737395183657, "button": 0, "buttons": 0, "modifiers": 0, "latency": 6.46},
{"t": 16.97543676, "m": "Page.dispatchMouseEvent", "type": "mousemove", "x": 427.93918116978733, "y": 273.27997425967544, "button": 0, "buttons": 0, "modifiers": 0, "latency": 11.55},
{"t": 16.990262807, "m": "Page.dispatchMouseEvent", "type": "mousemove", "x": 435.0676749245441, "y": 279.1591827834145, "button": 0, "buttons": 0, "modifiers": 0, "latency": 18.56},
{"t": 17.107663927, "m": "Page.dispatchMouseEvent", "type": "mousemove", "x": 435.8209069604248, "y": 280.462685154236, "button": 0, "buttons": 0, "modifiers": 0, "latency": 10.98},
{"t": 17.121128994, "m": "Page.dispatchMouseEvent", "type": "mousemove", "x": 436.6480487933325, "y": 281.97977586352454, "button": 0, "buttons": 0, "modifiers": 0, "latency": 8.12},
{"t": 17.133461595, "m": "Page.dispatchMouseEvent", "type": "mousemove", "x": 437.8353977551234, "y": 283.8443455565557, "button": 0, "buttons": 0, "modifiers": 0, "latency": 11.93},
{"t": 17.143543735, "m": "Page.dispatchMouseEvent", "type": "mousemove", "x": 439.02680943683157, "y": 285.52938058177733, "button": 0, "buttons": 0, "modifiers": 0, "latency": 4.43},
{"t": 17.162719015, "m": "Page.dispatchMouseEvent", "type": "mousemove", "x": 441.9119420936435, "y": 289.52671069541407, "button": 0, "buttons": 0, "modifiers": 0, "latency": 12.03},
{"t": 17.175058857, "m": "Page.dispatchMouseEvent", "type": "mousemove", "x": 444.10581192574944, "y": 292.647845677802, "button": 0, "buttons": 0, "modifiers": 0, "latency": 8.35},
{"t": 17.183786951, "m": "Page.dispatchMouseEvent", "type": "mousemove", "x": 445.383361359718, "y": 295.01765340578265, "button": 0, "buttons": 0, "modifiers": 0, "latency": 11.38},
{"t": 17.196282683, "m": "Page.dispatchMouseEvent", "type": "mousemove", "x": 448.1174403736159, "y": 298.0124589827435, "button": 0, "buttons": 0, "modifiers": 0, "latency": 4.69},
{"t": 17.206444138, "m": "Page.dispatchMouseEvent", "type": "mousemove", "x": 450.0042547771697, "y": 300.54290294833663, "button": 0, "buttons": 0, "modifiers": 0, "latency": 13.26},
{"t": 17.225111604, "m": "Page.dispatchMouseEvent", "type": "mousemove", "x": 453.7025331750035, "y": 305.0078912184608, "button": 0, "buttons": 0, "modifiers": 0, "latency": 10.99},
{"t": 17.234073011, "m": "Page.dispatchMouseEvent", "type": "mousemove", "x": 455.41838908207313, "y": 307.0645548424366, "button": 0, "buttons": 0, "modifiers": 0, "latency": 10.36},
{"t": 17.247033829, "m": "Page.dispatchMouseEvent", "type": "mousemove", "x": 457.3868511065989, "y": 309.7967417367015, "button": 0, "buttons": 0, "modifiers": 0, "latency": 8.66},
{"t": 17.259986243, "m": "Page.dispatchMouseEvent", "type": "mousemove", "x": 459.19617360471506, "y": 311.84539904953704, "button": 0, "buttons": 0, "modifiers": 0, "latency": 5.69},
{"t": 17.27404733, "m": "Page.dispatchMouseEvent", "type": "mousemove", "x": 460.5734932605181, "y": 313.62926225315016, "button": 0, "buttons": 0, "modifiers": 0, "latency": 7.18},
{"t": 17.289335088, "m": "Page.dispatchMouseEvent", "type": "mousemove", "x": 461.451693075982, "y": 314.7299835186661, "button": 0, "buttons": 0, "modifiers": 0, "latency": 9.51},
{"t": 17.302072086, "m": "Page.dispatchMouseEvent", "type": "mousemove", "x": 461.63922288239587, "y": 315.14345582387153, "button": 0, "buttons": 0, "modifiers": 0, "latency": 9.96},
{"t": 17.312710217, "m": "Page.dispatchMouseEvent", "type": "mousemove", "x": 461.4976580801775, "y": 315.31546484445585, "button": 0, "buttons": 0, "modifiers": 0, "latency": 12.55},
{"t": 17.394987302, "m": "Page.dispatchMouseEvent", "type": "mousedown", "x": 461.4976580801775, "y": 315.31546484445585, "button": 0, "buttons": 1, "modifiers": 0, "clickCount": 1, "latency": 4.96},
{"t": 17.49980119, "m": "Page.dispatchMouseEvent", "type": "mouseup", "x": 461.4976580801775, "y": 315.31546484445585, "button": 0, "buttons": 0, "modifiers": 0, "clickCount": 1, "latency": 10.46},
{"t": 17.512085278, "m": "Page.dispatchMouseEvent", "type": "mousemove", "x": 461.6564699819293, "y": 315.5230695111014, "button": 0, "buttons": 0, "modifiers": 0, "latency": 11.44},
{"t": 17.527754286, "m": "Page.dispatchMouseEvent", "type": "mousemove", "x": 463.1313435408408, "y": 316.82317729185047, "button": 0, "buttons": 0, "modifiers": 0, "latency": 9.17},
{"t": 17.540777628, "m": "Page.dispatchMouseEvent", "type": "mousemove", "x": 466.1861150281036, "y": 319.32483300640473, "button": 0, "buttons": 0, "modifiers": 0, "latency": 7.48},
{"t": 17.552212886, "m": "Page.dispatchMouseEvent", "type": "mousemove", "x": 470.8880616311443, "y": 322.96141283770294, "button": 0, "buttons": 0, "modifiers": 0, "latency": 11.62},
{"t": 17.566015946, "m": "Page.dispatchMouseEvent", "type": "mousemove", "x": 478.5309442319946, "y": 329.4200296606968, "button": 0, "buttons": 0, "modifiers": 0, "latency": 6.24},
{"t": 17.578295444, "m": "Page.dispatchMouseEvent", "type": "mousemove", "x": 487.8037706849211, "y": 336.9413458341431, "button": 0, "buttons": 0, "modifiers": 0, "latency": 7.23},
{"t": 17.587915132, "m": "Page.dispatchMouseEvent", "type": "mousemove", "x": 496.81426925844073, "y": 343.99891367351273, "button": 0, "buttons": 0, "modifiers": 0, "latency": 5.66},
{"t": 17.605824367, "m": "Page.dispatchMouseEvent", "type": "mousemove", "x": 516.8194316929125, "y": 359.1073295179121, "button": 0, "buttons": 0, "modifiers": 0, "latency": 6.7},
{"t": 17.617059163, "m": "Page.dispatchMouseEvent", "type": "mousemove", "x": 531.7272429630028, "y": 370.272505531219, "button": 0, "buttons": 0, "modifiers": 0, "latency": 7.08},
{"t": 17.629083695, "m": "Page.dispatchMouseEvent", "type": "mousemove", "x": 548.6706875755731, "y": 382.66927507629987, "button": 0, "buttons": 0, "modifiers": 0, "latency": 7.04},
{"t": 17.647962186, "m": "Page.dispatchMouseEvent", "type": "mousemove", "x": 577.8397442114884, "y": 403.8655960113904, "button": 0, "buttons": 0, "modifiers": 0, "latency": 12.28},
{"t": 17.65749881, "m": "Page.dispatchMouseEvent", "type": "mousemove", "x": 593.0845120538205, "y": 414.70563093398994, "button": 0, "buttons": 0, "modifiers": 0, "latency": 7.66},
{"t": 17.668992869, "m": "Page.dispatchMouseEvent", "type": "mousemove", "x": 611.5032123893371, "y": 427.9451641676644, "button": 0, "buttons": 0, "modifiers": 0, "latency": 12.21},
{"t": 17.684223095, "m": "Page.dispatchMouseEvent", "type": "mousemove", "x": 636.0024686430602, "y": 444.8289489010262, "button": 0, "buttons": 0, "modifiers": 0, "latency": 9.7},
{"t": 17.695746587, "m": "Page.dispatchMouseEvent", "type": "mousemove", "x": 653.6309388069786, "y": 457.0587964689046, "button": 0, "buttons": 0, "modifiers": 0, "latency": 12.49},
{"t": 17.706959236, "m": "Page.dispatchMouseEvent", "type": "mousemove", "x": 669.7913848307766, "y": 468.3830731306737, "button": 0, "buttons": 0, "modifiers": 0, "latency": 5.11},
{"t": 17.72052224, "m": "Page.dispatchMouseEvent", "type": "mousemove", "x": 687.5666768047254, "y": 480.54459569591813, "button": 0, "buttons": 0, "modifiers": 0, "latency": 12.69},
{"t": 17.733308785, "m": "Page.dispatchMouseEvent", "type": "mousemove", "x": 702.4855650744213, "y": 490.8013192442668, "button": 0, "buttons": 0, "modifiers": 0, "latency": 12.3},
{"t": 17.744525077, "m": "Page.dispatchMouseEvent", "type": "mousemove", "x": 713.4779148368445, "y": 498.3585383321013, "button": 0, "buttons": 0, "modifiers": 0, "latency": 18.24},
{"t": 17.760633731, "m": "Page.dispatchMouseEvent", "type": "mousemove", "x": 727.6144845193938, "y": 507.4822483525534, "button": 0, "buttons": 0, "modifiers": 0, "latency": 7.9},
{"t": 17.774700585, "m": "Page.dispatchMouseEvent", "type": "mousemove", "x": 738.3896444624652, "y": 514.5965707143748, "button": 0, "buttons": 0, "modifiers": 0, "latency": 7.53},
{"t": 17.787739558, "m": "Page.dispatchMouseEvent", "type": "mousemove", "x": 744.0997143376181, "y": 517.9477223272926, "button": 0, "buttons": 0, "modifiers": 0, "latency": 6.47},
{"t": 17.799821635, "m": "Page.dispatchMouseEvent", "type": "mousemove", "x": 745.5774717556743, "y": 519.2936624135915, "button": 0, "buttons": 0, "modifiers": 0, "latency": 12.31},
{"t": 17.81117772, "m": "Page.dispatchMouseEvent", "type": "mousemove", "x": 744.5099217771159, "y": 519.0198859970309, "button": 0, "buttons": 0, "modifiers": 0, "latency": 8.56},
{"t": 17.822097688, "m": "Page.dispatchMouseEvent", "type": "mousemove", "x": 741.4644048459211, "y": 517.6965980768376, "button": 0, "buttons": 0, "modifiers": 0, "latency": 5.62},
{"t": 18.020349901, "m": "Page.dispatchMouseEvent", "type": "mousemove", "x": 740.6218591466413, "y": 517.343899800976, "button": 0, "buttons": 0, "modifiers": 0, "latency": 7.21},
{"t": 18.036005116, "m": "Page.dispatchMouseEvent", "type": "mousemove", "x": 739.9973006358854, "y": 517.3258304329484, "button": 0, "buttons": 0, "modifiers": 0, "latency": 4.58},
{"t": 18.049151927, "m": "Page.dispatchMouseEvent", "type": "mousemove", "x": 739.451575908585, "y": 517.0522011428224, "button": 0, "buttons": 0, "modifiers": 0, "latency": 11.3},
{"t": 18.07610667, "m": "Page.dispatchMouseEvent", "type": "mousemove", "x": 737.7526735010507, "y": 516.456631935537, "button": 0, "buttons": 0, "modifiers": 0, "latency": 9.38},
{"t": 18.089606079, "m": "Page.dispatchMouseEvent", "type": "mousemove", "x": 736.7806180524246, "y": 516.1168892409596, "button": 0, "buttons": 0, "modifiers": 0, "latency": 8.26},
{"t": 18.101085, "m": "Page.dispatchMouseEvent", "type": "mousemove", "x": 735.8623681280088, "y": 515.8831718999555, "button": 0, "buttons": 0, "modifiers": 0, "latency": 12.89},
{"t": 18.115963759, "m": "Page.dispatchMouseEvent", "type": "mousemove", "x": 734.3833913329976, "y": 515.4342776494998, "button": 0, "buttons": 0, "modifiers": 0, "latency": 10.04},
{"t": 18.127464691, "m": "Page.dispatchMouseEvent", "type": "mousemove", "x": 733.4055084882502, "y": 514.8627559758797, "button": 0, "buttons": 0, "modifiers": 0, "latency": 6.23},
{"t": 18.139198822, "m": "Page.dispatchMouseEvent", "type": "mousemove", "x": 732.054962610776, "y": 514.3263287996339, "button": 0, "buttons": 0, "modifiers": 0, "latency": 12.15},
{"t": 18.153834012, "m": "Page.dispatchMouseEvent", "type": "mousemove", "x": 730.5526985218476, "y": 513.7814404194262, "button": 0, "buttons": 0, "modifiers": 0, "latency": 7.14},
{"t": 18.166414544, "m": "Page.dispatchMouseEvent", "type": "mousemove", "x": 729.0469873387722, "y": 513.381554989128, "button": 0, "buttons": 0, "modifiers": 0, "latency": 7.2},
{"t": 18.178140537, "m": "Page.dispatchMouseEvent", "type": "mousemove", "x": 727.6841089865759, "y": 512.9005604843763, "button": 0, "buttons": 0, "modifiers": 0, "latency": 8.1},
{"t": 18.190645858, "m": "Page.dispatchMouseEvent", "type": "mousemove", "x": 726.2246901658674, "y": 512.3182247822829, "button": 0, "buttons": 0, "modifiers": 0, "latency": 9.07},
{"t": 18.203331151, "m": "Page.dispatchMouseEvent", "type": "mousemove", "x": 724.7002258795351, "y": 511.730295213472, "button": 0, "buttons": 0, "modifiers": 0, "latency": 7.42},
{"t": 18.21808822, "m": "Page.dispatchMouseEvent", "type": "mousemove", "x": 722.8253489883233, "y": 511.093222013604, "button": 0, "buttons": 0, "modifiers": 0, "latency": 9.94},
{"t": 18.232666405, "m": "Page.dispatchMouseEvent", "type": "mousemove", "x": 721.1488584286233, "y": 510.3989321458138, "button": 0, "buttons": 0, "modifiers": 0, "latency": 8.21},
{"t": 18.241895276, "m": "Page.dispatchMouseEvent", "type": "mousemove", "x": 720.0575652630893, "y": 509.9987285320288, "button": 0, "buttons": 0, "modifiers": 0, "latency": 9.12},
{"t": 18.254761217, "m": "Page.dispatchMouseEvent", "type": "mousemove", "x": 718.4280376276511, "y": 509.6264024918027, "button": 0, "buttons": 0, "modifiers": 0, "latency": 14.3},
{"t": 18.271685182, "m": "Page.dispatchMouseEvent", "type": "mousemove", "x": 716.5408393744683, "y": 508.65554125148526, "button": 0, "buttons": 0, "modifiers": 0, "latency": 9.63},
{"t": 18.28302329, "m": "Page.dispatchMouseEvent", "type": "mousemove", "x": 715.3550010295463, "y": 508.27053439682135, "button": 0, "buttons": 0, "modifiers": 0, "latency": 4.21},
{"t": 18.293182262, "m": "Page.dispatchMouseEvent", "type": "mousemove", "x": 714.2378636258269, "y": 507.8827973405811, "button": 0, "buttons": 0, "modifiers": 0, "latency": 7.88},
{"t": 18.305151891, "m": "Page.dispatchMouseEvent", "type": "mousemove", "x": 713.08823651943, "y": 507.346902798479, "button": 0, "buttons": 0, "modifiers": 0, "latency": 10.32},
{"t": 18.317901838, "m": "Page.dispatchMouseEvent", "type": "mousemove", "x": 711.8174785977998, "y": 506.9116684131642, "button": 0, "buttons": 0, "modifiers": 0, "latency": 9.49},
{"t": 18.331705943, "m": "Page.dispatchMouseEvent", "type": "mousemove", "x": 710.4838368861047, "y": 506.5874640107701, "button": 0, "buttons": 0, "modifiers": 0, "latency": 7.17},
{"t": 18.343631425, "m": "Page.dispatchMouseEvent", "type": "mousemove", "x": 709.5347527363689, "y": 506.10160990326295, "button": 0, "buttons": 0, "modifiers": 0, "latency": 5.97},
{"t": 18.356634826, "m": "Page.dispatchMouseEvent", "type": "mousemove", "x": 708.4810642541655, "y": 505.56559371865916, "button": 0, "buttons": 0, "modifiers": 0, "latency": 24.03},
{"t": 18.370705906, "m": "Page.dispatchMouseEvent", "type": "mousemove", "x": 707.3858692984809, "y": 505.3524972558783, "button": 0, "buttons": 0, "modifiers": 0, "latency": 3.75},
{"t": 18.399022847, "m": "Page.dispatchMouseEvent", "type": "mousemove", "x": 705.6146306169035, "y": 504.79692510563467, "button": 0, "buttons": 0, "modifiers": 0, "latency": 7.7},
{"t": 18.40918857, "m": "Page.dispatchMouseEvent", "type": "mousemove", "x": 705.2316705461706, "y": 504.52222165720394, "button": 0, "buttons": 0, "modifiers": 0, "latency": 10.73},
{"t": 18.421212508, "m": "Page.dispatchMouseEvent", "type": "mousemove", "x": 704.8102674285518, "y": 504.2101735213016, "button": 0, "buttons": 0, "modifiers": 0, "latency": 13.96},
{"t": 18.432976302, "m": "Page.dispatchMouseEvent", "type": "mousemove", "x": 704.3804570995795, "y": 504.2629225712103, "button": 0, "buttons": 0, "modifiers": 0, "latency": 8.01},
{"t": 18.446869517, "m": "Page.dispatchMouseEvent", "type": "mousemove", "x": 704.1357342913873, "y": 504.0120402038818, "button": 0, "buttons": 0, "modifiers": 0, "latency": 22.93},
{"t": 18.526550785, "m": "Page.dispatchMouseEvent", "type": "mousemove", "x": 704.0, "y": 504.0, "button": 0, "buttons": 0, "modifiers": 0, "latency": 10.48},
{"t": 18.697655476, "m": "Page.dispatchMouseEvent", "type": "mousedown", "x": 704.0, "y": 504.0, "button": 0, "buttons": 1, "modifiers": 0, "clickCount": 1, "latency": 9.57},
{"t": 18.853368727, "m": "Page.dispatchMouseEvent", "type": "mouseup", "x": 704.0, "y": 504.0, "button": 0, "buttons": 0, "modifiers": 0, "clickCount": 1, "latency": 6.87}
]
},
"session_b_tight_cap": {
"spec": {"seed": 7, "number": 3, "budget": 0.4, "ops": [["click", "#c"], ["wait", 1.0], ["hover", "#b"], ["wait", 12.0], ["click", "#b"]]},
"engine_events": [
{"t": 0.008490309, "m": "Page.dispatchMouseEvent", "type": "mousemove", "x": 356.96812603147885, "y": 253.6067295937951, "button": 0, "buttons": 0, "modifiers": 0, "latency": 9.26},
{"t": 0.018914609, "m": "Page.dispatchMouseEvent", "type": "mousemove", "x": 363.95596200776413, "y": 252.5623951006021, "button": 0, "buttons": 0, "modifiers": 0, "latency": 8.78},
{"t": 0.032825159, "m": "Page.dispatchMouseEvent", "type": "mousemove", "x": 391.0370180797968, "y": 248.11493781561393, "button": 0, "buttons": 0, "modifiers": 0, "latency": 8.18},
{"t": 0.040994942, "m": "Page.dispatchMouseEvent", "type": "mousemove", "x": 418.1852951197895, "y": 243.6573207350179, "button": 0, "buttons": 0, "modifiers": 0, "latency": 6.96},
{"t": 0.056387195, "m": "Page.dispatchMouseEvent", "type": "mousemove", "x": 490.7060099606247, "y": 230.4362610565949, "button": 0, "buttons": 0, "modifiers": 0, "latency": 10.99},
{"t": 0.07606977, "m": "Page.dispatchMouseEvent", "type": "mousemove", "x": 611.9233473452, "y": 206.8458877615525, "button": 0, "buttons": 0, "modifiers": 0, "latency": 8.73},
{"t": 0.091780036, "m": "Page.dispatchMouseEvent", "type": "mousemove", "x": 715.028058199301, "y": 186.10011603647303, "button": 0, "buttons": 0, "modifiers": 0, "latency": 8.31},
{"t": 0.100544603, "m": "Page.dispatchMouseEvent", "type": "mousemove", "x": 771.000580718651, "y": 174.44031767211848, "button": 0, "buttons": 0, "modifiers": 0, "latency": 12.12},
{"t": 0.117954974, "m": "Page.dispatchMouseEvent", "type": "mousemove", "x": 866.3848417901391, "y": 155.18887292250704, "button": 0, "buttons": 0, "modifiers": 0, "latency": 6.23},
{"t": 0.12828781, "m": "Page.dispatchMouseEvent", "type": "mousemove", "x": 911.9662644756265, "y": 146.33851049527465, "button": 0, "buttons": 0, "modifiers": 0, "latency": 5.92},
{"t": 0.13703985, "m": "Page.dispatchMouseEvent", "type": "mousemove", "x": 943.6620909655195, "y": 141.36372147204557, "button": 0, "buttons": 0, "modifiers": 0, "latency": 6.78},
{"t": 0.149444353, "m": "Page.dispatchMouseEvent", "type": "mousemove", "x": 975.7185759954313, "y": 135.85320466611142, "button": 0, "buttons": 0, "modifiers": 0, "latency": 11.69},
{"t": 0.162531804, "m": "Page.dispatchMouseEvent", "type": "mousemove", "x": 993.3918610848285, "y": 132.22879944162378, "button": 0, "buttons": 0, "modifiers": 0, "latency": 12.56},
{"t": 0.190557182, "m": "Page.dispatchMouseEvent", "type": "mousemove", "x": 995.8566022435833, "y": 129.23353007110728, "button": 0, "buttons": 0, "modifiers": 0, "latency": 5.14},
{"t": 0.331901802, "m": "Page.dispatchMouseEvent", "type": "mousemove", "x": 992.0884531373958, "y": 129.02167285335116, "button": 0, "buttons": 0, "modifiers": 0, "latency": 7.84},
{"t": 0.346622533, "m": "Page.dispatchMouseEvent", "type": "mousemove", "x": 988.5899247063068, "y": 129.46711255259635, "button": 0, "buttons": 0, "modifiers": 0, "latency": 4.5},
{"t": 0.355668132, "m": "Page.dispatchMouseEvent", "type": "mousemove", "x": 986.8664278386591, "y": 130.01523491500492, "button": 0, "buttons": 0, "modifiers": 0, "latency": 8.26},
{"t": 0.4, "m": "Page.dispatchMouseEvent", "type": "mousemove", "x": 983.5336544917911, "y": 130.02246060592802, "button": 0, "buttons": 0, "modifiers": 0, "latency": 5.12},
{"t": 0.865810966, "m": "Page.dispatchMouseEvent", "type": "mousedown", "x": 983.5336544917911, "y": 130.02246060592802, "button": 0, "buttons": 1, "modifiers": 0, "clickCount": 1, "latency": 10.17},
{"t": 0.953346894, "m": "Page.dispatchMouseEvent", "type": "mouseup", "x": 983.5336544917911, "y": 130.02246060592802, "button": 0, "buttons": 0, "modifiers": 0, "clickCount": 1, "latency": 3.31},
{"t": 1.961959314, "m": "Page.dispatchMouseEvent", "type": "mousemove", "x": 983.3611062417348, "y": 129.66701849323348, "button": 0, "buttons": 0, "modifiers": 0, "latency": 12.48},
{"t": 1.975664439, "m": "Page.dispatchMouseEvent", "type": "mousemove", "x": 983.1424339436427, "y": 129.02531241854027, "button": 0, "buttons": 0, "modifiers": 0, "latency": 12.01},
{"t": 2.055346095, "m": "Page.dispatchMouseEvent", "type": "mousemove", "x": 982.4745770403288, "y": 127.56608645362608, "button": 0, "buttons": 0, "modifiers": 0, "latency": 6.11},
{"t": 2.069974782, "m": "Page.dispatchMouseEvent", "type": "mousemove", "x": 980.1857868110405, "y": 128.36765028786564, "button": 0, "buttons": 0, "modifiers": 0, "latency": 8.11},
{"t": 2.078331925, "m": "Page.dispatchMouseEvent", "type": "mousemove", "x": 976.0112811514915, "y": 129.71780703708782, "button": 0, "buttons": 0, "modifiers": 0, "latency": 8.68},
{"t": 2.088448073, "m": "Page.dispatchMouseEvent", "type": "mousemove", "x": 967.7940023774728, "y": 132.5509279183938, "button": 0, "buttons": 0, "modifiers": 0, "latency": 5.4},
{"t": 2.101297783, "m": "Page.dispatchMouseEvent", "type": "mousemove", "x": 951.8668976229515, "y": 138.44336667321332, "button": 0, "buttons": 0, "modifiers": 0, "latency": 11.12},
{"t": 2.113382246, "m": "Page.dispatchMouseEvent", "type": "mousemove", "x": 932.1546963122115, "y": 145.50464924829726, "button": 0, "buttons": 0, "modifiers": 0, "latency": 6.94},
{"t": 2.124425426, "m": "Page.dispatchMouseEvent", "type": "mousemove", "x": 910.0112841389363, "y": 153.19393459305132, "button": 0, "buttons": 0, "modifiers": 0, "latency": 8.37},
{"t": 2.143534323, "m": "Page.dispatchMouseEvent", "type": "mousemove", "x": 863.8772673530127, "y": 169.68642215012832, "button": 0, "buttons": 0, "modifiers": 0, "latency": 5.65},
{"t": 2.156817197, "m": "Page.dispatchMouseEvent", "type": "mousemove", "x": 827.568584290794, "y": 183.22921855901293, "button": 0, "buttons": 0, "modifiers": 0, "latency": 4.52},
{"t": 2.171115184, "m": "Page.dispatchMouseEvent", "type": "mousemove", "x": 785.1753104865703, "y": 198.22442297654698, "button": 0, "buttons": 0, "modifiers": 0, "latency": 9.32},
{"t": 2.186384752, "m": "Page.dispatchMouseEvent", "type": "mousemove", "x": 739.2761870384849, "y": 215.50368608160622, "button": 0, "buttons": 0, "modifiers": 0, "latency": 6.66},
{"t": 2.202538397, "m": "Page.dispatchMouseEvent", "type": "mousemove", "x": 688.8134642556183, "y": 233.62649530342898, "button": 0, "buttons": 0, "modifiers": 0, "latency": 8.65},
{"t": 2.216713455, "m": "Page.dispatchMouseEvent", "type": "mousemove", "x": 646.6355482798471, "y": 248.67634748732456, "button": 0, "buttons": 0, "modifiers": 0, "latency": 6.26},
{"t": 2.237745217, "m": "Page.dispatchMouseEvent", "type": "mousemove", "x": 589.2799434880477, "y": 270.0830781477646, "button": 0, "buttons": 0, "modifiers": 0, "latency": 7.09},
{"t": 2.253558999, "m": "Page.dispatchMouseEvent", "type": "mousemove", "x": 550.9333579286152, "y": 284.62617239662944, "button": 0, "buttons": 0, "modifiers": 0, "latency": 5.8},
{"t": 2.266752816, "m": "Page.dispatchMouseEvent", "type": "mousemove", "x": 523.3898388153605, "y": 293.911046176053, "button": 0, "buttons": 0, "modifiers": 0, "latency": 8.22},
{"t": 2.275779308, "m": "Page.dispatchMouseEvent", "type": "mousemove", "x": 507.27210996396036, "y": 299.89788509953127, "button": 0, "buttons": 0, "modifiers": 0, "latency": 9.8},
{"t": 2.284978949, "m": "Page.dispatchMouseEvent", "type": "mousemove", "x": 493.35379568656964, "y": 305.55564312490867, "button": 0, "buttons": 0, "modifiers": 0, "latency": 8.28},
{"t": 2.293061427, "m": "Page.dispatchMouseEvent", "type": "mousemove", "x": 482.5333618606385, "y": 309.700546094897, "button": 0, "buttons": 0, "modifiers": 0, "latency": 4.56},
{"t": 2.302706667, "m": "Page.dispatchMouseEvent", "type": "mousemove", "x": 472.2009942120036, "y": 313.106725289465, "button": 0, "buttons": 0, "modifiers": 0, "latency": 5.77},
{"t": 2.311728956, "m": "Page.dispatchMouseEvent", "type": "mousemove", "x": 465.04768882325976, "y": 315.83624244620717, "button": 0, "buttons": 0, "modifiers": 0, "latency": 14.32},
{"t": 2.32121749, "m": "Page.dispatchMouseEvent", "type": "mousemove", "x": 459.4106601418655, "y": 317.8938176553383, "button": 0, "buttons": 0, "modifiers": 0, "latency": 9.65},
{"t": 2.335339837, "m": "Page.dispatchMouseEvent", "type": "mousemove", "x": 455.01528795018044, "y": 319.5337561845812, "button": 0, "buttons": 0, "modifiers": 0, "latency": 6.82},
{"t": 2.353346894, "m": "Page.dispatchMouseEvent", "type": "mousemove", "x": 453.79708563500617, "y": 319.98542352423124, "button": 0, "buttons": 0, "modifiers": 0, "latency": 6.28},
{"t": 14.40162804, "m": "Page.dispatchMouseEvent", "type": "mousemove", "x": 453.1839429602604, "y": 319.51154241087124, "button": 0, "buttons": 0, "modifiers": 0, "latency": 9.98},
{"t": 14.471824715, "m": "Page.dispatchMouseEvent", "type": "mousemove", "x": 453.0299483945695, "y": 319.41809348329997, "button": 0, "buttons": 0, "modifiers": 0, "latency": 7.32},
{"t": 14.497684775, "m": "Page.dispatchMouseEvent", "type": "mousemove", "x": 452.40218024081184, "y": 319.5456167750744, "button": 0, "buttons": 0, "modifiers": 0, "latency": 6.61},
{"t": 14.51187721, "m": "Page.dispatchMouseEvent", "type": "mousemove", "x": 451.29631669220504, "y": 319.4067457514388, "button": 0, "buttons": 0, "modifiers": 0, "latency": 4.37},
{"t": 14.523288906, "m": "Page.dispatchMouseEvent", "type": "mousemove", "x": 450.37233051552676, "y": 319.7091689031047, "button": 0, "buttons": 0, "modifiers": 0, "latency": 6.0},
{"t": 14.532561739, "m": "Page.dispatchMouseEvent", "type": "mousemove", "x": 449.44259596284627, "y": 319.82437112152996, "button": 0, "buttons": 0, "modifiers": 0, "latency": 5.8},
{"t": 14.550008102, "m": "Page.dispatchMouseEvent", "type": "mousemove", "x": 447.57435637463385, "y": 320.02374386371594, "button": 0, "buttons": 0, "modifiers": 0, "latency": 6.02},
{"t": 14.560042963, "m": "Page.dispatchMouseEvent", "type": "mousemove", "x": 446.38176252851446, "y": 319.9567417460099, "button": 0, "buttons": 0, "modifiers": 0, "latency": 7.23},
{"t": 14.571637827, "m": "Page.dispatchMouseEvent", "type": "mousemove", "x": 445.1360587544923, "y": 320.3008479621948, "button": 0, "buttons": 0, "modifiers": 0, "latency": 5.95},
{"t": 14.582357266, "m": "Page.dispatchMouseEvent", "type": "mousemove", "x": 444.0110998635983, "y": 320.2247647865399, "button": 0, "buttons": 0, "modifiers": 0, "latency": 11.32},
{"t": 14.616277385, "m": "Page.dispatchMouseEvent", "type": "mousemove", "x": 442.0526655364946, "y": 320.3864875636935, "button": 0, "buttons": 0, "modifiers": 0, "latency": 9.83},
{"t": 14.651202788, "m": "Page.dispatchMouseEvent", "type": "mousemove", "x": 441.60275280322315, "y": 320.30790473698374, "button": 0, "buttons": 0, "modifiers": 0, "latency": 5.47},
{"t": 14.794283547, "m": "Page.dispatchMouseEvent", "type": "mousedown", "x": 441.60275280322315, "y": 320.30790473698374, "button": 0, "buttons": 1, "modifiers": 0, "clickCount": 1, "latency": 6.51},
{"t": 14.921894856, "m": "Page.dispatchMouseEvent", "type": "mouseup", "x": 441.60275280322315, "y": 320.30790473698374, "button": 0, "buttons": 0, "modifiers": 0, "clickCount": 1, "latency": 7.53}
]
},
"landing_misses": {
"spec": {"seed": 99, "number": 1, "budget": 1.5, "hits": "centre", "ops": [["click", "#b"], ["wait", 2.0], ["hover", "#c"]]},
"engine_events": [
{"t": 0.014033479, "m": "Page.dispatchMouseEvent", "type": "mousemove", "x": 546.9459997688896, "y": 28.115788792505047, "button": 0, "buttons": 0, "modifiers": 0, "latency": 11.73},
{"t": 0.02862793, "m": "Page.dispatchMouseEvent", "type": "mousemove", "x": 546.5660061892414, "y": 29.345423645195176, "button": 0, "buttons": 0, "modifiers": 0, "latency": 10.03},
{"t": 0.043807831, "m": "Page.dispatchMouseEvent", "type": "mousemove", "x": 545.84345951819, "y": 32.486947716915346, "button": 0, "buttons": 0, "modifiers": 0, "latency": 8.8},
{"t": 0.056248899, "m": "Page.dispatchMouseEvent", "type": "mousemove", "x": 544.9004686489449, "y": 36.787795924996004, "button": 0, "buttons": 0, "modifiers": 0, "latency": 7.81},
{"t": 0.076902681, "m": "Page.dispatchMouseEvent", "type": "mousemove", "x": 541.8997917265904, "y": 47.25418515715379, "button": 0, "buttons": 0, "modifiers": 0, "latency": 6.12},
{"t": 0.092879716, "m": "Page.dispatchMouseEvent", "type": "mousemove", "x": 538.7362827075324, "y": 59.17292622025591, "button": 0, "buttons": 0, "modifiers": 0, "latency": 9.3},
{"t": 0.110919826, "m": "Page.dispatchMouseEvent", "type": "mousemove", "x": 534.215186639881, "y": 75.06966464364211, "button": 0, "buttons": 0, "modifiers": 0, "latency": 3.36},
{"t": 0.129982867, "m": "Page.dispatchMouseEvent", "type": "mousemove", "x": 526.2074395125439, "y": 95.83682219159752, "button": 0, "buttons": 0, "modifiers": 0, "latency": 6.66},
{"t": 0.146468282, "m": "Page.dispatchMouseEvent", "type": "mousemove", "x": 518.9609874729464, "y": 116.27795583154466, "button": 0, "buttons": 0, "modifiers": 0, "latency": 9.68},
{"t": 0.160472808, "m": "Page.dispatchMouseEvent", "type": "mousemove", "x": 513.6582924657744, "y": 134.38350698888772, "button": 0, "buttons": 0, "modifiers": 0, "latency": 10.79},
{"t": 0.175185736, "m": "Page.dispatchMouseEvent", "type": "mousemove", "x": 506.64242618813506, "y": 155.68772291363624, "button": 0, "buttons": 0, "modifiers": 0, "latency": 7.26},
{"t": 0.18804914, "m": "Page.dispatchMouseEvent", "type": "mousemove", "x": 500.9981057654484, "y": 174.44392141231688, "button": 0, "buttons": 0, "modifiers": 0, "latency": 10.33},
{"t": 0.20274411, "m": "Page.dispatchMouseEvent", "type": "mousemove", "x": 492.33132414226293, "y": 194.5099994600349, "button": 0, "buttons": 0, "modifiers": 0, "latency": 7.49},
{"t": 0.219894266, "m": "Page.dispatchMouseEvent", "type": "mousemove", "x": 484.1752179303128, "y": 218.5631604866671, "button": 0, "buttons": 0, "modifiers": 0, "latency": 7.41},
{"t": 0.235974984, "m": "Page.dispatchMouseEvent", "type": "mousemove", "x": 476.36571024243807, "y": 240.1916585851474, "button": 0, "buttons": 0, "modifiers": 0, "latency": 5.86},
{"t": 0.250992238, "m": "Page.dispatchMouseEvent", "type": "mousemove", "x": 470.9683449623104, "y": 258.7673293667599, "button": 0, "buttons": 0, "modifiers": 0, "latency": 13.29},
{"t": 0.267190447, "m": "Page.dispatchMouseEvent", "type": "mousemove", "x": 465.0462859935003, "y": 276.90394454313247, "button": 0, "buttons": 0, "modifiers": 0, "latency": 9.6},
{"t": 0.278585501, "m": "Page.dispatchMouseEvent", "type": "mousemove", "x": 461.15339439046755, "y": 286.9088724399417, "button": 0, "buttons": 0, "modifiers": 0, "latency": 10.12},
{"t": 0.290995507, "m": "Page.dispatchMouseEvent", "type": "mousemove", "x": 457.80046658818725, "y": 296.59339534386595, "button": 0, "buttons": 0, "modifiers": 0, "latency": 8.09},
{"t": 0.310934152, "m": "Page.dispatchMouseEvent", "type": "mousemove", "x": 454.28111701723486, "y": 307.0955589794505, "button": 0, "buttons": 0, "modifiers": 0, "latency": 6.68},
{"t": 0.32396986, "m": "Page.dispatchMouseEvent", "type": "mousemove", "x": 453.07081749049775, "y": 310.65605826539144, "button": 0, "buttons": 0, "modifiers": 0, "latency": 5.76},
{"t": 0.340497752, "m": "Page.dispatchMouseEvent", "type": "mousemove", "x": 452.6261878284354, "y": 312.0860961717424, "button": 0, "buttons": 0, "modifiers": 0, "latency": 4.64},
{"t": 0.559895578, "m": "Page.dispatchMouseEvent", "type": "mousemove", "x": 452.6032044686836, "y": 312.6662169766068, "button": 0, "buttons": 0, "modifiers": 0, "latency": 18.69},
{"t": 0.576859652, "m": "Page.dispatchMouseEvent", "type": "mousemove", "x": 452.3843770359288, "y": 313.6423903723785, "button": 0, "buttons": 0, "modifiers": 0, "latency": 14.28},
{"t": 0.59276855, "m": "Page.dispatchMouseEvent", "type": "mousemove", "x": 451.984091283707, "y": 314.63988995402724, "button": 0, "buttons": 0, "modifiers": 0, "latency": 11.08},
{"t": 0.609137438, "m": "Page.dispatchMouseEvent", "type": "mousemove", "x": 451.64652702982346, "y": 315.9235921578531, "button": 0, "buttons": 0, "modifiers": 0, "latency": 8.52},
{"t": 0.621779478, "m": "Page.dispatchMouseEvent", "type": "mousemove", "x": 451.3611570617401, "y": 316.7765481749566, "button": 0, "buttons": 0, "modifiers": 0, "latency": 13.39},
{"t": 0.637009212, "m": "Page.dispatchMouseEvent", "type": "mousemove", "x": 451.051197757053, "y": 317.71790055639616, "button": 0, "buttons": 0, "modifiers": 0, "latency": 8.83},
{"t": 0.652832845, "m": "Page.dispatchMouseEvent", "type": "mousemove", "x": 450.32711044376526, "y": 318.5234454595098, "button": 0, "buttons": 0, "modifiers": 0, "latency": 5.6},
{"t": 0.68045686, "m": "Page.dispatchMouseEvent", "type": "mousemove", "x": 450.1854471991357, "y": 319.64682674368305, "button": 0, "buttons": 0, "modifiers": 0, "latency": 7.0},
{"t": 0.714207976, "m": "Page.dispatchMouseEvent", "type": "mousemove", "x": 450.0, "y": 320.0, "button": 0, "buttons": 0, "modifiers": 0, "latency": 6.44},
{"t": 0.864111294, "m": "Page.dispatchMouseEvent", "type": "mousedown", "x": 450.0, "y": 320.0, "button": 0, "buttons": 1, "modifiers": 0, "clickCount": 1, "latency": 8.38},
{"t": 0.931251112, "m": "Page.dispatchMouseEvent", "type": "mouseup", "x": 450.0, "y": 320.0, "button": 0, "buttons": 0, "modifiers": 0, "clickCount": 1, "latency": 7.2},
{"t": 2.945190929, "m": "Page.dispatchMouseEvent", "type": "mousemove", "x": 451.0, "y": 320.0, "button": 0, "buttons": 0, "modifiers": 0, "latency": 6.02},
{"t": 2.960047593, "m": "Page.dispatchMouseEvent", "type": "mousemove", "x": 438.7554821340008, "y": 309.65879809358086, "button": 0, "buttons": 0, "modifiers": 0, "latency": 7.01},
{"t": 2.974295999, "m": "Page.dispatchMouseEvent", "type": "mousemove", "x": 416.7439015977841, "y": 295.25498267668485, "button": 0, "buttons": 0, "modifiers": 0, "latency": 7.07},
{"t": 2.989446424, "m": "Page.dispatchMouseEvent", "type": "mousemove", "x": 386.2589326837006, "y": 273.66627373139573, "button": 0, "buttons": 0, "modifiers": 0, "latency": 7.75},
{"t": 3.006521665, "m": "Page.dispatchMouseEvent", "type": "mousemove", "x": 343.5263190292031, "y": 245.03535383167284, "button": 0, "buttons": 0, "modifiers": 0, "latency": 5.72},
{"t": 3.018458463, "m": "Page.dispatchMouseEvent", "type": "mousemove", "x": 310.23258057261785, "y": 222.94837771302412, "button": 0, "buttons": 0, "modifiers": 0, "latency": 5.76},
{"t": 3.03296782, "m": "Page.dispatchMouseEvent", "type": "mousemove", "x": 269.0661158098203, "y": 195.7874020119834, "button": 0, "buttons": 0, "modifiers": 0, "latency": 8.48},
{"t": 3.048652395, "m": "Page.dispatchMouseEvent", "type": "mousemove", "x": 225.39472701200043, "y": 167.643566896703, "button": 0, "buttons": 0, "modifiers": 0, "latency": 11.25},
{"t": 3.062050855, "m": "Page.dispatchMouseEvent", "type": "mousemove", "x": 190.2824305216621, "y": 143.46501615506475, "button": 0, "buttons": 0, "modifiers": 0, "latency": 4.17},
{"t": 3.082434351, "m": "Page.dispatchMouseEvent", "type": "mousemove", "x": 146.52770004267475, "y": 114.04909936146758, "button": 0, "buttons": 0, "modifiers": 0, "latency": 5.05},
{"t": 3.098190144, "m": "Page.dispatchMouseEvent", "type": "mousemove", "x": 118.6228300113659, "y": 95.7122021127006, "button": 0, "buttons": 0, "modifiers": 0, "latency": 5.11},
{"t": 3.116249558, "m": "Page.dispatchMouseEvent", "type": "mousemove", "x": 98.7632404760714, "y": 82.76616618347293, "button": 0, "buttons": 0, "modifiers": 0, "latency": 9.47},
{"t": 3.130061461, "m": "Page.dispatchMouseEvent", "type": "mousemove", "x": 90.93288126608613, "y": 77.08440419960472, "button": 0, "buttons": 0, "modifiers": 0, "latency": 7.72},
{"t": 3.147908151, "m": "Page.dispatchMouseEvent", "type": "mousemove", "x": 88.29664683430745, "y": 75.58151737755341, "button": 0, "buttons": 0, "modifiers": 0, "latency": 7.54},
{"t": 3.167992333, "m": "Page.dispatchMouseEvent", "type": "mousemove", "x": 91.41341795575042, "y": 75.77109787363312, "button": 0, "buttons": 0, "modifiers": 0, "latency": 9.49},
{"t": 3.180885818, "m": "Page.dispatchMouseEvent", "type": "mousemove", "x": 98.50529488905603, "y": 76.15676282606199, "button": 0, "buttons": 0, "modifiers": 0, "latency": 6.81},
{"t": 3.198236062, "m": "Page.dispatchMouseEvent", "type": "mousemove", "x": 115.76738966642708, "y": 77.060348437044, "button": 0, "buttons": 0, "modifiers": 0, "latency": 5.38},
{"t": 3.215915543, "m": "Page.dispatchMouseEvent", "type": "mousemove", "x": 141.59297195762736, "y": 78.42591706704597, "button": 0, "buttons": 0, "modifiers": 0, "latency": 25.16},
{"t": 3.229837222, "m": "Page.dispatchMouseEvent", "type": "mousemove", "x": 168.9712007832486, "y": 79.3283238594143, "button": 0, "buttons": 0, "modifiers": 0, "latency": 10.42},
{"t": 3.24554048, "m": "Page.dispatchMouseEvent", "type": "mousemove", "x": 205.3544560004897, "y": 81.58405253175758, "button": 0, "buttons": 0, "modifiers": 0, "latency": 8.56},
{"t": 3.260477295, "m": "Page.dispatchMouseEvent", "type": "mousemove", "x": 245.31154728147357, "y": 84.35490478782042, "button": 0, "buttons": 0, "modifiers": 0, "latency": 3.29},
{"t": 3.275573675, "m": "Page.dispatchMouseEvent", "type": "mousemove", "x": 289.8689420677468, "y": 87.65286190852387, "button": 0, "buttons": 0, "modifiers": 0, "latency": 10.06},
{"t": 3.291233174, "m": "Page.dispatchMouseEvent", "type": "mousemove", "x": 340.5161699707306, "y": 91.11143141295106, "button": 0, "buttons": 0, "modifiers": 0, "latency": 6.46},
{"t": 3.304322644, "m": "Page.dispatchMouseEvent", "type": "mousemove", "x": 385.1032091839648, "y": 93.93716194864434, "button": 0, "buttons": 0, "modifiers": 0, "latency": 15.54},
{"t": 3.320400459, "m": "Page.dispatchMouseEvent", "type": "mousemove", "x": 442.13959635233084, "y": 97.41832931061033, "button": 0, "buttons": 0, "modifiers": 0, "latency": 12.49},
{"t": 3.333729014, "m": "Page.dispatchMouseEvent", "type": "mousemove", "x": 489.57351378597156, "y": 101.3726718712356, "button": 0, "buttons": 0, "modifiers": 0, "latency": 5.58},
{"t": 3.348643082, "m": "Page.dispatchMouseEvent", "type": "mousemove", "x": 544.3036929806769, "y": 108.10376141347749, "button": 0, "buttons": 0, "modifiers": 0, "latency": 4.33},
{"t": 3.365400912, "m": "Page.dispatchMouseEvent", "type": "mousemove", "x": 602.0063488077709, "y": 111.61082113941393, "button": 0, "buttons": 0, "modifiers": 0, "latency": 20.58},
{"t": 3.377148357, "m": "Page.dispatchMouseEvent", "type": "mousemove", "x": 642.4671584404217, "y": 112.99415504817046, "button": 0, "buttons": 0, "modifiers": 0, "latency": 3.63},
{"t": 3.39015559, "m": "Page.dispatchMouseEvent", "type": "mousemove", "x": 685.3587089358681, "y": 117.67420239384236, "button": 0, "buttons": 0, "modifiers": 0, "latency": 5.08},
{"t": 3.405757288, "m": "Page.dispatchMouseEvent", "type": "mousemove", "x": 737.920451363054, "y": 120.94468369750834, "button": 0, "buttons": 0, "modifiers": 0, "latency": 8.55},
{"t": 3.420178987, "m": "Page.dispatchMouseEvent", "type": "mousemove", "x": 784.1105110432408, "y": 124.17506973963803, "button": 0, "buttons": 0, "modifiers": 0, "latency": 11.12},
{"t": 3.440131407, "m": "Page.dispatchMouseEvent", "type": "mousemove", "x": 840.9166737459955, "y": 126.7772705571035, "button": 0, "buttons": 0, "modifiers": 0, "latency": 4.63},
{"t": 3.457152514, "m": "Page.dispatchMouseEvent", "type": "mousemove", "x": 883.0452746369773, "y": 128.9472735536301, "button": 0, "buttons": 0, "modifiers": 0, "latency": 7.52},
{"t": 3.474310903, "m": "Page.dispatchMouseEvent", "type": "mousemove", "x": 916.3167582030682, "y": 130.95084836601714, "button": 0, "buttons": 0, "modifiers": 0, "latency": 6.02},
{"t": 3.489851645, "m": "Page.dispatchMouseEvent", "type": "mousemove", "x": 939.1663767346521, "y": 132.84447770699114, "button": 0, "buttons": 0, "modifiers": 0, "latency": 16.78},
{"t": 3.511166035, "m": "Page.dispatchMouseEvent", "type": "mousemove", "x": 958.6444974541273, "y": 134.22332404607533, "button": 0, "buttons": 0, "modifiers": 0, "latency": 19.75},
{"t": 3.527974021, "m": "Page.dispatchMouseEvent", "type": "mousemove", "x": 965.5140317098814, "y": 135.51980377652333, "button": 0, "buttons": 0, "modifiers": 0, "latency": 5.32},
{"t": 3.544486393, "m": "Page.dispatchMouseEvent", "type": "mousemove", "x": 966.4714518613126, "y": 136.75022929294252, "button": 0, "buttons": 0, "modifiers": 0, "latency": 14.08},
{"t": 3.563239516, "m": "Page.dispatchMouseEvent", "type": "mousemove", "x": 963.3440769749806, "y": 137.84395695335388, "button": 0, "buttons": 0, "modifiers": 0, "latency": 22.42},
{"t": 3.578609585, "m": "Page.dispatchMouseEvent", "type": "mousemove", "x": 960.5, "y": 138.25, "button": 0, "buttons": 0, "modifiers": 0, "latency": 10.02}
]
},
"explicit_pointer": {
"spec": {"seed": 31337, "number": 2, "budget": 1.5, "ops": [["move", 800.0, 500.0], ["wait", 0.2], ["mouse_click", 120.0, 60.0], ["wheel", 0.0, 900.0], ["wheel", 0.0, 150.0], ["wheel", 30.0, -420.0], ["click", "#b"]]},
"engine_events": [
{"t": 0.0, "m": "Page.dispatchMouseEvent", "type": "mousemove", "x": 669.8237780667007, "y": 38.22057666802541, "button": 0, "buttons": 0, "modifiers": 0, "latency": 10.07},
{"t": 0.015722854, "m": "Page.dispatchMouseEvent", "type": "mousemove", "x": 669.8743697012595, "y": 38.32442637365361, "button": 0, "buttons": 0, "modifiers": 0, "latency": 8.37},
{"t": 0.033144094, "m": "Page.dispatchMouseEvent", "type": "mousemove", "x": 670.0255944997084, "y": 38.763792931789254, "button": 0, "buttons": 0, "modifiers": 0, "latency": 6.14},
{"t": 0.043983798, "m": "Page.dispatchMouseEvent", "type": "mousemove", "x": 670.7334393566326, "y": 39.69588233123689, "button": 0, "buttons": 0, "modifiers": 0, "latency": 11.86},
{"t": 0.062565329, "m": "Page.dispatchMouseEvent", "type": "mousemove", "x": 671.3198985686138, "y": 41.80491224313506, "button": 0, "buttons": 0, "modifiers": 0, "latency": 7.54},
{"t": 0.084807711, "m": "Page.dispatchMouseEvent", "type": "mousemove", "x": 673.2447737584606, "y": 46.56677867607192, "button": 0, "buttons": 0, "modifiers": 0, "latency": 5.67},
{"t": 0.096887052, "m": "Page.dispatchMouseEvent", "type": "mousemove", "x": 674.6509522140641, "y": 49.969781295733306, "button": 0, "buttons": 0, "modifiers": 0, "latency": 14.07},
{"t": 0.113252153, "m": "Page.dispatchMouseEvent", "type": "mousemove", "x": 676.7516564002951, "y": 56.1063211220086, "button": 0, "buttons": 0, "modifiers": 0, "latency": 5.63},
{"t": 0.124299163, "m": "Page.dispatchMouseEvent", "type": "mousemove", "x": 678.9733683663479, "y": 61.07416401659172, "button": 0, "buttons": 0, "modifiers": 0, "latency": 10.02},
{"t": 0.139851247, "m": "Page.dispatchMouseEvent", "type": "mousemove", "x": 682.2603120899383, "y": 69.2140729013216, "button": 0, "buttons": 0, "modifiers": 0, "latency": 14.81},
{"t": 0.151504436, "m": "Page.dispatchMouseEvent", "type": "mousemove", "x": 684.6790697559456, "y": 76.32204345784702, "button": 0, "buttons": 0, "modifiers": 0, "latency": 7.14},
{"t": 0.166386452, "m": "Page.dispatchMouseEvent", "type": "mousemove", "x": 688.9210726352829, "y": 85.46297472496106, "button": 0, "buttons": 0, "modifiers": 0, "latency": 16.64},
{"t": 0.184084071, "m": "Page.dispatchMouseEvent", "type": "mousemove", "x": 693.054829032825, "y": 99.45558467301537, "button": 0, "buttons": 0, "modifiers": 0, "latency": 6.49},
{"t": 0.199746029, "m": "Page.dispatchMouseEvent", "type": "mousemove", "x": 697.444130097179, "y": 113.39576053468464, "button": 0, "buttons": 0, "modifiers": 0, "latency": 11.9},
{"t": 0.222491832, "m": "Page.dispatchMouseEvent", "type": "mousemove", "x": 704.8763130235726, "y": 135.50619036305386, "button": 0, "buttons": 0, "modifiers": 0, "latency": 15.55},
{"t": 0.23478762, "m": "Page.dispatchMouseEvent", "type": "mousemove", "x": 710.074237101277, "y": 148.6243893866018, "button": 0, "buttons": 0, "modifiers": 0, "latency": 11.41},
{"t": 0.247109498, "m": "Page.dispatchMouseEvent", "type": "mousemove", "x": 713.1163727723589, "y": 161.94588266998917, "button": 0, "buttons": 0, "modifiers": 0, "latency": 7.35},
{"t": 0.260072784, "m": "Page.dispatchMouseEvent", "type": "mousemove", "x": 717.654316711481, "y": 177.16116595215496, "button": 0, "buttons": 0, "modifiers": 0, "latency": 8.0},
{"t": 0.275864153, "m": "Page.dispatchMouseEvent", "type": "mousemove", "x": 722.6628984765106, "y": 195.62944872096102, "button": 0, "buttons": 0, "modifiers": 0, "latency": 12.77},
{"t": 0.299548359, "m": "Page.dispatchMouseEvent", "type": "mousemove", "x": 730.7270608229929, "y": 225.93197298563993, "button": 0, "buttons": 0, "modifiers": 0, "latency": 14.7},
{"t": 0.31351718, "m": "Page.dispatchMouseEvent", "type": "mousemove", "x": 735.5257049337298, "y": 243.07806548663038, "button": 0, "buttons": 0, "modifiers": 0, "latency": 13.04},
{"t": 0.335041761, "m": "Page.dispatchMouseEvent", "type": "mousemove", "x": 742.2394881482776, "y": 270.7661165846679, "button": 0, "buttons": 0, "modifiers": 0, "latency": 9.96},
{"t": 0.349948102, "m": "Page.dispatchMouseEvent", "type": "mousemove", "x": 747.1873606857182, "y": 290.80388465337603, "button": 0, "buttons": 0, "modifiers": 0, "latency": 8.82},
{"t": 0.363623812, "m": "Page.dispatchMouseEvent", "type": "mousemove", "x": 752.918592244724, "y": 307.54729791419584, "button": 0, "buttons": 0, "modifiers": 0, "latency": 10.68},
{"t": 0.373077608, "m": "Page.dispatchMouseEvent", "type": "mousemove", "x": 756.4805650611914, "y": 320.6186480847803, "button": 0, "buttons": 0, "modifiers": 0, "latency": 9.43},
{"t": 0.385574032, "m": "Page.dispatchMouseEvent", "type": "mousemove", "x": 759.9560599300341, "y": 336.8077599130476, "button": 0, "buttons": 0, "modifiers": 0, "latency": 12.26},
{"t": 0.397909198, "m": "Page.dispatchMouseEvent", "type": "mousemove", "x": 762.9727903626099, "y": 351.07589532489516, "button": 0, "buttons": 0, "modifiers": 0, "latency": 11.05},
{"t": 0.408098264, "m": "Page.dispatchMouseEvent", "type": "mousemove", "x": 766.2867472903744, "y": 363.61424318742127, "button": 0, "buttons": 0, "modifiers": 0, "latency": 11.26},
{"t": 0.422745197, "m": "Page.dispatchMouseEvent", "type": "mousemove", "x": 770.354118375111, "y": 380.66426895730854, "button": 0, "buttons": 0, "modifiers": 0, "latency": 5.79},
{"t": 0.438369525, "m": "Page.dispatchMouseEvent", "type": "mousemove", "x": 774.98817400208, "y": 397.61732371961904, "button": 0, "buttons": 0, "modifiers": 0, "latency": 19.22},
{"t": 0.458740748, "m": "Page.dispatchMouseEvent", "type": "mousemove", "x": 779.4187623953463, "y": 418.28242825624073, "button": 0, "buttons": 0, "modifiers": 0, "latency": 18.97},
{"t": 0.475484056, "m": "Page.dispatchMouseEvent", "type": "mousemove", "x": 783.9188770499877, "y": 433.9413705079561, "button": 0, "buttons": 0, "modifiers": 0, "latency": 7.48},
{"t": 0.49657012, "m": "Page.dispatchMouseEvent", "type": "mousemove", "x": 787.8270719282825, "y": 451.00120773510736, "button": 0, "buttons": 0, "modifiers": 0, "latency": 11.51},
{"t": 0.504869088, "m": "Page.dispatchMouseEvent", "type": "mousemove", "x": 789.9036266058326, "y": 457.15761442602843, "button": 0, "buttons": 0, "modifiers": 0, "latency": 15.72},
{"t": 0.522190115, "m": "Page.dispatchMouseEvent", "type": "mousemove", "x": 792.0272752713952, "y": 468.49509292402837, "button": 0, "buttons": 0, "modifiers": 0, "latency": 6.5},
{"t": 0.539390323, "m": "Page.dispatchMouseEvent", "type": "mousemove", "x": 794.8035074297031, "y": 478.33227602121354, "button": 0, "buttons": 0, "modifiers": 0, "latency": 5.67},
{"t": 0.55011589, "m": "Page.dispatchMouseEvent", "type": "mousemove", "x": 795.5784348100282, "y": 483.30672166292874, "button": 0, "buttons": 0, "modifiers": 0, "latency": 8.7},
{"t": 0.559221015, "m": "Page.dispatchMouseEvent", "type": "mousemove", "x": 796.5637958304569, "y": 487.02620147644353, "button": 0, "buttons": 0, "modifiers": 0, "latency": 4.8},
{"t": 0.570555672, "m": "Page.dispatchMouseEvent", "type": "mousemove", "x": 797.8954186029472, "y": 490.36994463150296, "button": 0, "buttons": 0, "modifiers": 0, "latency": 8.96},
{"t": 0.578632285, "m": "Page.dispatchMouseEvent", "type": "mousemove", "x": 798.3433629411729, "y": 492.9252231252378, "button": 0, "buttons": 0, "modifiers": 0, "latency": 7.29},
{"t": 0.594428972, "m": "Page.dispatchMouseEvent", "type": "mousemove", "x": 799.0545535594716, "y": 495.79793463322494, "button": 0, "buttons": 0, "modifiers": 0, "latency": 11.01},
{"t": 0.608222457, "m": "Page.dispatchMouseEvent", "type": "mousemove", "x": 799.4353298820264, "y": 498.18595951438607, "button": 0, "buttons": 0, "modifiers": 0, "latency": 9.73},
{"t": 0.621208908, "m": "Page.dispatchMouseEvent", "type": "mousemove", "x": 799.8577000668871, "y": 499.31791583764556, "button": 0, "buttons": 0, "modifiers": 0, "latency": 13.51},
{"t": 0.649614479, "m": "Page.dispatchMouseEvent", "type": "mousemove", "x": 800.0, "y": 500.0, "button": 0, "buttons": 0, "modifiers": 0, "latency": 6.05},
{"t": 0.870255247, "m": "Page.dispatchMouseEvent", "type": "mousemove", "x": 798.6284229251934, "y": 498.7079796171799, "button": 0, "buttons": 0, "modifiers": 0, "latency": 5.57},
{"t": 0.894047899, "m": "Page.dispatchMouseEvent", "type": "mousemove", "x": 793.0208096235413, "y": 493.7963833669658, "button": 0, "buttons": 0, "modifiers": 0, "latency": 6.62},
{"t": 0.903855228, "m": "Page.dispatchMouseEvent", "type": "mousemove", "x": 789.1944917534062, "y": 490.4429132179522, "button": 0, "buttons": 0, "modifiers": 0, "latency": 8.32},
{"t": 0.91587009, "m": "Page.dispatchMouseEvent", "type": "mousemove", "x": 783.3438127257997, "y": 485.61133730052006, "button": 0, "buttons": 0, "modifiers": 0, "latency": 10.86},
{"t": 0.928468415, "m": "Page.dispatchMouseEvent", "type": "mousemove", "x": 775.9804380285501, "y": 479.4134557939997, "button": 0, "buttons": 0, "modifiers": 0, "latency": 11.13},
{"t": 0.94284755, "m": "Page.dispatchMouseEvent", "type": "mousemove", "x": 765.4537396515834, "y": 471.1936902449277, "button": 0, "buttons": 0, "modifiers": 0, "latency": 8.29},
{"t": 0.960095368, "m": "Page.dispatchMouseEvent", "type": "mousemove", "x": 751.0306357965043, "y": 459.7192079375931, "button": 0, "buttons": 0, "modifiers": 0, "latency": 12.21},
{"t": 0.968931417, "m": "Page.dispatchMouseEvent", "type": "mousemove", "x": 742.185238774693, "y": 453.4044482587211, "button": 0, "buttons": 0, "modifiers": 0, "latency": 8.71},
{"t": 0.989947625, "m": "Page.dispatchMouseEvent", "type": "mousemove", "x": 719.5408164379734, "y": 437.2232020208582, "button": 0, "buttons": 0, "modifiers": 0, "latency": 14.33},
{"t": 1.005091345, "m": "Page.dispatchMouseEvent", "type": "mousemove", "x": 701.4738261994077, "y": 423.99343928907325, "button": 0, "buttons": 0, "modifiers": 0, "latency": 18.37},
{"t": 1.019573615, "m": "Page.dispatchMouseEvent", "type": "mousemove", "x": 681.9674368075146, "y": 411.17597060006085, "button": 0, "buttons": 0, "modifiers": 0, "latency": 9.79},
{"t": 1.032846177, "m": "Page.dispatchMouseEvent", "type": "mousemove", "x": 664.5478306678408, "y": 398.604974753745, "button": 0, "buttons": 0, "modifiers": 0, "latency": 17.39},
{"t": 1.045500966, "m": "Page.dispatchMouseEvent", "type": "mousemove", "x": 645.9378923545486, "y": 386.2411163747011, "button": 0, "buttons": 0, "modifiers": 0, "latency": 12.25},
{"t": 1.055789394, "m": "Page.dispatchMouseEvent", "type": "mousemove", "x": 630.3952049032139, "y": 375.64210344983826, "button": 0, "buttons": 0, "modifiers": 0, "latency": 16.48},
{"t": 1.076008233, "m": "Page.dispatchMouseEvent", "type": "mousemove", "x": 599.1333367132288, "y": 354.53050978028926, "button": 0, "buttons": 0, "modifiers": 0, "latency": 6.04},
{"t": 1.085213769, "m": "Page.dispatchMouseEvent", "type": "mousemove", "x": 584.0856724197923, "y": 345.9366148640131, "button": 0, "buttons": 0, "modifiers": 0, "latency": 8.31},
{"t": 1.097375352, "m": "Page.dispatchMouseEvent", "type": "mousemove", "x": 562.8748098533948, "y": 333.72720237806806, "button": 0, "buttons": 0, "modifiers": 0, "latency": 7.1},
{"t": 1.115307243, "m": "Page.dispatchMouseEvent", "type": "mousemove", "x": 534.7880280589615, "y": 313.8099345386338, "button": 0, "buttons": 0, "modifiers": 0, "latency": 10.63},
{"t": 1.12728354, "m": "Page.dispatchMouseEvent", "type": "mousemove", "x": 514.8703711708633, "y": 301.65601405534545, "button": 0, "buttons": 0, "modifiers": 0, "latency": 9.62},
{"t": 1.136002738, "m": "Page.dispatchMouseEvent", "type": "mousemove", "x": 500.6456623563215, "y": 292.50240803176445, "button": 0, "buttons": 0, "modifiers": 0, "latency": 16.2},
{"t": 1.146610734, "m": "Page.dispatchMouseEvent", "type": "mousemove", "x": 482.2747189069864, "y": 280.50241051702824, "button": 0, "buttons": 0, "modifiers": 0, "latency": 16.02},
{"t": 1.160154665, "m": "Page.dispatchMouseEvent", "type": "mousemove", "x": 459.35103430337324, "y": 266.38897449629883, "button": 0, "buttons": 0, "modifiers": 0, "latency": 9.16},
{"t": 1.17732137, "m": "Page.dispatchMouseEvent", "type": "mousemove", "x": 430.67211764041303, "y": 249.0447595696038, "button": 0, "buttons": 0, "modifiers": 0, "latency": 9.24},
{"t": 1.188163227, "m": "Page.dispatchMouseEvent", "type": "mousemove", "x": 414.3619076806458, "y": 236.80844378350778, "button": 0, "buttons": 0, "modifiers": 0, "latency": 5.04},
{"t": 1.199835404, "m": "Page.dispatchMouseEvent", "type": "mousemove", "x": 394.11650420947655, "y": 226.1925254595866, "button": 0, "buttons": 0, "modifiers": 0, "latency": 10.53},
{"t": 1.212974768, "m": "Page.dispatchMouseEvent", "type": "mousemove", "x": 372.4509348017313, "y": 214.5282798733867, "button": 0, "buttons": 0, "modifiers": 0, "latency": 9.53},
{"t": 1.22712573, "m": "Page.dispatchMouseEvent", "type": "mousemove", "x": 351.15481452279454, "y": 199.768706556972, "button": 0, "buttons": 0, "modifiers": 0, "latency": 9.26},
{"t": 1.237840491, "m": "Page.dispatchMouseEvent", "type": "mousemove", "x": 335.3354527897677, "y": 189.5553524719586, "button": 0, "buttons": 0, "modifiers": 0, "latency": 16.36},
{"t": 1.264784835, "m": "Page.dispatchMouseEvent", "type": "mousemove", "x": 296.52252139791767, "y": 167.1997512107113, "button": 0, "buttons": 0, "modifiers": 0, "latency": 13.09},
{"t": 1.27547019, "m": "Page.dispatchMouseEvent", "type": "mousemove", "x": 280.7543861100484, "y": 157.83550085410945, "button": 0, "buttons": 0, "modifiers": 0, "latency": 9.29},
{"t": 1.303502982, "m": "Page.dispatchMouseEvent", "type": "mousemove", "x": 246.88782516895387, "y": 136.71557982159317, "button": 0, "buttons": 0, "modifiers": 0, "latency": 9.54},
{"t": 1.31699646, "m": "Page.dispatchMouseEvent", "type": "mousemove", "x": 230.80531416354054, "y": 128.060839675906, "button": 0, "buttons": 0, "modifiers": 0, "latency": 10.96},
{"t": 1.33129703, "m": "Page.dispatchMouseEvent", "type": "mousemove", "x": 215.69602326257677, "y": 118.75922346744575, "button": 0, "buttons": 0, "modifiers": 0, "latency": 8.5},
{"t": 1.355871534, "m": "Page.dispatchMouseEvent", "type": "mousemove", "x": 192.3729634984068, "y": 103.94583221653293, "button": 0, "buttons": 0, "modifiers": 0, "latency": 9.98},
{"t": 1.368348622, "m": "Page.dispatchMouseEvent", "type": "mousemove", "x": 182.19033917863825, "y": 97.67013576791487, "button": 0, "buttons": 0, "modifiers": 0, "latency": 4.4},
{"t": 1.384308848, "m": "Page.dispatchMouseEvent", "type": "mousemove", "x": 169.51257887181865, "y": 90.9888683971273, "button": 0, "buttons": 0, "modifiers": 0, "latency": 10.43},
{"t": 1.401653116, "m": "Page.dispatchMouseEvent", "type": "mousemove", "x": 157.88377976143147, "y": 83.01132198843663, "button": 0, "buttons": 0, "modifiers": 0, "latency": 15.34},
{"t": 1.414079161, "m": "Page.dispatchMouseEvent", "type": "mousemove", "x": 149.48397823639462, "y": 78.70894561878525, "button": 0, "buttons": 0, "modifiers": 0, "latency": 12.08},
{"t": 1.429230891, "m": "Page.dispatchMouseEvent", "type": "mousemove", "x": 143.01062148478883, "y": 74.29798236784546, "button": 0, "buttons": 0, "modifiers": 0, "latency": 5.89},
{"t": 1.446544773, "m": "Page.dispatchMouseEvent", "type": "mousemove", "x": 135.90191570849998, "y": 69.9834984477113, "button": 0, "buttons": 0, "modifiers": 0, "latency": 8.52},
{"t": 1.466371112, "m": "Page.dispatchMouseEvent", "type": "mousemove", "x": 129.5039870475156, "y": 65.98893958364602, "button": 0, "buttons": 0, "modifiers": 0, "latency": 12.95},
{"t": 1.474922168, "m": "Page.dispatchMouseEvent", "type": "mousemove", "x": 127.34043556107143, "y": 64.71567107769661, "button": 0, "buttons": 0, "modifiers": 0, "latency": 11.74},
{"t": 1.490756661, "m": "Page.dispatchMouseEvent", "type": "mousemove", "x": 124.09013407052329, "y": 62.95641062376332, "button": 0, "buttons": 0, "modifiers": 0, "latency": 12.49},
{"t": 1.501647947, "m": "Page.dispatchMouseEvent", "type": "mousemove", "x": 122.6535051800142, "y": 61.70505861990413, "button": 0, "buttons": 0, "modifiers": 0, "latency": 10.17},
{"t": 1.516760266, "m": "Page.dispatchMouseEvent", "type": "mousemove", "x": 121.2609488259719, "y": 60.84749532485219, "button": 0, "buttons": 0, "modifiers": 0, "latency": 8.59},
{"t": 1.527724882, "m": "Page.dispatchMouseEvent", "type": "mousemove", "x": 120.62727478197868, "y": 60.313514912084216, "button": 0, "buttons": 0, "modifiers": 0, "latency": 10.0},
{"t": 1.562696784, "m": "Page.dispatchMouseEvent", "type": "mousemove", "x": 120.0, "y": 60.0, "button": 0, "buttons": 0, "modifiers": 0, "latency": 15.03},
{"t": 1.696221443, "m": "Page.dispatchMouseEvent", "type": "mousedown", "x": 120.0, "y": 60.0, "button": 0, "buttons": 1, "modifiers": 0, "clickCount": 1, "latency": 7.89},
{"t": 1.735916218, "m": "Page.dispatchMouseEvent", "type": "mouseup", "x": 120.0, "y": 60.0, "button": 0, "buttons": 0, "modifiers": 0, "clickCount": 1, "latency": 6.97},
{"t": 1.90038739, "m": "Page.dispatchWheelEvent", "x": 120.0, "y": 60.0, "deltaX": 0.0, "deltaY": 90.44942489453564, "deltaZ": 0, "modifiers": 0, "latency": 5.88},
{"t": 1.970053841, "m": "Page.dispatchWheelEvent", "x": 120.0, "y": 60.0, "deltaX": 0.0, "deltaY": 105.51925181734764, "deltaZ": 0, "modifiers": 0, "latency": 6.44},
{"t": 2.018235157, "m": "Page.dispatchWheelEvent", "x": 120.0, "y": 60.0, "deltaX": 0.0, "deltaY": 95.93335773893521, "deltaZ": 0, "modifiers": 0, "latency": 10.99},
{"t": 2.062897909, "m": "Page.dispatchMouseEvent", "type": "mousemove", "x": 119.47330547047764, "y": 60.01388132148192, "button": 0, "buttons": 0, "modifiers": 0, "latency": 13.84},
{"t": 2.083449295, "m": "Page.dispatchMouseEvent", "type": "mousemove", "x": 117.97373002269046, "y": 60.405615705928504, "button": 0, "buttons": 0, "modifiers": 0, "latency": 13.04},
{"t": 2.091942792, "m": "Page.dispatchMouseEvent", "type": "mousemove", "x": 117.16084926050918, "y": 60.52937438167784, "button": 0, "buttons": 0, "modifiers": 0, "latency": 4.94},
{"t": 2.101203793, "m": "Page.dispatchMouseEvent", "type": "mousemove", "x": 116.41650944599151, "y": 60.59843127638006, "button": 0, "buttons": 0, "modifiers": 0, "latency": 6.99},
{"t": 2.115303169, "m": "Page.dispatchMouseEvent", "type": "mousemove", "x": 115.40561517615129, "y": 60.76112596260784, "button": 0, "buttons": 0, "modifiers": 0, "latency": 12.12},
{"t": 2.15232649, "m": "Page.dispatchMouseEvent", "type": "mousemove", "x": 114.29950903921967, "y": 60.955317979925006, "button": 0, "buttons": 0, "modifiers": 0, "latency": 8.81},
{"t": 2.195534369, "m": "Page.dispatchWheelEvent", "x": 114.29950903921967, "y": 60.955317979925006, "deltaX": 0.0, "deltaY": 91.0930046588155, "deltaZ": 0, "modifiers": 0, "latency": 9.76},
{"t": 2.2348259, "m": "Page.dispatchWheelEvent", "x": 114.29950903921967, "y": 60.955317979925006, "deltaX": 0.0, "deltaY": 114.80301425904082, "deltaZ": 0, "modifiers": 0, "latency": 9.33},
{"t": 2.267701446, "m": "Page.dispatchMouseEvent", "type": "mousemove", "x": 113.48007089886912, "y": 60.869751949189585, "button": 0, "buttons": 0, "modifiers": 0, "latency": 13.16},
{"t": 2.285486873, "m": "Page.dispatchMouseEvent", "type": "mousemove", "x": 112.04127255405707, "y": 61.01886289328246, "button": 0, "buttons": 0, "modifiers": 0, "latency": 17.16},
{"t": 2.30328, "m": "Page.dispatchMouseEvent", "type": "mousemove", "x": 110.1375251699708, "y": 61.08550793970611, "button": 0, "buttons": 0, "modifiers": 0, "latency": 10.16},
{"t": 2.343744949, "m": "Page.dispatchMouseEvent", "type": "mousemove", "x": 108.84284708028639, "y": 61.23024887542001, "button": 0, "buttons": 0, "modifiers": 0, "latency": 7.04},
{"t": 2.388978835, "m": "Page.dispatchWheelEvent", "x": 108.84284708028639, "y": 61.23024887542001, "deltaX": 0.0, "deltaY": 95.51212861292878, "deltaZ": 0, "modifiers": 0, "latency": 5.35},
{"t": 2.442056425, "m": "Page.dispatchWheelEvent", "x": 108.84284708028639, "y": 61.23024887542001, "deltaX": 0.0, "deltaY": 106.02044279605919, "deltaZ": 0, "modifiers": 0, "latency": 6.76},
{"t": 2.490813809, "m": "Page.dispatchMouseEvent", "type": "mousemove", "x": 109.03025193997327, "y": 60.390050019123045, "button": 0, "buttons": 0, "modifiers": 0, "latency": 17.09},
{"t": 2.507692236, "m": "Page.dispatchMouseEvent", "type": "mousemove", "x": 109.16266142052112, "y": 59.2007865401591, "button": 0, "buttons": 0, "modifiers": 0, "latency": 12.81},
{"t": 2.52536171, "m": "Page.dispatchMouseEvent", "type": "mousemove", "x": 109.21791688795838, "y": 58.04834664561802, "button": 0, "buttons": 0, "modifiers": 0, "latency": 14.34},
{"t": 2.564687529, "m": "Page.dispatchMouseEvent", "type": "mousemove", "x": 109.3905665912139, "y": 56.644860075169326, "button": 0, "buttons": 0, "modifiers": 0, "latency": 13.07},
{"t": 2.609298397, "m": "Page.dispatchWheelEvent", "x": 109.3905665912139, "y": 56.644860075169326, "deltaX": 0.0, "deltaY": 102.63102172676088, "deltaZ": 0, "modifiers": 0, "latency": 6.29},
{"t": 2.658451756, "m": "Page.dispatchMouseEvent", "type": "mousemove", "x": 109.01829057261162, "y": 56.171032629142836, "button": 0, "buttons": 0, "modifiers": 0, "latency": 13.19},
{"t": 2.6798926, "m": "Page.dispatchMouseEvent", "type": "mousemove", "x": 107.95788862898587, "y": 55.18363303473927, "button": 0, "buttons": 0, "modifiers": 0, "latency": 14.88},
{"t": 2.688283542, "m": "Page.dispatchMouseEvent", "type": "mousemove", "x": 107.32106152679437, "y": 54.701983013935305, "button": 0, "buttons": 0, "modifiers": 0, "latency": 9.94},
{"t": 2.705326184, "m": "Page.dispatchMouseEvent", "type": "mousemove", "x": 106.25738790993937, "y": 54.132102732237854, "button": 0, "buttons": 0, "modifiers": 0, "latency": 12.41},
{"t": 2.716305575, "m": "Page.dispatchMouseEvent", "type": "mousemove", "x": 105.76618744539226, "y": 53.4087207896433, "button": 0, "buttons": 0, "modifiers": 0, "latency": 9.0},
{"t": 2.725972188, "m": "Page.dispatchMouseEvent", "type": "mousemove", "x": 105.26346415330535, "y": 53.17162915844664, "button": 0, "buttons": 0, "modifiers": 0, "latency": 21.17},
{"t": 2.747961294, "m": "Page.dispatchMouseEvent", "type": "mousemove", "x": 104.84206335708153, "y": 52.841262160825785, "button": 0, "buttons": 0, "modifiers": 0, "latency": 10.83},
{"t": 2.802013066, "m": "Page.dispatchWheelEvent", "x": 104.84206335708153, "y": 52.841262160825785, "deltaX": 0.0, "deltaY": 98.0383534955763, "deltaZ": 0, "modifiers": 0, "latency": 4.4},
{"t": 2.854532632, "m": "Page.dispatchMouseEvent", "type": "mousemove", "x": 105.36916477617206, "y": 53.81225137797755, "button": 0, "buttons": 0, "modifiers": 0, "latency": 5.31},
{"t": 2.863593355, "m": "Page.dispatchMouseEvent", "type": "mousemove", "x": 105.57363115357671, "y": 54.51632166526124, "button": 0, "buttons": 0, "modifiers": 0, "latency": 9.19},
{"t": 2.877482866, "m": "Page.dispatchMouseEvent", "type": "mousemove", "x": 105.81943586751125, "y": 55.91142739194493, "button": 0, "buttons": 0, "modifiers": 0, "latency": 9.37},
{"t": 2.88725095, "m": "Page.dispatchMouseEvent", "type": "mousemove", "x": 106.21203218177574, "y": 56.755938011246194, "button": 0, "buttons": 0, "modifiers": 0, "latency": 6.68},
{"t": 2.899800303, "m": "Page.dispatchMouseEvent", "type": "mousemove", "x": 106.38671609331439, "y": 57.65119390368251, "button": 0, "buttons": 0, "modifiers": 0, "latency": 11.55},
{"t": 2.909593626, "m": "Page.dispatchMouseEvent", "type": "mousemove", "x": 106.53875412677557, "y": 58.163422231300295, "button": 0, "buttons": 0, "modifiers": 0, "latency": 25.67},
{"t": 2.940517766, "m": "Page.dispatchMouseEvent", "type": "mousemove", "x": 106.67628640511181, "y": 58.583430225571014, "button": 0, "buttons": 0, "modifiers": 0, "latency": 13.63},
{"t": 3.130323369, "m": "Page.dispatchMouseEvent", "type": "mousemove", "x": 108.15812783696384, "y": 60.90268089429578, "button": 0, "buttons": 0, "modifiers": 0, "latency": 6.25},
{"t": 3.145037802, "m": "Page.dispatchMouseEvent", "type": "mousemove", "x": 111.32176402724562, "y": 65.34584710416436, "button": 0, "buttons": 0, "modifiers": 0, "latency": 8.55},
{"t": 3.153985871, "m": "Page.dispatchMouseEvent", "type": "mousemove", "x": 113.3693475192238, "y": 69.02302796852928, "button": 0, "buttons": 0, "modifiers": 0, "latency": 5.35},
{"t": 3.164483718, "m": "Page.dispatchMouseEvent", "type": "mousemove", "x": 116.94210542322162, "y": 73.41866622141907, "button": 0, "buttons": 0, "modifiers": 0, "latency": 6.4},
{"t": 3.180462864, "m": "Page.dispatchMouseEvent", "type": "mousemove", "x": 121.7684802566454, "y": 81.18480935409218, "button": 0, "buttons": 0, "modifiers": 0, "latency": 9.04},
{"t": 3.193721432, "m": "Page.dispatchMouseEvent", "type": "mousemove", "x": 126.83471532063326, "y": 87.35223642499211, "button": 0, "buttons": 0, "modifiers": 0, "latency": 14.09},
{"t": 3.218370683, "m": "Page.dispatchMouseEvent", "type": "mousemove", "x": 130.70401449068356, "y": 95.82279920322075, "button": 0, "buttons": 0, "modifiers": 0, "latency": 11.59},
{"t": 3.235916218, "m": "Page.dispatchMouseEvent", "type": "mousemove", "x": 131.50139184747144, "y": 97.36123073087597, "button": 0, "buttons": 0, "modifiers": 0, "latency": 11.0},
{"t": 3.417893339, "m": "Page.dispatchWheelEvent", "x": 131.50139184747144, "y": 97.36123073087597, "deltaX": 0.0, "deltaY": 77.84342044961163, "deltaZ": 0, "modifiers": 0, "latency": 13.26},
{"t": 3.481098227, "m": "Page.dispatchWheelEvent", "x": 131.50139184747144, "y": 97.36123073087597, "deltaX": 0.0, "deltaY": 72.15657955038837, "deltaZ": 0, "modifiers": 0, "latency": 7.89},
{"t": 3.623976007, "m": "Page.dispatchWheelEvent", "x": 131.50139184747144, "y": 97.36123073087597, "deltaX": 7.839989203614794, "deltaY": -109.75984885060711, "deltaZ": 0, "modifiers": 0, "latency": 13.98},
{"t": 3.669131998, "m": "Page.dispatchMouseEvent", "type": "mousemove", "x": 131.3815300472714, "y": 97.42249022707509, "button": 0, "buttons": 0, "modifiers": 0, "latency": 6.73},
{"t": 3.677855627, "m": "Page.dispatchMouseEvent", "type": "mousemove", "x": 131.2165002035945, "y": 97.50657773392517, "button": 0, "buttons": 0, "modifiers": 0, "latency": 18.73},
{"t": 3.711111786, "m": "Page.dispatchMouseEvent", "type": "mousemove", "x": 130.00914686252813, "y": 98.09151356844563, "button": 0, "buttons": 0, "modifiers": 0, "latency": 7.88},
{"t": 3.721674544, "m": "Page.dispatchMouseEvent", "type": "mousemove", "x": 129.4427680973685, "y": 98.22426666049283, "button": 0, "buttons": 0, "modifiers": 0, "latency": 5.02},
{"t": 3.731875278, "m": "Page.dispatchMouseEvent", "type": "mousemove", "x": 129.24068880876294, "y": 98.36795404179801, "button": 0, "buttons": 0, "modifiers": 0, "latency": 3.87},
{"t": 3.743577339, "m": "Page.dispatchMouseEvent", "type": "mousemove", "x": 128.61025484546533, "y": 98.65658733436685, "button": 0, "buttons": 0, "modifiers": 0, "latency": 7.69},
{"t": 3.795822452, "m": "Page.dispatchMouseEvent", "type": "mousemove", "x": 127.8760658684901, "y": 99.01769519114215, "button": 0, "buttons": 0, "modifiers": 0, "latency": 21.44},
{"t": 3.884670448, "m": "Page.dispatchWheelEvent", "x": 127.8760658684901, "y": 99.01769519114215, "deltaX": 7.1881153335990025, "deltaY": -100.63361467038604, "deltaZ": 0, "modifiers": 0, "latency": 10.33},
{"t": 3.953719937, "m": "Page.dispatchMouseEvent", "type": "mousemove", "x": 128.3830914846765, "y": 99.7177421891983, "button": 0, "buttons": 0, "modifiers": 0, "latency": 10.88},
{"t": 3.967176243, "m": "Page.dispatchMouseEvent", "type": "mousemove", "x": 128.5478503678504, "y": 100.26472820494625, "button": 0, "buttons": 0, "modifiers": 0, "latency": 8.03},
{"t": 3.976778434, "m": "Page.dispatchMouseEvent", "type": "mousemove", "x": 128.86954300068368, "y": 100.54488164693495, "button": 0, "buttons": 0, "modifiers": 0, "latency": 6.39},
{"t": 4.011962015, "m": "Page.dispatchMouseEvent", "type": "mousemove", "x": 129.51618791157694, "y": 101.92393275228162, "button": 0, "buttons": 0, "modifiers": 0, "latency": 10.3},
{"t": 4.020850762, "m": "Page.dispatchMouseEvent", "type": "mousemove", "x": 129.7019420065711, "y": 102.3087393613028, "button": 0, "buttons": 0, "modifiers": 0, "latency": 6.55},
{"t": 4.031894463, "m": "Page.dispatchMouseEvent", "type": "mousemove", "x": 130.01549203730764, "y": 102.73864105677714, "button": 0, "buttons": 0, "modifiers": 0, "latency": 14.32},
{"t": 4.067259875, "m": "Page.dispatchMouseEvent", "type": "mousemove", "x": 130.39372329309865, "y": 103.58471249031042, "button": 0, "buttons": 0, "modifiers": 0, "latency": 6.6},
{"t": 4.111970294, "m": "Page.dispatchMouseEvent", "type": "mousemove", "x": 130.49380779901747, "y": 103.80840970940216, "button": 0, "buttons": 0, "modifiers": 0, "latency": 9.38},
{"t": 4.185311973, "m": "Page.dispatchWheelEvent", "x": 130.49380779901747, "y": 103.80840970940216, "deltaX": 7.452078027112093, "deltaY": -104.3290923795693, "deltaZ": 0, "modifiers": 0, "latency": 10.65},
{"t": 4.258477943, "m": "Page.dispatchMouseEvent", "type": "mousemove", "x": 129.24569154860365, "y": 104.08556335673966, "button": 0, "buttons": 0, "modifiers": 0, "latency": 10.94},
{"t": 4.272026641, "m": "Page.dispatchMouseEvent", "type": "mousemove", "x": 128.3830224065804, "y": 104.38780440050613, "button": 0, "buttons": 0, "modifiers": 0, "latency": 14.83},
{"t": 4.290015276, "m": "Page.dispatchMouseEvent", "type": "mousemove", "x": 127.20246896419874, "y": 104.47865839573413, "button": 0, "buttons": 0, "modifiers": 0, "latency": 3.18},
{"t": 4.29846799, "m": "Page.dispatchMouseEvent", "type": "mousemove", "x": 126.8291214115412, "y": 104.70564402679267, "button": 0, "buttons": 0, "modifiers": 0, "latency": 7.17},
{"t": 4.311229412, "m": "Page.dispatchMouseEvent", "type": "mousemove", "x": 126.0564238964579, "y": 104.86869792495604, "button": 0, "buttons": 0, "modifiers": 0, "latency": 12.63},
{"t": 4.377819466, "m": "Page.dispatchMouseEvent", "type": "mousemove", "x": 124.89648114111318, "y": 105.17606078313771, "button": 0, "buttons": 0, "modifiers": 0, "latency": 5.76},
{"t": 4.439100083, "m": "Page.dispatchWheelEvent", "x": 124.89648114111318, "y": 105.17606078313771, "deltaX": 7.51981743567411, "deltaY": -105.27744409943756, "deltaZ": 0, "modifiers": 0, "latency": 9.51},
{"t": 4.488822667, "m": "Page.dispatchMouseEvent", "type": "mousemove", "x": 124.45493258962857, "y": 105.39814581934124, "button": 0, "buttons": 0, "modifiers": 0, "latency": 7.35},
{"t": 4.498483902, "m": "Page.dispatchMouseEvent", "type": "mousemove", "x": 124.190879874337, "y": 105.61167125744338, "button": 0, "buttons": 0, "modifiers": 0, "latency": 8.96},
{"t": 4.519290753, "m": "Page.dispatchMouseEvent", "type": "mousemove", "x": 123.21928032026241, "y": 106.35711582222, "button": 0, "buttons": 0, "modifiers": 0, "latency": 8.51},
{"t": 4.538086302, "m": "Page.dispatchMouseEvent", "type": "mousemove", "x": 122.6116428504774, "y": 106.99563828874764, "button": 0, "buttons": 0, "modifiers": 0, "latency": 11.1},
{"t": 4.554060894, "m": "Page.dispatchMouseEvent", "type": "mousemove", "x": 121.97700851351668, "y": 107.40173334287029, "button": 0, "buttons": 0, "modifiers": 0, "latency": 13.5},
{"t": 4.566198108, "m": "Page.dispatchMouseEvent", "type": "mousemove", "x": 121.59331390008086, "y": 107.66933850666328, "button": 0, "buttons": 0, "modifiers": 0, "latency": 9.33},
{"t": 4.601836782, "m": "Page.dispatchMouseEvent", "type": "mousemove", "x": 121.27731068462782, "y": 107.949755409335, "button": 0, "buttons": 0, "modifiers": 0, "latency": 10.71},
{"t": 4.828789654, "m": "Page.dispatchMouseEvent", "type": "mousemove", "x": 120.22901139934152, "y": 110.34130337175719, "button": 0, "buttons": 0, "modifiers": 0, "latency": 9.03},
{"t": 4.84223649, "m": "Page.dispatchMouseEvent", "type": "mousemove", "x": 119.8857148011499, "y": 112.70143396265777, "button": 0, "buttons": 0, "modifiers": 0, "latency": 12.88},
{"t": 4.852417774, "m": "Page.dispatchMouseEvent", "type": "mousemove", "x": 118.34675867187399, "y": 115.97231667387469, "button": 0, "buttons": 0, "modifiers": 0, "latency": 9.86},
{"t": 4.861779923, "m": "Page.dispatchMouseEvent", "type": "mousemove", "x": 116.92164255968103, "y": 118.81242095685232, "button": 0, "buttons": 0, "modifiers": 0, "latency": 4.84},
{"t": 4.876955775, "m": "Page.dispatchMouseEvent", "type": "mousemove", "x": 115.5713624589263, "y": 124.45401870360959, "button": 0, "buttons": 0, "modifiers": 0, "latency": 5.72},
{"t": 4.885858651, "m": "Page.dispatchMouseEvent", "type": "mousemove", "x": 114.0699148111332, "y": 127.65246523974116, "button": 0, "buttons": 0, "modifiers": 0, "latency": 6.89},
{"t": 4.894211592, "m": "Page.dispatchMouseEvent", "type": "mousemove", "x": 112.93339064619482, "y": 130.5706163538006, "button": 0, "buttons": 0, "modifiers": 0, "latency": 9.69},
{"t": 4.905906986, "m": "Page.dispatchMouseEvent", "type": "mousemove", "x": 111.38749452882294, "y": 134.4598534560125, "button": 0, "buttons": 0, "modifiers": 0, "latency": 5.17},
{"t": 4.915075954, "m": "Page.dispatchMouseEvent", "type": "mousemove", "x": 110.1090450964935, "y": 137.53908815355175, "button": 0, "buttons": 0, "modifiers": 0, "latency": 9.58},
{"t": 4.926921555, "m": "Page.dispatchMouseEvent", "type": "mousemove", "x": 109.24905577255122, "y": 140.8309514226937, "button": 0, "buttons": 0, "modifiers": 0, "latency": 15.48},
{"t": 4.940063688, "m": "Page.dispatchMouseEvent", "type": "mousemove", "x": 108.16140700570233, "y": 143.75200723223892, "button": 0, "buttons": 0, "modifiers": 0, "latency": 7.9},
{"t": 4.950119389, "m": "Page.dispatchMouseEvent", "type": "mousemove", "x": 107.45111787738823, "y": 145.2302671958072, "button": 0, "buttons": 0, "modifiers": 0, "latency": 4.52},
{"t": 4.960488465, "m": "Page.dispatchMouseEvent", "type": "mousemove", "x": 107.11873836011638, "y": 146.18351950777338, "button": 0, "buttons": 0, "modifiers": 0, "latency": 7.12},
{"t": 4.981098227, "m": "Page.dispatchMouseEvent", "type": "mousemove", "x": 106.8947452304634, "y": 146.85659356429883, "button": 0, "buttons": 0, "modifiers": 0, "latency": 8.0},
{"t": 4.990115695, "m": "Page.dispatchMouseEvent", "type": "mousemove", "x": 107.59813229646859, "y": 147.1374545932956, "button": 0, "buttons": 0, "modifiers": 0, "latency": 6.69},
{"t": 5.003457847, "m": "Page.dispatchMouseEvent", "type": "mousemove", "x": 111.56451225231646, "y": 148.67708308157793, "button": 0, "buttons": 0, "modifiers": 0, "latency": 7.49},
{"t": 5.024238657, "m": "Page.dispatchMouseEvent", "type": "mousemove", "x": 124.34437388380606, "y": 153.9366156286102, "button": 0, "buttons": 0, "modifiers": 0, "latency": 17.54},
{"t": 5.034413922, "m": "Page.dispatchMouseEvent", "type": "mousemove", "x": 133.57214191522127, "y": 157.4901960456731, "button": 0, "buttons": 0, "modifiers": 0, "latency": 15.54},
{"t": 5.047696096, "m": "Page.dispatchMouseEvent", "type": "mousemove", "x": 147.87473193960153, "y": 163.63495980614496, "button": 0, "buttons": 0, "modifiers": 0, "latency": 10.54},
{"t": 5.064975068, "m": "Page.dispatchMouseEvent", "type": "mousemove", "x": 170.22453174247218, "y": 173.30836657023033, "button": 0, "buttons": 0, "modifiers": 0, "latency": 19.44},
{"t": 5.082274789, "m": "Page.dispatchMouseEvent", "type": "mousemove", "x": 195.64288382642482, "y": 184.93920828631516, "button": 0, "buttons": 0, "modifiers": 0, "latency": 9.6},
{"t": 5.100001132, "m": "Page.dispatchMouseEvent", "type": "mousemove", "x": 224.49642269669522, "y": 199.10216800205185, "button": 0, "buttons": 0, "modifiers": 0, "latency": 9.45},
{"t": 5.119212611, "m": "Page.dispatchMouseEvent", "type": "mousemove", "x": 257.0994929521104, "y": 215.98442657490781, "button": 0, "buttons": 0, "modifiers": 0, "latency": 12.31},
{"t": 5.130846027, "m": "Page.dispatchMouseEvent", "type": "mousemove", "x": 280.2918548352319, "y": 224.17434816053202, "button": 0, "buttons": 0, "modifiers": 0, "latency": 13.54},
{"t": 5.157065937, "m": "Page.dispatchMouseEvent", "type": "mousemove", "x": 324.9461388856563, "y": 250.98831553332806, "button": 0, "buttons": 0, "modifiers": 0, "latency": 9.67},
{"t": 5.180098313, "m": "Page.dispatchMouseEvent", "type": "mousemove", "x": 364.12271425692006, "y": 271.14309873684226, "button": 0, "buttons": 0, "modifiers": 0, "latency": 7.47},
{"t": 5.194698162, "m": "Page.dispatchMouseEvent", "type": "mousemove", "x": 386.8064254105853, "y": 283.28681315243745, "button": 0, "buttons": 0, "modifiers": 0, "latency": 9.55},
{"t": 5.208416456, "m": "Page.dispatchMouseEvent", "type": "mousemove", "x": 406.24687538712215, "y": 293.8263015902012, "button": 0, "buttons": 0, "modifiers": 0, "latency": 9.82},
{"t": 5.227982237, "m": "Page.dispatchMouseEvent", "type": "mousemove", "x": 429.33297902709205, "y": 306.14957689944737, "button": 0, "buttons": 0, "modifiers": 0, "latency": 14.68},
{"t": 5.243859481, "m": "Page.dispatchMouseEvent", "type": "mousemove", "x": 443.45622273802485, "y": 313.89183316395724, "button": 0, "buttons": 0, "modifiers": 0, "latency": 13.66},
{"t": 5.258203091, "m": "Page.dispatchMouseEvent", "type": "mousemove", "x": 451.78940689332, "y": 318.2145810715442, "button": 0, "buttons": 0, "modifiers": 0, "latency": 10.35},
{"t": 5.271553352, "m": "Page.dispatchMouseEvent", "type": "mousemove", "x": 454.3486048580999, "y": 319.8272260593664, "button": 0, "buttons": 0, "modifiers": 0, "latency": 8.09},
{"t": 5.492019718, "m": "Page.dispatchMouseEvent", "type": "mousemove", "x": 453.6079275352587, "y": 319.4677176760962, "button": 0, "buttons": 0, "modifiers": 0, "latency": 6.69},
{"t": 5.506447613, "m": "Page.dispatchMouseEvent", "type": "mousemove", "x": 453.04442241368463, "y": 319.0535804086115, "button": 0, "buttons": 0, "modifiers": 0, "latency": 9.53},
{"t": 5.525967148, "m": "Page.dispatchMouseEvent", "type": "mousemove", "x": 451.8366303025648, "y": 318.7848425911238, "button": 0, "buttons": 0, "modifiers": 0, "latency": 6.04},
{"t": 5.539231526, "m": "Page.dispatchMouseEvent", "type": "mousemove", "x": 451.01616218657375, "y": 318.35503597958984, "button": 0, "buttons": 0, "modifiers": 0, "latency": 6.45},
{"t": 5.551509227, "m": "Page.dispatchMouseEvent", "type": "mousemove", "x": 449.82293386385265, "y": 317.99202785458925, "button": 0, "buttons": 0, "modifiers": 0, "latency": 8.85},
{"t": 5.572462813, "m": "Page.dispatchMouseEvent", "type": "mousemove", "x": 448.5020652805724, "y": 317.8493946527941, "button": 0, "buttons": 0, "modifiers": 0, "latency": 6.22},
{"t": 5.582383698, "m": "Page.dispatchMouseEvent", "type": "mousemove", "x": 447.95583413312863, "y": 317.25766775481094, "button": 0, "buttons": 0, "modifiers": 0, "latency": 10.97},
{"t": 5.601464719, "m": "Page.dispatchMouseEvent", "type": "mousemove", "x": 446.8489330013245, "y": 317.41468525394225, "button": 0, "buttons": 0, "modifiers": 0, "latency": 21.47},
{"t": 5.623177686, "m": "Page.dispatchMouseEvent", "type": "mousemove", "x": 445.9775300587278, "y": 316.87779113872415, "button": 0, "buttons": 0, "modifiers": 0, "latency": 7.72},
{"t": 5.679440378, "m": "Page.dispatchMouseEvent", "type": "mousemove", "x": 445.01102336637433, "y": 316.70682455678354, "button": 0, "buttons": 0, "modifiers": 0, "latency": 10.58},
{"t": 5.836607209, "m": "Page.dispatchMouseEvent", "type": "mousedown", "x": 445.01102336637433, "y": 316.70682455678354, "button": 0, "buttons": 1, "modifiers": 0, "clickCount": 1, "latency": 7.56},
{"t": 5.893006928, "m": "Page.dispatchMouseEvent", "type": "mouseup", "x": 445.01102336637433, "y": 316.70682455678354, "button": 0, "buttons": 0, "modifiers": 0, "clickCount": 1, "latency": 4.76}
]
}
}
}
+411
View File
@@ -0,0 +1,411 @@
"""Golden generator: what the page's engine receives from the in-process client's
humanised pointer, computed with the CLIENT-SIDE code of commit 5d9ad70
(`invisible_playwright/_cursor.py` wrappers: `_approach`, `_wrap_mouse_move`,
`_wrap_mouse_click`, `_wrap_mouse_wheel`), through a real `invisible_core`
`Actions` object whose connection only records.
Run against the OLD tree only:
PYTHONPATH=<worktree at 5d9ad70>/src python gen_golden.py > pointer_golden.json
REVISION 1 (feat/rt-dblmove): the `explicit_pointer` session, the only one with
a `Mouse.click`, no longer carries the duplicate the client's `Mouse._click`
made. That click moved to the point (`move`) and `click_at` then moved there
again as its own approach: two `mousemove` with the same coordinates at the same
instant before the press, which no mouse reports and a page can count. The
server now sends the stroke and lets `Actions.click_at` make the one move onto
the point (`Pointer.click_at`). Only that session changes (one `mousemove`
fewer; the per-event `latency` draws follow the event ordinal, so the ones
after it are the draws of the same ordinals); the other three sessions are
byte-for-byte what the client made at 5d9ad70. Regenerate that session with
the CURRENT tree, never by hand:
PYTHONPATH=<this tree>/src python tests/data/pointer_golden_origin.py --revise-mouse-click
It refuses to write unless the new session is the old one minus exactly one
repeated mousemove on the click point.
REVISION 2 (feat/rt-dblmove): the same session had a second repeat, at the
START of the stroke of the `Mouse.click` that follows the explicit move and a
pause: the stroke's first waypoint is its start point, and the engine had
already been told the pointer stood on that pixel. `Pointer._travel` now does
not send a first waypoint that coincides with the position the engine knows.
Again one `mousemove` fewer in `explicit_pointer` only (t, x, y and type of
every other event unchanged; the latency draws follow the event ordinal); the
other three sessions are identical event for event, and the generator checks
that before it writes:
PYTHONPATH=<this tree>/src python tests/data/pointer_golden_origin.py --revise-standstill
"""
import asyncio
import json
import sys
import time
from types import SimpleNamespace
from invisible_core.juggler import PageActs
from invisible_core.juggler import actions as core_actions
from invisible_core.juggler.actions import Actions
from invisible_playwright import _cursor
VIEWPORT = {"width": 1280, "height": 720}
BOXES = {
"#b": {"x": 400.0, "y": 300.0, "width": 100.0, "height": 40.0},
"#c": {"x": 880.5, "y": 120.25, "width": 160.0, "height": 36.0},
"#tiny": {"x": 700.0, "y": 500.0, "width": 8.0, "height": 8.0},
}
HITS = "all"
def hit_ok(selector, x, y):
"""The element's shape as the engine's hit test sees it: a box ("all"), or
a round control whose only sure point is the centre ("centre")."""
if HITS == "all":
return True
b = BOXES[selector]
return abs(x - (b["x"] + b["width"] / 2.0)) <= 1.0 and abs(y - (b["y"] + b["height"] / 2.0)) <= 1.0
class VT:
def __init__(self):
self.t = 0.0
def now(self):
return self.t
async def sleep(self, s):
self.t += max(0.0, s)
def sync_sleep(self, s):
self.t += max(0.0, s)
class Conn:
def __init__(self, vt):
self.vt = vt
self.log = []
def send(self, method, params=None, session=None, timeout=None, **kw):
if method.startswith("Page.dispatch"):
rec = {"t": round(self.vt.t, 9), "m": method}
rec.update({k: v for k, v in (params or {}).items()
if k not in ("landsOn",)})
self.log.append(rec)
if method == "Page.getContentQuads":
b = BOXES[self.current]
return {"quads": [{"p1": {"x": b["x"], "y": b["y"]},
"p2": {"x": b["x"] + b["width"], "y": b["y"]},
"p3": {"x": b["x"] + b["width"], "y": b["y"] + b["height"]},
"p4": {"x": b["x"], "y": b["y"] + b["height"]}}]}
if method == "Page.dispatchMouseEvent" and "landsOn" in (params or {}):
return {"landing": {"landed": True, "on": "el"}}
return {}
class Injected:
def __init__(self, conn):
self.conn = conn
self.checked = False
def query_selector(self, f, selector, strict=False):
if selector in BOXES:
self.conn.current = selector
return "el"
return None
def element_states(self, f, el, states):
return {"ok": True}
def evaluate(self, f, expr, **kw):
return {"w": VIEWPORT["width"], "h": VIEWPORT["height"]}
def check_hit_target(self, f, el, point):
return "done" if hit_ok(self.conn.current, point[0], point[1]) else "other"
def element_state(self, f, el, state):
# unchecked before the click, checked after it
self.n = getattr(self, "n", 0) + 1
return self.n > 1
def dispose(self, f, el):
pass
def scroll_into_view(self, *a, **k):
raise AssertionError("not expected")
class Life:
main_frame = "main"
def build_actions(vt, seed, budget, number):
conn = Conn(vt)
inj = Injected(conn)
act = Actions(conn, "sess", Life(), inj, acts=PageActs(number),
session_seed=seed, motion_budget_s=budget, layout="us")
return act, conn, inj
# ── old client side ─────────────────────────────────────────────────────────
class OMouse:
def __init__(self, page):
self._channel = SimpleNamespace(_object=page)
class OPage:
def __init__(self, ctx, number, actions):
self._browser_context = ctx
self._initializer = {"pageNumber": number}
self._viewport_size = dict(VIEWPORT)
self.mouse = OMouse(self)
self.actions = actions
class OHandle:
def __init__(self, selector, hits_fn):
self.selector = selector
self._channel = SimpleNamespace(send=self._send)
async def _send(self, method, tc=None, params=None, **kw):
# the real server answers with the ACTION'S OWN hit test (Actions.hit_target)
assert method == "checkHitTarget"
return hit_ok(self.selector, params["point"]["x"], params["point"]["y"])
async def bounding_box(self):
return dict(BOXES[self.selector])
async def dispose(self):
pass
class OFrame:
def __init__(self, page, hits_fn):
self._page = page
self.hits_fn = hits_fn
async def query_selector(self, selector):
if selector not in BOXES:
return None
return OHandle(selector, self.hits_fn)
def scenario(spec):
seed, number, budget = spec["seed"], spec["number"], spec["budget"]
vt = VT()
# one timer for the cursor and the sleeps of the actions
_cursor._TIMER = vt
core_actions.time = SimpleNamespace(sleep=vt.sync_sleep, monotonic=time.monotonic,
perf_counter=time.perf_counter)
act, conn, inj = build_actions(vt, seed, budget, number)
class B: pass
browser = B()
assert _cursor._ensure_patched()
assert _cursor.enable_for(browser, seed=seed, max_seconds=budget)
class C: pass
ctx = C()
ctx._browser = browser
page = OPage(ctx, number, act)
async def fake_move(mouse, x, y, steps=None):
act.move(x, y)
_cursor._ORIGINAL_MOUSE_MOVE = fake_move
async def fake_click(mouse, x, y, **kw):
act.click_at(x, y, clicks=kw.get("clickCount") or 1)
_cursor._ORIGINAL_MOUSE_CLICK = fake_click
async def fake_wheel(mouse, dx, dy):
act.wheel(dx, dy)
_cursor._ORIGINAL_MOUSE_WHEEL = fake_wheel
global HITS
HITS = spec.get("hits", "all")
frame = OFrame(page, None)
async def run():
for op in spec["ops"]:
kind = op[0]
if kind == "wait":
vt.t += op[1]
continue
if kind in ("click", "hover", "dblclick", "tap", "check"):
sel = op[1]
kw = dict(op[2]) if len(op) > 2 else {}
ov = await _cursor._approach(frame, (sel,), kw, timer=vt)
kw = {**kw, **(ov or {})}
pos = kw.get("position")
timeout = (kw["timeout"] / 1000.0) if "timeout" in kw else 30.0
fn = getattr(act, {"check": "check"}.get(kind, kind))
fn(sel, timeout=timeout, position=pos)
elif kind == "move":
w = _cursor._wrap_mouse_move(fake_move)
await w(page.mouse, op[1], op[2], None)
elif kind == "mouse_click":
# Mouse._click wrapper calls self.move (wrapped) then the original
mv = _cursor._wrap_mouse_move(fake_move)
class M:
_channel = SimpleNamespace(_object=page)
async def move(self, x, y, steps=None):
return await mv(self, x, y, steps)
w = _cursor._wrap_mouse_click(fake_click)
await w(M(), op[1], op[2], **(op[3] if len(op) > 3 else {}))
elif kind == "wheel":
w = _cursor._wrap_mouse_wheel(fake_wheel)
class M2:
_channel = SimpleNamespace(_object=page)
await w(M2(), op[1], op[2])
else:
raise ValueError(kind)
asyncio.run(run())
return conn.log
SCENARIOS = {
"session_a": {
"seed": 4242, "number": 0, "budget": 1.5, "ops": [
["click", "#b"], ["wait", 0.1], ["hover", "#c"], ["wait", 3.0],
["dblclick", "#b"], ["wait", 2.0], ["tap", "#c"], ["wait", 0.05],
["click", "#c", {"position": {"x": 10.0, "y": 5.0}}], ["wait", 7.5],
["check", "#b"], ["click", "#tiny"],
]},
"session_b_tight_cap": {
"seed": 7, "number": 3, "budget": 0.4, "ops": [
["click", "#c"], ["wait", 1.0], ["hover", "#b"], ["wait", 12.0],
["click", "#b"],
]},
"landing_misses": {
"seed": 99, "number": 1, "budget": 1.5, "hits": "centre", "ops": [
["click", "#b"], ["wait", 2.0], ["hover", "#c"],
]},
"explicit_pointer": {
"seed": 31337, "number": 2, "budget": 1.5, "ops": [
["move", 800.0, 500.0], ["wait", 0.2], ["mouse_click", 120.0, 60.0],
["wheel", 0.0, 900.0], ["wheel", 0.0, 150.0], ["wheel", 30.0, -420.0],
["click", "#b"],
]},
}
# ── revision 1: the server's own run of the Mouse.click session ──────────────
def _line(obj):
return json.dumps(obj, separators=(", ", ": "))
def dump_golden(g):
"""The file's layout: one line per event, so a diff shows events."""
out = ["{", ' "_origin": ' + _line(g["_origin"]) + ",", ' "scenarios": {']
names = list(g["scenarios"])
for n, name in enumerate(names):
sc = g["scenarios"][name]
out.append(" %s: {" % json.dumps(name))
out.append(' "spec": ' + _line(sc["spec"]) + ",")
out.append(' "engine_events": [')
evs = sc["engine_events"]
for i, e in enumerate(evs):
out.append(" " + _line(e) + ("," if i < len(evs) - 1 else ""))
out.append(" ]")
out.append(" }" + ("," if n < len(names) - 1 else ""))
out += [" }", "}"]
return "\r\n".join(out) + "\r\n"
def _server_session(spec, name):
"""What the engine receives from the CURRENT server for one session."""
from invisible_playwright._juggler import pointer as pointer_mod
import tests.test_pointer_server as T
clock = T.VirtualClock()
pointer_mod._CLOCK = clock
core_actions.time = SimpleNamespace(
sleep=clock.sleep, monotonic=time.monotonic,
perf_counter=time.perf_counter)
page = T.build_page(clock, T._boxes_of(name), seed=spec["seed"],
number=spec["number"], budget=spec["budget"],
hits=spec.get("hits", "all"))
T.play(page, clock, spec["ops"])
return json.loads(json.dumps(page.log))
def _shape(evs): # the latency is a draw per event ordinal, not an event
return [{k: v for k, v in e.items() if k != "latency"} for e in evs]
def _revise(path, is_dup, revision):
"""Rewrite `explicit_pointer` from the current server, refusing unless it
is the file's session minus EXACTLY the one event `is_dup` names (same
t, x, y and type everywhere else), and every other session is what the
file already holds, event for event, latency included."""
import pathlib
root = pathlib.Path(__file__).resolve().parents[2]
sys.path.insert(0, str(root))
gp = pathlib.Path(path)
with open(gp, newline="", encoding="utf-8") as fh:
text = fh.read()
g = json.loads(text)
assert dump_golden(g) == text, \
"the writer does not reproduce the file: refusing to rewrite it"
name = "explicit_pointer"
old = g["scenarios"][name]["engine_events"]
dup = [i for i in range(1, len(old)) if is_dup(g["scenarios"][name]["spec"], old, i)]
assert len(dup) == 1, "expected exactly one such event, found %r" % dup
for other, sc in g["scenarios"].items():
if other != name:
assert _server_session(sc["spec"], other) == sc["engine_events"], \
"session %s is not what the file holds: refusing" % other
new = _server_session(g["scenarios"][name]["spec"], name)
assert _shape(new) == _shape(old[:dup[0]] + old[dup[0] + 1:]), \
"the session differs from the old one by more than that event"
g["scenarios"][name]["engine_events"] = new
g["_origin"].setdefault("revisions", []).append(revision)
with open(gp, "w", newline="", encoding="utf-8") as fh:
fh.write(dump_golden(g))
def _same_point_as_before(old, i, point=None):
a, b = old[i - 1], old[i]
return (a["m"] == b["m"] == "Page.dispatchMouseEvent"
and a["type"] == b["type"] == "mousemove"
and (a["x"], a["y"]) == (b["x"], b["y"])
and (point is None or (b["x"], b["y"]) == point))
def revise_mouse_click(path):
_revise(path,
lambda spec, old, i: _same_point_as_before(
old, i, tuple(spec["ops"][2][1:3])),
{
"what": "explicit_pointer: the Mouse.click no longer repeats its mousemove on the click point",
"why": "Pointer.click_at sent the endpoint as a move and Actions.click_at moved onto it again before the press; the server now lets click_at make the one move",
"change": "one mousemove fewer (same x, y, t as its twin); the other sessions are untouched",
"generator": "tests/data/pointer_golden_origin.py --revise-mouse-click, run against feat/rt-dblmove",
})
def revise_standstill(path):
_revise(path,
lambda spec, old, i: _same_point_as_before(
old, i, tuple(spec["ops"][0][1:3])),
{
"what": "explicit_pointer: a stroke from standstill no longer opens with a mousemove on the point it stands on",
"why": "the first waypoint of a stroke is its start; Pointer._travel sent it although the engine had already been told the pointer was on that pixel (a zero-displacement move no mouse reports)",
"change": "one mousemove fewer (the repeat of (800, 500) after the wait); t, x, y and type of every other event are unchanged, the latency draws follow the event ordinal; the other three sessions are identical event for event",
"generator": "tests/data/pointer_golden_origin.py --revise-standstill, run against feat/rt-dblmove",
})
if __name__ == "__main__":
import pathlib
for flag, fn in (("--revise-mouse-click", revise_mouse_click),
("--revise-standstill", revise_standstill)):
if flag in sys.argv:
i = sys.argv.index(flag)
fn(sys.argv[i + 1] if len(sys.argv) > i + 1 else
pathlib.Path(__file__).with_name("pointer_golden.json"))
sys.exit(0)
out = {name: {"spec": spec, "engine_events": scenario(spec)}
for name, spec in SCENARIOS.items()}
json.dump(out, sys.stdout, indent=1)
+54
View File
@@ -0,0 +1,54 @@
"""The engine processes that belong to THIS test, found from the tree and not from the machine.
An e2e run opens several browsers at once (pytest-xdist workers, each with its own). A test that
wants "the engine process that does X" and looks for it over the whole of /proc can be handed the
process of another worker's browser, which has not done X yet: that is how
test_webgl_draws_on_the_engine_s_own_gl failed on one run of the Linux gate and passed on the
next with the same engine and the same core.
The tree is the answer: a worker's browsers are its descendants, and a process that is not below
the worker is not the test's business. `maps_of_the_engine_below` takes the root, the engine's
folder and a `view` of the machine (the real one, or a stand-in in the unit test).
"""
from __future__ import annotations
from typing import Dict, List, Optional
class Machine:
"""What the selector asks of the machine: the real one, through psutil and /proc."""
def descendants(self, pid: int) -> List[int]:
import psutil
try:
return [p.pid for p in psutil.Process(pid).children(recursive=True)]
except psutil.Error:
return []
def exe(self, pid: int) -> Optional[str]:
import os
try:
return os.readlink("/proc/%d/exe" % pid)
except OSError:
return None
def maps(self, pid: int) -> List[str]:
try:
with open("/proc/%d/maps" % pid) as f:
return sorted({line.split()[-1] for line in f if len(line.split()) > 5})
except OSError:
return []
def maps_of_the_engine_below(root: int, binary_dir: str, machine: Optional[Machine] = None) -> Dict[int, List[str]]:
"""{pid: mapped files} of every engine process (executable inside `binary_dir`) that is a
descendant of `root`. Nothing outside the tree is looked at."""
machine = machine or Machine()
found: Dict[int, List[str]] = {}
for pid in machine.descendants(root):
exe = machine.exe(pid)
if exe and exe.startswith(binary_dir):
found[pid] = machine.maps(pid)
return found
+83
View File
@@ -0,0 +1,83 @@
"""The e2e run stops at the first refusal of the engine.
The engine refuses a launch whose declarations are incomplete ("stealth: zoom.stealth.X is not
declared. Engine rule 7 ..."), and it refuses it the same way for every test that follows: the
core and the engine do not agree, and no test after the first can say anything the first did not.
Before this plugin the run went on for 26 minutes, launching the browser for each of ~450 tests
and filling the desktop with crash windows, to report one cause 313 times.
The plugin reads the text of a FAILED report. A refusal in it is the engine's own sentence, and
the run is stopped there, with that sentence as the reason:
* serial: `session.shouldstop` on the test's session (pytest stops before the next test);
* under xdist: the controller's `DSession.shouldstop` (the workers are told to finish, and the
tests that have not started do not start). A worker's own session is not touched: stopping a
worker alone would make the controller schedule its tests on the others.
A test that EXPECTS a refusal (`pytest.raises`) does not fail, so it never reaches here.
"""
from __future__ import annotations
import re
from typing import Optional
#: The sentences the engine's gate writes through StealthRefuse (StealthDeclarationGate.cpp).
REFUSAL = re.compile(
r"stealth: [^\n]*(?:is not declared\. Engine rule 7"
r"|The scale is part of the declaration)")
def refusal_in(text: str) -> Optional[str]:
"""The engine's refusal sentence in `text` (one line, as printed), or None."""
match = REFUSAL.search(text or "")
if not match:
return None
end = text.find("\n", match.end())
return text[match.start():end if end != -1 else None].strip()[:300]
def reason_to_stop(report) -> Optional[str]:
"""Why the run must stop after this report, or None. Only the failure of an e2e test counts:
a unit test that quotes the sentence (this plugin's own) did not launch the engine."""
if not getattr(report, "failed", False):
return None
if "e2e" not in getattr(report, "keywords", {}):
return None
sentence = refusal_in(getattr(report, "longreprtext", "") or "")
if sentence is None:
return None
return ("the engine refused a launch (%s): every test after this one would launch the same "
"browser and be refused the same way. First seen in %s" % (sentence, report.nodeid))
class StopAtTheFirstRefusal:
"""The pytest plugin. Register an instance with `config.pluginmanager.register`."""
def __init__(self, config) -> None:
self.config = config
self.stopped_by: Optional[str] = None
self.session = None
def _controller(self):
return self.config.pluginmanager.getplugin("dsession")
def pytest_sessionstart(self, session) -> None:
self.session = session
def pytest_runtest_logreport(self, report) -> None:
if self.stopped_by is not None:
return
reason = reason_to_stop(report)
if reason is None:
return
self.stopped_by = reason
controller = self._controller()
if controller is not None: # the controller of an xdist run
controller.shouldstop = reason
elif not hasattr(self.config, "workerinput"): # the serial path (a worker has workerinput)
self.session.shouldstop = reason
def pytest_terminal_summary(self, terminalreporter) -> None:
if self.stopped_by:
terminalreporter.write_sep("!", "stopped at the first refusal of the engine")
terminalreporter.write_line(self.stopped_by)
+35
View File
@@ -0,0 +1,35 @@
"""What a page can tell about a stroke from the mousemoves it received, without counting them.
How many mousemoves reach a page is not the stroke's: the pacer drops a sample rather than send it
late, so the same stroke is 15 events on an idle machine and 6 to 9 on a loaded one (measured on
Windows with 32 busy processes; the Linux gate with four workers gave 9). A test that wants "a
stroke, not a jump" asks for its SHAPE: it set out from somewhere else, it came in steps, it ended
on the target, and nowhere did two consecutive events repeat.
"""
from __future__ import annotations
import math
from typing import List, Sequence, Tuple
#: A stroke starts at least this far from where it ends. The departure of the test's seed is
#: about 870 px away; a jump or a stroke that "began" at the target is 0.
MIN_REACH_PX = 150.0
#: Departure, at least one step on the way, landing.
MIN_EVENTS = 3
def stroke_problems(moves: Sequence[Sequence[float]], target: Tuple[float, float]) -> List[str]:
"""What is wrong with `moves` as a stroke to `target`; an empty list is a stroke."""
problems: List[str] = []
if len(moves) < MIN_EVENTS:
problems.append("only %d mousemove(s): no departure, no steps" % len(moves))
return problems
if list(moves[-1]) != list(target):
problems.append("the last mousemove %r is not the target %r" % (list(moves[-1]), list(target)))
reach = math.hypot(moves[0][0] - target[0], moves[0][1] - target[1])
if reach < MIN_REACH_PX:
problems.append("the first mousemove %r is only %.0f px from the target" % (list(moves[0]), reach))
repeated = [(i, list(m)) for i, m in enumerate(moves) if i and list(m) == list(moves[i - 1])]
if repeated:
problems.append("the same mousemove twice in a row: %r" % repeated)
return problems
@@ -0,0 +1,167 @@
"""A message in the 1.62 form reaches the operations as the 1.61 form did.
Playwright 1.62 moved the call's `timeout` out of the parameters of nearly
every command and into the metadata, and added optional fields and two
commands. The server read `params["timeout"]` only, so a 1.62 client's
`page.goto(url, timeout=5000)` arrived with the timeout in `metadata`, the
operation found none and waited the 30 s default: the caller's own limit was
silently lost. `Dispatcher.handle` now folds the variants into one shape
(`_juggler/variants.py`) without asking which version sent the message.
The messages go through the real `Server.handle` to the real dispatcher
classes (routing tables included); only the operations behind them are
replaced by a recorder, because the thing under test is what they are GIVEN.
"""
from __future__ import annotations
import pytest
from invisible_playwright._juggler._marshal import _caller_timeout
from invisible_playwright._juggler.dispatcher import ProtocolException, Server
from invisible_playwright._juggler.server import (
ElementHandleDispatcher, FrameDispatcher, PageDispatcher)
pytestmark = pytest.mark.unit
def _put(server, cls, guid, seen, monkeypatch, ops):
"""One `cls` object in the server, its operations `ops` replaced by a
recorder of the timeout they would wait, read the way the real ones do."""
obj = cls.__new__(cls)
obj.server, obj.guid, obj.parent, obj.disposed = server, guid, None, False
server.register(obj)
for op in ops:
def record(self, params, _op=op):
seen.append((_op, _caller_timeout(params), dict(params)))
return {}
monkeypatch.setattr(cls, op, record)
def _timeout_of(server, seen, guid, method, params, metadata=None):
message = {"guid": guid, "method": method, "params": params}
if metadata is not None:
message["metadata"] = metadata
server.handle(message)
return seen[-1][1]
CASES = [
("frame@1", "goto", {"url": "http://x/"}),
("frame@1", "click", {"selector": "a", "strict": True}),
("frame@1", "fill", {"selector": "a", "value": "v", "strict": True}),
("frame@1", "waitForSelector", {"selector": "a", "strict": True}),
("page@1", "reload", {}),
("page@1", "screenshot", {"type": "png"}),
]
@pytest.fixture
def world(monkeypatch):
server, seen = Server(), []
_put(server, FrameDispatcher, "frame@1", seen, monkeypatch,
("op_goto", "op_click", "op_fill", "op_wait_for_selector"))
_put(server, PageDispatcher, "page@1", seen, monkeypatch,
("op_reload", "op_screenshot"))
_put(server, ElementHandleDispatcher, "handle@1", seen, monkeypatch,
("op_click",))
return server, seen
@pytest.mark.parametrize("guid,method,params", CASES,
ids=[c[1] for c in CASES])
def test_a_timeout_in_the_metadata_is_the_timeout_of_the_call(
world, guid, method, params):
server, seen = world
in_params = _timeout_of(server, seen, guid, method,
dict(params, timeout=5000))
in_metadata = _timeout_of(server, seen, guid, method, dict(params),
{"timeout": 5000})
assert in_params == 5.0
assert in_metadata == in_params
@pytest.mark.parametrize("guid,method,params", CASES,
ids=[c[1] for c in CASES])
def test_no_timeout_anywhere_is_the_default_and_zero_is_no_limit(
world, guid, method, params):
server, seen = world
assert _timeout_of(server, seen, guid, method, dict(params),
{"title": "x"}) == 30.0
assert _timeout_of(server, seen, guid, method, dict(params),
{"timeout": 0}) is None
assert _timeout_of(server, seen, guid, method, dict(params, timeout=0),
{"timeout": 7000}) is None
def test_the_timeout_of_the_parameters_wins_over_the_metadata(world):
server, seen = world
assert _timeout_of(server, seen, "frame@1", "goto",
{"url": "u", "timeout": 2000}, {"timeout": 9000}) == 2.0
def test_the_callers_message_is_not_changed(world):
server, seen = world
params, metadata = {"url": "u"}, {"timeout": 4000, "title": "t"}
server.handle({"guid": "frame@1", "method": "goto", "params": params,
"metadata": metadata})
assert params == {"url": "u"}
assert metadata == {"timeout": 4000, "title": "t"}
def test_a_field_this_server_does_not_know_is_not_a_failure(world):
server, seen = world
server.handle({"guid": "frame@1", "method": "click",
"params": {"selector": "a", "scroll": "none",
"someFieldOfTheFuture": {"a": [1]}},
"metadata": {"timeout": 1000, "stepId": "s", "other": 1}})
op, timeout, params = seen[-1]
assert op == "op_click" and timeout == 1.0
assert params["selector"] == "a" and params["scroll"] == "none"
def test_an_element_handle_takes_the_timeout_from_the_metadata_too(world):
server, seen = world
assert _timeout_of(server, seen, "handle@1", "click", {},
{"timeout": 3000}) == 3.0
@pytest.mark.parametrize("guid,method,params,why", [
("page@1", "screenshot", {"type": "webp"}, "webp"),
("frame@1", "waitForFunction",
{"expression": "e => e", "selector": "a"}, "selector"),
])
def test_a_command_not_served_refuses_with_its_reason(world, guid, method,
params, why):
server, seen = world
before = len(seen)
with pytest.raises(ProtocolException) as refused:
server.handle({"guid": guid, "method": method, "params": params})
assert why in str(refused.value)
assert "has no method" not in str(refused.value)
assert len(seen) == before
@pytest.mark.parametrize("method,params", [
("storageState", {"credentials": True}),
("setStorageState", {"storageState": {"credentials": [{"id": "x"}]}}),
("newContext", {"storageState": {"credentials": [{"id": "x"}]}}),
])
def test_virtual_credentials_refuse_and_their_absence_does_not(method, params):
from invisible_playwright._juggler import variants
with pytest.raises(ProtocolException, match="credentials"):
variants.to_internal(method, params, {})
for nothing in (False, None, []):
variants.to_internal(
method, {"credentials": nothing,
"storageState": {"credentials": nothing}}, {})
def test_a_screencast_frame_ack_is_accepted_and_does_nothing(world):
"""A 1.62 client acknowledges every screencast frame; the server already acknowledged it to the
engine, so the ack is answered, not refused. Known-bad: variants refusing it, or the Page without
the method (`has no method 'screencastFrameAck'`)."""
server, seen = world
before = len(seen)
assert server.handle({"guid": "page@1", "method": "screencastFrameAck",
"params": {"frameId": 4}}) is None
assert len(seen) == before
@@ -0,0 +1,175 @@
"""`Mouse.click` in a humanising session puts ONE `mousemove` on its point.
The stroke the hand draws to the point stops short of it (`Pointer.travel`
leaves the endpoint to the caller). The click then used to emit that endpoint
twice: `Pointer.click_at` sent it as an explicit move, and the core's
`Actions.click_at` sent it again as its own approach before the press, so the
engine received two `mousemove` with the same coordinates at the same instant,
which no mouse produces and a page can count.
Nothing here launches a browser. The page is a real `PageDispatcher` over a real
`invisible_core` `Actions` whose connection only records (the same fakes as
`test_pointer_server`), on a virtual clock. Both transports end in the same
call, `PageDispatcher.call("mouseClick", ...)`: the in-process client sends it
through `_impl/_input.py`, a remote client over the wire, and the table that
routes it is asserted below, so one sequence is the sequence of both.
"""
from __future__ import annotations
import json
import pathlib
import pytest
from invisible_playwright._juggler.server import PageDispatcher
import test_pointer_server as _pointer_server
from test_pointer_server import _boxes_of, build_page
#: the fixture of the other module, under its own name
clock = _pointer_server.clock
pytestmark = pytest.mark.unit
GOLDEN = json.loads(
(pathlib.Path(__file__).parent / "data" / "pointer_golden.json").read_text(
encoding="utf-8"))["scenarios"]
def _mouse_events(log):
return [e for e in log if e["m"] == "Page.dispatchMouseEvent"]
def _repeated_moves(events):
"""Consecutive `mousemove` with the same coordinates: (index, x, y)."""
return [(i, e["x"], e["y"]) for i, e in enumerate(events)
if i and e["type"] == "mousemove"
and events[i - 1]["type"] == "mousemove"
and (e["x"], e["y"]) == (events[i - 1]["x"], events[i - 1]["y"])]
@pytest.mark.parametrize("point", [(120.0, 60.0), (640.5, 360.25), (3.0, 700.0)])
@pytest.mark.parametrize("seed", [4242, 31337])
def test_a_humanised_mouse_click_has_no_repeated_mousemove(clock, seed, point):
page = build_page(clock, _boxes_of("x"), seed=seed, number=0, budget=1.5)
page.call("mouseClick", {"x": point[0], "y": point[1]})
events = _mouse_events(page.log)
assert _repeated_moves(events) == []
# and the click is still where it was asked: one move onto the exact
# point, then the press and the release on it
assert [e["type"] for e in events[-3:]] == ["mousemove", "mousedown", "mouseup"]
assert all((e["x"], e["y"]) == point for e in events[-3:])
assert len(events) > 10 # still a stroke, not a jump
def test_the_point_is_reached_by_exactly_one_mousemove(clock):
page = build_page(clock, _boxes_of("x"), seed=4242, number=0, budget=1.5)
page.call("mouseClick", {"x": 120.0, "y": 60.0})
on_point = [e for e in _mouse_events(page.log)
if e["type"] == "mousemove" and (e["x"], e["y"]) == (120.0, 60.0)]
assert len(on_point) == 1
def test_a_double_click_still_presses_twice_on_one_move(clock):
page = build_page(clock, _boxes_of("x"), seed=4242, number=0, budget=1.5)
page.call("mouseClick", {"x": 120.0, "y": 60.0, "clickCount": 2})
events = _mouse_events(page.log)
assert _repeated_moves(events) == []
assert [e["type"] for e in events[-5:]] == [
"mousemove", "mousedown", "mouseup", "mousedown", "mouseup"]
def test_without_a_hand_a_click_is_one_move_and_the_press(clock):
"""No humanising: the server adds nothing, and the click's own approach is
the only move (the sequence a plain protocol client always got)."""
page = build_page(clock, _boxes_of("x"), seed=None, number=0, budget=None)
assert not page.pointer.active
page.call("mouseClick", {"x": 120.0, "y": 60.0})
assert [e["type"] for e in _mouse_events(page.log)] == [
"mousemove", "mousedown", "mouseup"]
def test_both_transports_reach_the_click_through_the_same_operation():
"""The in-process client and a remote one send `mouseClick`; the server
routes that one name to the one function that draws the stroke."""
assert PageDispatcher.METHODS["mouseClick"] == "op_mouse_click"
import inspect
from invisible_playwright._pw._impl import _input
assert '"mouseClick"' in inspect.getsource(_input)
def test_the_pointer_stands_on_the_point_after_the_click(clock):
"""The next walk departs from where the click ended, not from where the
stroke stopped short."""
page = build_page(clock, _boxes_of("x"), seed=4242, number=0, budget=1.5)
page.call("mouseClick", {"x": 120.0, "y": 60.0})
assert page.pointer._here() == (120.0, 60.0)
before = len(page.log)
clock.t += 0.01
page.frame.op_click({"selector": "#b", "noWaitAfter": True})
first_of_next = [e for e in _mouse_events(page.log[before:])
if e["type"] == "mousemove"][0]
assert abs(first_of_next["x"] - 120.0) < 60
assert abs(first_of_next["y"] - 60.0) < 60
def test_the_golden_mouse_click_session_has_one_move_on_its_point():
events = _mouse_events(GOLDEN["explicit_pointer"]["engine_events"])
downs = [i for i, e in enumerate(events) if e["type"] == "mousedown"]
i = downs[0]
on_point = [e for e in events[:i] if e["type"] == "mousemove"
and (e["x"], e["y"]) == (120.0, 60.0)]
assert len(on_point) == 1
# ═══════════════════════════════════════════════════════════════════════════
# The other end: a stroke that starts where the pointer already stands
# ═══════════════════════════════════════════════════════════════════════════
def _zero_displacement_moves(events):
"""A `mousemove` onto the very point the previous mouse event was at."""
return [(i, e["x"], e["y"]) for i, e in enumerate(events)
if i and e["type"] == "mousemove"
and (e["x"], e["y"]) == (events[i - 1]["x"], events[i - 1]["y"])]
@pytest.mark.parametrize("pause", [0.0, 0.2, 5.0])
@pytest.mark.parametrize("then", ["mouseClick", "mouseMove"])
def test_a_stroke_from_standstill_does_not_repeat_the_point_it_stands_on(
clock, pause, then):
page = build_page(clock, _boxes_of("x"), seed=31337, number=2, budget=1.5)
page.call("mouseMove", {"x": 800.0, "y": 500.0, "humanise": True})
clock.t += pause
params = {"x": 120.0, "y": 60.0}
if then == "mouseMove":
params["humanise"] = True
page.call(then, params)
events = _mouse_events(page.log)
assert _repeated_moves(events) == []
assert _zero_displacement_moves(events) == []
# the walk still departs from there and the page still got the stroke
assert len([e for e in events if e["type"] == "mousemove"]) > 10
def test_a_second_click_does_not_open_with_a_move_onto_the_press(clock):
page = build_page(clock, _boxes_of("x"), seed=4242, number=0, budget=1.5)
page.call("mouseClick", {"x": 120.0, "y": 60.0})
clock.t += 0.3
page.call("mouseClick", {"x": 640.0, "y": 360.0})
assert _zero_displacement_moves(_mouse_events(page.log)) == []
def test_the_first_ever_stroke_still_starts_with_its_first_waypoint(clock):
"""The page has been told nothing yet: the seeded start point is a real
first move for it, not a repeat."""
page = build_page(clock, _boxes_of("x"), seed=4242, number=0, budget=1.5)
page.call("mouseMove", {"x": 800.0, "y": 500.0, "humanise": True})
first = _mouse_events(page.log)[0]
assert (first["x"], first["y"]) != (0.0, 0.0)
assert first["t"] == 0.0
def test_no_golden_session_has_a_zero_displacement_mousemove():
for name, sc in GOLDEN.items():
events = _mouse_events(sc["engine_events"])
assert _zero_displacement_moves(events) == [], name
@@ -0,0 +1,206 @@
"""A context that is closed leaves nothing behind in a long-lived browser.
NO BROWSER HERE: the real `BrowserDispatcher`, `BrowserContextDispatcher` and
`PageDispatcher` over a scripted Juggler connection that answers the handful of
commands a context and a page need and sends the events a page's birth sends.
Measured before the fix (500 contexts, a page each, opened and closed): the
guid registry went from 7 objects to 1,507, `browser.contexts` kept 500
disposed contexts - each with its options and the connection that owned it -
and `browser._artifacts` kept every download. A recycled context (a server that
renews its context every few dozen fetches) pays that for the life of the
browser. The three children of a context (Debugger, Tracing, APIRequestContext)
were announced under the browser and adopted by the context on the wire, but
`dispose` forgets a subtree by walking `parent`, and theirs stayed the browser.
Known-bad: with `child.parent = self` removed from `BrowserContextDispatcher`,
the registry test fails; with `released` removed from the context, the list test
and the census fail; with the artifact's `released` removed, the artifact test
fails.
"""
from __future__ import annotations
import collections
import gc
import itertools
import os
import tempfile
import pytest
from invisible_core.juggler.connection import EventListeners
from invisible_playwright._juggler import remote
from invisible_playwright._juggler.server import (
ArtifactDispatcher, BrowserContextDispatcher, BrowserDispatcher,
DebuggerDispatcher, JugglerServer, LocalUtilsDispatcher, PageDispatcher,
StreamDispatcher, TracingDispatcher)
pytestmark = pytest.mark.unit
class ScriptedJuggler(EventListeners):
"""Just enough of the engine: contexts, pages born with their events, a
page's close as the engine's detach."""
def __init__(self):
super().__init__()
self._contexts = itertools.count(1)
self._targets = itertools.count(1)
self.sessions = {}
def startup_send(self, method, params=None):
return {}
def post(self, method, params=None, session=None):
pass
def send(self, method, params=None, session=None, timeout=30):
params = params or {}
if method == "Browser.createBrowserContext":
return {"browserContextId": "c%d" % next(self._contexts)}
if method == "Browser.newPage":
n = next(self._targets)
target, session = "t%d" % n, "s%d" % n
self.sessions[target] = session
self.dispatch_event("Browser.attachedToTarget", {
"sessionId": session,
"targetInfo": {"targetId": target, "type": "page",
"browserContextId": params.get("browserContextId")}},
None)
self.dispatch_event("Page.frameAttached",
{"frameId": "f" + target, "parentFrameId": None}, session)
for world in ("", "utility"):
self.dispatch_event("Runtime.executionContextCreated", {
"executionContextId": "e%s%s" % (target, world),
"auxData": {"frameId": "f" + target, "name": world}}, session)
return {"targetId": target}
if method == "Page.close":
target = next(t for t, s in self.sessions.items() if s == session)
del self.sessions[target]
self.dispatch_event("Browser.detachedFromTarget",
{"targetId": target, "sessionId": session}, None)
return {}
@pytest.fixture
def browser():
server = remote._SharedServer()
browser_type = remote.SharedBrowserType(server)
LocalUtilsDispatcher(server)
conn = ScriptedJuggler()
browser = remote.SharedBrowserDispatcher(server, browser_type, conn, "firefox/1")
yield browser
server.shutdown()
def _traffic(conn, session, tag, size=20000):
"""What a fetch does to a page: requests and responses carrying a payload,
a console line."""
blob = "x" * size
for k in range(5):
rid = "r%s-%d" % (tag, k)
conn.dispatch_event("Network.requestWillBeSent", {
"requestId": rid, "url": "http://x/%d" % k, "method": "GET",
"headers": [{"name": "h", "value": blob}], "frameId": None,
"navigationId": None, "resourceType": "Script"}, session)
conn.dispatch_event("Network.responseReceived", {
"requestId": rid, "status": 200, "statusText": "OK",
"headers": [{"name": "h", "value": blob}]}, session)
conn.dispatch_event("Network.requestFinished",
{"requestId": rid, "protocolVersion": "h2"}, session)
conn.dispatch_event("Runtime.console", {"type": "log", "args": [{"value": blob}]},
session)
def _cycle(browser, n, *, close_page_first):
"""One recycled context: newContext, newPage, traffic, close."""
server = browser.server
context = server.object(server.handle(
{"guid": browser.guid, "method": "newContext", "params": {}}
)["context"]["guid"])
page = server.object(server.handle(
{"guid": context.guid, "method": "newPage",
"params": {"pageNumber": n}})["page"]["guid"])
_traffic(browser.conn, page.session, n)
if close_page_first:
server.handle({"guid": page.guid, "method": "close", "params": {}})
server.handle({"guid": context.guid, "method": "close", "params": {}})
return context
def _registry(browser):
return collections.Counter(o.TYPE for o in browser.server._objects.values())
@pytest.mark.parametrize("close_page_first", [True, False])
def test_the_registry_is_what_it_was_after_the_contexts_close(browser, close_page_first):
before = _registry(browser)
for n in range(25):
_cycle(browser, n, close_page_first=close_page_first)
assert _registry(browser) == before
def test_the_browser_does_not_keep_the_contexts_it_closed(browser):
for n in range(10):
_cycle(browser, n, close_page_first=True)
assert browser.contexts == []
assert browser._page_targets == {} and browser._sessions == {}
assert browser._buffered == {} and browser._live == set()
def test_the_count_of_objects_is_stable_across_cycles(browser):
"""The census of what the server builds, after a collection, does not move
between 20 cycles and 60."""
kinds = (BrowserContextDispatcher, PageDispatcher, DebuggerDispatcher,
TracingDispatcher)
def census():
gc.collect()
return collections.Counter(type(o).__name__ for o in gc.get_objects()
if type(o) in kinds)
for n in range(20):
_cycle(browser, n, close_page_first=n % 2 == 0)
first = census()
for n in range(20, 60):
_cycle(browser, n, close_page_first=n % 2 == 0)
assert census() == first
assert first.get("BrowserContextDispatcher", 0) == 0, first
def test_a_download_and_its_stream_are_let_go_with_their_context(browser):
server = browser.server
context = server.object(server.handle(
{"guid": browser.guid, "method": "newContext", "params": {}}
)["context"]["guid"])
directory = tempfile.mkdtemp(prefix="invpw-test-dl-")
path = os.path.join(directory, "u1")
with open(path, "wb") as out:
out.write(b"hello")
artifact = ArtifactDispatcher(server, context, "u1", path)
browser._artifacts["u1"] = artifact
artifact.report_finished(None)
stream = server.object(artifact.op_stream({})["stream"]["guid"])
assert isinstance(stream, StreamDispatcher) and not stream._file.closed
server.handle({"guid": context.guid, "method": "close", "params": {}})
try:
assert browser._artifacts == {}
assert stream._file.closed, "the descendant's file stayed open"
finally:
stream._file.close()
os.remove(path)
os.rmdir(directory)
def test_the_errors_of_the_wire_are_the_last_few_not_all_of_them():
server = remote._SharedServer()
browser_type = remote.SharedBrowserType(server)
LocalUtilsDispatcher(server)
conn = ScriptedJuggler()
browser = remote.SharedBrowserDispatcher(server, browser_type, conn, "firefox/1")
endpoint = remote.RemoteEndpoint(server, browser_type, browser)
client = remote.RemoteClient(endpoint, None, None, {})
client.alive = False
for _ in range(500):
client.post_message({"guid": "x", "method": "m", "params": {"bad": {1, 2}}})
assert 0 < len(endpoint.wire_errors) <= 64
@@ -0,0 +1,81 @@
"""A route turns the context's cache off, and the last route turns it back on.
Playwright upstream pairs the two commands in `doUpdateRequestInterception`
(`packages/playwright-core/src/server/firefox/ffBrowser.ts`, v1.61.0 line 351):
`Browser.setRequestInterception` and `Browser.setCacheDisabled` carry the same
flag, for the same `browserContextId`. A server that sends only the first leaves
the engine's cache2 filling while a route holds every request: ~200 MB of disk
cache in a long routed session. Both commands are about the context, so a page
route (`Network.setRequestInterception`) sends no cache command, as upstream.
"""
from __future__ import annotations
import pytest
from invisible_core.juggler.connection import EventListeners
from invisible_playwright._juggler.server import (
BrowserContextDispatcher, BrowserDispatcher, Server,
)
class _Engine(EventListeners):
"""Records every command the server sends."""
def __init__(self):
super().__init__()
self.sent = []
def startup_send(self, method, params=None):
return self.send(method, params, timeout=None)
def send(self, method, params=None, session=None, timeout=30.0):
self.sent.append((method, params))
return {}
def _context(context_id="C1"):
engine = _Engine()
browser = BrowserDispatcher(Server(), None, engine, "151.0", session_seed=1)
context = BrowserContextDispatcher(browser.server, browser, {}, context_id)
browser.contexts.append(context)
return engine, context
def _flags(engine, command):
return [p for m, p in engine.sent if m == command]
@pytest.mark.unit
def test_a_route_disables_the_cache_of_its_context():
engine, context = _context("C1")
context.op_set_interception({"patterns": [{"glob": "**/*"}]})
assert _flags(engine, "Browser.setRequestInterception") == [
{"browserContextId": "C1", "enabled": True}]
assert _flags(engine, "Browser.setCacheDisabled") == [
{"browserContextId": "C1", "cacheDisabled": True}]
@pytest.mark.unit
def test_the_last_route_gone_enables_the_cache_again():
engine, context = _context("C1")
context.op_set_interception({"patterns": [{"glob": "**/*"}]})
engine.sent.clear()
context.op_set_interception({"patterns": []})
assert _flags(engine, "Browser.setRequestInterception") == [
{"browserContextId": "C1", "enabled": False}]
assert _flags(engine, "Browser.setCacheDisabled") == [
{"browserContextId": "C1", "cacheDisabled": False}]
@pytest.mark.unit
def test_the_default_context_is_addressed_by_absence():
engine, context = _context(None)
context.op_set_interception({"patterns": [{"glob": "**/*"}]})
assert _flags(engine, "Browser.setCacheDisabled") == [
{"cacheDisabled": True}]
@@ -0,0 +1,143 @@
"""A context that ends leaves no content process behind, on a real engine.
⛔ THE KNOWN-BAD INPUT, measured on the engine before the fix: a page that registers a service worker whose
script is `for (;;) {}` (an endless install handler) keeps its content process alive after its context is
closed. The worker never answers the shutdown, no shutdown starts for the process, and nothing else ends it:
four such contexts left four more processes (8 web content processes at the end instead of 4). The engine's
BrowserContext now waits a few seconds for the processes of its container once its pages are gone, and kills the
ones that stay.
The test closes five such contexts in a row and counts the web content processes under the engine after each.
The first context may add ONE process that is not the leak (the engine starts a spare content process when the
first page takes one, and Linux keeps it), so the count after the fifth must not be above the count after the
SECOND: a flat line from there on (on the old engine every context adds one: [4, 5, 6, 7, 8]).
The engine that does it is not published when this file is written: `engine_at_least` makes the test wait for
it, and on an older engine it is skipped, never passed.
"""
from __future__ import annotations
import asyncio
import json
import threading
import time
import pytest
import websockets # noqa: F401 - the dev extra installs it: a missing one is a failure, never a skip
from websockets.asyncio.client import connect # noqa: E402
from _servers import LocalServer # noqa: E402
pytestmark = pytest.mark.e2e
ENGINE_WITH_THE_FIX = "firefox-61"
PAGE = (b"<!doctype html><title>sw</title><script>"
b"navigator.serviceWorker.register('/sw.js').catch(e => { document.title = 'ERR ' + e; });</script>")
WORKER = b"self.addEventListener('install', () => { for (;;) {} }); self.addEventListener('fetch', () => {});"
def _serve():
import http.server
class Handler(http.server.BaseHTTPRequestHandler):
def do_GET(self):
body, kind = (WORKER, "text/javascript") if self.path.startswith("/sw.js") else (PAGE, "text/html")
self.send_response(200)
self.send_header("Content-Type", kind)
self.send_header("Content-Length", str(len(body)))
self.send_header("Cache-Control", "no-store")
self.end_headers()
self.wfile.write(body)
def log_message(self, *args):
pass
server = LocalServer(("127.0.0.1", 0), Handler)
threading.Thread(target=server.serve_forever, daemon=True).start()
return server, "http://127.0.0.1:%d" % server.server_address[1]
def _web_processes(root_pid):
import psutil
found = set()
try:
children = psutil.Process(root_pid).children(recursive=True)
except psutil.Error:
return found
for process in children:
try:
command = " ".join(process.cmdline())
except psutil.Error:
continue
if "-contentproc" in command and command.rstrip().endswith(" tab"):
found.add(process.pid)
return found
class _Client:
"""The few calls of Playwright's protocol this test needs, over the served WebSocket."""
def __init__(self, ws):
self.ws, self.objects, self.counter = ws, {}, 0
async def call(self, guid, method, params=None):
self.counter += 1
await self.ws.send(json.dumps({"id": self.counter, "guid": guid, "method": method,
"params": params or {}, "metadata": {}}))
while True:
message = json.loads(await self.ws.recv())
if message.get("method") == "__create__":
self.objects[message["params"]["guid"]] = message["params"]
if message.get("id") == self.counter:
assert "error" not in message, message
return message.get("result")
async def start(self):
await self.call("", "initialize", {"sdkLanguage": "python"})
self.browser = [g for g, o in self.objects.items() if o["type"] == "Browser"][0]
async def new_page(self):
context = (await self.call(self.browser, "newContext", {}))["context"]["guid"]
page = (await self.call(context, "newPage", {}))["page"]["guid"]
frame = self.objects[page]["initializer"]["mainFrame"]["guid"]
return context, frame
def test_closed_contexts_with_a_never_stopping_service_worker_leave_no_process(firefox_binary, engine_at_least):
engine_at_least(ENGINE_WITH_THE_FIX)
from invisible_playwright import launch_server
server, base = _serve()
launched = launch_server(host="127.0.0.1", port=0, headless=True, virtual_display=False, humanize=False,
seed=4266, binary_path=firefox_binary, launch_timeout_ms=180_000)
async def drive():
counts = []
async with connect(launched.ws_endpoint, max_size=None) as ws:
client = _Client(ws)
await client.start()
for i in range(5):
context, frame = await client.new_page()
await client.call(frame, "goto", {"url": "%s/?i=%d" % (base, i), "waitUntil": "load", "timeout": 30000})
await asyncio.sleep(1.0) # the worker is registered, its install loop is running
await client.call(context, "close")
deadline = time.time() + 10
settled = None
while time.time() < deadline: # the count after the close, once it stops moving
now = _web_processes(launched.process.pid)
if settled is not None and len(now) == settled:
break
settled = len(now)
await asyncio.sleep(1.0)
counts.append(len(_web_processes(launched.process.pid)))
return counts
try:
counts = asyncio.run(drive())
finally:
launched.close()
server.shutdown()
assert counts[4] <= counts[1], "web content processes after each closed context: %r" % (counts,)
@@ -0,0 +1,106 @@
"""A frame that left the page answers a call with "Frame was detached", as Playwright's driver does.
⛔ THE KNOWN-BAD INPUT: an iframe removed from the DOM (in the same process or in another, with a process per site).
The lifecycle retires it and the server disposed the frame's dispatcher on the spot, so the next call on the Frame
object named a guid that no longer existed and was answered "Target page, context or browser has been closed". The
page was not closed. Measured on the engine with the Fission work, in both places: `frame.frame_element()`,
`frame.evaluate(...)`, `frame.content()` and `frame.query_selector(...)` on a removed iframe, every one. The driver
never disposes a Frame at detach: the call reaches the dispatcher, which refuses "Frame was detached" (the page and its
other frames keep working, and a script that handles that error finds it).
"""
from types import SimpleNamespace
from unittest.mock import Mock
import pytest
from invisible_core.juggler.connection import EventListeners
from invisible_core.juggler.lifecycle import Lifecycle
from invisible_playwright._juggler.dispatcher import Dispatcher, ProtocolException, TargetClosedError
from invisible_playwright._juggler.server import FrameDispatcher, JugglerServer, PageDispatcher
pytestmark = pytest.mark.unit
@pytest.fixture
def page():
server = JugglerServer()
messages = []
server.attach(SimpleNamespace(emit_message=messages.append))
context = Dispatcher(server, None)
context.options = {}
page = object.__new__(PageDispatcher)
page.context = context
page.lifecycle = Lifecycle(EventListeners(), "session")
page.injected = Mock()
page.actions = Mock()
page._frames = {}
page._navigation_requests = {}
page._announced_closed = False
Dispatcher.__init__(page, server, context)
page.frame = FrameDispatcher(server, page, "main")
for fid, parent in (("main", None), ("payment", "main"), ("widget", "payment")):
page.lifecycle._on_event("Page.frameAttached", {"frameId": fid, "parentFrameId": parent})
page.messages = messages
page.lifecycle.announce = page._on_lifecycle
return page
def _call(page, frame, method, params=None):
return page.server.handle({"guid": frame.guid, "method": method, "params": params or {}})
def _detach(page, frame_id):
page.lifecycle._on_event("Page.frameDetached", {"frameId": frame_id})
@pytest.mark.parametrize("method", ["frameElement", "content", "title", "evaluateExpression", "querySelector"])
def test_a_call_on_a_detached_frame_says_it_was_detached_not_that_the_target_closed(page, method):
payment = page.frame_for("payment")
_detach(page, "payment")
with pytest.raises(ProtocolException, match="detached") as raised:
_call(page, payment, method, {"selector": "#h", "expression": "1"})
assert not isinstance(raised.value, TargetClosedError)
def test_the_frame_is_told_detached_and_not_disposed(page):
payment = page.frame_for("payment")
page.messages.clear()
_detach(page, "payment")
mine = [m for m in page.messages if m.get("guid") == payment.guid or
(m.get("params") or {}).get("frame", {}).get("guid") == payment.guid]
assert [m["method"] for m in mine] == ["frameDetached"], mine
assert not payment.disposed and payment.guid in page.server._objects
assert page._frames.get("payment") is None
def test_the_handles_of_a_detached_frame_go_with_it(page):
from invisible_playwright._juggler.server import ElementHandleDispatcher
payment = page.frame_for("payment")
handle = ElementHandleDispatcher(page.server, payment, "object-1")
_detach(page, "payment")
assert handle.disposed and handle.guid not in page.server._objects
def test_the_other_frames_and_the_page_keep_answering(page):
page.frame_for("payment")
_detach(page, "payment")
with pytest.raises(ProtocolException) as raised:
_call(page, page.frame, "no-such-method")
assert "detached" not in str(raised.value) # the main frame is not the detached one
def test_a_detached_frame_leaves_with_its_page(page):
payment = page.frame_for("payment")
_detach(page, "payment")
page.dispose()
assert payment.guid not in page.server._objects and payment.disposed
def test_a_frame_that_comes_back_with_the_same_id_is_a_new_one(page):
first = page.frame_for("payment")
_detach(page, "payment")
page.lifecycle._on_event("Page.frameAttached", {"frameId": "payment", "parentFrameId": "main"})
again = page.frame_for("payment")
assert again is not first and not again.detached
with pytest.raises(ProtocolException, match="detached"):
_call(page, first, "content")
@@ -0,0 +1,98 @@
"""A dialog is an object of the protocol, and the server never reads the client.
⛔ WHAT IT REPLACES. The dialog was a "fused" class: no `__create__`, no guid,
no channel. The server built it from the client's own registry
(`Server.twin`, bound by `bind_impl_objects`) and handed it to the context by
calling a client function. Now it is announced with `__create__` under its
Page, and the `dialog` event of the context carries its channel, like every
other object.
Known-bad: `PageDispatcher._emit_fused_dialog` and `Server.bind_twins`.
"""
from __future__ import annotations
from typing import Any, Dict, List
from invisible_playwright._juggler import dispatcher as dispatcher_mod
from invisible_playwright._juggler.dispatcher import Server
from invisible_playwright._juggler.server import PageDispatcher
class _Wire:
"""The transport, reduced to what the server sends up."""
def __init__(self) -> None:
self.sent: List[Dict] = []
def emit_message(self, message: Dict) -> None:
self.sent.append(message)
class _Context:
"""The context's `emit` goes where a real one does: up the wire."""
def __init__(self, server: Server, guid: str) -> None:
self.server = server
self.guid = guid
def emit(self, method: str, params: Dict) -> None:
self.server.send_up({"guid": self.guid, "method": method,
"params": params})
def _opened() -> "tuple[Server, _Wire, PageDispatcher]":
server = Server()
wire = _Wire()
server.attach(wire)
page = PageDispatcher.__new__(PageDispatcher)
page.server = server
page.guid = "page@1"
page.parent = None
page.context = _Context(server, "browsercontext@1")
page.number = 1
page._dialogs_open = {}
page._dialogs_seen = 0
page._on_juggler_event("Page.dialogOpened", {
"dialogId": "d1", "type": "prompt", "message": "Name?",
"defaultValue": "x"})
return server, wire, page
def test_a_dialog_is_announced_with_a_guid_under_its_page_before_the_event():
_server, wire, _page = _opened()
created = [m for m in wire.sent if m["method"] == "__create__"]
assert len(created) == 1
create = created[0]
assert create["guid"] == "page@1" # the parent is the Page
assert create["params"]["type"] == "Dialog"
assert create["params"]["guid"].startswith("dialog@")
assert create["params"]["initializer"] == {
"type": "prompt", "message": "Name?", "defaultValue": "x",
"page": {"guid": "page@1"}}
event = [m for m in wire.sent if m["method"] == "dialog"]
assert len(event) == 1
assert event[0]["guid"] == "browsercontext@1"
assert event[0]["params"] == {"dialog": {"guid": create["params"]["guid"]}}
# ORDER IS THE PROTOCOL: the object exists on the client before it is named.
assert wire.sent.index(create) < wire.sent.index(event[0])
def test_the_server_has_no_way_to_reach_the_clients_objects():
server = Server()
for gone in ("bind_twins", "twin", "deliver", "call_soon", "run_blocking"):
assert not hasattr(server, gone), gone
assert not hasattr(PageDispatcher, "_emit_fused_dialog")
assert not hasattr(PageDispatcher, "send_async")
def test_a_dialog_answers_accept_and_dismiss_by_its_guid():
server, _wire, page = _opened()
sent: List[Any] = []
page.send = lambda command, params, timeout=None: sent.append((command, params))
guid = next(o.guid for o in server._objects.values() if o.TYPE == "Dialog")
server.handle({"guid": guid, "method": "dismiss", "params": {}})
assert sent == [("Page.handleDialog", {"dialogId": "d1", "accept": False})]
def test_the_module_keeps_no_client_registry():
assert not hasattr(dispatcher_mod.Server(), "_twins")
@@ -6,18 +6,18 @@ handler registered) or a handler's own `accept()`. A page timing `alert()`'s
return saw single digits of milliseconds where every hand shows hundreds. The
stock driver behaves the same, which is why a site can afford to test for it.
Known-bad: `PageDispatcher.send_async` forwarding every command straight to
Known-bad: `PageDispatcher.answer_dialog` forwarding every command straight to
`send`, with nothing recorded at `Page.dialogOpened`.
"""
from __future__ import annotations
import asyncio
from typing import Any, Dict, List
import pytest
from invisible_playwright._juggler import dialogs
from invisible_playwright._juggler import server as server_mod
from invisible_playwright._juggler.dispatcher import Server
from invisible_playwright._juggler.server import PageDispatcher
SEED = 4242
@@ -50,16 +50,6 @@ def test_only_the_remainder_is_waited():
# ── the wiring ─────────────────────────────────────────────────────────────
class _Server:
"""The transport: it runs blocking work, and it knows NO seed. The seed
lives on the browser (`BrowserDispatcher.session_seed`), reached from a
page through `page.browser`; 0.46.0's first CI run hung three e2e tests
because the pause read it from here."""
async def run_blocking(self, fn: Any, *args: Any) -> Any:
return fn(*args)
class _Browser:
def __init__(self, seed: Any) -> None:
self.session_seed = seed
@@ -69,17 +59,21 @@ class _Context:
def __init__(self, seed: Any) -> None:
self.browser = _Browser(seed)
def emit(self, method: str, params: Dict) -> None:
pass
def _page(seed: Any, sent: List[Any]) -> PageDispatcher:
"""The dispatcher's dialog half alone: no engine, no client."""
page = PageDispatcher.__new__(PageDispatcher)
page.server = _Server()
page.server = Server()
page.guid = "page@1"
page.parent = None
page.context = _Context(seed)
page.number = 1
page._dialogs_open = {}
page._dialogs_seen = 0
page.send = lambda command, params, timeout=None: sent.append((command, params))
page._emit_fused_dialog = lambda *a: None
return page
@@ -94,7 +88,7 @@ def _open_then_answer(monkeypatch: Any, seed: Any, handler_took_s: float,
page._on_juggler_event("Page.dialogOpened",
{"dialogId": "d1", "type": "confirm", "message": message})
clock["now"] += handler_took_s
asyncio.run(page.send_async("Page.handleDialog", {"dialogId": "d1", "accept": True}))
page.answer_dialog("Page.handleDialog", {"dialogId": "d1", "accept": True})
return {"slept": slept, "sent": sent, "page": page}
@@ -128,8 +122,8 @@ def test_the_second_dialog_of_a_page_draws_its_own_pause(monkeypatch):
for dialog_id in ("d1", "d2"):
page._on_juggler_event("Page.dialogOpened",
{"dialogId": dialog_id, "type": "alert", "message": "Saved"})
asyncio.run(page.send_async("Page.handleDialog",
{"dialogId": dialog_id, "accept": True}))
page.answer_dialog("Page.handleDialog",
{"dialogId": dialog_id, "accept": True})
assert len(slept) == 2 and slept[0] != slept[1]
assert slept == [dialogs.plan_answer_ms(SEED, 1, n, "Saved") / 1000.0 for n in (1, 2)]
@@ -141,18 +135,28 @@ def test_the_answer_goes_out_even_when_the_pause_cannot_be_planned(monkeypatch):
sent: List[Any] = []
monkeypatch.setattr(server_mod.time, "sleep", slept.append)
page = _page(SEED, sent)
page.context = None # no browser to ask: the planning raises
page._on_juggler_event("Page.dialogOpened",
{"dialogId": "d1", "type": "alert", "message": "Hi"})
page.context = None # no browser to ask: the planning raises
with pytest.warns(RuntimeWarning, match="answering at once"):
asyncio.run(page.send_async("Page.handleDialog", {"dialogId": "d1", "accept": True}))
page.answer_dialog("Page.handleDialog", {"dialogId": "d1", "accept": True})
assert slept == [] and sent == [("Page.handleDialog", {"dialogId": "d1", "accept": True})]
def test_a_command_that_is_not_a_dialog_goes_straight_through(monkeypatch):
def test_an_answer_over_the_channel_waits_the_same_pause(monkeypatch):
"""The client's `dialog.accept()` arrives as a call on the Dialog object;
it must go through the pause too, not straight to `Page.handleDialog`."""
clock = {"now": 100.0}
slept: List[float] = []
sent: List[Any] = []
monkeypatch.setattr(server_mod.time, "monotonic", lambda: clock["now"])
monkeypatch.setattr(server_mod.time, "sleep", slept.append)
page = _page(SEED, sent)
asyncio.run(page.send_async("Page.bringToFront", {}))
assert slept == [] and sent == [("Page.bringToFront", {})]
page._on_juggler_event("Page.dialogOpened",
{"dialogId": "d1", "type": "prompt", "message": "Name?"})
dialog = next(o for o in page.server._objects.values() if o.TYPE == "Dialog")
page.server.handle({"guid": dialog.guid, "method": "accept",
"params": {"promptText": "Ada"}})
assert slept == [pytest.approx(dialogs.plan_answer_ms(SEED, 1, 1, "Name?") / 1000.0)]
assert sent == [("Page.handleDialog",
{"dialogId": "d1", "accept": True, "promptText": "Ada"})]
@@ -39,8 +39,7 @@ def display(monkeypatch):
vd = RecordingDisplay()
geo = types.SimpleNamespace(timezone="Europe/Rome",
locale=SessionLocale.of("it-IT"),
egress_ip=None,
srflx_to_declare=lambda: None)
egress_ip=None)
def refuse(**_kw):
raise FontManifestMismatch("the engine does not carry these faces")
@@ -0,0 +1,92 @@
"""`grant_permissions(["geolocation"])` grants the permission the page asks for.
⛔ The names a caller uses (`geolocation`, `notifications`) are the ones of the web platform; the engine keeps a
grant under its own (`geo`, `desktop-notification`). The wrapper passed the web names through, the engine stored
a grant under a name it never reads, and the page was asked, or refused, as if nothing had been granted:
`navigator.geolocation.getCurrentPosition` ended in a denial with a context that had been granted the permission
and given a position. The Playwright client of this browser translates the five names it knows and refuses any
other (playwright-core `ffBrowser.js`, `doGrantPermissions`); so does the wrapper now.
A grant with no origin was sent as the empty string, and the engine finds the origin of a page with
`find(key => url.startsWith(key))`, whose answer `''` is false: it fell back to `'*'`, which held nothing. No origin
is `'*'`, as it is for the Playwright client of this browser, and as the grant made with the context already was.
Red before: the page answers PERMISSION_DENIED (code 1) or never answers.
"""
from __future__ import annotations
import threading
from http.server import BaseHTTPRequestHandler
import pytest
from _servers import LocalServer
READ = """() => new Promise(resolve => {
const timer = setTimeout(() => resolve({timeout: true}), 8000);
navigator.geolocation.getCurrentPosition(
p => { clearTimeout(timer); resolve({lat: p.coords.latitude, lon: p.coords.longitude}); },
e => { clearTimeout(timer); resolve({error: e.code, message: e.message}); });
})"""
@pytest.fixture
def local_page_url():
class Handler(BaseHTTPRequestHandler):
timeout = 5
def log_message(self, *args):
pass
def do_GET(self):
body = b"<!doctype html><title>geo</title><p>geo"
self.send_response(200)
self.send_header("Content-Type", "text/html")
self.send_header("Content-Length", str(len(body)))
self.end_headers()
self.wfile.write(body)
server = LocalServer(("127.0.0.1", 0), Handler)
thread = threading.Thread(target=server.serve_forever, daemon=True)
thread.start()
try:
yield "http://127.0.0.1:%d/" % server.server_address[1]
finally:
server.shutdown()
server.server_close()
thread.join()
@pytest.mark.e2e
def test_a_granted_geolocation_gives_the_page_the_position(firefox_binary, local_page_url):
from invisible_playwright import InvisiblePlaywright
with InvisiblePlaywright(seed=42, binary_path=firefox_binary, humanize=False, headless=True) as browser:
context = browser.new_context(geolocation={"latitude": 41.9, "longitude": 12.5})
context.grant_permissions(["geolocation"])
page = context.new_page()
page.goto(local_page_url)
answer = page.evaluate(READ)
assert answer == {"lat": 41.9, "lon": 12.5}, answer
@pytest.mark.e2e
def test_a_permission_granted_when_the_context_is_made_is_the_same(firefox_binary, local_page_url):
from invisible_playwright import InvisiblePlaywright
with InvisiblePlaywright(seed=42, binary_path=firefox_binary, humanize=False, headless=True) as browser:
context = browser.new_context(geolocation={"latitude": 45.4, "longitude": 9.2}, permissions=["geolocation"])
page = context.new_page()
page.goto(local_page_url)
answer = page.evaluate(READ)
assert answer == {"lat": 45.4, "lon": 9.2}, answer
@pytest.mark.e2e
def test_a_name_outside_the_table_is_refused_and_nothing_is_granted(firefox_binary, local_page_url):
from invisible_playwright import InvisiblePlaywright
with InvisiblePlaywright(seed=42, binary_path=firefox_binary, humanize=False, headless=True) as browser:
context = browser.new_context(geolocation={"latitude": 41.9, "longitude": 12.5})
with pytest.raises(Exception, match="Unknown permission: camera"):
context.grant_permissions(["geolocation", "camera"])
@@ -0,0 +1,155 @@
"""A launch that names no session gets one: the profile is always a composed session.
Before, `op_launch` wrote into `user.js` only the prefs the client sent. The launcher
(`InvisiblePlaywright`, `launch_server`) sends a composed session, but a bare
`BrowserType.launch` from any other client of the server (Playwright's own suite, a
script on `invisible_playwright._pw`) sent none, and the browser was the engine with
Mozilla's defaults: no persona, and on Linux the first-run policy tab that makes
`Browser.newPage` refuse with "Unexpected number of tabs in the new window: 2".
Here, with the engine replaced by a stub, what the profile holds is read back from
`user.js`: an unmarked launch gets the session `InvisiblePlaywright()` composes (with
the caller's prefs on top), and a composed one is written as it came.
"""
from __future__ import annotations
import json
import pathlib
import re
import pytest
from invisible_core.juggler.connection import EventListeners
from invisible_playwright import _session
from invisible_playwright._juggler import server as module
from invisible_playwright._juggler.server import (SESSION_SEED_PREF, BrowserTypeDispatcher,
JugglerServer)
# Read with a default so that, on the code before the fix, the test fails on what the
# profile holds and not on an import.
COMPOSED_PREF = getattr(module, "COMPOSED_PREF", "invisible.server.composed")
_LINE = re.compile(r'^user_pref\("([^"]+)",\s*(.*)\);\s*$')
class _Engine(EventListeners):
def __init__(self):
EventListeners.__init__(self)
def send(self, method, params=None, session=None, timeout=30.0):
return {"browserContextId": "ctx-1", "targetId": "t-1"}
def startup_send(self, method, params=None):
return self.send(method, params)
def close(self, timeout=5.0):
pass
def _launch(monkeypatch, prefs, env=None):
"""Launch with these firefoxUserPrefs (and protocol `env`); return what `user.js` holds and the
environment the engine was started with."""
server = JugglerServer()
server.attach(type("R", (), {"emit_message": lambda self, m: None})())
seen = {}
def fake_launch(executable, profile_dir, **kwargs):
seen["prefs"] = _read(pathlib.Path(profile_dir) / "user.js")
seen["env"] = dict(kwargs.get("env") or {})
return _Engine()
monkeypatch.setattr(module.juggler, "launch", fake_launch)
params = {"executablePath": "x", "firefoxUserPrefs": prefs}
if env is not None:
params["env"] = [{"name": k, "value": v} for k, v in env.items()]
try:
BrowserTypeDispatcher(server).op_launch(params)
finally:
server.shutdown()
return seen
def _user_js(monkeypatch, prefs):
return _launch(monkeypatch, prefs)["prefs"]
def _read(path):
out = {}
for line in path.read_text(encoding="utf-8").splitlines():
m = _LINE.match(line)
if m:
out[m.group(1)] = json.loads(m.group(2))
return out
@pytest.mark.unit
def test_a_launch_that_names_no_session_writes_a_composed_one(monkeypatch):
written = _user_js(monkeypatch, {})
# The Terms of Use the core declares accepted: without them Linux opens the policy tab.
assert written.get("termsofuse.acceptedVersion") == 4, (
"a bare launch wrote no session into the profile: %d prefs" % len(written))
composed, _ = _session.default_session("x")
missing = sorted(k for k in composed if k not in written and not k.startswith("invisible.server."))
assert not missing, "prefs of the composed session absent from user.js: %s" % missing[:10]
assert COMPOSED_PREF not in written and SESSION_SEED_PREF not in written, (
"the server's own keys reached the profile")
@pytest.mark.unit
def test_the_caller_s_prefs_go_on_top_of_the_composed_session(monkeypatch):
written = _user_js(monkeypatch, {"termsofuse.acceptedVersion": 9, "a.pref.of.the.caller": True})
assert written["termsofuse.acceptedVersion"] == 9
assert written["a.pref.of.the.caller"] is True
assert "fission.webContentIsolationStrategy" in written
@pytest.mark.unit
def test_a_composed_session_is_written_as_it_came(monkeypatch):
def refuse(*_a, **_k):
raise AssertionError("a composed session was composed again on the server")
monkeypatch.setattr(_session, "default_session", refuse)
written = _user_js(monkeypatch, {COMPOSED_PREF: True, "only.this": 1})
assert written == {"only.this": 1}
@pytest.mark.unit
def test_the_launcher_marks_what_it_composes():
"""`build_prefs` is what `InvisiblePlaywright` and `launch_server` (`remote._launch_params`,
through `session._build_prefs`) send as firefoxUserPrefs: each must arrive marked."""
from invisible_core import decide_session_locale
from invisible_core._fpforge import generate_profile
for humanize in (False, True):
prefs = _session.build_prefs(
profile=generate_profile(seed=7), locale=decide_session_locale("en-US"),
timezone="America/New_York", extra_prefs=None, virtual_display=False,
cursor_engine=_session.ENGINE_BINARY, humanize=humanize, session_seed=7)
assert prefs.get(COMPOSED_PREF) is True, humanize
MANIFEST = "STEALTHFOX_FONT_MANIFEST"
@pytest.mark.unit
def test_a_launch_that_names_no_session_starts_with_the_session_s_fonts(monkeypatch):
"""The engine lists its fonts at startup from the manifest this variable names; without it,
the fonts of the machine (`_session.build_env`)."""
monkeypatch.delenv(MANIFEST, raising=False)
env = _launch(monkeypatch, {})["env"]
assert env.get(MANIFEST), "a bare launch started the engine without the font manifest"
assert env[MANIFEST].endswith(".list")
@pytest.mark.unit
def test_a_variable_the_caller_names_wins_over_the_session_s(monkeypatch):
env = _launch(monkeypatch, {}, env={MANIFEST: "/the/caller/s.list", "DISPLAY": ":7"})["env"]
assert env[MANIFEST] == "/the/caller/s.list"
assert env["DISPLAY"] == ":7"
assert env.get("MOZ_ENABLE_WAYLAND") == "0", "the session's other variables were not added"
@pytest.mark.unit
def test_a_composed_launch_gets_no_variable_it_did_not_send(monkeypatch):
env = _launch(monkeypatch, {COMPOSED_PREF: True}, env={"ONLY": "1"})["env"]
assert MANIFEST not in env and "MOZ_ENABLE_WAYLAND" not in env, sorted(env)
@@ -0,0 +1,152 @@
"""A browser launched without a session is still a session, on the engine (see the unit file of the same name).
A bare `firefox.launch()` on the server's client (`invisible_playwright._pw`, the client Playwright's own
suite drives) wrote no prefs of the core: the engine came up with Mozilla's defaults. On Linux its first
window then held the first-run policy tab next to the page's (the Terms of Use, which the core declares
accepted, were not), and the first `new_page` failed with "Browser.newPage: Unexpected number of tabs in
the new window: 2", 15 times in 15 on firefox-61 and on the firefox-62 candidate. Every value a page read
was the engine's own default, not a persona: the Linux engine said "X11; Linux" where every session says
Windows.
And the remote transport (`launch_server`, what a remote client drives): every context a client opens on the
served browser lives in the profile the server composed, so each says the same Windows machine.
"""
from __future__ import annotations
import pytest
pytestmark = pytest.mark.e2e
_READ = "() => [navigator.userAgent, navigator.platform, navigator.hardwareConcurrency]"
def test_a_bare_launch_has_one_tab_and_a_persona(firefox_binary):
from invisible_playwright._pw.sync_api import sync_playwright
for attempt in range(3): # the policy tab came in every first window: three are three chances
with sync_playwright() as p:
browser = p.firefox.launch(executable_path=firefox_binary, headless=True)
try:
context = browser.new_context()
page = context.new_page() # refused before: "Unexpected number of tabs: 2"
agent, platform, cores = page.evaluate(_READ)
assert len(context.pages) == 1
assert "Windows NT" in agent and platform == "Win32", (
"a bare launch is the engine's defaults, not a session: %r %r" % (agent, platform))
context.close()
finally:
browser.close()
async def _two_contexts(endpoint):
"""Two contexts on the served browser, a page in each, what each page reads; a client written on
`websockets` alone, as in test_a_served_browser_answers_a_plain_client_e2e.py."""
import json
from websockets.asyncio.client import connect
objects, counter = {}, [0]
async with connect(endpoint, max_size=None) as ws:
async def call(guid, method, params=None):
counter[0] += 1
await ws.send(json.dumps({"id": counter[0], "guid": guid, "method": method,
"params": params or {}, "metadata": {}}))
while True:
m = json.loads(await ws.recv())
if m.get("method") == "__create__":
objects[m["params"]["guid"]] = m["params"]
if m.get("id") == counter[0]:
assert "error" not in m, m
return m.get("result")
await call("", "initialize", {"sdkLanguage": "python"})
browser = [g for g, p in objects.items() if p["type"] == "Browser"][0]
seen = []
for _ in range(2):
ctx = (await call(browser, "newContext", {}))["context"]["guid"]
page = (await call(ctx, "newPage", {}))["page"]["guid"]
frame = objects[page]["initializer"]["mainFrame"]["guid"]
value = (await call(frame, "evaluateExpression", {
"expression": "() => JSON.stringify([navigator.userAgent, navigator.platform, "
"navigator.hardwareConcurrency])",
"isFunction": True, "arg": {"value": {"v": "undefined"}, "handles": []}}))["value"]
seen.append(json.loads(value["s"]))
await call(ctx, "close", {})
return seen
def test_every_context_of_a_served_browser_is_the_session(firefox_binary):
import asyncio
import websockets # noqa: F401 - the dev extra installs it: a missing one is a failure, never a skip
from invisible_playwright._juggler.remote import launch_server
server = launch_server(headless=True, binary_path=firefox_binary, locale="en-US",
timezone="America/New_York")
try:
seen = asyncio.run(asyncio.wait_for(_two_contexts(server.ws_endpoint), 120))
finally:
server.close()
assert seen[0] == seen[1], "two contexts of one served session are two machines: %r" % seen
agent, platform, _ = seen[0]
assert "Windows NT" in agent and platform == "Win32", seen[0]
def test_a_bare_launch_behind_a_proxy_is_composed_through_it(firefox_binary, monkeypatch):
"""A bare launch behind a proxy gets a session composed THROUGH that proxy (the egress, the timezone and
the locale measured there, the network declared from the seed), and the page's WebRTC gather still
completes with mDNS hosts. The declaration (STEALTHFOX_WEBRTC_NETWORK) is read by the new engine only;
its value is asserted without a browser in test_the_network_declaration_reaches_the_engine.py. The
proxy is the local TCP-only SOCKS5 of test_webrtc_realness.py; the egress the session measures through
it is answered with a TEST-NET address (RFC 5737), as in those tests."""
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
import threading
from invisible_core import decide_session_locale
from invisible_core._geo import SessionGeo
from invisible_playwright import _session
from invisible_playwright._pw.sync_api import sync_playwright
from test_webrtc_realness import _PROBE_JS, _Socks5TcpOnly, candidates, host_is_mdns
egress = "203.0.113.7"
monkeypatch.delenv("STEALTHFOX_WEBRTC_NETWORK", raising=False)
measured = []
def through_the_proxy(timezone, proxy, locale):
measured.append(proxy)
return SessionGeo("America/New_York", egress,
locale=decide_session_locale("en-US"))
monkeypatch.setattr(_session, "session_geo", through_the_proxy, raising=False) # absent before the fix
class Page(BaseHTTPRequestHandler):
timeout = 5
def do_GET(self):
self.send_response(200)
self.send_header("Content-Type", "text/html")
self.end_headers()
self.wfile.write(b"<html><body>wrtc</body></html>")
def log_message(self, *a):
pass
httpd = ThreadingHTTPServer(("127.0.0.1", 0), Page)
threading.Thread(target=httpd.serve_forever, daemon=True).start()
socks = _Socks5TcpOnly()
try:
with sync_playwright() as p:
browser = p.firefox.launch(executable_path=firefox_binary, headless=True,
proxy={"server": "socks5://127.0.0.1:%d" % socks.port})
try:
page = browser.new_context().new_page()
page.goto("http://127.0.0.1:%d/" % httpd.server_address[1], wait_until="domcontentloaded")
res = page.evaluate(_PROBE_JS)
finally:
browser.close()
finally:
socks.close()
httpd.shutdown()
cands = candidates(res["candidates"])
assert cands and host_is_mdns(cands), "behind the proxy the gather is blocked or leaks a host: %s" % res["candidates"]
assert measured and measured[0] and measured[0].get("server", "").startswith("socks5://"), (
"the session was not composed through the launch's proxy: %r" % measured)
@@ -0,0 +1,106 @@
"""The body of a response of a document the tab left is evicted, on a real engine.
⛔ THE KNOWN-BAD INPUT, measured on firefox-59 over 95 sites in one reused tab: the engine's
`ResponseStorage` kept one entry per request for good, and the bodies of every page the tab had
left (compressed bytes, HTML, CSS: 105 MB, 5,000 entries) stayed readable and held in the parent
process, up to its 100 MB cap. A retail Firefox holds none of them.
Chromium clears a tab's bodies when the main frame commits a navigation (`DidCommitLoad`, which
keeps only the loader that committed), and the engine does the same from firefox-60: the body of
a document the tab left, and of its sub-resources, answers "evicted" (Playwright's own message for
a body over the engine's cap), while the bodies of the document that is current stay readable.
Also here: nothing else is lost. A second context loads a page, and a context that was closed
leaves the browser usable.
The engine that does it is not published when this file is written: `engine_at_least` makes the
test wait for it, and on an older engine it is skipped, never passed.
"""
from __future__ import annotations
import threading
import pytest
from _servers import LocalServer
pytestmark = pytest.mark.e2e
PAGES = {
"/a.html": (b"<html><head><link rel=stylesheet href=/a.css><script src=/a.js></script></head>"
b"<body>document A</body></html>", "text/html"),
"/a.css": (b"body{color:red} /* A */", "text/css"),
"/a.js": (b"window.fromA = 1;", "text/javascript"),
"/b.html": (b"<html><head><script src=/b.js></script></head><body>document B</body></html>",
"text/html"),
"/b.js": (b"window.fromB = 2;", "text/javascript"),
}
def _serve():
import http.server
class Handler(http.server.BaseHTTPRequestHandler):
def do_GET(self):
body, content_type = PAGES.get(self.path, (b"", "text/plain"))
self.send_response(200 if self.path in PAGES else 404)
self.send_header("Content-Type", content_type)
self.send_header("Content-Length", str(len(body)))
self.end_headers()
self.wfile.write(body)
def log_message(self, *args):
pass
server = LocalServer(("127.0.0.1", 0), Handler)
threading.Thread(target=server.serve_forever, daemon=True).start()
return server, "http://127.0.0.1:%d" % server.server_address[1]
def test_the_body_of_a_document_the_tab_left_is_evicted(firefox_binary, engine_at_least):
engine_at_least("firefox-60")
from invisible_playwright import InvisiblePlaywright
server, base = _serve()
try:
with InvisiblePlaywright(seed=4249, binary_path=firefox_binary, headless=True) as browser:
page = browser.new_page()
responses = {}
page.on("response", lambda r: responses.setdefault(r.url.rsplit("/", 1)[-1], r))
page.goto(base + "/a.html", wait_until="load", timeout=20_000)
page.wait_for_timeout(300)
assert b"document A" in responses["a.html"].body()
assert b"/* A */" in responses["a.css"].body(), "the current document's sub-resource is readable"
page.goto(base + "/b.html", wait_until="load", timeout=20_000)
page.wait_for_timeout(300)
assert b"document B" in responses["b.html"].body(), "the document that committed keeps its body"
assert b"fromB" in responses["b.js"].body()
for name in ("a.html", "a.css", "a.js"):
with pytest.raises(Exception) as err:
responses[name].body()
assert "evicted" in str(err.value).lower(), (name, str(err.value))
finally:
server.shutdown()
def test_nothing_else_is_lost_when_the_bodies_go(firefox_binary, engine_at_least):
engine_at_least("firefox-60")
from invisible_playwright import InvisiblePlaywright
server, base = _serve()
try:
with InvisiblePlaywright(seed=4250, binary_path=firefox_binary, headless=True) as browser:
page = browser.new_page()
for i in range(6):
page.goto(base + "/%s.html" % "ab"[i % 2], wait_until="load", timeout=20_000)
second = browser.new_page()
second.goto(base + "/a.html", wait_until="load", timeout=20_000)
assert "document A" in second.content()
second.close()
page.goto(base + "/b.html", wait_until="load", timeout=20_000)
assert "document B" in page.content()
finally:
server.shutdown()
@@ -16,6 +16,7 @@ from __future__ import annotations
import json
import re
import shutil
import sys
import tempfile
from pathlib import Path
@@ -33,7 +34,7 @@ def _drop(user_js: Path, names) -> int:
variants are other prefs and stay). Returns how many lines went."""
kept, dropped = [], 0
for line in user_js.read_text(encoding="utf-8").splitlines():
m = re.match(r'user_pref\(("(?:[^"\]|\.)*"),', line)
m = re.match(r'user_pref\(("(?:[^"\\]|\\.)*"),', line)
if m and json.loads(m.group(1)) in names:
dropped += 1
else:
@@ -54,16 +55,26 @@ def _launch(firefox_binary, drop):
assert _drop(Path(profile_dir) / "user.js", {drop}) == 1, (
"%s is not declared by this core, so there is nothing to remove" % drop)
return conn.launch(firefox_binary, profile_dir, headless=True,
env=plan.env, ready_timeout=60.0), profile_dir
# A refusal ends in an abort on purpose, and the crash reporter would open
# a window on the desktop of whoever runs the test.
env=dict(plan.env, MOZ_CRASHREPORTER_DISABLE="1"),
ready_timeout=60.0), profile_dir
except BaseException:
shutil.rmtree(profile_dir, ignore_errors=True)
raise
# Linux only: on Windows the engine takes these from the Windows toolkit as retail does
# (StealthVerifySystemTheme in widget/StealthSystemFonts.cpp returns unless MOZ_WIDGET_GTK), so a
# missing ui.* pref does not refuse there (candidate 42673795394's Windows gate: DID NOT RAISE).
ON_WINDOWS = sys.platform == "win32"
@pytest.mark.e2e
@pytest.mark.skipif(ON_WINDOWS, reason="the system theme is declared, and its absence refused, on Linux only")
@pytest.mark.parametrize("pref", MISSING)
def test_a_missing_pref_refuses_the_launch(firefox_binary, engine_at_least, pref):
engine_at_least("firefox-60")
engine_at_least("firefox-64")
with pytest.raises(RuntimeError) as err:
c, profile_dir = _launch(firefox_binary, pref)
# Not reached when the engine refuses: close what must not be running.
@@ -77,7 +88,7 @@ def test_a_missing_pref_refuses_the_launch(firefox_binary, engine_at_least, pref
@pytest.mark.e2e
def test_every_pref_declared_the_launch_succeeds(firefox_binary, engine_at_least):
engine_at_least("firefox-60")
engine_at_least("firefox-64")
c, profile_dir = _launch(firefox_binary, None)
try:
assert c.ready_seen, "the browser did not announce the protocol"
@@ -0,0 +1,62 @@
"""In a real browser, `page.mouse.click` on a button reaches it with ONE
`mousemove` on the click point: the page counts no two consecutive `mousemove`
with the same coordinates.
The unit test (`test_a_click_makes_one_mousemove_at_its_point`) holds the
sequence the engine is sent; this asks the page, which is the only reader that
matters. One browser, humanising on, closed at the end of the test.
"""
from __future__ import annotations
import pytest
from stroke_shape import stroke_problems
PAGE = """<!doctype html><html><body style="margin:0">
<button id="b" style="position:absolute;left:300px;top:200px;width:200px;height:80px">b</button>
<script>
window.moves = []; window.clicks = 0;
document.addEventListener('mousemove', e => window.moves.push([e.clientX, e.clientY]));
document.getElementById('b').addEventListener('click', () => window.clicks++);
</script></body></html>"""
@pytest.mark.e2e
def test_a_humanised_mouse_click_gives_the_page_no_repeated_mousemove(firefox_binary):
from invisible_playwright import InvisiblePlaywright
with InvisiblePlaywright(seed=4251, binary_path=firefox_binary, headless=True,
humanize=True) as browser:
page = browser.new_context().new_page()
page.set_content(PAGE)
page.mouse.click(400, 240)
moves = page.evaluate("window.moves")
assert page.evaluate("window.clicks") == 1
# The SHAPE of the stroke, not its length: the pacer drops a sample it cannot send on
# time, so a loaded machine gives the page 6 to 9 events where an idle one gives 15
# (tests/stroke_shape.py). The Linux gate failed on `len(moves) > 10` with a page that
# had received [[1116, 731], ..., [383, 225], [385, 227], [400, 240]].
assert stroke_problems(moves, (400, 240)) == [], moves
@pytest.mark.e2e
def test_a_stroke_from_standstill_does_not_open_with_the_point_it_stands_on(firefox_binary):
"""After a move that stopped on (500, 300) and a pause, the click's stroke
begins at its first real step: the page's next `mousemove` is not (500, 300)
again."""
import time
from invisible_playwright import InvisiblePlaywright
with InvisiblePlaywright(seed=4252, binary_path=firefox_binary, headless=True,
humanize=True) as browser:
page = browser.new_context().new_page()
page.set_content(PAGE)
page.mouse.move(500, 300)
time.sleep(0.3)
seen = len(page.evaluate("window.moves"))
assert page.evaluate("window.moves")[-1] == [500, 300]
page.mouse.click(400, 240)
moves = page.evaluate("window.moves")
# A stroke left the point it stood on: something before the landing, whatever its count.
assert len(moves) >= seen + 2, moves[seen:]
assert moves[seen] != [500, 300], "the stroke repeated the point it stood on"
@@ -0,0 +1,40 @@
"""NaN, the infinities and -0 are not JSON numbers, so they cross the wire as a tag.
Found by the e2e run with INVPW_WIRE=json: `page.evaluate_handle("() => NaN").json_value()`
passed in process and failed on the strict wire with "$.result.value.n: nan is not JSON". The
server answered `{"n": nan}`, which Python's json writes as the bare word NaN and no other
JSON reader accepts. Playwright's own serializer sends `{"v": "NaN"}`; so must the server.
"""
from __future__ import annotations
import math
import pytest
from invisible_playwright._juggler import wire
from invisible_playwright._juggler._marshal import _serialize
pytestmark = pytest.mark.unit
@pytest.mark.parametrize("value, tag", [
(float("nan"), "NaN"),
(float("inf"), "Infinity"),
(float("-inf"), "-Infinity"),
(-0.0, "-0"),
])
def test_a_non_finite_number_is_a_tag(value, tag):
assert _serialize(value) == {"v": tag}
@pytest.mark.parametrize("value", [float("nan"), float("inf"), float("-inf"), -0.0,
[float("nan"), 1.5], {"a": float("inf")}])
def test_what_the_server_serializes_survives_the_strict_wire(value):
wire.loads(wire.dumps({"result": {"value": _serialize(value)}}))
def test_a_finite_number_stays_a_number():
assert _serialize(1.5) == {"n": 1.5}
assert _serialize(0.0) == {"n": 0.0}
assert _serialize(-3) == {"n": -3}
assert not math.isnan(_serialize(2.0)["n"])
@@ -0,0 +1,91 @@
"""A page reached over IPv6 still gathers host candidates on a machine declared without IPv6.
The default address is looked up for the family of the page's server. The real network may reach the page over IPv6 (a
site with an AAAA record, here a server on `[::1]`), while the declared machine has IPv4 only (`v6=0`): it has no default
address of that family, and the gathering found no address at all - it completed in a few milliseconds with zero
candidates, with no error, even without a proxy (measured on the firefox-63 candidate, Windows, direct).
The machine the persona declares answers with the family it has: one host name (UDP and TCP), ranked 127 (an IPv4-only
machine has one address), exactly as with the page served over IPv4. Hermetic: no proxy, no external network.
Red on an engine before webrtc/declared-interfaces ddaf867f03 (empty gathering).
"""
from __future__ import annotations
import socket
import threading
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
import pytest
from test_webrtc_realness import _e2e_binary, _launch, candidates, host_candidates # noqa: F401
pytestmark = [pytest.mark.e2e, pytest.mark.usefixtures("the_udp_line")]
V4_ONLY = "v4=192.168.31.7;v6=0;p6="
UDP_127, TCP_127 = 2122252543, 2105524479
_GATHER_JS = r"""async () => {
const pc = new RTCPeerConnection({iceServers: []});
pc.createDataChannel('');
const cands = [];
pc.addEventListener('icecandidate', e => { if (e.candidate && e.candidate.candidate) cands.push(e.candidate.candidate); });
await pc.setLocalDescription(await pc.createOffer());
await new Promise(r => setTimeout(r, 2500));
try { pc.close(); } catch (e) {}
return cands;
}"""
class _V6Server(ThreadingHTTPServer):
address_family = socket.AF_INET6
daemon_threads = True
class _Page(BaseHTTPRequestHandler):
timeout = 5
def do_GET(self):
body = b"<!doctype html><title>over ipv6</title><p>page"
self.send_response(200)
self.send_header("Content-Type", "text/html")
self.send_header("Content-Length", str(len(body)))
self.end_headers()
self.wfile.write(body)
def log_message(self, *a):
pass
@pytest.fixture
def page_over_ipv6():
try:
srv = _V6Server(("::1", 0), _Page)
except OSError as exc: # the environment has no IPv6 loopback: the test cannot mean anything, so it says so
pytest.fail("no IPv6 loopback to serve the page on (%s): the test needs [::1]" % exc, pytrace=False)
threading.Thread(target=srv.serve_forever, daemon=True).start()
try:
yield "http://[::1]:%d/" % srv.server_address[1]
finally:
srv.shutdown()
srv.server_close()
def _gather(url, monkeypatch, declaration):
binary = _e2e_binary()
if not binary:
pytest.fail("no patched binary: set STEALTHFOX_E2E_BINARY", pytrace=False)
monkeypatch.setenv("STEALTHFOX_WEBRTC_NETWORK", declaration)
with _launch(binary_path=binary, seed=42) as browser:
page = browser.new_context().new_page()
page.goto(url, wait_until="domcontentloaded", timeout=60000)
assert page.evaluate("location.hostname") == "[::1]"
return host_candidates(candidates(page.evaluate(_GATHER_JS)))
def test_a_page_served_over_ipv6_gets_the_host_candidates_of_an_ipv4_only_machine(page_over_ipv6, monkeypatch):
hosts = _gather(page_over_ipv6, monkeypatch, V4_ONLY)
assert hosts, "an empty gathering: the declared machine found no default address for the family of the page"
by_proto = {proto: sorted((c["priority"] for c in hosts if c["proto"] == proto), reverse=True)
for proto in ("UDP", "TCP")}
assert by_proto == {"UDP": [UDP_127], "TCP": [TCP_127]}, hosts
assert all(c["address"].endswith(".local") for c in hosts), "host candidates are mDNS names, never an address: %r" % hosts
@@ -0,0 +1,131 @@
"""A request and its response weigh what they hold, and let go of what the wire carried.
Measured on a real browser, one context, 95 navigations of pages with ~100 subresources
(registry 18,000 objects): a Request was 4.5 KB and a Response 6.0 KB (headers as a list of
dicts, kept twice - in the initializer and beside it - and the POST body in the initializer),
and the process grew from 37 to 149 MB. Kept as interned pairs, with the initializer reduced
to what is asked again, they are 0.84 KB each and the same run ends at 73 MB.
Known-bad: with the headers kept as the list of dicts the size test fails; with the headers
dropped from the initializer BEFORE the message is sent the wire test fails; with
`rawRequestHeaders` answering from the initializer the answer test fails.
"""
from __future__ import annotations
import sys
import pytest
import test_a_closed_context_leaves_nothing_in_the_registry as _registry
#: the fixture of the other module, under its own name
browser = _registry.browser
pytestmark = pytest.mark.unit
HEADERS = [{"name": "Host", "value": "example.com"},
{"name": "User-Agent", "value": "Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:159.0) Gecko/20100101 Firefox/159.0"},
{"name": "Accept", "value": "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8"},
{"name": "Accept-Language", "value": "en-US,en;q=0.5"},
{"name": "Accept-Encoding", "value": "gzip, deflate, br"},
{"name": "Connection", "value": "keep-alive"},
{"name": "Cookie", "value": "sid=" + "c" * 200},
{"name": "Sec-Fetch-Dest", "value": "document"},
{"name": "Sec-Fetch-Mode", "value": "navigate"},
{"name": "Sec-Fetch-Site", "value": "none"}]
DETAILS = {"protocol": "TLS 1.3", "subjectName": "example.com", "issuer": "CA",
"validFrom": 1, "validTo": 2}
def deep(obj, seen=None):
seen = set() if seen is None else seen
if id(obj) in seen:
return 0
seen.add(id(obj))
size = sys.getsizeof(obj)
if isinstance(obj, dict):
size += sum(deep(k, seen) + deep(v, seen) for k, v in obj.items())
elif isinstance(obj, (list, tuple)):
size += sum(deep(i, seen) for i in obj)
return size
def page_of(browser):
server = browser.server
context = server.object(server.handle(
{"guid": browser.guid, "method": "newContext", "params": {}})["context"]["guid"])
return context, server.object(server.handle(
{"guid": context.guid, "method": "newPage", "params": {"pageNumber": 0}})["page"]["guid"])
def traffic(page, n, post=None, details=None):
conn = page.conn
rid = "R%d" % n
request = {"requestId": rid, "url": "https://example.com/%d" % n, "method": "POST" if post else "GET",
"headers": HEADERS, "frameId": None, "navigationId": None, "resourceType": "Script"}
if post:
request["postData"] = post
conn.dispatch_event("Network.requestWillBeSent", request, page.session)
conn.dispatch_event("Network.responseReceived", {
"requestId": rid, "status": 200, "statusText": "OK", "headers": HEADERS,
"remoteIPAddress": "93.184.216.34", "remotePort": 443,
"securityDetails": dict(details) if details else None}, page.session)
conn.dispatch_event("Network.requestFinished", {"requestId": rid, "protocolVersion": "h2"},
page.session)
return page._request_log[-1]
def test_the_announcement_carries_the_headers_and_the_body_and_the_object_keeps_neither(browser):
context, page = page_of(browser)
sent = []
real = browser.server.send_up
browser.server.send_up = lambda m: (sent.append(m), real(m))[1]
request = traffic(page, 1, post="p" * 1000)
created = {m["params"]["type"]: m["params"]["initializer"] for m in sent
if m["method"] == "__create__" and m["params"]["type"] in ("Request", "Response")}
assert created["Request"]["headers"] == HEADERS
assert created["Request"]["postData"] == "p" * 1000
assert created["Response"]["headers"] == HEADERS
assert "timing" in created["Response"]
for kept in (request.initializer, request.response.initializer):
assert "headers" not in kept and "postData" not in kept and "timing" not in kept
assert request.initializer["url"] == "https://example.com/1"
assert request.response.initializer["status"] == 200
def test_the_raw_headers_are_still_answered_as_they_were_sent(browser):
context, page = page_of(browser)
request = traffic(page, 1, details=DETAILS)
assert request.op_raw_request_headers({}) == {"headers": HEADERS}
assert request.response.op_raw_response_headers({}) == {"headers": HEADERS}
assert request.response.op_server_addr({}) == {"value": {"ipAddress": "93.184.216.34", "port": 443}}
assert request.response.op_security_details({}) == {"value": DETAILS}
def test_a_request_with_ten_headers_is_a_fraction_of_what_it_was(browser):
"""What a request costs ON TOP of the one before it: a site repeats most of its headers."""
context, page = page_of(browser)
skip = ("server", "parent", "page", "response", "_owner")
previous = traffic(page, 1)
seen: set = set()
deep({k: v for k, v in vars(previous).items() if k not in skip}, seen)
request = traffic(page, 2)
marginal = deep({k: v for k, v in vars(request).items() if k not in skip}, seen)
assert marginal < 2000, marginal # 4.5 KB with the list of dicts, kept twice
def test_headers_and_certificates_are_shared_between_responses(browser):
context, page = page_of(browser)
a = traffic(page, 1, details=DETAILS)
b = traffic(page, 2, details=DETAILS)
assert a.response.security_details is b.response.security_details
assert a._headers[0][1] is b._headers[0][1]
def test_what_a_request_held_is_let_go_when_it_is_disposed(browser):
context, page = page_of(browser)
request = traffic(page, 1)
response = request.response
browser.server.handle({"guid": page.guid, "method": "close", "params": {}})
assert request._headers == () and request.response is None
assert response._headers == () and response.security_details is None
@@ -0,0 +1,68 @@
"""`launch_server()` launches ONE real browser and a client that only speaks the protocol
over a WebSocket drives it: a context, a page, a navigation, a read. Then it closes it all.
The client is hand-written on `websockets` (no Playwright on this side), which is the
point: nothing of this package is in the client. One browser, once.
Known-bad, run before this file was trusted: with no `remote.py` the import fails.
"""
from __future__ import annotations
import asyncio
import json
import pytest
import websockets # noqa: F401 - the dev extra installs it: a missing one is a failure, never a skip
from websockets.asyncio.client import connect # noqa: E402
pytestmark = pytest.mark.e2e
async def _drive(endpoint):
objects = {}
pending = {}
async with connect(endpoint, max_size=None) as ws:
counter = [0]
async def call(guid, method, params=None):
counter[0] += 1
await ws.send(json.dumps({"id": counter[0], "guid": guid, "method": method,
"params": params or {}, "metadata": {}}))
while True:
m = json.loads(await ws.recv())
if m.get("method") == "__create__":
objects[m["params"]["guid"]] = m["params"]
if m.get("id") == counter[0]:
assert "error" not in m, m
return m.get("result")
init = await call("", "initialize", {"sdkLanguage": "python"})
browser = [g for g, p in objects.items() if p["type"] == "Browser"][0]
ctx = (await call(browser, "newContext", {}))["context"]["guid"]
page = (await call(ctx, "newPage", {}))["page"]["guid"]
frame = objects[page]["initializer"]["mainFrame"]["guid"]
await call(frame, "goto", {"url": "data:text/html,<title>served</title>",
"waitUntil": "load", "timeout": 30000})
title = (await call(frame, "title", {}))["value"]
await call(ctx, "close", {})
return title
def test_a_plain_client_drives_a_served_browser(firefox_binary):
from invisible_playwright._juggler.remote import launch_server
closed = []
server = launch_server(headless=True, binary_path=firefox_binary,
locale="en-US", timezone="Europe/Rome",
on_engine_closed=lambda: closed.append(1))
try:
assert server.ws_endpoint.startswith("ws://127.0.0.1:")
pid = server.process.pid
assert isinstance(server.seed, int)
title = asyncio.run(asyncio.wait_for(_drive(server.ws_endpoint), 120))
assert title == "served"
assert server.process.poll() is None # the client leaving left the browser
finally:
server.close()
assert server.process.poll() is not None
assert closed == [] # close() is not "the engine died"
@@ -0,0 +1,46 @@
"""stroke_problems: what a page can say about a stroke without counting its events.
The e2e that asked for more than 10 mousemoves failed on the Linux gate with 9 events from a
loaded runner while the stroke was a real one (it left from far away, came in steps, ended on the
target). This file holds that page's events, as data, and the cases the shape rule must still
refuse.
"""
from __future__ import annotations
import pytest
from stroke_shape import stroke_problems
pytestmark = pytest.mark.unit
TARGET = (400, 240)
#: What the page of the failed Linux job received (job 129606776422, seed 4251).
FROM_THE_GATE = [[1116, 731], [1049, 689], [1007, 661], [827, 541], [747, 486],
[550, 347], [383, 225], [385, 227], [400, 240]]
def the_old_rule(moves):
"""The criterion of the test before: more than 10 events."""
return len(moves) > 10
def test_the_stroke_the_gate_received_is_a_stroke_and_the_old_rule_refused_it():
assert not the_old_rule(FROM_THE_GATE)
assert stroke_problems(FROM_THE_GATE, TARGET) == []
def test_a_stroke_with_more_events_is_one_too():
long_one = [[1116 - 40 * i, 731 - 28 * i] for i in range(17)] + [[400, 240]]
assert stroke_problems(long_one, TARGET) == []
@pytest.mark.parametrize("moves, what", [
([[400, 240]], "a jump: one event on the target"),
([[1116, 731], [400, 240]], "two events: no step on the way"),
([[1116, 731], [900, 600], [500, 300]], "ends beside the target"),
([[410, 250], [405, 245], [400, 240]], "began at the target"),
([[1116, 731], [900, 600], [900, 600], [400, 240]], "a repeated mousemove"),
([], "nothing"),
])
def test_what_is_not_a_stroke_is_refused(moves, what):
assert stroke_problems(moves, TARGET), what
@@ -0,0 +1,215 @@
"""A live worker leaves with its page for the back-forward cache and comes back with it (Fission strategy 1).
A document starts a worker that answers (`postMessage('tick')` -> 1, 2, ...). The top goes forward to another
page, which puts the document in the back-forward cache with its worker frozen, and `go_back()` restores it
(`pageshow.persisted` is read: without the cache there is no restore and the test would prove nothing). The
client sees what a user's page has, read from the protocol events it receives (the client has no `worker` event
yet), in order:
1. `Page.workerCreated(w)` when the worker starts;
2. `Page.workerDestroyed(w)` when the top goes forward, before the commit of the new page;
3. at `go_back()`, after the contexts of the restored document are cleared (`Runtime.executionContextsCleared`,
and `Page.frameDocumentRestored` when the engine sends it): `Page.workerCreated(w)` again, with the SAME
`workerId`, once, and no `Page.workerDestroyed(w)` after the restore;
4. one live worker in the end (created minus destroyed), and it is the page's: it answers 3, not 1.
The worker lives in the top (a root that is the main one) or in a frame of another site (an out-of-process root
that is not the main one, announced again when it is reattached). The top goes forward to the same site (it keeps
its process: only the back-forward cache can end the worker, which is the case Juggler a95bbc6808 fixed) or to
another site (with strategy 1 the top changes process), by `page.goto` (Page.navigate gives the top a new browsing
context even on the same site) or by the page's own `location.href` (the same browsing context). Hosts a.test / b.test / c.test resolve to one local server
(`network.dns.localDomains`): two hosts are two sites, one port.
"""
from __future__ import annotations
import threading
import time
from http.server import BaseHTTPRequestHandler
import pytest
from _servers import LocalServer
STRATEGY_1 = {
"fission.autostart": True,
"fission.webContentIsolationStrategy": 1,
"dom.ipc.processCount.webIsolated": 4,
"network.dns.localDomains": "a.test,b.test,c.test",
}
# What a document with a worker runs: the worker answers every message with its count.
OWNER = """<script>
window.__shown = [];
addEventListener('pageshow', e => window.__shown.push(e.persisted));
window.__w = new Worker('/worker.js');
window.__ask = () => new Promise(resolve => {
window.__w.onmessage = e => { if (e.data !== 'started') resolve(e.data); };
window.__w.postMessage('tick');
});
</script>"""
WORKER = "let n = 0; postMessage('started'); onmessage = () => postMessage(++n);"
@pytest.fixture
def sites():
routes = {}
class Handler(BaseHTTPRequestHandler):
timeout = 5
def log_message(self, *args):
pass
def do_GET(self):
path = self.path.split("?")[0]
if path not in routes:
self.send_response(404)
self.send_header("Content-Length", "0")
self.end_headers()
return
ctype, body = routes[path]
body = body.encode()
self.send_response(200)
self.send_header("Content-Type", ctype + "; charset=utf-8")
self.send_header("Content-Length", str(len(body)))
self.end_headers()
self.wfile.write(body)
server = LocalServer(("127.0.0.1", 0), Handler)
threading.Thread(target=server.serve_forever, daemon=True).start()
port = server.server_address[1]
def at(host, path):
return "http://%s:%d%s" % (host, port, path)
routes["/worker.js"] = ("text/javascript", WORKER)
routes["/top-worker"] = ("text/html", "<!doctype html><title>top</title>" + OWNER)
routes["/frame-worker"] = ("text/html", "<!doctype html><title>frame</title>" + OWNER)
routes["/top-frame"] = ("text/html", "<!doctype html><title>top</title>"
"<script>window.__shown = []; addEventListener('pageshow', e => window.__shown.push(e.persisted));"
"</script><iframe id=f src='%s' width=300 height=150></iframe>" % at("b.test", "/frame-worker"))
routes["/other"] = ("text/html", "<!doctype html><title>other</title><p>other")
try:
yield {"top": {"page": at("a.test", "/top-worker")}, "oop-frame": {"page": at("a.test", "/top-frame")},
"same-site": at("a.test", "/other"), "other-site": at("c.test", "/other")}
finally:
server.shutdown()
server.server_close()
@pytest.fixture
def events(monkeypatch):
"""Every protocol event the client receives, in order."""
from invisible_core.juggler.connection import EventListeners
seen = []
dispatch = EventListeners.dispatch_event
def record(self, method, params, session):
seen.append((method, params))
return dispatch(self, method, params, session)
monkeypatch.setattr(EventListeners, "dispatch_event", record)
return seen
def _wait(check, seconds=10.0):
end = time.monotonic() + seconds
while time.monotonic() < end:
if check():
return True
time.sleep(0.1)
return bool(check())
def _index(events, start, method, pred=lambda p: True):
for i in range(start, len(events)):
if events[i][0] == method and pred(events[i][1]):
return i
return None
def _ask(page, where):
target = page if where == "top" else next(f for f in page.frames if f.url.endswith("/frame-worker"))
return target.evaluate("window.__ask()")
@pytest.mark.e2e
@pytest.mark.parametrize("how", ["goto", "location"])
@pytest.mark.parametrize("away", ["same-site", "other-site"])
@pytest.mark.parametrize("where", ["top", "oop-frame"])
def test_a_worker_leaves_with_its_page_for_the_cache_and_comes_back_the_same(firefox_binary, sites, events, where,
away, how, engine_at_least):
engine_at_least("firefox-62")
from invisible_playwright import InvisiblePlaywright
with InvisiblePlaywright(seed=42, binary_path=firefox_binary, humanize=False,
headless=True, extra_prefs=STRATEGY_1) as browser:
page = browser.new_context().new_page()
page.set_default_timeout(10000)
page.goto(sites[where]["page"], wait_until="load")
# 1. the worker starts and is told
assert _wait(lambda: _index(events, 0, "Page.workerCreated", lambda p: p["url"].endswith("/worker.js")) is not None), \
"the worker was never announced"
created = events[_index(events, 0, "Page.workerCreated", lambda p: p["url"].endswith("/worker.js"))][1]
wid = created["workerId"]
if where == "oop-frame":
assert _wait(lambda: any(f.url.endswith("/frame-worker") for f in page.frames)), (
"the frame of the worker is not listed with its url: %r" % [f.url for f in page.frames])
assert _ask(page, where) == 1
assert _ask(page, where) == 2
# 2. the top goes forward: the worker ends for the client, before the new page commits
forward = len(events)
if how == "goto":
page.goto(sites[away], wait_until="load") # Page.navigate: a new browsing context for the top
else:
with page.expect_navigation(wait_until="load"): # the page's own navigation: the same browsing context
page.evaluate("url => { location.href = url; }", sites[away])
committed = _index(events, forward, "Page.navigationCommitted", lambda p: p.get("url", "").endswith("/other"))
assert committed is not None, "no commit of the new page was seen"
ended = _index(events, forward, "Page.workerDestroyed", lambda p: p["workerId"] == wid)
assert ended is not None, "the worker was not told ended when its page left: %r" % _methods(events, forward)
assert ended < committed, "the worker was told ended only after the new page committed: %r" % _methods(events, forward)
# 3. back from the cache: the same worker, told once, after the restored document's contexts are cleared
back = len(events)
page.go_back(wait_until="load")
assert page.evaluate("window.__shown") == [False, True], (
"the page was loaded again instead of restored from the back-forward cache, so this test proves nothing")
if not _wait(lambda: _index(events, back, "Page.workerCreated", lambda p: p["workerId"] == wid) is not None):
other = [p["workerId"] for m, p in events[back:] if m == "Page.workerCreated"]
raise AssertionError(("the restored worker was announced under a NEW id %s, not %s: " % (other, wid)
if other else "the restored document did not announce its worker again: ")
+ repr(_methods(events, back)))
again = _index(events, back, "Page.workerCreated", lambda p: p["workerId"] == wid)
cleared = _index(events, back, "Runtime.executionContextsCleared")
if cleared is not None:
assert cleared < again, "the worker was announced before the contexts were cleared: %r" % _methods(events, back)
restored = _index(events, back, "Page.frameDocumentRestored")
if restored is not None:
assert restored < again, "the worker was announced before the document was restored: %r" % _methods(events, back)
time.sleep(1.0) # what comes in excess comes now
after = events[back:]
assert not [p for m, p in after if m == "Page.workerDestroyed" and p["workerId"] == wid], (
"the restored worker was told ended: %r" % _methods(events, back))
assert len([p for m, p in after if m == "Page.workerCreated" and p["workerId"] == wid]) == 1, (
"the restored worker was announced more than once: %r" % _methods(events, back))
# 4. one live worker, the page's, with its count
live = {}
for m, p in events:
if m == "Page.workerCreated":
live[p["workerId"]] = p
elif m == "Page.workerDestroyed":
live.pop(p["workerId"], None)
assert list(live) == [wid], "live workers after the restore: %r" % list(live.values())
assert _ask(page, where) == 3, "the worker that came back is not the page's worker with its state"
def _methods(events, start):
return [m + (" " + p.get("workerId", "") if m.startswith("Page.worker") else "")
for m, p in events[start:] if m.startswith(("Page.worker", "Page.navigationCommitted", "Page.frameDocument",
"Runtime.executionContextsCleared", "Page.frameDetached",
"Page.frameAttached"))]
@@ -5,10 +5,10 @@ tag (an iCCP chunk, cICP, gAMA + cHRM, an sRGB chunk, a JPEG APP2 profile) from
to the output profile with qcms, and the output profile is the monitor's: on a stock Windows
that is "sRGB Color Space Profile.icm", which qcms does not take for sRGB, so the bytes
getImageData returns for drawImage and createImageBitmap change by a few units. The engine
declares that profile (it never reads the host's) and converts like retail from firefox-60.
declares that profile (it never reads the host's) and converts like retail from firefox-64.
Until firefox-59 it skipped the conversion (force_srgb): 27 of the 72 probes below differ
there, and this test fails on such an engine, naming each of them. It is gated on
firefox-60 only so that those releases skip it instead of failing the run.
firefox-64 only so that those releases skip it instead of failing the run.
tests/data/canvas_icc_ref/index.html, a page served on localhost, measures 72 probes:
@@ -113,7 +113,7 @@ def _serve(imgs, listing):
@pytest.mark.e2e
@pytest.mark.timeout(300, method="thread")
def test_tagged_images_read_back_as_retail_windows_reads_them(firefox_binary, engine_at_least):
engine_at_least("firefox-60")
engine_at_least("firefox-64")
refs_path = DATA / "refs.json"
if not refs_path.is_file():
pytest.fail("tests/data/canvas_icc_ref/refs.json is missing: it is the reference "
@@ -0,0 +1,143 @@
"""Coloured canvas text, and text under other ClearType keys, is what retail Windows draws.
tests/test_canvas_text_is_windows_e2e.py compares 342 cases of black text on white, drawn
with one ClearType state (the seed's: gamma 1.8, contrast 1.0). The text of a page is not
always black, and a machine's ClearType gamma and contrast are not always the untuned ones
(the registry values the Windows tuner writes), so this test adds what that one does not
reach, each with the hashes retail Firefox 159.0 on Windows gave for the same page:
coloured text tests/data/canvas_text_ref_colors/index.html draws Arial 16 and 33 px, fillText,
of seven colour pairs (black, teal, rgba(102,204,0,0.2) on white, grey, white on
black, red, white on blue): 14 cases, with the seed's configuration. An
engine that quantises its A8 text masks to 17 levels (a hook, which firefox-64
removes) moves a coloured edge pixel by a few units, and black on white hides
it: 12 of the 14 differ on such an engine.
ClearType keys gamma/contrast 1800/100 (the seed's), 1400/50 and 2200/0: 39 cases for each,
the 14 coloured ones and 25 black ones of tests/data/canvas_text_ref (Arial,
Calibri, Consolas, Segoe UI at 9, 12.5, 16 and 33 px; stroke, opaque canvas
above 48 px, rotated and scaled, Twemoji COLR v0). The engine is launched with
the pins font.cleartype_gamma and font.cleartype_contrast of the key, one
launch for each; the page is the same, the bytes are not (the keys give
different hashes in refs.json, which tests/unit/test_canvas_text_colors_refs.py
checks, so the test tells them apart).
Each canvas is read back with getImageData and its RGBA bytes are hashed with SHA-256. The
fonts are the engine's own bundled files, served by this test (their sha256 is checked
against the reference first). tests/data/canvas_text_ref_colors/refs.json is built by
scripts/build_canvas_text_colors_refs.py from the bytes retail drew.
Every differing case is listed (name, expected hash, hash got), not just the first.
Run: pytest tests/test_canvas_text_colors_and_cleartype_is_windows_e2e.py -m e2e -v
"""
from __future__ import annotations
import json
from pathlib import Path
import pytest
from _canvas_text import DATA as BASE_DATA, diff_lines, only_cases, pin, serve, wrong_fonts
from invisible_playwright import InvisiblePlaywright
DATA = Path(__file__).parent / "data" / "canvas_text_ref_colors"
SEED = 21
def _refs():
path = DATA / "refs.json"
if not path.is_file():
pytest.fail("tests/data/canvas_text_ref_colors/refs.json is missing: it is the reference "
"retail Firefox on Windows wrote for these pages (see the module docstring)")
return json.loads(path.read_text(encoding="utf-8"))
def _draw(url, page):
"""The sha256 of each case the page at ``url`` draws, by case id."""
page.goto(url, timeout=60_000)
page.wait_for_function("window.DONE === true || window.ERR", timeout=300_000)
err = page.evaluate("window.ERR || null")
assert err is None, "the reference page %s failed: %s" % (url, err)
return page.evaluate(
"Object.fromEntries(Object.entries(window.R).map(([k, v]) => [k, v.sha256]))")
def _launch(firefox_binary, refs, key, pages_for):
"""One engine launch with the persona's pin (and the ClearType ``key`` when given, a
(gamma, contrast) pair); returns what each page of ``pages_for`` ({name: (path, ids)})
drew."""
base = json.loads((BASE_DATA / "refs.json").read_text(encoding="utf-8"))
fonts_dir = Path(firefox_binary).parent / "fonts"
wrong = wrong_fonts(fonts_dir, base["fonts"])
assert not wrong, (
"the reference was measured with other font files than the engine's bundle, so it "
"compares nothing; rebuild the references from the bundled files:\n "
+ "\n ".join(wrong))
prefs = pin(base)
if key is not None:
prefs["font.cleartype_gamma"], prefs["font.cleartype_contrast"] = key
colors_page = (DATA / "index.html").read_bytes()
black_page = only_cases((BASE_DATA / "index.html").read_text(encoding="utf-8"),
pages_for.get("black", []))
server = serve(fonts_dir, base["fonts"],
{"/": colors_page, "/index.html": colors_page,
"/black.html": black_page.encode("utf-8")})
try:
root = "http://127.0.0.1:%d" % server.server_address[1]
with InvisiblePlaywright(seed=SEED, binary_path=firefox_binary, headless=True,
pin=prefs) as b:
page = b.new_context().new_page()
got = {}
if pages_for.get("black"):
got["black"] = _draw(root + "/black.html", page)
got["colors"] = _draw(root + "/", page)
return got
finally:
server.shutdown()
def _want(cases):
return {cid: c["sha256"] for cid, c in cases.items()}
@pytest.mark.e2e
@pytest.mark.timeout(600, method="thread")
def test_coloured_text_is_what_retail_windows_draws(firefox_binary, engine_at_least):
engine_at_least("firefox-64")
refs = _refs()
assert refs["colors"]["count"] == len(refs["colors"]["cases"]) == 14
got = _launch(firefox_binary, refs, None, {})
lines = diff_lines(_want(refs["colors"]["cases"]), got["colors"])
assert not lines, (
"%d of %d coloured canvas text cases differ from retail Firefox on Windows "
"(seed ClearType state, gamma 1800 contrast 100):\n %s"
% (len(lines), len(refs["colors"]["cases"]), "\n ".join(lines)))
def _keys():
# collected without the reference file: a missing one fails the test, not the collection
path = DATA / "refs.json"
if not path.is_file():
return ["1800_100", "1400_50", "2200_0"]
return list(json.loads(path.read_text(encoding="utf-8"))["keys"])
@pytest.mark.e2e
@pytest.mark.timeout(900, method="thread")
@pytest.mark.parametrize("tag", _keys())
def test_text_under_a_cleartype_key_is_what_retail_windows_draws(
tag, firefox_binary, engine_at_least):
engine_at_least("firefox-64")
refs = _refs()
k = refs["keys"][tag]
want_black, want_colors = _want(k["black"]), _want(k["colors"])
assert len(want_black) + len(want_colors) == k["count"] == 39
got = _launch(firefox_binary, refs, (k["gamma"], k["contrast"]), {"black": list(want_black)})
lines = (diff_lines(want_black, got["black"], "black ")
+ diff_lines(want_colors, got["colors"], "colour "))
assert not lines, (
"%d of %d canvas text cases differ from retail Firefox on Windows under ClearType "
"gamma %d contrast %d:\n %s"
% (len(lines), k["count"], k["gamma"], k["contrast"], "\n ".join(lines)))
+6 -68
View File
@@ -1,7 +1,7 @@
"""Canvas 2D text is drawn as retail Firefox on Windows draws it, on every OS.
Retail Firefox on Windows draws canvas text with Skia over DirectWrite. The engine draws it
with Skia over idwr (DirectWrite 10.0.26100.9711 in portable C) from firefox-60, so the
with Skia over idwr (DirectWrite 10.0.26100.9711 in portable C) from firefox-64, so the
same page gives the same RGBA bytes on Windows, on Debian 12 and on Ubuntu 24.04.
tests/data/canvas_text_ref/index.html draws 342 cases, in groups (the ``gruppo`` field of
@@ -45,77 +45,20 @@ Run: pytest tests/test_canvas_text_is_windows_e2e.py -m e2e -v
"""
from __future__ import annotations
import hashlib
import http.server
import json
import os
import threading
from pathlib import Path
import pytest
from _canvas_text import DATA, pin as _pin, serve as _serve, wrong_fonts
from invisible_playwright import InvisiblePlaywright
DATA = Path(__file__).parent / "data" / "canvas_text_ref"
#: What the reference's ``cleartype`` field says the retail machine had: FontSmoothing 2 with
#: FontSmoothingType 2 is ClearType (system text quality 5). The other tuning values are an
#: untuned Windows machine's (gamma 1.8, contrast 1.0, level 1.0), which refs.json does not
#: record.
_UNTUNED = {"font.cleartype_gamma": 1800, "font.cleartype_contrast": 100,
"font.cleartype_level": 100}
def _pin(refs):
ct = refs["cleartype"]
smoothing, kind = str(ct["FontSmoothing"]), str(ct["FontSmoothingType"])
if smoothing == "2" and kind in ("2", "0x2"):
quality = 5
elif smoothing == "2":
quality = 4
else:
quality = 0
return {"screen.dpr": 1.0, "font.system_text_quality": quality, **_UNTUNED}
def _bundle_font(fonts_dir, entry):
"""The bundled file a reference entry names."""
return fonts_dir / entry["bundle_file"]
def _serve(fonts_dir, entries):
"""The page and, under fonts/<name from the page>, the engine's bundled files."""
by_url = {"/bundle/" + e["bundle_file"]: _bundle_font(fonts_dir, e) for e in entries}
page = (DATA / "index.html").read_bytes()
class _H(http.server.BaseHTTPRequestHandler):
def do_GET(self):
path = self.path.split("?")[0]
if path in ("/", "/index.html"):
body, kind = page, "text/html"
elif path in by_url and by_url[path].is_file():
body, kind = by_url[path].read_bytes(), "font/ttf"
else:
self.send_error(404)
return
self.send_response(200)
self.send_header("Content-Type", kind)
self.send_header("Content-Length", str(len(body)))
self.end_headers()
self.wfile.write(body)
def log_message(self, *args):
pass
server = http.server.ThreadingHTTPServer(("127.0.0.1", 0), _H)
threading.Thread(target=server.serve_forever, daemon=True).start()
return server
@pytest.mark.e2e
@pytest.mark.timeout(1800, method="thread")
def test_canvas_text_is_what_retail_windows_draws(firefox_binary, engine_at_least):
engine_at_least("firefox-60")
engine_at_least("firefox-64")
refs_path = DATA / "refs.json"
if not refs_path.is_file():
pytest.fail("tests/data/canvas_text_ref/refs.json is missing: it is the reference "
@@ -123,19 +66,14 @@ def test_canvas_text_is_what_retail_windows_draws(firefox_binary, engine_at_leas
refs = json.loads(refs_path.read_text(encoding="utf-8"))
fonts_dir = Path(firefox_binary).parent / "fonts"
wrong = []
for e in refs["fonts"]:
f = _bundle_font(fonts_dir, e)
got = hashlib.sha256(f.read_bytes()).hexdigest() if f.is_file() else None
if got != e["sha256"]:
wrong.append("%s: the engine's %s has sha256 %s, the reference was made with %s"
% (e["family"], f.name, got, e["sha256"]))
wrong = wrong_fonts(fonts_dir, refs["fonts"])
assert not wrong, (
"the reference was measured with other font files than the engine's bundle, so it "
"compares nothing; rebuild refs.json from the bundled files:\n " + "\n ".join(wrong))
pin = _pin(refs)
server = _serve(fonts_dir, refs["fonts"])
page = (DATA / "index.html").read_bytes()
server = _serve(fonts_dir, refs["fonts"], {"/": page, "/index.html": page})
try:
url = "http://127.0.0.1:%d/" % server.server_address[1]
with InvisiblePlaywright(seed=21, binary_path=firefox_binary, headless=True,
-47
View File
@@ -1,47 +0,0 @@
"""The drive gate's copy of the first-run declaration must not diverge from the core.
`scripts/ci_drive_gate.py` runs in a job that installs only Playwright, so it
carries FIRST_RUN, a literal copy of what invisible_core declares for the first
run, and writes it into the profile's user.js. Since firefox-55 the engine leaves
Mozilla's first-run lines and the core alone declares that state: without the
copy, run 41388672849 (2026-11-02) showed the terms-of-use modal on Windows
(no mouse event reached the page) and opened Mozilla's privacy page in a second
tab on Linux. This test binds the copy: a first-run pref the core adds, drops or
changes turns it red.
"""
from __future__ import annotations
import sys
from pathlib import Path
import pytest
_GATE = Path(__file__).resolve().parents[1] / "scripts" / "ci_drive_gate.py"
_FIRST_RUN_PREFIXES = ("termsofuse.", "browser.preonboarding.", "datareporting.policy.")
def _first_run_from_gate() -> dict:
"""FIRST_RUN as the gate defines it, without importing Playwright (imported
inside `_drive`)."""
ns: dict = {}
head = _GATE.read_text(encoding="utf-8").split("\nHTML = (")[0]
exec(compile(head, str(_GATE), "exec"), ns) # noqa: S102 - our own file
return ns["FIRST_RUN"]
@pytest.mark.unit
@pytest.mark.parametrize("platform", ["win32", "linux"])
def test_ci_drive_gate_first_run_matches_the_core(monkeypatch, platform):
from invisible_core._fpforge import generate_profile
from invisible_core.prefs import translate_profile_to_prefs
monkeypatch.setattr(sys, "platform", platform)
prefs = translate_profile_to_prefs(generate_profile(970411), timezone="America/New_York")
from_core = {k: v for k, v in prefs.items() if k.startswith(_FIRST_RUN_PREFIXES)}
from_gate = _first_run_from_gate()
assert from_core, "the core declares no first-run state: the engine would show the modal"
assert from_gate == from_core, (
"FIRST_RUN in scripts/ci_drive_gate.py is no longer what invisible_core declares.\n"
" core: %r\n gate: %r" % (from_core, from_gate))
for k, v in from_gate.items():
assert type(v) is type(from_core[k]), k
@@ -0,0 +1,53 @@
"""The drive gate launches the binary through the wrapper and the core, never through bare Playwright.
Since firefox-63 the engine holds every channel that asks the proxy service until the client has said how the session
leaves the host (`Browser.setBrowserProxy`, or `Browser.setNoBrowserProxy` for a session without a proxy). The core's launch
sends that decision first; stock Playwright sends it only when it is given a proxy. A drive gate that launches with
`p.firefox.launch_persistent_context(executable_path=...)` therefore waits for a decision nobody takes: run 43134774602,
`Page.goto: Timeout 30000ms` on every leg, three attempts.
The core also declares the first run (terms of use, pre-onboarding), which the gate used to copy into user.js
(`FIRST_RUN`, tied to the core by a test of its own): with the launch through the core the copy has no reason to exist.
This test reads the script; it launches nothing.
"""
from __future__ import annotations
import ast
from pathlib import Path
import pytest
_GATE = Path(__file__).resolve().parents[1] / "scripts" / "ci_drive_gate.py"
def _tree() -> ast.Module:
return ast.parse(_GATE.read_text(encoding="utf-8"))
@pytest.mark.unit
def test_the_drive_gate_imports_no_playwright_client():
imported = []
for node in ast.walk(_tree()):
if isinstance(node, ast.Import):
imported += [a.name for a in node.names]
elif isinstance(node, ast.ImportFrom):
imported.append(node.module or "")
bare = [m for m in imported if m == "playwright" or m.startswith("playwright.")]
assert not bare, "the drive gate imports %s: a bare Playwright never tells the engine the road of the session" % bare
@pytest.mark.unit
def test_the_drive_gate_launches_with_the_wrapper_on_the_binary_under_test():
calls = [n for n in ast.walk(_tree()) if isinstance(n, ast.Call)
and getattr(n.func, "id", getattr(n.func, "attr", None)) == "InvisiblePlaywright"]
assert len(calls) == 1, "the drive gate must launch with InvisiblePlaywright, once"
keywords = {k.arg: k.value for k in calls[0].keywords}
assert isinstance(keywords.get("binary_path"), ast.Name) and keywords["binary_path"].id == "exe", \
"the binary under test is the gate's argument, handed over as binary_path="
assert isinstance(keywords.get("headless"), ast.Constant) and keywords["headless"].value is True
@pytest.mark.unit
def test_the_drive_gate_keeps_no_copy_of_the_first_run_declaration():
names = {t.id for n in ast.walk(_tree()) if isinstance(n, ast.Assign) for t in n.targets if isinstance(t, ast.Name)}
assert "FIRST_RUN" not in names, "the core declares the first run; a copy in the gate can only drift from it"
+572
View File
@@ -0,0 +1,572 @@
"""scripts/ci_verdict.py is the one judge of the mandatory suites: it must fail on every hole (a skip, a failure, too few
tests collected, a required file that never ran, a list that lost a row or a minimum against main) and only then. The
junit files here are written by hand in tmp_path; the last tests read the real ci/required-suites.json."""
import importlib.util
import json
import re
from pathlib import Path
import pytest
pytestmark = pytest.mark.unit
ROOT = Path(__file__).resolve().parents[1]
REQUIRED = ROOT / "ci" / "required-suites.json"
def _load():
spec = importlib.util.spec_from_file_location("ci_verdict_under_test", ROOT / "scripts" / "ci_verdict.py")
module = importlib.util.module_from_spec(spec)
spec.loader.exec_module(module)
return module
verdict = _load()
FILE_A = "tests/test_a.py"
FILE_B = "tests/test_b.py"
NODE = "tests/test_c.py::test_one"
def _suite(**over):
row = {"id": "s.one", "giro": "G2", "os": ["linux", "windows"], "min_tests": 4,
"tests": [FILE_A, FILE_B, NODE], "marker": "unit", "needs_root": False, "exact": True,
"note": ""}
row.update(over)
return row
def _write_required(path, rows):
path.write_text("[\n" + ",\n".join(" " + json.dumps(r) for r in rows) + "\n]\n", encoding="utf-8")
return path
def _case(file, name, tag=None, classname=None):
classname = file[:-3].replace("/", ".") if classname is None else classname
inner = {None: "", "skipped": '<skipped message="s"/>', "failure": '<failure message="f">x</failure>',
"error": '<error message="e">x</error>'}[tag]
return '<testcase classname="%s" name="%s" time="0.1">%s</testcase>' % (classname, name, inner)
def _junit(path, cases):
path.write_text('<?xml version="1.0" encoding="utf-8"?><testsuites><testsuite name="pytest" tests="%d">%s'
"</testsuite></testsuites>" % (len(cases), "".join(cases)), encoding="utf-8")
return path
GREEN = [_case(FILE_A, "test_x"), _case(FILE_A, "test_y[p1]"), _case(FILE_B, "test_z"), _case("tests/test_c.py", "test_one")]
SHA = "a" * 40
def _judge(tmp_path, cases, rows=None, extra=(), suite="s.one", os_name="linux", with_binary=True, commit=SHA):
required = _write_required(tmp_path / "required.json", rows or [_suite()])
junit = _junit(tmp_path / "junit.xml", cases) if cases is not None else tmp_path / "absent.xml"
binary = tmp_path / "firefox.bin"
binary.write_bytes(b"engine")
out = tmp_path / "result" / ("%s.%s.json" % (suite, os_name))
argv = ["judge", "--required", str(required), "--suite", suite, "--os", os_name, "--junit", str(junit),
"--out", str(out), *extra]
if with_binary:
argv += ["--binary", str(binary)]
if commit:
argv += ["--commit", commit]
code = verdict.main(argv)
return code, (json.loads(out.read_text(encoding="utf-8")) if out.exists() else None)
def test_everything_green_exits_0_and_writes_the_result(tmp_path, capsys):
code, result = _judge(tmp_path, GREEN)
assert code == 0, capsys.readouterr().out
assert result["suite"] == "s.one" and result["os"] == "linux" and result["commit"] == SHA
assert result["verdict"] == "green"
assert (result["collected"], result["passed"], result["failed"], result["skipped"], result["errors"]) == (4, 4, 0, 0, 0)
assert result["missing_tests"] == [] and result["problems"] == []
def test_the_binary_hash_is_the_sha256_of_the_file(tmp_path):
import hashlib
_code, result = _judge(tmp_path, GREEN)
assert result["binary_sha256"] == hashlib.sha256(b"engine").hexdigest()
def test_judge_without_binary_is_a_wrong_use(tmp_path, capsys):
code, result = _judge(tmp_path, GREEN, with_binary=False)
assert code == 2 and result is None
assert "--binary" in capsys.readouterr().err
def test_a_binary_that_does_not_exist_is_red_never_a_null_hash_green(tmp_path, capsys):
required = _write_required(tmp_path / "required.json", [_suite()])
junit = _junit(tmp_path / "junit.xml", GREEN)
out = tmp_path / "r.json"
code = verdict.main(["judge", "--required", str(required), "--suite", "s.one", "--os", "linux", "--junit", str(junit),
"--binary", str(tmp_path / "nowhere.bin"), "--commit", SHA, "--out", str(out)])
result = json.loads(out.read_text(encoding="utf-8"))
assert code == 1 and result["binary_sha256"] is None and result["verdict"] == "red"
assert "does not exist" in capsys.readouterr().out
def test_a_skipped_test_is_red(tmp_path, capsys):
cases = GREEN[:-1] + [_case("tests/test_c.py", "test_one", "skipped")]
code, result = _judge(tmp_path, cases)
out = capsys.readouterr().out
assert code == 1 and result["skipped"] == 1
assert "skipped" in out and NODE in out
def test_a_failed_test_is_red(tmp_path, capsys):
cases = GREEN + [_case(FILE_B, "test_bad", "failure")]
code, result = _judge(tmp_path, cases)
out = capsys.readouterr().out
assert code == 1 and result["failed"] == 1
assert "failed" in out and FILE_B in out
def test_an_error_is_red(tmp_path):
cases = GREEN + [_case(FILE_B, "test_bad", "error")]
code, result = _judge(tmp_path, cases)
assert code == 1 and result["errors"] == 1
def test_fewer_tests_than_the_minimum_is_red(tmp_path, capsys):
code, result = _judge(tmp_path, GREEN, rows=[_suite(min_tests=5)])
assert code == 1 and result["collected"] == 4
assert "fewer than the minimum 5" in capsys.readouterr().out
def test_a_required_file_that_did_not_run_is_red(tmp_path, capsys):
cases = [c for c in GREEN if "test_b" not in c]
code, result = _judge(tmp_path, cases, rows=[_suite(min_tests=3)])
assert code == 1 and result["missing_tests"] == [FILE_B]
assert FILE_B in capsys.readouterr().out
def test_a_required_node_id_that_did_not_run_is_red(tmp_path):
cases = [c for c in GREEN if "test_one" not in c]
code, result = _judge(tmp_path, cases, rows=[_suite(min_tests=3)])
assert code == 1 and result["missing_tests"] == [NODE]
def test_a_parametrized_node_id_is_matched_without_its_parameters(tmp_path):
cases = [_case(FILE_A, "test_x"), _case("tests/test_c.py", "test_one[a]"), _case("tests/test_c.py", "test_one[b]")]
rows = [_suite(tests=[FILE_A, NODE], min_tests=3)]
assert _judge(tmp_path, cases, rows=rows)[0] == 0
cases[2] = _case("tests/test_c.py", "test_one[b]", "failure")
assert _judge(tmp_path, cases, rows=rows)[0] == 1
def test_a_missing_junit_is_red(tmp_path, capsys):
code, result = _judge(tmp_path, None)
assert code == 1 and result["collected"] == 0
assert "junit" in capsys.readouterr().out
def test_every_problem_is_printed_one_per_line(tmp_path, capsys):
cases = [_case(FILE_A, "test_x", "failure"), _case(FILE_A, "test_y", "skipped")]
code, _result = _judge(tmp_path, cases)
lines = [l for l in capsys.readouterr().out.splitlines() if l.startswith("VERDICT RED")]
assert code == 1 and len(lines) >= 5, lines
def test_a_row_the_suite_does_not_have_for_that_os_is_red(tmp_path, capsys):
code, _result = _judge(tmp_path, GREEN, rows=[_suite(os=["linux"])], os_name="windows")
assert code == 1 and "does not run on windows" in capsys.readouterr().out
def test_a_class_in_the_junit_is_part_of_the_node_id():
assert verdict.node_id("tests.test_x.TestThing", "test_y") == "tests/test_x.py::TestThing::test_y"
assert verdict.node_id("tests.test_x", "test_y[p]") == "tests/test_x.py::test_y[p]"
# --- against main ------------------------------------------------------------------------------------------------
def _main_file(tmp_path, rows):
return _write_required(tmp_path / "main.json", rows)
def test_a_list_that_only_grew_is_green(tmp_path):
main = _main_file(tmp_path, [_suite(min_tests=3, tests=[FILE_A])])
code, _r = _judge(tmp_path, GREEN, rows=[_suite(), _suite(id="s.two")], extra=["--main-required", str(main)])
assert code == 0
def test_a_suite_of_main_that_is_gone_is_red(tmp_path, capsys):
main = _main_file(tmp_path, [_suite(), _suite(id="s.gone")])
code, _r = _judge(tmp_path, GREEN, extra=["--main-required", str(main)])
assert code == 1 and "s.gone" in capsys.readouterr().out
def test_a_lost_test_row_against_main_is_red(tmp_path, capsys):
main = _main_file(tmp_path, [_suite(tests=[FILE_A, FILE_B, NODE, "tests/test_d.py"])])
code, _r = _judge(tmp_path, GREEN, extra=["--main-required", str(main)])
assert code == 1 and "tests/test_d.py" in capsys.readouterr().out
def test_a_higher_minimum_on_main_is_red(tmp_path, capsys):
main = _main_file(tmp_path, [_suite(min_tests=9)])
code, _r = _judge(tmp_path, GREEN, extra=["--main-required", str(main)])
assert code == 1 and "went down" in capsys.readouterr().out
def test_a_main_list_that_does_not_exist_is_red_unless_the_gate_declares_main_has_none(tmp_path, capsys):
missing = str(tmp_path / "no" / "required.json")
code, result = _judge(tmp_path, GREEN, extra=["--main-required", missing])
assert code == 1 and result["verdict"] == "red"
assert "it is not known what main has" in capsys.readouterr().out
def test_a_main_list_declared_absent_is_said_and_passed(tmp_path, capsys):
missing = str(tmp_path / "no" / "required.json")
code, _r = _judge(tmp_path, GREEN, extra=["--main-required", missing, "--main-has-no-list"])
assert code == 0 and "main was checked out and has none" in capsys.readouterr().out
def test_declaring_main_has_none_while_the_file_is_there_is_red(tmp_path, capsys):
main = _main_file(tmp_path, [_suite()])
code, _r = _judge(tmp_path, GREEN, extra=["--main-required", str(main), "--main-has-no-list"])
assert code == 1 and "says main has none" in capsys.readouterr().out
def test_main_has_no_list_without_a_main_path_is_red(tmp_path):
assert _judge(tmp_path, GREEN, extra=["--main-has-no-list"])[0] == 1
def test_an_exact_turned_off_against_main_is_red(tmp_path, capsys):
main = _main_file(tmp_path, [_suite(exact=True)])
code, _r = _judge(tmp_path, GREEN, rows=[_suite(exact=False)], extra=["--main-required", str(main)])
assert code == 1 and "no longer exact" in capsys.readouterr().out
def test_a_reduced_os_against_main_is_red(tmp_path, capsys):
main = _main_file(tmp_path, [_suite()])
code, _r = _judge(tmp_path, GREEN, rows=[_suite(os=["linux"])], extra=["--main-required", str(main)])
assert code == 1 and "no longer runs on windows" in capsys.readouterr().out
def test_a_changed_marker_against_main_is_red(tmp_path, capsys):
main = _main_file(tmp_path, [_suite(marker="e2e")])
code, _r = _judge(tmp_path, GREEN, extra=["--main-required", str(main)])
assert code == 1 and "marker of s.one changed" in capsys.readouterr().out
def test_a_main_list_older_than_the_format_is_still_compared(tmp_path):
old = {k: v for k, v in _suite(min_tests=3, tests=[FILE_A]).items() if k != "exact"}
main = _main_file(tmp_path, [old])
assert _judge(tmp_path, GREEN, extra=["--main-required", str(main)])[0] == 0
# --- args --------------------------------------------------------------------------------------------------------
def test_args_prints_the_files_and_node_ids_one_per_line(tmp_path, capsys):
required = _write_required(tmp_path / "required.json", [_suite()])
assert verdict.main(["args", "--required", str(required), "--suite", "s.one", "--os", "linux"]) == 0
assert capsys.readouterr().out.splitlines() == [FILE_A, FILE_B, NODE]
def test_args_with_the_marker_puts_it_first(tmp_path, capsys):
required = _write_required(tmp_path / "required.json", [_suite(marker="e2e")])
assert verdict.main(["args", "--required", str(required), "--suite", "s.one", "--os", "windows", "--with-marker"]) == 0
assert capsys.readouterr().out.splitlines()[:2] == ["-m", "e2e"]
def test_args_for_windows_of_a_linux_only_suite_is_an_error(tmp_path, capsys):
required = _write_required(tmp_path / "required.json", [_suite(os=["linux"])])
assert verdict.main(["args", "--required", str(required), "--suite", "s.one", "--os", "windows"]) != 0
captured = capsys.readouterr()
assert captured.out == "" and "does not run on windows" in captured.err
# --- the commit: the wrapper's, never GITHUB_SHA -------------------------------------------------------------------
def test_the_commit_is_not_taken_from_github_sha(tmp_path, monkeypatch, capsys):
monkeypatch.setenv("GITHUB_SHA", "e" * 40) # in a called workflow this is the commit of the ENGINE's repository
code, result = _judge(tmp_path, GREEN, commit="b" * 40)
assert code == 0 and result["commit"] == "b" * 40
monkeypatch.chdir(tmp_path) # not a git checkout
monkeypatch.setenv("GIT_CEILING_DIRECTORIES", str(tmp_path.parent))
code, result = _judge(tmp_path, GREEN, commit=None)
assert code == 1 and result["commit"] is None
assert "commit of the wrapper is not known" in capsys.readouterr().out
def test_without_commit_it_is_git_head_of_the_current_directory(tmp_path, monkeypatch):
import subprocess
repo = tmp_path / "wrapper"
repo.mkdir()
git = ["git", "-C", str(repo), "-c", "user.name=t", "-c", "user.email=ci-verdict-test"]
subprocess.run(git + ["init", "-q"], check=True)
subprocess.run(git + ["commit", "-q", "--allow-empty", "-m", "x"], check=True)
head = subprocess.run(git + ["rev-parse", "HEAD"], capture_output=True, text=True, check=True).stdout.strip()
monkeypatch.setenv("GITHUB_SHA", "e" * 40)
monkeypatch.chdir(repo)
code, result = _judge(tmp_path, GREEN, commit=None)
assert code == 0 and result["commit"] == head
# --- the seal of the gate ------------------------------------------------------------------------------------------
def test_a_readable_seal_is_noted_as_having_no_binary_hash(tmp_path, capsys):
seal = tmp_path / "gate.seal.json"
seal.write_text('{"schema": 2, "tag": "t", "assets": {}, "build_id": "1"}', encoding="utf-8")
code, result = _judge(tmp_path, GREEN, extra=["--seal", str(seal)])
assert code == 0 and result["seal_binary_hash"] == "absent"
assert "carries no sha256 of the engine binary" in capsys.readouterr().out
def test_a_seal_that_cannot_be_read_is_red(tmp_path, capsys):
code, _r = _judge(tmp_path, GREEN, extra=["--seal", str(tmp_path / "no.seal.json")])
assert code == 1 and "cannot be read" in capsys.readouterr().out
# --- exact, every test of a file, xunit2 ---------------------------------------------------------------------------
def test_an_exact_suite_with_more_tests_than_min_tests_is_red(tmp_path, capsys):
cases = GREEN + [_case(FILE_B, "test_new")]
code, result = _judge(tmp_path, cases)
assert code == 1 and result["collected"] == 5
assert "exact" in capsys.readouterr().out
def test_a_suite_that_is_not_exact_allows_more_tests(tmp_path):
cases = GREEN + [_case(FILE_B, "test_new")]
assert _judge(tmp_path, cases, rows=[_suite(exact=False)])[0] == 0
def test_a_deselected_test_is_caught_by_the_exact_count(tmp_path, capsys):
cases = [c for c in GREEN if "test_y" not in c] # test_y[p1] deselected: not in the junit at all
code, _r = _judge(tmp_path, cases)
assert code == 1 and "fewer than the minimum 4" in capsys.readouterr().out
def test_a_file_with_one_test_that_did_not_pass_is_red_even_if_another_passed(tmp_path, capsys):
cases = [_case(FILE_A, "test_x"), _case(FILE_A, "test_y[p1]", "skipped"), _case(FILE_B, "test_z"),
_case("tests/test_c.py", "test_one")]
code, result = _judge(tmp_path, cases)
assert code == 1 and result["missing_tests"] == [FILE_A]
assert "the file %s has tests that did not pass (skipped)" % FILE_A in capsys.readouterr().out
def test_a_junit_written_as_xunit1_is_red_even_if_it_keeps_the_classname(tmp_path, capsys):
xunit1 = _case(FILE_A, "test_x").replace(' time=', ' file="tests\test_a.py" line="3" time=')
code, _r = _judge(tmp_path, [xunit1, *GREEN[1:]])
assert code == 1 and "not xunit2" in capsys.readouterr().out
def test_a_junit_without_classname_is_red(tmp_path, capsys):
cases = [_case(FILE_A, "test_x", classname=""), *GREEN[1:]] # what junit_family=xunit1 leaves
code, _r = _judge(tmp_path, cases)
out = capsys.readouterr().out
assert code == 1 and "not xunit2" in out and "junit_family=xunit2" in out
# --- the list is validated -----------------------------------------------------------------------------------------
@pytest.mark.parametrize("bad, why", [
(dict(os=[]), "os must be"), (dict(os=["macos"]), "os must be"), (dict(os="linux"), "os must be"),
(dict(os=["linux", "linux"]), "os must be"),
(dict(tests=[]), "tests must be"), (dict(tests=[1]), "tests must be"), (dict(tests=[FILE_A, FILE_A]), "duplicates"),
(dict(min_tests=0), "min_tests"), (dict(min_tests="4"), "min_tests"), (dict(min_tests=True), "min_tests"),
(dict(exact="yes"), "exact"), (dict(marker=""), "marker"), (dict(id=""), "no id"),
(dict(needs_root="linux"), "needs_root"), (dict(needs_root=["macos"]), "needs_root"),
(dict(os=["linux"], needs_root=["windows"]), "needs_root"),
])
def test_a_malformed_row_is_exit_2_with_the_reason_in_all_three_commands(tmp_path, capsys, bad, why):
required = _write_required(tmp_path / "required.json", [_suite(**bad)])
assert verdict.main(["args", "--required", str(required), "--suite", "s.one", "--os", "linux"]) == 2
assert why in capsys.readouterr().err
code, result = _judge(tmp_path, GREEN, rows=[_suite(**bad)])
assert code == 2 and result["verdict"] == "red" and why in capsys.readouterr().out
assert verdict.main(["complete", "--required", str(required), "--results", str(tmp_path)]) == 2
assert why in capsys.readouterr().err
def test_duplicate_ids_and_a_row_that_is_not_an_object_are_exit_2(tmp_path, capsys):
required = _write_required(tmp_path / "required.json", [_suite(), _suite()])
assert verdict.main(["args", "--required", str(required), "--suite", "s.one", "--os", "linux"]) == 2
assert "more than once" in capsys.readouterr().err
required.write_text('[1, "x"]', encoding="utf-8")
assert verdict.main(["args", "--required", str(required), "--suite", "s.one", "--os", "linux"]) == 2
assert "is not an object" in capsys.readouterr().err
# --- complete ------------------------------------------------------------------------------------------------------
def _results(tmp_path, rows):
"""Run judge for every (suite, os) of rows into tmp_path/results/<artifact>/, as the gate downloads them."""
required = _write_required(tmp_path / "required.json", rows)
for row in rows:
for os_name in row["os"]:
binary = tmp_path / ("engine-%s.bin" % os_name)
binary.write_bytes(("engine-" + os_name).encode())
junit = _junit(tmp_path / ("j-%s-%s.xml" % (row["id"], os_name)), GREEN)
out = tmp_path / "results" / ("result-%s-%s" % (row["id"], os_name)) / ("%s.%s.json" % (row["id"], os_name))
code = verdict.main(["judge", "--required", str(required), "--suite", row["id"], "--os", os_name,
"--junit", str(junit), "--binary", str(binary), "--commit", SHA, "--out", str(out)])
assert code == 0
return required, tmp_path / "results"
def _complete(required, results):
return verdict.main(["complete", "--required", str(required), "--results", str(results)])
def _edit(results, name, **fields):
path = next(results.rglob(name))
data = json.loads(path.read_text(encoding="utf-8"))
data.update(fields)
path.write_text(json.dumps(data), encoding="utf-8")
ROWS = [_suite(), _suite(id="s.two", os=["linux"])]
def test_complete_is_green_when_every_leg_reported_green_at_one_commit(tmp_path, capsys):
required, results = _results(tmp_path, ROWS)
capsys.readouterr()
assert _complete(required, results) == 0
assert "COMPLETE GREEN: 3 result(s)" in capsys.readouterr().out
def test_complete_fails_on_a_leg_that_never_reported(tmp_path, capsys):
required, results = _results(tmp_path, ROWS)
next(results.rglob("s.one.windows.json")).unlink()
capsys.readouterr()
assert _complete(required, results) == 1
assert "s.one/windows has no result" in capsys.readouterr().out
def test_complete_fails_on_a_missing_results_folder(tmp_path, capsys):
required = _write_required(tmp_path / "required.json", ROWS)
assert _complete(required, tmp_path / "nothing") == 1
out = capsys.readouterr().out
assert "does not exist" in out and "s.two/linux has no result" in out
def test_complete_fails_on_a_red_result(tmp_path, capsys):
required, results = _results(tmp_path, ROWS)
_edit(results, "s.two.linux.json", verdict="red", problems=["1 test(s) failed"])
capsys.readouterr()
assert _complete(required, results) == 1
assert "s.two/linux is not green" in capsys.readouterr().out
def test_complete_fails_on_a_result_with_no_verdict(tmp_path):
required, results = _results(tmp_path, ROWS)
_edit(results, "s.two.linux.json", verdict=None)
assert _complete(required, results) == 1
def test_complete_fails_on_a_result_of_a_suite_that_is_not_in_the_list(tmp_path, capsys):
required, results = _results(tmp_path, ROWS)
(results / "result-s.ghost-linux").mkdir()
(results / "result-s.ghost-linux" / "g.json").write_text(
json.dumps({"suite": "s.ghost", "os": "linux", "verdict": "green"}), encoding="utf-8")
capsys.readouterr()
assert _complete(required, results) == 1
assert "s.ghost/linux, which is not in the required list" in capsys.readouterr().out
def test_complete_fails_on_a_result_of_an_os_the_suite_does_not_run_on(tmp_path, capsys):
required, results = _results(tmp_path, ROWS)
(results / "result-s.two-windows").mkdir()
(results / "result-s.two-windows" / "w.json").write_text(
json.dumps({"suite": "s.two", "os": "windows", "verdict": "green"}), encoding="utf-8")
capsys.readouterr()
assert _complete(required, results) == 1
assert "s.two/windows, which is not in the required list" in capsys.readouterr().out
def test_complete_fails_on_the_same_leg_reported_twice(tmp_path, capsys):
required, results = _results(tmp_path, ROWS)
src = next(results.rglob("s.two.linux.json"))
(results / "again").mkdir()
(results / "again" / "copy.json").write_text(src.read_text(encoding="utf-8"), encoding="utf-8")
capsys.readouterr()
assert _complete(required, results) == 1
assert "s.two/linux has two results" in capsys.readouterr().out
def test_complete_fails_on_legs_at_different_commits(tmp_path, capsys):
required, results = _results(tmp_path, ROWS)
_edit(results, "s.one.windows.json", commit="c" * 40)
capsys.readouterr()
assert _complete(required, results) == 1
assert "different commits" in capsys.readouterr().out
def test_complete_fails_when_two_suites_of_one_os_ran_with_different_binaries(tmp_path, capsys):
required, results = _results(tmp_path, ROWS)
_edit(results, "s.two.linux.json", binary_sha256="f" * 64)
capsys.readouterr()
assert _complete(required, results) == 1
assert "linux legs ran with different binaries" in capsys.readouterr().out
def test_complete_fails_on_a_result_with_no_binary_hash(tmp_path, capsys):
required, results = _results(tmp_path, ROWS)
_edit(results, "s.two.linux.json", binary_sha256=None)
capsys.readouterr()
assert _complete(required, results) == 1
assert "no binary sha256" in capsys.readouterr().out
def test_complete_allows_different_binaries_for_different_os(tmp_path):
required, results = _results(tmp_path, ROWS) # engine-linux.bin and engine-windows.bin differ
assert _complete(required, results) == 0
def test_complete_fails_on_an_unreadable_json_and_on_a_json_that_is_not_a_result(tmp_path, capsys):
required, results = _results(tmp_path, ROWS)
(results / "junk.json").write_text("{not json", encoding="utf-8")
(results / "other.json").write_text("[1]", encoding="utf-8")
capsys.readouterr()
assert _complete(required, results) == 1
out = capsys.readouterr().out
assert "junk.json cannot be read" in out and "other.json is not a result" in out
# --- the real list-----------------------------------------------------------------------------------------------
def _real():
return json.loads(REQUIRED.read_text(encoding="utf-8"))
def test_the_real_list_is_well_formed_for_the_judge_and_every_row_is_exact():
rows = _real()
assert verdict.validate_list(rows) == []
assert [r["id"] for r in rows if r["exact"] is not True] == []
def test_the_real_list_has_unique_ids_and_sane_rows():
rows = _real()
ids = [r["id"] for r in rows]
assert rows and len(ids) == len(set(ids)), ids
for r in rows:
assert set(r["os"]) and set(r["os"]) <= {"linux", "windows"}, r["id"]
assert isinstance(r["min_tests"], int) and r["min_tests"] > 0, r["id"]
assert r["tests"] and len(r["tests"]) == len(set(r["tests"])), r["id"]
assert r["giro"] in {"G1", "G2"}, r["id"]
# needs_root is a bool (every OS of the row) or the list of the OSes that need root
root = r["needs_root"]
assert isinstance(root, bool) or (isinstance(root, list) and set(root) <= set(r["os"])), r["id"]
def test_every_required_file_exists_and_every_node_id_is_defined_in_it():
for r in _real():
for entry in r["tests"]:
path, _sep, name = entry.partition("::")
file = ROOT / path
assert file.is_file(), "%s: %s does not exist" % (r["id"], path)
if name:
text = file.read_text(encoding="utf-8")
base = name.split("[", 1)[0]
assert re.search(r"^\s*(async\s+)?def %s\(" % re.escape(base), text, re.M), \
"%s: %s has no def %s" % (r["id"], path, base)
def test_a_required_suite_runs_with_the_marker_it_names():
for r in _real():
assert r["marker"] in {"unit", "e2e"}, r["id"]
if r["marker"] == "unit":
for entry in r["tests"]:
assert "pytestmark = pytest.mark.unit" in (ROOT / entry.split("::")[0]).read_text(encoding="utf-8") \
or "@pytest.mark.unit" in (ROOT / entry.split("::")[0]).read_text(encoding="utf-8"), entry
def test_a_suite_that_needs_root_only_on_linux_still_runs_on_windows():
doh = [r for r in _real() if r["id"] == "wrapper.e2e.doh"][0]
assert doh["os"] == ["linux", "windows"] and doh["needs_root"] == ["linux"]
+50 -36
View File
@@ -6,23 +6,35 @@ consent iframe was completely unreachable from Playwright in 0.1.7 -
threw cross-origin SOP errors, and ``frame_locator().click()`` timed
out.
Root cause was a missing pref. FF150 ships with
``fission.webContentIsolationStrategy=1`` (IsolateEverything), which
site-isolates cross-origin iframes into separate webIsolated content
processes even when ``fission.autostart=False``. The Juggler code paths
inherited from the FF146 era assume same-process iframes. The wrapper's
``_BASELINE`` now pins the pref to 0 (IsolateNothing).
Root cause was that the Juggler code paths inherited from the FF146 era
assumed same-process iframes, while the engine site-isolated cross-origin
iframes into separate webIsolated content processes. The baseline then
pinned ``fission.webContentIsolationStrategy`` to 0 (IsolateNothing) and
kept ``fission.autostart`` off, so every iframe lived in the process of
its page.
firefox-62 reaches a frame in another process like any other, so the
baseline now runs Fission the way retail Firefox does on desktop:
``fission.webContentIsolationStrategy=1`` (IsolateEverything, one content
process per site), ``fission.autostart=True`` and four isolated content
processes. ``fission.autostart.session`` is written by the parent at
startup and is not declared.
These tests exist so a future Firefox upgrade or a fingerprint A/B
that flips this pref by accident cannot ship without a red CI signal.
that flips these prefs by accident cannot ship without a red CI signal.
The prefs belong to ``invisible_core.prefs._BASELINE``: the unit layer
needs an ``invisible-core`` that declares them.
Layers:
* ``unit`` - ``_BASELINE`` contains the pref with the right value. No browser.
* ``unit`` - ``_BASELINE`` contains the prefs with the right values. No browser.
* ``e2e`` - launch the real binary against a LOCAL HTTP harness on
``127.0.0.1`` (two ports = two SOP origins) and verify the
four protocol operations that regressed: frame URL tracking,
``handle.content_frame()``, ``frame.evaluate()``, and
``frame_locator(...).locator(...)`` element resolution.
``127.0.0.1`` and verify the four protocol operations that
regressed: frame URL tracking, ``handle.content_frame()``,
``frame.evaluate()``, and ``frame_locator(...).locator(...)``
element resolution. The harness uses two ports of one host,
which is one SITE: those iframes stay in the process of the
page even at strategy 1. The iframes that leave the process
(different hosts) are held by ``test_fission_strategy1_bench.py``.
The e2e tests run entirely offline. They never call out to a real site;
the cross-origin shape is reproduced with two local HTTP servers on
@@ -46,51 +58,53 @@ from invisible_core.prefs import _BASELINE, translate_profile_to_prefs
@pytest.mark.unit
def test_baseline_pins_web_content_isolation_strategy_to_zero():
def test_baseline_pins_web_content_isolation_strategy_to_one():
"""Regression sentinel.
``fission.webContentIsolationStrategy`` MUST be 0 (IsolateNothing).
The FF150 default is 1 (IsolateEverything), which site-isolates
cross-origin iframes into separate webIsolated content processes
and breaks Playwright frame tracking from the parent process.
``fission.webContentIsolationStrategy`` MUST be 1 (IsolateEverything):
one content process per site, as retail Firefox on desktop. The
Juggler of firefox-62 reaches an iframe of another process like any
other; strategy 0 (IsolateNothing) put every iframe in the process of
its page and is no longer the baseline.
"""
assert _BASELINE["fission.webContentIsolationStrategy"] == 0, (
"fission.webContentIsolationStrategy must be 0 (IsolateNothing). "
"If you bumped it for an A/B, cross-origin iframes will appear "
"in page.frames with empty URLs and content_frame() will return "
"None - see the changelog entry that introduced this test."
assert _BASELINE["fission.webContentIsolationStrategy"] == 1, (
"fission.webContentIsolationStrategy must be 1 (IsolateEverything). "
"With 0, a cross-site iframe shares the process of its page, "
"which no retail Firefox on desktop does."
)
@pytest.mark.unit
def test_baseline_keeps_fission_autostart_off():
"""Belt for the suspenders above. All three prefs are required."""
assert _BASELINE["fission.autostart"] is False
assert _BASELINE["fission.autostart.session"] is False
assert _BASELINE["dom.ipc.processCount.webIsolated"] == 1
def test_baseline_runs_fission_with_four_isolated_processes():
"""Belt for the suspenders above. All three prefs go together."""
assert _BASELINE["fission.autostart"] is True
# The parent writes `fission.autostart.session` at startup (nsAppRunner):
# declaring it would be overwritten, so the baseline must not carry it.
assert "fission.autostart.session" not in _BASELINE
assert _BASELINE["dom.ipc.processCount.webIsolated"] == 4
@pytest.mark.unit
def test_translated_profile_propagates_isolation_strategy():
"""The fix must survive translate_profile_to_prefs, not just live in _BASELINE."""
"""The strategy must survive translate_profile_to_prefs, not just live in _BASELINE."""
p = generate_profile(seed=42)
prefs = translate_profile_to_prefs(p, timezone="America/New_York")
assert prefs["fission.webContentIsolationStrategy"] == 0
assert prefs["fission.webContentIsolationStrategy"] == 1
@pytest.mark.unit
def test_extra_prefs_override_can_break_isolation_only_explicitly():
"""If a caller wants to A/B isolation, they have to set it explicitly.
The wrapper does not silently flip it back on.
The wrapper does not silently flip it back off.
"""
p = generate_profile(seed=42)
prefs_default = translate_profile_to_prefs(p, timezone="America/New_York")
assert prefs_default["fission.webContentIsolationStrategy"] == 0
assert prefs_default["fission.webContentIsolationStrategy"] == 1
prefs_ab = translate_profile_to_prefs(
p, timezone="America/New_York", extra_prefs={"fission.webContentIsolationStrategy": 1}
p, timezone="America/New_York", extra_prefs={"fission.webContentIsolationStrategy": 0}
)
assert prefs_ab["fission.webContentIsolationStrategy"] == 1
assert prefs_ab["fission.webContentIsolationStrategy"] == 0
# ────────────────────────────────────────────────────────────────────
@@ -190,9 +204,9 @@ def cross_origin_harness():
def test_cross_origin_iframe_url_appears_in_page_frames(firefox_binary, cross_origin_harness):
"""``page.frames`` must list the cross-origin iframe with its real URL.
Before the pref fix, the URL came back as '' because the navigation
observer for the iframe fired in a different content process than
the parent's FrameTree was registered in.
Before the fix of issue #20, the URL came back as '' because the
navigation observer for the iframe fired in a different content process
than the parent's FrameTree was registered in.
"""
from invisible_playwright import InvisiblePlaywright
+1 -1
View File
@@ -73,7 +73,7 @@ def test_the_data_has_every_function_and_the_inputs_that_tell_the_libraries_apar
@pytest.mark.e2e
def test_css_calc_functions_are_ucrtbase_bytes(firefox_binary, engine_at_least):
engine_at_least("firefox-60")
engine_at_least("firefox-64")
from invisible_playwright import InvisiblePlaywright
cases = _cases()
+120 -269
View File
@@ -3,131 +3,40 @@
The other cursor test file asks whether the plumbing is connected. This one
asks whether the schedule survives contact with a real machine, and whether
the behaviour planner - which for a while was 1000 lines that nothing in the
package imported - is now driving events.
package imported - is now driving events. The pointer it drives is the
SERVER's (`_juggler/pointer.py`), the one every client's actions arrive at.
Nothing here launches a browser. Two clocks are used:
* a VIRTUAL clock, which advances only when something sleeps, for every
property that is about the plan rather than about the platform. It makes
those tests exact and instant.
* the REAL clock, for the three assertions that are specifically about
delivery. Windows quantises a short sleep to the system timer, so this is
the only way to see the thing the dispatcher exists to fix. They are kept
short on purpose (a couple of seconds in total).
* the REAL clock, for the assertions that are specifically about delivery.
Windows quantises a short sleep to the system timer, so this is the only
way to see the thing the dispatcher exists to fix. They are kept short on
purpose (a couple of seconds in total).
The measured "before" numbers quoted below come from running the same paths
through the previous dispatcher - one ``asyncio.sleep(dt)`` per waypoint,
relative delays - on this machine.
through the previous dispatcher - one ``sleep(dt)`` per waypoint, relative
delays - on this machine.
"""
from __future__ import annotations
import asyncio
import statistics
import time
import pytest
from invisible_core.juggler import _behaviour, _motion
from invisible_core.juggler import Ev, MIN_EVENT_INTERVAL_MS, fit_timeline
from invisible_core.juggler import _motion
from invisible_playwright import _cursor
from invisible_playwright._juggler import pointer as pointer_mod
from _pointer_fakes import BOX, LateClock, VirtualClock, make_pointer, use_clock
pytestmark = pytest.mark.unit
# ── clocks ──────────────────────────────────────────────────────────────────
class VirtualTimer:
def __init__(self) -> None:
self.t = 0.0
def now(self) -> float:
return self.t
async def sleep(self, seconds: float) -> None:
self.t += max(0.0, seconds)
class LateTimer(VirtualTimer):
"""A platform that always oversleeps by a fixed amount.
This is Windows with its default 15.6 ms timer tick, in a form that can be
asserted on exactly. It is the condition the old dispatcher turned into a
1.5x stretch of every movement, because it slept for each gap in turn and
so added the overshoot once per waypoint.
"""
def __init__(self, overshoot: float = 0.006) -> None:
super().__init__()
self.overshoot = overshoot
async def sleep(self, seconds: float) -> None:
self.t += max(0.0, seconds) + self.overshoot
# ── fakes ───────────────────────────────────────────────────────────────────
class _FakeMouse:
def __init__(self, page):
self._channel = type("_Ch", (), {"_object": page})()
self._page = page
async def move(self, x, y, steps=None):
self._page.moves.append((x, y))
async def wheel(self, dx, dy):
self._page.wheels.append((dx, dy))
class _FakeContext:
def __init__(self, browser=None):
self._browser = browser
class _FakeBrowser:
pass
class _FakePage:
def __init__(self, context, width=1280, height=720, number=0):
self._browser_context = context
# The page's number in the session, as the server's initializer
# carries it (`_cursor.page_number`).
self._initializer = {"pageNumber": number}
self._viewport_size = {"width": width, "height": height}
self.moves = []
self.wheels = []
self.mouse = _FakeMouse(self)
_BOX = {"x": 500.0, "y": 300.0, "width": 140.0, "height": 44.0}
class _FakeChannel:
async def send(self, method, timeout_calculator=None, params=None, **kwargs):
# `checkHitTarget`: the server says the point lands on the element.
return True
class _FakeHandle:
_channel = _FakeChannel()
async def bounding_box(self):
return dict(_BOX)
async def dispose(self):
pass
def _frame(page):
class _FakeFrame:
_page = page
async def query_selector(self, selector):
return _FakeHandle()
return _FakeFrame()
@pytest.fixture(autouse=True)
def quiet():
_cursor._reset_warnings()
@@ -135,27 +44,10 @@ def quiet():
_cursor._reset_warnings()
@pytest.fixture
def cursor_page(monkeypatch):
async def fake_move(mouse, x, y):
await mouse.move(x, y)
# Arm first: installing the wrappers is what captures the real
# Mouse.move, so patching before that would be undone by it.
_cursor._ensure_patched()
monkeypatch.setattr(_cursor, "_ORIGINAL_MOUSE_MOVE", fake_move)
@pytest.fixture(autouse=True)
def landing_on(monkeypatch):
monkeypatch.delenv(_cursor.LANDING_ENV, raising=False)
def build(seed=4242, max_seconds=1.5):
browser = _FakeBrowser()
assert _cursor.enable_for(browser, seed=seed, max_seconds=max_seconds)
page = _FakePage(_FakeContext(browser))
cursor = _cursor._cursor_for_page(page)
assert cursor is not None
return page, cursor
return build
# ═══════════════════════════════════════════════════════════════════════════
# 1. B2 - the schedule survives a platform that cannot keep it
@@ -166,12 +58,10 @@ def _path(seed=42, frm=(120.0, 640.0), to=(980.0, 200.0)):
def _events(path):
return _cursor._fit_timeline(
[_cursor._Ev(wp.t_ms, wp.x, wp.y) for wp in path[1:]], 0.0
)
return fit_timeline([Ev(wp.t_ms, wp.x, wp.y) for wp in path[1:]], 0.0)
def test_lateness_does_not_accumulate():
def test_lateness_does_not_accumulate(monkeypatch):
"""The defect, stated exactly.
A platform that oversleeps by 6 ms on every wait used to add 6 ms to every
@@ -182,13 +72,11 @@ def test_lateness_does_not_accumulate():
path = _path()
evs = _events(path)
planned_ms = evs[-1].t_ms
timer = LateTimer(0.006)
clock = LateClock(0.006)
use_clock(monkeypatch, clock)
sink = []
async def emit(x, y):
sink.append(timer.now())
asyncio.run(_cursor._dispatch(evs, emit, timer=timer))
pointer_mod._drive(evs, lambda x, y: sink.append(clock.now()))
delivered_ms = (sink[-1] - sink[0]) * 1000.0
naive_ms = planned_ms + 6.0 * len(evs)
@@ -202,17 +90,15 @@ def test_lateness_does_not_accumulate():
assert len(sink) == len(evs)
def test_a_platform_too_slow_for_the_plan_pays_in_waypoints():
def test_a_platform_too_slow_for_the_plan_pays_in_waypoints(monkeypatch):
"""When the machine cannot deliver the planned density, the plan loses
events and keeps its timing - not the other way round."""
evs = _events(_path())
timer = LateTimer(0.03)
clock = LateClock(0.03)
use_clock(monkeypatch, clock)
sink = []
async def emit(x, y):
sink.append(timer.now())
asyncio.run(_cursor._dispatch(evs, emit, timer=timer))
pointer_mod._drive(evs, lambda x, y: sink.append(clock.now()))
assert len(sink) < len(evs) * 0.75, (
"%d of %d waypoints survived a platform three times too slow"
% (len(sink), len(evs))
@@ -221,31 +107,25 @@ def test_a_platform_too_slow_for_the_plan_pays_in_waypoints():
assert delivered_ms <= evs[-1].t_ms + 40.0, delivered_ms
def test_no_two_events_are_delivered_in_the_same_instant():
def test_no_two_events_are_delivered_in_the_same_instant(monkeypatch):
"""Catching up must not turn into an event rate no device produces."""
timer = LateTimer(0.011)
clock = LateClock(0.011)
use_clock(monkeypatch, clock)
evs = _events(_path())
sink = []
async def emit(x, y):
sink.append(timer.now())
asyncio.run(_cursor._dispatch(evs, emit, timer=timer))
pointer_mod._drive(evs, lambda x, y: sink.append(clock.now()))
gaps = [(sink[i] - sink[i - 1]) * 1000.0 for i in range(1, len(sink))]
assert min(gaps) >= _cursor.MIN_EVENT_INTERVAL_MS - 1e-6, min(gaps)
assert min(gaps) >= MIN_EVENT_INTERVAL_MS - 1e-6, min(gaps)
def test_a_dropped_waypoint_is_the_one_that_was_superseded():
def test_a_dropped_waypoint_is_the_one_that_was_superseded(monkeypatch):
"""What survives is the plan's own timeline, sampled coarsely - not a
prefix of it and not a rescaled copy of it."""
timer = LateTimer(0.02)
clock = LateClock(0.02)
use_clock(monkeypatch, clock)
evs = _events(_path())
sink = []
async def emit(x, y):
sink.append((timer.now(), x, y))
asyncio.run(_cursor._dispatch(evs, emit, timer=timer))
pointer_mod._drive(evs, lambda x, y: sink.append((clock.now(), x, y)))
assert (sink[-1][1], sink[-1][2]) == (evs[-1].x, evs[-1].y), (
"the endpoint of a movement is never dropped"
)
@@ -273,16 +153,12 @@ def test_delivered_timing_on_a_real_clock(seed):
evs = _events(path)
planned_span = evs[-1].t_ms - evs[0].t_ms
async def run(dispatch):
def run(dispatch):
sink = []
async def emit(x, y):
sink.append(time.perf_counter())
await dispatch(evs, emit)
dispatch(evs, lambda x, y: sink.append(time.perf_counter()))
return sink
async def naive(events, emit):
def naive(events, emit):
"""The dispatcher this replaced: sleep the gap, once per waypoint.
Its error is O(n) - every sleep contributes its own quantisation, and
@@ -294,9 +170,9 @@ def test_delivered_timing_on_a_real_clock(seed):
for e in events:
gap = (e.t_ms - prev) / 1000.0
if gap > 0:
await asyncio.sleep(gap)
time.sleep(gap)
prev = e.t_ms
await emit(e.x, e.y)
emit(e.x, e.y)
# INTERLEAVED, not measured against a constant. A bound like "within 1.20x
# of plan" is a statement about the machine, not about the code: this test
@@ -305,13 +181,9 @@ def test_delivered_timing_on_a_real_clock(seed):
# BOTH dispatchers, so comparing them back to back on the same busy machine
# is the only form that measures the change instead of the moment. Same
# rule the project applies to every other A/B.
async def both():
a = await run(_cursor._dispatch) # A
b = await run(naive) # B
c = await run(_cursor._dispatch) # A again, so a drifting machine shows up
return a, b, c
a, b, c = asyncio.run(both())
a = run(pointer_mod._drive) # A
b = run(naive) # B
c = run(pointer_mod._drive) # A again, so a drifting machine shows up
def span_ms(sink):
return (sink[-1] - sink[0]) * 1000.0
@@ -333,7 +205,7 @@ def test_delivered_timing_on_a_real_clock(seed):
# And a floor that does not depend on the clock at all: the schedule must
# never be compressed below what a device could report.
delivered = [(a[i] - a[i - 1]) * 1000.0 for i in range(1, len(a))]
assert min(delivered) >= _cursor.MIN_EVENT_INTERVAL_MS - 1.0
assert min(delivered) >= MIN_EVENT_INTERVAL_MS - 1.0
# ═══════════════════════════════════════════════════════════════════════════
@@ -347,12 +219,12 @@ def test_the_time_cap_drops_waypoints_instead_of_speeding_them_up(cap):
every 0.55 ms, i.e. 1800 Hz. No mouse reports that and no browser emits
it."""
raw = _motion.CursorMotion(4242).path(10.0, 10.0, 1200.0, 680.0)
paced = _cursor._normalise_waypoints(raw, cap)
paced = pointer_mod._normalise_waypoints(raw, cap)
assert paced, "the cap must not swallow the whole movement"
total = sum(d for _, _, d in paced)
assert total <= cap + 1e-9
gaps = [d for _, _, d in paced[1:]]
assert min(gaps) * 1000.0 >= _cursor.MIN_EVENT_INTERVAL_MS - 1e-9, (
assert min(gaps) * 1000.0 >= MIN_EVENT_INTERVAL_MS - 1e-9, (
"%.3f ms between events is %.0f Hz" % (min(gaps) * 1000.0,
1.0 / max(min(gaps), 1e-9))
)
@@ -360,22 +232,22 @@ def test_the_time_cap_drops_waypoints_instead_of_speeding_them_up(cap):
def test_a_tighter_cap_means_strictly_fewer_events():
raw = _motion.CursorMotion(99).path(10.0, 10.0, 1200.0, 680.0)
counts = [len(_cursor._normalise_waypoints(raw, cap))
counts = [len(pointer_mod._normalise_waypoints(raw, cap))
for cap in (0.05, 0.15, 0.5, 2.0)]
assert counts[0] < counts[1] < counts[2] <= counts[3]
def test_the_cap_bounds_a_whole_action_not_each_stroke(cursor_page, monkeypatch):
def test_the_cap_bounds_a_whole_action_not_each_stroke(monkeypatch):
"""An approach is several strokes plus whatever fidget precedes it. The
budget the caller asked for is for the action, not for each piece of it."""
timer = VirtualTimer()
monkeypatch.setattr(_cursor, "_TIMER", timer)
page, cursor = cursor_page(seed=5, max_seconds=0.3)
cursor.last_event_at = timer.now()
timer.t += 9.0 # a long think, so the fidget is in play too
t0 = timer.now()
asyncio.run(_cursor._approach(_frame(page), ("#buy",), {}, timer=timer))
assert timer.now() - t0 <= 0.3 + 1e-6, timer.now() - t0
clock = VirtualClock()
use_clock(monkeypatch, clock)
page, pointer = make_pointer(seed=5, max_seconds=0.3)
pointer.hand.last_event_at = clock.now()
clock.t += 9.0 # a long think, so the fidget is in play too
t0 = clock.now()
pointer.approach("main", "#buy", None)
assert clock.now() - t0 <= 0.3 + 1e-6, clock.now() - t0
assert page.moves
@@ -383,19 +255,18 @@ def test_the_cap_bounds_a_whole_action_not_each_stroke(cursor_page, monkeypatch)
# 3. B1 - the macro layer is actually driving events
# ═══════════════════════════════════════════════════════════════════════════
def test_an_approach_is_more_than_one_stroke(cursor_page, monkeypatch):
def test_an_approach_is_more_than_one_stroke(monkeypatch):
"""Overshoot and correction, from ``_behaviour.plan_approach``. Without it
every approach is a single monotone glide, which is a shape as recognisable
as any constant."""
timer = VirtualTimer()
monkeypatch.setattr(_cursor, "_TIMER", timer)
use_clock(monkeypatch, VirtualClock())
reversals = 0
for seed in range(30):
page, cursor = cursor_page(seed=seed)
asyncio.run(_cursor._approach(_frame(page), ("#buy",), {}, timer=timer))
page, pointer = make_pointer(seed=seed)
pointer.approach("main", "#buy", None)
pts = page.moves
assert len(pts) > 3
target = (_BOX["x"] + _BOX["width"] / 2.0, _BOX["y"] + _BOX["height"] / 2.0)
target = (BOX["x"] + BOX["width"] / 2.0, BOX["y"] + BOX["height"] / 2.0)
d = [((x - target[0]) ** 2 + (y - target[1]) ** 2) ** 0.5 for x, y in pts]
# a corrective submovement shows up as distance-to-target going back up
if any(d[i] > d[i - 1] + 0.5 for i in range(len(d) // 2, len(d))):
@@ -405,66 +276,64 @@ def test_an_approach_is_more_than_one_stroke(cursor_page, monkeypatch):
)
def test_nothing_fidgets_between_two_back_to_back_actions(cursor_page, monkeypatch):
def test_nothing_fidgets_between_two_back_to_back_actions(monkeypatch):
"""Two calls in a row are one piece of work. Inserting idle motion between
them would be both a lie and a delay on a caller who asked for neither."""
timer = VirtualTimer()
monkeypatch.setattr(_cursor, "_TIMER", timer)
page, cursor = cursor_page(seed=3)
cursor.last_event_at = timer.now()
assert _cursor._plan_fidget(cursor, page, timer) == []
timer.t += 0.2
assert _cursor._plan_fidget(cursor, page, timer) == []
clock = VirtualClock()
use_clock(monkeypatch, clock)
page, pointer = make_pointer(seed=3)
pointer.hand.last_event_at = clock.now()
assert pointer._plan_fidget() == []
clock.t += 0.2
assert pointer._plan_fidget() == []
def test_a_long_pause_produces_motion_the_caller_never_asked_for(cursor_page,
monkeypatch):
def test_a_long_pause_produces_motion_the_caller_never_asked_for(monkeypatch):
"""The point of the whole macro layer: a pointer that is motionless except
for the second it takes to slide onto the next control is measurably a
pointer that exists in order to click."""
timer = VirtualTimer()
monkeypatch.setattr(_cursor, "_TIMER", timer)
clock = VirtualClock()
use_clock(monkeypatch, clock)
found = 0
for seed in range(20):
page, cursor = cursor_page(seed=seed)
cursor.last_event_at = timer.now()
timer.t += 12.0
steps = _cursor._plan_fidget(cursor, page, timer)
page, pointer = make_pointer(seed=seed)
pointer.hand.last_event_at = clock.now()
clock.t += 12.0
steps = pointer._plan_fidget()
if steps:
found += 1
assert all(s.kind != "wait" for s in steps)
assert found >= 16, "only %d/20 sessions fidgeted after a 12 s pause" % found
def test_the_fidget_is_bounded_by_its_share_of_the_budget(cursor_page,
monkeypatch):
timer = VirtualTimer()
monkeypatch.setattr(_cursor, "_TIMER", timer)
def test_the_fidget_is_bounded_by_its_share_of_the_budget(monkeypatch):
clock = VirtualClock()
use_clock(monkeypatch, clock)
for seed in range(25):
page, cursor = cursor_page(seed=seed, max_seconds=1.0)
cursor.last_event_at = timer.now()
timer.t += 30.0
steps = _cursor._plan_fidget(cursor, page, timer)
page, pointer = make_pointer(seed=seed, max_seconds=1.0)
pointer.hand.last_event_at = clock.now()
clock.t += 30.0
steps = pointer._plan_fidget()
spent = sum(s.delay_ms for s in steps[1:])
assert spent <= 1000.0 * _cursor._IDLE_BUDGET_FRAC + 1.0, spent
assert spent <= 1000.0 * pointer_mod._IDLE_BUDGET_FRAC + 1.0, spent
def test_some_bursts_end_nowhere_near_a_control(cursor_page, monkeypatch):
def test_some_bursts_end_nowhere_near_a_control(monkeypatch):
"""If every movement of a session terminates on a clickable element then
the set of endpoints is a signature on its own."""
timer = VirtualTimer()
monkeypatch.setattr(_cursor, "_TIMER", timer)
clock = VirtualClock()
use_clock(monkeypatch, clock)
off_control = 0
for seed in range(30):
page, cursor = cursor_page(seed=seed)
cursor.last_event_at = timer.now()
timer.t += 8.0
steps = _cursor._plan_fidget(cursor, page, timer)
page, pointer = make_pointer(seed=seed)
pointer.hand.last_event_at = clock.now()
clock.t += 8.0
steps = pointer._plan_fidget()
if not steps:
continue
x, y = steps[-1].x, steps[-1].y
inside = (_BOX["x"] <= x <= _BOX["x"] + _BOX["width"]
and _BOX["y"] <= y <= _BOX["y"] + _BOX["height"])
inside = (BOX["x"] <= x <= BOX["x"] + BOX["width"]
and BOX["y"] <= y <= BOX["y"] + BOX["height"])
if not inside:
off_control += 1
assert off_control >= 20, off_control
@@ -474,53 +343,44 @@ def test_some_bursts_end_nowhere_near_a_control(cursor_page, monkeypatch):
# 4. B1 - the wheel
# ═══════════════════════════════════════════════════════════════════════════
def _wheel(page, dx, dy, timer):
async def original(mouse, deltaX, deltaY):
page.wheels.append((deltaX, deltaY))
wrapped = _cursor._wrap_mouse_wheel(original)
# By keyword, exactly as both generated API layers call it. Positionally
# this would pass whatever the parameters were called.
asyncio.run(wrapped(page.mouse, deltaX=dx, deltaY=dy))
def _wheel(page, pointer, dx, dy):
"""What `PageDispatcher.op_mouse_wheel` does with it."""
if not pointer.wheel(dx, dy):
page.actions.wheel(dx, dy)
def test_a_scroll_becomes_detents_with_a_hand_on_the_mouse(cursor_page,
monkeypatch):
timer = VirtualTimer()
monkeypatch.setattr(_cursor, "_TIMER", timer)
page, cursor = cursor_page(seed=8)
_wheel(page, 0.0, 900.0, timer)
def test_a_scroll_becomes_detents_with_a_hand_on_the_mouse(monkeypatch):
use_clock(monkeypatch, VirtualClock())
page, pointer = make_pointer(seed=8)
_wheel(page, pointer, 0.0, 900.0)
assert len(page.wheels) >= 5, page.wheels
assert page.moves, "the pointer held perfectly still while the wheel turned"
def test_a_scroll_still_scrolls_exactly_what_it_was_asked_to(cursor_page,
monkeypatch):
def test_a_scroll_still_scrolls_exactly_what_it_was_asked_to(monkeypatch):
"""A scroll that lands somewhere else is a broken call, not a subtle one."""
timer = VirtualTimer()
monkeypatch.setattr(_cursor, "_TIMER", timer)
use_clock(monkeypatch, VirtualClock())
for dx, dy in [(0.0, 900.0), (0.0, -640.0), (300.0, 300.0), (0.0, 37.0)]:
page, cursor = cursor_page(seed=8)
_wheel(page, dx, dy, timer)
page, pointer = make_pointer(seed=8)
_wheel(page, pointer, dx, dy)
assert sum(w[0] for w in page.wheels) == pytest.approx(dx)
assert sum(w[1] for w in page.wheels) == pytest.approx(dy)
def test_a_short_scroll_is_left_alone(cursor_page, monkeypatch):
timer = VirtualTimer()
monkeypatch.setattr(_cursor, "_TIMER", timer)
page, cursor = cursor_page(seed=8)
_wheel(page, 0.0, 40.0, timer)
def test_a_short_scroll_is_left_alone(monkeypatch):
use_clock(monkeypatch, VirtualClock())
page, pointer = make_pointer(seed=8)
_wheel(page, pointer, 0.0, 40.0)
assert page.wheels == [(0.0, 40.0)]
def test_the_scroll_burst_respects_the_budget(cursor_page, monkeypatch):
timer = VirtualTimer()
monkeypatch.setattr(_cursor, "_TIMER", timer)
page, cursor = cursor_page(seed=8, max_seconds=0.5)
t0 = timer.now()
_wheel(page, 0.0, 4000.0, timer)
assert timer.now() - t0 <= 0.5 + 1e-6
def test_the_scroll_burst_respects_the_budget(monkeypatch):
clock = VirtualClock()
use_clock(monkeypatch, clock)
page, pointer = make_pointer(seed=8, max_seconds=0.5)
t0 = clock.now()
_wheel(page, pointer, 0.0, 4000.0)
assert clock.now() - t0 <= 0.5 + 1e-6
# ═══════════════════════════════════════════════════════════════════════════
@@ -528,22 +388,13 @@ def test_the_scroll_burst_respects_the_budget(cursor_page, monkeypatch):
# ═══════════════════════════════════════════════════════════════════════════
def _session(seed, monkeypatch):
timer = VirtualTimer()
monkeypatch.setattr(_cursor, "_TIMER", timer)
async def fake_move(mouse, x, y):
await mouse.move(x, y)
_cursor._ensure_patched()
monkeypatch.setattr(_cursor, "_ORIGINAL_MOUSE_MOVE", fake_move)
browser = _FakeBrowser()
_cursor.enable_for(browser, seed=seed, max_seconds=1.5)
page = _FakePage(_FakeContext(browser))
cursor = _cursor._cursor_for_page(page)
clock = VirtualClock()
use_clock(monkeypatch, clock)
page, pointer = make_pointer(seed=seed, max_seconds=1.5)
for _ in range(3):
cursor.last_event_at = timer.now()
timer.t += 6.0
asyncio.run(_cursor._approach(_frame(page), ("#buy",), {}, timer=timer))
pointer.hand.last_event_at = clock.now()
clock.t += 6.0
pointer.approach("main", "#buy", None)
return page.moves
File diff suppressed because it is too large. Load diff
+196
View File
@@ -0,0 +1,196 @@
"""The host network a page sees is the one the session DECLARES, not the one of the machine (red until it is declared).
Design: ``invisible_WebRTC/notes/declared-interfaces-design.md`` and ``declared-interfaces-proofs.md`` (the private study
repository). Behind a
proxy the engine must not read the host's interfaces: the core declares one adapter in ``STEALTHFOX_WEBRTC_NETWORK``,
``v4=<private address>;v6=<0|1>;p6=<the exit's /64 prefix, empty without IPv6>`` (the IPv6 host is that prefix and a
temporary identifier; v6=1 without a prefix is no IPv6), and the engine answers the reads of the host (the interface list,
the default route, the address and port a bound socket reports) from it (nr_stealth_network.h). A page
then sees what retail Firefox on Windows shows on a machine with that adapter, whatever the machine under the browser has:
* no IPv6: ONE host name (udp + tcp), ranked 127 (the only address);
* IPv6: TWO host names, the IPv6 one ranked 127 above the IPv4 one at 126 (``nrinterfaceprioritizer.cpp:82-85``);
* the host ports are those of a Windows machine, chosen by our code: 49152-65535, a consecutive pair per connection
(IPv4 N, IPv6 N+1), drawn at random by our code for each connection (not by the kernel, not from the seed: two visits
with the same seed must not share ports), the same distribution on every host;
* two connections on one page connect to each other in the time retail takes.
Reference shape (retail 159, measured 2026-11-11, ``captures/retail/firefox-159.0-win/direct-dualstack-stun-candidates``):
host udp 2122252543 (IPv6) and 2122187007 (IPv4), host tcp 2105524479 and 2105458943, one name per address.
Red on an engine without the declared network (before webrtc/declared-interfaces b9bdb3c3ad + 6ca7a8c104): it gathered
every filtered address of the OS and let the kernel hand out the ports, so these failed on every machine with more than
one interface or a port range that is not Windows's, the IPv6 case everywhere, and the loopback test was slower than
retail and died with no usable interface. Hermetic: a local TCP-only SOCKS5 proxy and a local page, no external network.
"""
from __future__ import annotations
import statistics
import pytest
from test_webrtc_realness import (_FAKE_EGRESS, _e2e_binary, _launch, candidates, decode_priority, host_candidates,
is_mdns, local_https_page, socks5_tcp_only) # noqa: F401 (fixtures)
pytestmark = [pytest.mark.e2e, pytest.mark.usefixtures("the_udp_line")]
NETWORK_ENV = "STEALTHFOX_WEBRTC_NETWORK"
# retail 159 on Windows. The interface rank is the position in the prioritizer's sort, starting at 127
# (nrinterfaceprioritizer.cpp:183-189), so an IPv4-only machine ranks its one host 127, and with IPv6 the IPv6 host
# takes 127 and the IPv4 host 126.
UDP_127, UDP_126, TCP_127, TCP_126 = 2122252543, 2122187007, 2105524479, 2105458943
# The two shapes of the declared adapter: without IPv6, and with the exit's /64 prefix.
V4_ONLY = "v4=192.168.31.7;v6=0;p6="
DUAL = "v4=192.168.31.7;v6=1;p6=2a01:e0a:1f2:3450::/64"
_GATHER_JS = r"""async () => {
const pc = new RTCPeerConnection({iceServers: []});
pc.createDataChannel('');
const cands = [];
pc.addEventListener('icecandidate', e => { if (e.candidate && e.candidate.candidate) cands.push(e.candidate.candidate); });
await pc.setLocalDescription(await pc.createOffer());
await new Promise(r => setTimeout(r, 2500));
try { pc.close(); } catch (e) {}
return cands;
}"""
# Two connections on one page, connected to each other in script (the loopback test many demos use).
_LOOPBACK_JS = r"""async () => {
const t0 = performance.now();
const pc1 = new RTCPeerConnection(), pc2 = new RTCPeerConnection();
pc1.onicecandidate = e => { if (e.candidate) pc2.addIceCandidate(e.candidate).catch(() => {}); };
pc2.onicecandidate = e => { if (e.candidate) pc1.addIceCandidate(e.candidate).catch(() => {}); };
const dc = pc1.createDataChannel('x');
let opened = null, echoed = false;
dc.onopen = () => { opened = Math.round(performance.now() - t0); dc.send('ping'); };
pc2.ondatachannel = ev => { ev.channel.onmessage = m => ev.channel.send('pong:' + m.data); };
dc.onmessage = m => { echoed = (m.data === 'pong:ping'); };
await pc1.setLocalDescription(await pc1.createOffer());
await pc2.setRemoteDescription(pc1.localDescription);
await pc2.setLocalDescription(await pc2.createAnswer());
await pc1.setRemoteDescription(pc2.localDescription);
const deadline = performance.now() + 8000;
while (performance.now() < deadline && !(opened !== null && echoed)) await new Promise(r => setTimeout(r, 5));
pc1.close(); pc2.close();
return {opened, echoed};
}"""
# Retail 159 on Windows, 12 cold launches (``captures/mdns-loopback/retail-159-win-12``): 37-52 ms in ten of twelve, two
# slow ones at about 110, median 41.5. Without mDNS retail takes about 20 ms (``retail-159-win-nomdns``): the other 20 ms are
# the multicast round trip of the responder. The engine makes that round trip too, on the loopback (the responder joins and
# speaks on 127.0.0.1; a name of ours answers with the loopback of its family), so the window is the retail one: 30-55 ms on
# the MEDIAN of five cold launches. It keeps out "dead" (no usable interface), "slower than retail" and "faster than retail"
# (an answer that skips the round trip).
RETAIL_MEDIAN_WINDOW_MS = (30, 55)
def _session(declaration, socks, page_url, monkeypatch, seed, script):
"""One proxied launch with the declaration in the environment; runs ``script`` on the page and returns the result."""
binary = _e2e_binary()
if not binary:
pytest.skip("no patched binary (set STEALTHFOX_E2E_BINARY)")
monkeypatch.setenv("STEALTHFOX_WEBRTC_PUBLIC_IP", _FAKE_EGRESS)
monkeypatch.delenv("STEALTHFOX_WEBRTC_DISABLE_IPV6", raising=False) # the declaration replaces it
monkeypatch.setenv(NETWORK_ENV, declaration)
prefs = {"network.proxy.allow_hijacking_localhost": True, "network.proxy.no_proxies_on": ""}
proxy = {"server": "socks5://127.0.0.1:%d" % socks.port}
with _launch(binary_path=binary, proxy=proxy, extra_prefs=prefs, seed=seed) as browser:
page = browser.new_context().new_page()
page.goto(page_url, wait_until="domcontentloaded", timeout=60000)
return script(page)
def _host_shape(declaration, socks, page_url, monkeypatch, seed=42):
return host_candidates(candidates(
_session(declaration, socks, page_url, monkeypatch, seed, lambda page: page.evaluate(_GATHER_JS))))
def _by_protocol(hosts):
return {proto: sorted((c["priority"] for c in hosts if c["proto"] == proto), reverse=True)
for proto in ("UDP", "TCP")}
def _udp_ports_by_rank(hosts):
return {decode_priority(c["priority"])["iface_pref"]: c["port"] for c in hosts if c["proto"] == "UDP"}
def test_without_a_declared_ipv6_the_page_sees_one_host_name(local_https_page, socks5_tcp_only, monkeypatch):
"""One adapter, no IPv6: a udp and a tcp host candidate on ONE mDNS name, ranked 127 as the only address.
The shape is a function of the declaration alone, so this must hold on every machine: run it on a host with three
IPv4 adapters (the engine gathers all three today), in a container with two interfaces (``docker network connect``
before ``docker start``), and in a container with one."""
hosts = _host_shape(V4_ONLY, socks5_tcp_only, local_https_page, monkeypatch)
assert all(is_mdns(c["address"]) for c in hosts), [c["address"] for c in hosts]
assert len({c["address"] for c in hosts}) == 1, "host names: %r" % sorted({c["address"] for c in hosts})
assert _by_protocol(hosts) == {"UDP": [UDP_127], "TCP": [TCP_127]}, _by_protocol(hosts)
def test_a_declared_ipv6_gives_two_host_names_ranked_127_and_126(local_https_page, socks5_tcp_only, monkeypatch):
"""One adapter with IPv6: two names; the IPv6 host ranks one above the IPv4 one, as on the retail capture."""
hosts = _host_shape(DUAL, socks5_tcp_only, local_https_page, monkeypatch)
assert all(is_mdns(c["address"]) for c in hosts), [c["address"] for c in hosts]
assert len({c["address"] for c in hosts}) == 2, "host names: %r" % sorted({c["address"] for c in hosts})
assert _by_protocol(hosts) == {"UDP": [UDP_127, UDP_126], "TCP": [TCP_127, TCP_126]}, _by_protocol(hosts)
assert [decode_priority(p)["iface_pref"] for p in _by_protocol(hosts)["UDP"]] == [127, 126]
def test_ipv6_without_the_exit_prefix_is_no_ipv6(local_https_page, socks5_tcp_only, monkeypatch):
"""v6=1 with an empty prefix: the exit gave the core no /64, so the machine has no IPv6 address, and no fallback
invents one. One host name, as without IPv6."""
hosts = _host_shape("v4=192.168.31.7;v6=1;p6=", socks5_tcp_only, local_https_page, monkeypatch)
assert _by_protocol(hosts) == {"UDP": [UDP_127], "TCP": [TCP_127]}, hosts
def test_the_host_ports_are_those_of_a_windows_machine(local_https_page, socks5_tcp_only, monkeypatch):
"""Retail on Windows (6 of 6 runs, ``captures/retail/firefox-159.0-win/direct-dualstack-srflx-ports``): the UDP host
ports are in the dynamic range 49152-65535 and, on one connection, the IPv4 port and the IPv6 port are consecutive
(N, N+1). A page reads them. Linux hands out 32768-60999 at random, so on a Linux host this is red today."""
hosts = _host_shape(DUAL, socks5_tcp_only, local_https_page, monkeypatch)
by_rank = _udp_ports_by_rank(hosts)
assert sorted(by_rank) == [126, 127], by_rank
assert all(49152 <= port <= 65535 for port in by_rank.values()), by_rank
assert by_rank[127] == by_rank[126] + 1, "IPv4 port %d, IPv6 port %d" % (by_rank[126], by_rank[127])
def test_the_host_port_is_in_the_windows_range_without_ipv6_too(local_https_page, socks5_tcp_only, monkeypatch):
"""The one-address case of the range check. On a Linux host it can pass by luck (a kernel port in 49152-60999 falls
in the range); the same-seed test above is the one that cannot."""
hosts = _host_shape(V4_ONLY, socks5_tcp_only, local_https_page, monkeypatch)
by_rank = _udp_ports_by_rank(hosts)
assert list(by_rank) == [127] and 49152 <= by_rank[127] <= 65535, by_rank
def _ports_of_two_connections(declaration, socks, page_url, monkeypatch, seed):
def script(page):
first = host_candidates(candidates(page.evaluate(_GATHER_JS)))
second = host_candidates(candidates(page.evaluate(_GATHER_JS)))
return first, second
first, second = _session(declaration, socks, page_url, monkeypatch, seed, script)
return (sorted(c["port"] for c in first if c["proto"] == "UDP"),
sorted(c["port"] for c in second if c["proto"] == "UDP"))
def test_two_connections_on_one_page_get_their_own_port_pair(local_https_page, socks5_tcp_only, monkeypatch):
"""Retail (``captures/retail/firefox-159.0-win/two-pc-port-sequence``, 6 of 6): each connection gets its own pair,
consecutive (N, N+1) in the range, and the second pair is unrelated to the first (not increasing)."""
first, second = _ports_of_two_connections(DUAL, socks5_tcp_only, local_https_page, monkeypatch, 42)
for pair in (first, second):
assert len(pair) == 2 and pair[1] == pair[0] + 1 and 49152 <= pair[0] and pair[1] <= 65535, (first, second)
assert first != second, (first, second)
def test_two_connections_on_one_page_connect_in_the_time_of_retail(local_https_page, socks5_tcp_only, monkeypatch):
"""The names the browser registered for itself must resolve although the declared address is not the host's, and in
the time retail takes: not slower (a responder that cannot hear itself, or an OS list that is empty, kills the test),
not faster (an answer that skips the round trip). Five cold launches, median in the retail window."""
times = []
for n in range(5):
res = _session(V4_ONLY, socks5_tcp_only, local_https_page, monkeypatch, 100 + n,
lambda page: page.evaluate(_LOOPBACK_JS))
assert res["echoed"] and res["opened"] is not None, "run %d: the data channel did not open: %r" % (n, res)
times.append(res["opened"])
low, high = RETAIL_MEDIAN_WINDOW_MS
median = statistics.median(times)
assert low <= median <= high, "median %s ms of %r, retail window %d-%d ms" % (median, sorted(times), low, high)
+101
View File
@@ -0,0 +1,101 @@
"""The core declares the PROVIDER of Firefox's DoH for every session; the engine derives the rest from the proxies it receives.
The contract: with a proxy, every name the browser resolves goes to DoH, and a DoH request is a channel like any other, so it
leaves through the proxy of the context of the lookup. What the core writes to make that so is only the provider, with or
without a proxy (a DoH state would be two declarations of one fact):
network.trr.uri = https://mozilla.cloudflare-dns.com/dns-query
network.trr.bootstrapAddr = <an IP> the DoH host is found with no DNS at all
network.proxy.allow_bypass = False with a proxy: no channel falls back to direct when the proxy stumbles
network.parental_controls_cached_state = False declared off, as retail without the service
and NOT `network.trr.mode`, `network.trr.exclude-etc-hosts` or `network.trr.excluded-domains` (the engine derives the state, the
hosts file and the proxy's own name from the proxies Juggler gives it).
Two doors are checked, because the e2e launches through the second: the core's composer, and the wrapper's own path
(`InvisiblePlaywright._build_prefs` and the core's proxy step, what a launch composes). Nothing here starts a browser or the network (the
suite's autouse fixture answers the egress lookup).
"""
from __future__ import annotations
import ipaddress
import pytest
from invisible_core import decide_session_locale
from invisible_core._fpforge import generate_profile
from invisible_core.prefs import compose_session_prefs
from invisible_playwright import _session
pytestmark = pytest.mark.unit
URI = "https://mozilla.cloudflare-dns.com/dns-query"
NAMED = {"server": "socks5://gw.example.test:1080"}
BY_ADDRESS = {"server": "socks5://203.0.113.9:1080"}
HTTP_WITH_CREDENTIALS = {"server": "http://gw.example.test:3128", "username": "u", "password": "p"}
HTTP_BY_V6_ADDRESS = {"server": "http://[2001:db8::1]:3128"}
def _core(proxy):
return compose_session_prefs(generate_profile(seed=42), locale=decide_session_locale("en-US"),
timezone="America/New_York", proxy=proxy).prefs
def _wrapper(proxy):
"""What the launcher composes: the session's prefs (`_build_prefs`), then the core's proxy step
(`configure_proxy`) on them, exactly as `launcher.__enter__` and `remote.op_launch` do."""
from invisible_core import configure_proxy
from invisible_playwright.launcher import InvisiblePlaywright
session = InvisiblePlaywright(seed=42, binary_path="firefox.exe", humanize=False, proxy=proxy or None)
geo = _session.session_geo(session._timezone, session._proxy, session._locale_requested)
session._timezone, session._locale = geo.timezone, geo.locale
prefs = session._build_prefs()
configure_proxy(session._proxy, prefs)
return prefs
@pytest.fixture(params=[_core, _wrapper], ids=["core", "wrapper"])
def compose(request):
return request.param
@pytest.mark.parametrize("proxy", [NAMED, BY_ADDRESS, HTTP_WITH_CREDENTIALS, HTTP_BY_V6_ADDRESS],
ids=["socks-name", "socks-ip", "http-name", "http-ipv6"])
def test_a_proxied_session_declares_the_doh_provider_and_closes_the_bypass(compose, proxy):
prefs = compose(proxy)
assert prefs["network.trr.uri"] == URI
ipaddress.ip_address(prefs["network.trr.bootstrapAddr"]) # raises unless it is an IP literal
for derived in ("network.trr.mode", "network.trr.exclude-etc-hosts"):
assert derived not in prefs, "%s is derived by the engine from the proxies, not declared by the core" % derived
assert prefs["network.proxy.allow_bypass"] is False
assert prefs["network.parental_controls_cached_state"] is False
@pytest.mark.parametrize("proxy", [NAMED, HTTP_WITH_CREDENTIALS, BY_ADDRESS, HTTP_BY_V6_ADDRESS],
ids=["socks-name", "http-name", "ipv4", "ipv6"])
def test_the_core_excludes_no_domain_the_engine_derives_the_proxys_own_name(compose, proxy):
assert "network.trr.excluded-domains" not in compose(proxy)
def test_the_bootstrap_address_is_a_public_address_and_not_the_proxy(compose):
bootstrap = ipaddress.ip_address(compose(BY_ADDRESS)["network.trr.bootstrapAddr"])
assert bootstrap.is_global and str(bootstrap) != "203.0.113.9"
def test_a_session_without_a_proxy_declares_the_provider_and_no_state(compose):
prefs = compose(None)
assert sorted(k for k in prefs if k.startswith("network.trr.")) == ["network.trr.bootstrapAddr", "network.trr.uri"]
assert prefs.get("network.proxy.allow_bypass") is not False, "no proxy, no closed fallback"
assert prefs["network.parental_controls_cached_state"] is False, "declared off with or without a proxy"
def test_the_doh_prefs_are_the_same_for_the_same_proxy_whatever_the_seed():
"""Nothing about the DoH is drawn from the seed: two sessions behind the same proxy declare the same DoH."""
def trr(seed):
prefs = compose_session_prefs(generate_profile(seed=seed), locale=decide_session_locale("en-US"),
timezone="America/New_York", proxy=NAMED).prefs
return {k: v for k, v in prefs.items() if k.startswith("network.trr.")}
assert trr(1) == trr(2) == trr(970411)
+496
View File
@@ -0,0 +1,496 @@
"""E2E: behind a proxy every name is resolved by Firefox's DoH THROUGH the proxy, and nothing leaves the host.
Hermetic on a real binary. The tools they stand on are proven by `test_the_fake_doh_answers.py`,
`test_the_http_proxy_helper_asks_for_credentials.py` and `test_the_leak_watcher_sees_a_direct_connection.py`, and the
session declaration they start from by `test_doh_session_prefs_unit.py`. Run against an engine that keeps the contract,
they are the proof; run against one that does not, each of them fails on the thing it names.
The fake DoH is NOT `mozilla.cloudflare-dns.com`. That host is HSTS-preloaded/pinned, and Firefox refuses any
certificate override for such a host ("HSTS or pinned host - no overrides allowed", MOZILLA_PKIX_ERROR_SELF_SIGNED_CERT),
so a self-signed fake for it is rejected whatever `ignore_https_errors` says. The test declares its own provider through
the core's `extra_prefs` overlay (applied last, documented for this): `network.trr.uri` = `https://doh.gateway.test/
dns-query` (a `.test` name is on no preload list) and `network.trr.bootstrapAddr` = `192.0.2.53` (TEST-NET-1: the
address of the FakeDoh as a gateway knows it, never a real one). The gateways map a CONNECT to that address (or name) to
the FakeDoh. The core's own default provider is checked by `test_doh_session_prefs_unit.py`, not here.
The contract (core-19 and motore-18): a PROXIED session declares TRR mode 3 (`network.trr.uri` the DoH of Mozilla,
`network.trr.bootstrapAddr` an address so the DoH host is found with no DNS, `network.proxy.allow_bypass` false).
Every name the browser resolves - page hosts, ICE server names, HTTP/3 hosts - goes to that DoH; a DoH request is a
channel like any other, so it leaves THROUGH the session proxy (a SOCKS5 CONNECT or an HTTP CONNECT to
162.159.61.4:443), by the proxy of the context of the lookup; the browser then connects to the resolved ADDRESS (SOCKS5
by address, never by name). The session proxy is the first command on the pipe, and every proxied channel waits for
it: nothing goes DIRECT. No UDP/53 and no direct TCP leave the browser, and no helper process (crash reporter, default
browser agent, maintenance service, updater, pingsender) is started.
How each test sees it, with nothing but loopback:
* `FakeDoh` answers the names (`page-a.test`...) and records every query with the gateway it arrived by (`via`);
* `DohGateway` / `HttpProxy` are the proxies; a CONNECT to the DoH address is handed to the FakeDoh, every other one to
a loopback address is relayed, and every CONNECT is recorded (a CONNECT that carries a NAME is a defect to find);
* `Watcher` samples the connections of every browser process from before the launch: one to a non-loopback address is
a direct connection;
* `ResolverTrap` (Linux, root) points /etc/resolv.conf at a counting resolver: one question is a leak to the resolver
of the machine. Where it cannot run, its assertions are skipped, not the test - unless the gate sets
INVPW_REQUIRE_TRAP=1: then a trap that cannot run, or whose port 53 cannot be bound, is a failure.
Pages are served by a local HTTP server on 127.0.0.1 and reached by NAMES only the FakeDoh can resolve. The browser must
accept the FakeDoh certificate: the pages are opened in contexts made with `ignore_https_errors=True`, which the engine
implements per user context (`Browser.setIgnoreHTTPSErrors` -> `nsICertOverrideService`, keyed by the origin attributes
of the TLS socket), and a DoH request of a lookup carries the user context of that lookup
(`StealthApplyTRRContextToChannel`). So the lookups of THESE contexts accept the certificate; a lookup of the default
context (user context 0: the browser's own background resolutions, telemetry and the like) cannot be made to, and mode 3
does not need it: those lookups fail against the FakeDoh BY DESIGN, so no assertion here counts the FakeDoh's TLS
failures or treats a name of the default context as a result; every assertion is about the names and the contexts the
test itself creates. This is why a test says "a context with no proxy of its own" where the brief says "the default
context".
Assumptions that could not be verified without the engine, each one the first place to look if a test fails for no
visible reason: (1) the TRR channel of a lookup in a context honours `ignore_https_errors` of that context; (2) the
ICE resolver's lookup carries the origin attributes of its document; (3) Firefox's TRR accepts HTTP/1.1 as well as h2
(the FakeDoh offers both; `doh.alpn_of(...)` says which one was used); (4) the DoH and page connections reach a SOCKS
gateway as ADDRESSES; (5) behind an HTTP proxy an `http` page's name goes to the proxy inside the request (it is the
proxy that resolves it), so the DoH is triggered there by an ICE server name, which the browser always resolves itself.
"""
from __future__ import annotations
import base64
import http.server
import ipaddress
import threading
import time
from pathlib import Path
import pytest
from invisible_core import SessionGeo, decide_session_locale
from invisible_playwright import InvisiblePlaywright
import _doh_servers as ds
import _trap_policy
from _doh_servers import DOH_BOOTSTRAP, DOH_HOST, DOH_PORT, DOH_PROVIDER_PREFS, QTYPE_A, DohGateway, FakeDoh
from _http_proxy import HttpProxy, basic
from _leaks import ResolverTrap, Watcher
from _servers import LocalServer
pytestmark = [pytest.mark.e2e, pytest.mark.usefixtures("the_udp_line")]
#: The zone of the FakeDoh: every name a test uses, all pointing at the loopback where the page server is.
ZONE = {"page-a.test": "127.0.0.1", "page-b.test": "127.0.0.1", "page-c.test": "127.0.0.1",
"stun-a.test": "127.0.0.1"}
#: Loopback targets go through the proxy too (as in test_proxy_socks_auth_e2e.py), so the road of a page is observable.
#: The two `network.trr.*` entries replace the core's default provider (a preloaded host whose certificate cannot be
#: overridden) with the FakeDoh's: https://doh.gateway.test/dns-query, found at 192.0.2.53 with no DNS.
PREFS = {"network.proxy.allow_hijacking_localhost": True, "network.proxy.no_proxies_on": "", **DOH_PROVIDER_PREFS}
#: The helper processes of Firefox that a session behind a proxy must never start (match on the executable's stem).
HELPERS = ("crashreporter", "default-browser-agent", "maintenanceservice", "updater", "pingsender")
GEO = SessionGeo("America/New_York", "203.0.113.7", latitude=40.7128, longitude=-74.0060,
locale=decide_session_locale("en-US"))
# ------------------------------------------------------------------------------------------------------- fixtures
@pytest.fixture(autouse=True)
def _hermetic_session(monkeypatch):
"""No egress lookup on the internet, and no egress drift check through the proxy.
A launch asks "who am I" through the proxy (api.ipify.org by NAME, resolved by the TEST process: a question to the
resolver trap and a connection past the loopback), and re-asks at every new context. This test is about the
BROWSER's roads, so the answer is declared: the same facts (timezone, locale, position, an exit address) the
lookup would have returned.
"""
monkeypatch.setattr("invisible_playwright.launcher.prepare_session_geo", lambda tz, proxy, locale: GEO)
monkeypatch.setattr(InvisiblePlaywright, "_assert_uscita_invariata", lambda self: None)
@pytest.fixture
def doh():
import h2 # noqa: F401 - the dev extra installs it: a missing one is a failure, never a skip
server = FakeDoh(ZONE)
yield server
server.close()
@pytest.fixture
def gateway(doh):
made = []
def make(name, **kwargs):
gw = DohGateway(name, doh, **kwargs)
made.append(gw)
return gw
yield make
for gw in made:
gw.close()
@pytest.fixture
def trap():
"""The resolver trap, counting every question the machine's resolver is asked.
None only where it cannot run AND the gate does not require it (a developer's machine). With INVPW_REQUIRE_TRAP=1
(the gate's Linux leg) a trap that is unavailable or whose port 53 cannot be bound is a failure with its reason."""
if not ResolverTrap.available:
why = _trap_policy.failure(None, False, ResolverTrap.reason)
if why:
pytest.fail(why)
yield None
return
resolver = ResolverTrap()
try:
resolver.__enter__()
except OSError as exc: # port 53 taken (another worker holds the trap)
why = _trap_policy.failure(None, True, bind_error=exc)
if why:
pytest.fail(why)
yield None
return
try:
yield resolver
finally:
resolver.__exit__(None, None, None)
@pytest.fixture
def watcher(firefox_binary):
"""Started BEFORE the test body, so before any launch; stopped by the test or here."""
w = Watcher(match=("firefox", Path(firefox_binary).stem.lower())).start()
yield w
w.stop()
class Pages:
"""A local HTTP server: every path answers a page that says which Host it was asked for."""
def __init__(self):
outer = self
self.hits = []
class Handler(http.server.BaseHTTPRequestHandler):
def do_GET(self): # noqa: N802
host = self.headers.get("Host", "")
outer.hits.append((host, self.path))
body = ("<!doctype html><title>page</title><body>HOST=%s</body>" % host).encode()
self.send_response(200)
self.send_header("Content-Type", "text/html; charset=utf-8")
self.send_header("Content-Length", str(len(body)))
self.end_headers()
self.wfile.write(body)
def log_message(self, *args):
pass
self._server = LocalServer(("127.0.0.1", 0), Handler)
self.port = self._server.server_address[1]
threading.Thread(target=self._server.serve_forever, daemon=True).start()
def url(self, name):
return "http://%s:%d/" % (name, self.port)
def close(self):
self._server.shutdown()
self._server.server_close()
@pytest.fixture
def pages():
server = Pages()
yield server
server.close()
# --------------------------------------------------------------------------------------------------------- helpers
def _launch(binary, proxy, **kwargs):
return InvisiblePlaywright(seed=42, binary_path=binary, proxy=proxy, extra_prefs=dict(PREFS), **kwargs)
def _page_in(browser, proxy=None):
"""A page in a new context, with its own proxy when given and the FakeDoh's certificate accepted."""
options = {"ignore_https_errors": True}
if proxy is not None:
options["proxy"] = proxy
context = browser.new_context(**options)
return context, context.new_page()
def _text(page):
return page.evaluate("() => document.body.innerText")
def _why(doh, *proxies):
"""What every side saw, for the message of a failed assertion."""
lines = ["FakeDoh queries: %s" % [tuple(q) for q in doh.queries],
"FakeDoh connections (via, protocol): %s" % doh.connections,
"FakeDoh TLS failures (the default context's background lookups fail by design): %s" % doh.tls_failures]
for p in proxies:
lines.append("%s CONNECTs: %s" % (p.name, p.connects))
if getattr(p, "refused", None):
lines.append("%s refused: %s" % (p.name, p.refused))
return "\n " + "\n ".join(lines)
def _is_address(host):
try:
ipaddress.ip_address(host)
return True
except ValueError:
return False
def _assert_every_connection_went_through_the_gateway(doh, *proxies):
"""Every connection the browser made, the test's own and the background traffic of the default context, is
accounted for at a gateway, and none reached the FakeDoh by another road.
The background lookups of the default context (telemetry and the like) have no `ignore_https_errors`, so their TLS
handshake with the FakeDoh fails BY DESIGN. That is an expected outcome, counted here, not ignored:
* the FakeDoh served no connection (successful or failed) by `direct`: each one arrived by a named gateway;
* per gateway, the connections the FakeDoh served (completed + failed handshakes) are all tunnels of a DoH CONNECT
that the gateway itself recorded (it records the CONNECT before it hands the socket over), so none is
unaccounted for: served <= recorded DoH CONNECTs;
* no CONNECT of any gateway carries the name of the test's own zone (the browser resolves those with the DoH and
connects by address); a CONNECT to some other non-loopback target is listed by the gateway in `refused`, i.e. it
was attempted THROUGH the gateway and went no further, which is the point.
"""
why = _why(doh, *proxies)
names = {p.name for p in proxies}
served = list(doh.connections) + [(via, "tls-failed") for via, _error in doh.tls_failures]
by_road = {via for via, _what in served}
assert by_road <= names, "the FakeDoh served a connection by a road that is no gateway of the test: %s" % (
sorted(by_road - names)) + why
for proxy in proxies:
mine = [what for via, what in served if via == proxy.name]
recorded = len(proxy.doh_connects())
assert len(mine) <= recorded, (
"%s: the FakeDoh served %d connection(s) (%d failed handshakes) but the gateway recorded only %d DoH "
"CONNECT(s)" % (proxy.name, len(mine), mine.count("tls-failed"), recorded) + why)
zone_names = [h for h, _p in proxy.connects if h.lower() in ZONE]
assert zone_names == [], "%s was sent the NAME %s instead of an address" % (proxy.name, zone_names) + why
def _assert_stayed_home(watcher, trap=None, doh=None, *proxies):
"""Nothing went past the gateway (no direct connection), nothing asked the machine's resolver, and (when the
FakeDoh and the proxies are given) every connection is accounted for at a gateway."""
if doh is not None:
_assert_every_connection_went_through_the_gateway(doh, *proxies)
assert watcher.watched_pids, ("the watcher never saw a browser process (it saw: %s): a watcher that cannot see "
"proves nothing" % watcher.process_names)
assert watcher.direct == [], "the browser connected past the gateway: %s" % watcher.describe()
if trap is not None:
assert trap.queries == [], "the browser asked the resolver of the machine: %s" % trap.describe()
def _create_a_peer_connection_for(page, name):
"""An RTCPeerConnection whose ICE server is `stun:<name>:3478`, gathering started: the browser resolves the name."""
page.evaluate("""(name) => {
const pc = new RTCPeerConnection({iceServers: [{urls: 'stun:' + name + ':3478'}]});
window.__pc = pc;
pc.createDataChannel('probe');
pc.createOffer().then(offer => pc.setLocalDescription(offer));
}""", name)
# ============================================================================================================ tests
def test_names_resolve_through_doh_by_the_proxy(firefox_binary, doh, pages, gateway, trap, watcher):
"""A page name is asked to the DoH, by the proxy, and the page is then reached by ADDRESS."""
gw1 = gateway("gw1")
with _launch(firefox_binary, gw1.proxy) as browser:
context, page = _page_in(browser)
page.goto(pages.url("page-a.test"), wait_until="load", timeout=30000)
text = _text(page)
context.close()
watcher.stop()
assert "HOST=page-a.test:%d" % pages.port in text, "the page did not load through the proxy: %r" % text
why = _why(doh, gw1)
assert doh.vias_of("page-a.test", QTYPE_A) == {"gw1"}, "page-a.test (A) was not asked by gw1 only" + why
assert (DOH_BOOTSTRAP, DOH_PORT) in gw1.connects, "no DoH CONNECT to the bootstrap address" + why
assert not [h for h, _p in gw1.connects if h == "page-a.test"], (
"the browser sent the NAME page-a.test to the proxy instead of resolving it" + why)
assert [h for h, _p in gw1.connects if not _is_address(h) and h != DOH_HOST] == [], (
"a CONNECT carried a name: the browser must resolve with the DoH and connect by address" + why)
assert ("127.0.0.1", pages.port) in gw1.connects, "the page was not reached by address through gw1" + why
assert "direct" not in {q.via for q in doh.queries}, "something reached the DoH without the proxy" + why
_assert_stayed_home(watcher, trap, doh, gw1)
def test_an_ice_server_name_resolves_the_same_way(firefox_binary, doh, pages, gateway, trap, watcher):
"""A name chosen by the PAGE (a STUN server in iceServers) is resolved by the DoH through the proxy too."""
gw1 = gateway("gw1")
with _launch(firefox_binary, gw1.proxy) as browser:
context, page = _page_in(browser)
page.goto(pages.url("page-a.test"), wait_until="load", timeout=30000)
_create_a_peer_connection_for(page, "stun-a.test")
asked = ds.wait_until(lambda: doh.queries_for("stun-a.test"), 30)
page.evaluate("() => window.__pc.close()")
context.close()
watcher.stop()
why = _why(doh, gw1)
assert asked, "the browser never asked the DoH for the ICE server name" + why
assert doh.vias_of("stun-a.test") == {"gw1"}, "stun-a.test was not asked by gw1 only" + why
_assert_stayed_home(watcher, trap, doh, gw1)
def test_two_contexts_two_doh_exits(firefox_binary, doh, pages, gateway, trap, watcher):
"""Each context resolves by ITS proxy: the browser's for a context with none, its own for context B, each with
the credentials of that gateway."""
gw1 = gateway("gw1", user="gw1-user", password="gw1-pass")
gw2 = gateway("gw2", user="gw2-user", password="gw2-pass")
with _launch(firefox_binary, gw1.proxy) as browser:
context_a, page_a = _page_in(browser) # no proxy of its own: the browser's, gw1
context_b, page_b = _page_in(browser, proxy=gw2.proxy) # its own: gw2
page_a.goto(pages.url("page-a.test"), wait_until="load", timeout=30000)
page_b.goto(pages.url("page-b.test"), wait_until="load", timeout=30000)
text_a, text_b = _text(page_a), _text(page_b)
context_a.close()
context_b.close()
watcher.stop()
why = _why(doh, gw1, gw2)
assert "HOST=page-a.test" in text_a and "HOST=page-b.test" in text_b, (text_a, text_b)
assert doh.vias_of("page-a.test", QTYPE_A) == {"gw1"}, "page-a.test must be resolved by gw1 only" + why
assert doh.vias_of("page-b.test", QTYPE_A) == {"gw2"}, "page-b.test must be resolved by gw2 only" + why
assert gw1.doh_connects() and gw2.doh_connects(), "each gateway must have carried a DoH CONNECT" + why
assert ("127.0.0.1", pages.port) in gw1.connects and ("127.0.0.1", pages.port) in gw2.connects, (
"each page must be reached by address through the gateway of its context" + why)
assert gw1.credentials_seen and set(gw1.credentials_seen) == {("gw1-user", "gw1-pass")}, (
"gw1 saw: %s" % gw1.credentials_seen)
assert gw2.credentials_seen and set(gw2.credentials_seen) == {("gw2-user", "gw2-pass")}, (
"gw2 saw: %s" % gw2.credentials_seen)
_assert_stayed_home(watcher, trap, doh, gw1, gw2)
def test_an_authenticated_http_proxy_resolves(firefox_binary, doh, pages, trap, watcher):
"""An http proxy with credentials: the DoH CONNECT carries the PREEMPTIVE `Proxy-Authorization: Basic`, so it
never needs a 407 round trip, and the page loads.
Behind an HTTP proxy an `http` page's NAME goes to the proxy (which resolves it), so the browser's own DoH is
triggered here by an ICE server name, which the browser always resolves itself.
"""
user, password = "ferd_http_user", "pw-é42"
proxy = HttpProxy("http1", doh, user=user, password=password)
try:
with _launch(firefox_binary, proxy.proxy) as browser:
context, page = _page_in(browser)
page.goto(pages.url("page-a.test"), wait_until="load", timeout=30000)
text = _text(page)
_create_a_peer_connection_for(page, "stun-a.test")
asked = ds.wait_until(lambda: doh.queries_for("stun-a.test"), 30)
page.evaluate("() => window.__pc.close()")
context.close()
watcher.stop()
expected = "Basic " + base64.b64encode(("%s:%s" % (user, password)).encode("utf-8")).decode("ascii")
assert expected == basic(user, password)
why = _why(doh, proxy)
assert "HOST=page-a.test:%d" % pages.port in text, "the page did not load through the proxy: %r" % text
assert asked and doh.vias_of("stun-a.test") == {"http1"}, "the DoH was not reached through the proxy" + why
authorizations = proxy.doh_authorizations()
assert authorizations, "no DoH CONNECT reached the proxy" + why
assert set(authorizations) == {expected}, (
"every DoH CONNECT must carry the preemptive Basic header %r, saw %r" % (expected, authorizations) + why)
assert [s for s in proxy.refused_for_credentials if (s.host, s.port) in ds.DOH_TARGETS] == [], (
"the DoH CONNECT needed a 407 round trip: the header was not preemptive" + why)
_assert_stayed_home(watcher, trap, doh, proxy)
finally:
proxy.close()
def test_nothing_leaves_the_host_between_launch_and_the_first_command(firefox_binary, doh, pages, gateway, trap,
watcher):
"""The watcher runs from before the launch to the first navigation, against a gateway that is slow to say hello
(its first accepted connection is answered a second late): the session proxy is the first command on the pipe and
every proxied channel is held until then, so nothing may leave meanwhile."""
gw1 = gateway("gw1", first_connection_delay=1.0)
with _launch(firefox_binary, gw1.proxy) as browser:
context, page = _page_in(browser)
page.goto(pages.url("page-a.test"), wait_until="load", timeout=45000)
text = _text(page)
context.close()
watcher.stop()
why = _why(doh, gw1)
assert "HOST=page-a.test" in text
assert gw1.accepted_at, "the browser never connected to the gateway" + why
_assert_stayed_home(watcher, trap, doh, gw1)
def test_no_helper_process_starts(firefox_binary, doh, pages, gateway, trap, watcher):
"""No crash reporter client, default browser agent, maintenance service, updater or pingsender is started,
through the first five seconds of the session and its teardown (pingsender is the one that starts at exit)."""
gw1 = gateway("gw1")
with _launch(firefox_binary, gw1.proxy) as browser:
context, page = _page_in(browser)
page.goto(pages.url("page-a.test"), wait_until="load", timeout=30000)
time.sleep(5)
context.close()
time.sleep(1) # the processes of the exit
watcher.stop()
assert watcher.watched_pids, "the watcher never saw a browser process: %s" % watcher.process_names
started = watcher.helpers_seen(HELPERS)
assert started == [], "helper processes were started: %s (all processes seen: %s)" % (
started, watcher.process_names)
def test_a_dead_proxy_does_not_fall_back(firefox_binary, doh, pages, gateway, trap, watcher):
"""When the proxy dies, a navigation fails: it does not go direct and does not reach the resolver of the machine.
`page-c.test` is not cached anywhere and the FakeDoh would answer it if it were reached.
"""
gw1 = gateway("gw1")
with _launch(firefox_binary, gw1.proxy) as browser:
context, page = _page_in(browser)
page.goto(pages.url("page-a.test"), wait_until="load", timeout=30000)
gw1.kill()
with pytest.raises(Exception) as failed:
page.goto(pages.url("page-c.test"), wait_until="load", timeout=20000)
context.close()
watcher.stop()
why = _why(doh, gw1)
assert pages.hits and all(host.startswith("page-a.test") for host, _p in pages.hits), (
"the dead proxy still served a page: %s" % pages.hits + why)
assert doh.queries_for("page-c.test") == [], "page-c.test was resolved after the proxy died" + why
assert gw1.killed and failed.value is not None
_assert_stayed_home(watcher, trap, doh, gw1)
def test_a_session_without_a_proxy_resolves_with_the_system_resolver(firefox_binary, pages, watcher):
"""The negative control: with no proxy the exit is the machine's own network and retail resolves with the system
resolver (mode 0). The core declares the DoH provider (uri + bootstrapAddr) in every session, but no engine-owned
state (`network.trr.mode` and the other two), so TRR stays off. Where the resolver trap can run (Linux, root) it also sees
the question; where it cannot (Windows) the page is reached by a name the system resolves by itself, and the trap's
assertion is the only one that is not made."""
trapped = ResolverTrap.available
why = _trap_policy.failure(None, trapped, ResolverTrap.reason)
if why:
pytest.fail(why)
name = "page-d.test" if trapped else "localhost"
session = InvisiblePlaywright(seed=42, binary_path=firefox_binary, proxy=None)
session._timezone, session._locale = GEO.timezone, GEO.locale
prefs = session._build_prefs()
assert prefs.get("network.trr.mode") != 3, "a session without a proxy turned TRR on: %s" % prefs.get("network.trr.mode")
engine_owned = [k for k in ("network.trr.mode", "network.trr.exclude-etc-hosts", "network.trr.excluded-domains")
if k in prefs]
assert engine_owned == [], "a session without a proxy declared engine-owned TRR prefs: %s" % engine_owned
trap = None
if trapped:
trap = ResolverTrap({"page-d.test": "127.0.0.1"})
trap.__enter__() # port 53 taken by another worker is a failure of the setup, not a reason to skip
try:
with session as browser:
context = browser.new_context()
page = context.new_page()
page.goto(pages.url(name), wait_until="load", timeout=30000)
text = _text(page)
context.close()
finally:
if trap is not None:
trap.__exit__(None, None, None)
watcher.stop()
assert "HOST=%s:%d" % (name, pages.port) in text, "the page did not load through the system resolver: %r" % text
if trap is not None:
assert trap.asked(name), "the system resolver was never asked for %s: %s" % (name, trap.describe())
@@ -0,0 +1,77 @@
"""Every route command (continue, abort, fulfill, redirect) leaves through `RouteDispatcher._send`, and `_send` swallows the one
error that is not an error: the request the browser has already closed.
Stock Playwright's server sends the three interception commands as may-fail. Here a new command that talked to the page
directly (`self.request.page.send("Network....")`) would bring the old defect back: the client keeps an error for the whole
connection and raises it on the next route command, which is then never sent (see
`test_networkidle_through_a_served_browser_with_routes_e2e.py`). No browser: the source is read.
"""
from __future__ import annotations
import ast
import pathlib
import pytest
pytestmark = pytest.mark.unit
SERVER = pathlib.Path(__file__).resolve().parents[1] / "src" / "invisible_playwright" / "_juggler" / "server.py"
def _route_dispatcher():
tree = ast.parse(SERVER.read_text(encoding="utf-8"))
return next(n for n in tree.body if isinstance(n, ast.ClassDef) and n.name == "RouteDispatcher")
def _methods(cls):
return {n.name: n for n in cls.body if isinstance(n, ast.FunctionDef)}
def _sends_network_command(fn):
"""The `page.send` / `conn.send` / `_send` calls of a function that name a Network.* command string."""
out = []
for node in ast.walk(fn):
if isinstance(node, ast.Call):
for arg in node.args[:1]:
if isinstance(arg, ast.Constant) and isinstance(arg.value, str) and arg.value.startswith("Network."):
out.append((getattr(node.func, "attr", getattr(node.func, "id", "?")), arg.value))
return out
def test_every_op_of_a_route_goes_through__send_and_nothing_else_talks_to_the_page():
methods = _methods(_route_dispatcher())
ops = {name: fn for name, fn in methods.items() if name.startswith("op_")}
assert set(ops) >= {"op_abort", "op_continue", "op_fulfill", "op_redirect"}, sorted(ops)
for name, fn in ops.items():
sends = _sends_network_command(fn)
assert sends, "%s sends no Network command at all: update this guard if it is a new kind" % name
for via, command in sends:
assert via == "_send", "%s sends %s through %s, not through RouteDispatcher._send" % (name, command, via)
# and the only direct talk to the page in the class is _send's
for name, fn in methods.items():
if name in ops or name == "_send":
continue
assert not _sends_network_command(fn), "%s sends a Network command by itself" % name
def test__send_swallows_a_request_the_browser_already_closed_and_nothing_else():
send = _methods(_route_dispatcher())["_send"]
handlers = [n for n in ast.walk(send) if isinstance(n, ast.ExceptHandler)]
caught = {ast.unparse(h.type) for h in handlers if h.type is not None}
assert caught == {"juggler.ProtocolError", "juggler.TargetClosedError"}, caught
source = ast.get_source_segment(SERVER.read_text(encoding="utf-8"), send)
assert '"Cannot find request" not in str(exc)' in source and "raise" in source, \
"a ProtocolError other than 'Cannot find request' must still reach the client"
assert source.index("self.dispose()") > source.index("except juggler.TargetClosedError"), \
"the route is disposed after a swallowed error too"
def test_the_stock_client_the_networkidle_e2e_drives_the_server_with_is_a_pinned_dev_dependency():
"""That e2e fails (not skips) without the stock Playwright client, so CI must install it: the `dev` extra pins it to the
version of scripts/playwright_pin.txt."""
import tomllib
root = SERVER.parents[3]
dev = tomllib.loads((root / "pyproject.toml").read_text(encoding="utf-8"))["project"]["optional-dependencies"]["dev"]
pin = (root / "scripts" / "playwright_pin.txt").read_text(encoding="utf-8").strip()
assert "playwright==%s" % pin in dev, dev
+635
View File
@@ -0,0 +1,635 @@
"""The identity a page reads is the same in the top document and in every iframe, whatever
process the iframe runs in.
With ``fission.webContentIsolationStrategy=0`` every iframe shares the content process of
its parent. With strategy 1 (site isolation) an iframe on another site runs in a content
process of its own, and the identity has to reach that process by itself: the seed
(``zoom.stealth.fpp.hw_seed``), the font manifest, the language and the time zone are
declared by the core and read by each process, none of them is inherited from the parent
document. A process that reads an empty or a different declaration draws a different
canvas, renders a different audio buffer, or reports a different language: to a site that
embeds its own iframe, that is a browser whose identity changes from one frame to the
next, the loudest mismatch there is.
What is compared, in the top document and in three iframes (``127.0.0.2`` on another site,
``127.0.0.1`` nested inside that one, and ``127.0.0.3`` on a third site), all served by one
local server so that the hosts, not the ports, tell the sites apart:
- the hash of a fixed canvas drawing (its pixels and its PNG bytes) and of a fixed
``OfflineAudioContext`` buffer,
- ``WEBGL_debug_renderer_info`` vendor and renderer,
- ``Intl`` time zone, ``navigator.language``/``languages``/``userAgent``,
- ``screen.width/height/availWidth/availHeight`` and ``devicePixelRatio``,
- ``document.fonts`` and the measured width of a family of the font bundle.
The negative case is the persona, not the canvas: the 2D canvas is drawn as it is, without noise
(decisions/prodotto-06), and the audio buffer carries no per-seed value either, so neither moves
with the seed. What moves is the machine the seed describes: the WebGL renderer and the screen.
A different seed has to give a different machine in every frame, or equal values prove nothing.
The canvas PNG is compared inside one launch only: the bytes of a PNG made on a page served over
HTTP end with a ``deBG`` chunk that differs from one launch to the next.
Not compared: ``window.screenX``/``screenY``. They are the position of the window and the
geometry invariant of an iframe has its own test (``test_cross_origin_iframe.py``).
The values are read BY THE PAGES, from inside each document, and sent to the top with
``postMessage``: what a site sees, not what the protocol reports, and nothing here depends
on how the driver reaches an iframe of another process.
An absence is not an agreement: a context that reports no value, or an error, for a field
the top document answers is a mismatch, never a pass.
Two strategies run: ``0`` (what the core writes today: the iframes share the process) and
``1`` (``fission.autostart=true``, ``fission.webContentIsolationStrategy=1``, passed as
``extra_prefs``; ``dom.ipc.processCount.webIsolated`` stays at its default of 1, which is
one process per site). Each run also proves where the iframes ran, from inside the page: the
iframe on the third site spins for 400 ms and the top times a 10 ms timer, which stalls only
when the two share a process. A run that silently stayed in one process cannot pass for the
isolated case, and the other way round.
"""
from __future__ import annotations
import http.server
import json
import os
import socketserver
import sys
import threading
import time
from urllib.parse import urlsplit
import pytest
sys.path.insert(0, os.path.dirname(__file__))
from _servers import LocalServer # noqa: E402
SEED = 4242
OTHER_SEED = 4243
#: The three sites. Sites are told apart by host, never by port: the port does not separate them.
HOST_TOP = "127.0.0.1"
HOST_OOP = "127.0.0.2"
HOST_OOP_2 = "127.0.0.3"
#: The four documents, in the order the page builds them.
CONTEXTS = ("top", "oop_127_0_0_2", "nested_127_0_0_1", "oop_127_0_0_3")
#: What every context reads, by the group a test checks. ``screenX``/``screenY`` are read but
#: belong to no group: see the module docstring.
GROUPS = {
"canvas": ("canvas", "canvas_png"),
"audio": ("audio",),
"webgl": ("webgl_vendor", "webgl_renderer"),
"locale_and_agent": ("time_zone", "language", "languages", "user_agent"),
"screen": ("screen_width", "screen_height", "screen_avail_width", "screen_avail_height",
"device_pixel_ratio"),
"fonts": ("fonts_check", "font_width_arial", "font_width_segoe_ui", "font_width_fallback"),
}
#: How long the second iframe keeps its main thread busy, and the gaps the top then sees in a
#: 10 ms timer: a process shared with the top delays the timer by about the whole spin, a process
#: of its own does not delay it at all.
SPIN_MS = 400
SHARED_PROCESS_GAP_MS = 300
OWN_PROCESS_GAP_MS = 200
#: The strategy-0 prefs, passed explicitly so that the case keeps its meaning on the day the core
#: writes strategy 1 by default.
STRATEGY_0_PREFS = {"fission.autostart": False, "fission.webContentIsolationStrategy": 0}
#: The fields a seed decides: the machine it describes. Compared between two seeds.
PERSONA_FIELDS = ("webgl_renderer", "screen_width", "screen_height")
#: The strategy-1 prefs. ``dom.ipc.processCount.webIsolated`` is not here on purpose: the core
#: writes 1 and the Firefox default is 1, so it is already one process per site.
STRATEGY_1_PREFS = {"fission.autostart": True, "fission.webContentIsolationStrategy": 1}
# ---------------------------------------------------------------------------
# The pages
# ---------------------------------------------------------------------------
#: What every document computes. ``cyrb53`` is a plain string hash: ``crypto.subtle`` needs a
#: secure context and not every one of these hosts is one.
PROBE_JS = r"""
function cyrb53(str, seed) {
let h1 = 0xdeadbeef ^ (seed || 0), h2 = 0x41c6ce57 ^ (seed || 0);
for (let i = 0, ch; i < str.length; i++) {
ch = str.charCodeAt(i);
h1 = Math.imul(h1 ^ ch, 2654435761);
h2 = Math.imul(h2 ^ ch, 1597334677);
}
h1 = Math.imul(h1 ^ (h1 >>> 16), 2246822507) ^ Math.imul(h2 ^ (h2 >>> 13), 3266489909);
h2 = Math.imul(h2 ^ (h2 >>> 16), 2246822507) ^ Math.imul(h1 ^ (h1 >>> 13), 3266489909);
return (4294967296 * (2097151 & h2) + (h1 >>> 0)).toString(16);
}
function attempt(fn) {
try { return fn(); } catch (e) { return 'error:' + e; }
}
function canvasHashes() {
const c = document.createElement('canvas');
c.width = 260; c.height = 90;
const x = c.getContext('2d');
const g = x.createLinearGradient(0, 0, 260, 90);
g.addColorStop(0, '#d94f30'); g.addColorStop(1, '#2f6fd9');
x.fillStyle = g; x.fillRect(0, 0, 260, 90);
x.fillStyle = 'rgba(255, 255, 255, 0.55)';
x.beginPath(); x.arc(70, 45, 32, 0, Math.PI * 2); x.fill();
x.strokeStyle = '#102030'; x.lineWidth = 3;
x.beginPath(); x.moveTo(10, 80); x.bezierCurveTo(60, 10, 160, 120, 250, 20); x.stroke();
x.font = '18px Arial'; x.fillStyle = '#101010';
x.fillText('Fission parity 0123 \u00e9\u00fc', 12, 30);
x.font = '14px "Segoe UI"'; x.fillStyle = '#ffffff';
x.fillText('seed identity', 120, 70);
const px = x.getImageData(0, 0, 260, 90).data;
let s = '';
for (let i = 0; i < px.length; i++) s += px[i] + ',';
const url = c.toDataURL();
return {pixels: cyrb53(s) + ':' + px.length, png: cyrb53(url) + ':' + url.length};
}
async function audioHash() {
const Ctx = window.OfflineAudioContext || window.webkitOfflineAudioContext;
const ctx = new Ctx(1, 5000, 44100);
const osc = ctx.createOscillator();
osc.type = 'triangle'; osc.frequency.value = 10000;
const comp = ctx.createDynamicsCompressor();
comp.threshold.value = -50; comp.knee.value = 40; comp.ratio.value = 12;
comp.attack.value = 0; comp.release.value = 0.2;
osc.connect(comp); comp.connect(ctx.destination); osc.start(0);
const buf = await ctx.startRendering();
const data = buf.getChannelData(0);
const bits = new Uint32Array(data.buffer, data.byteOffset, data.length);
let s = '';
for (let i = 0; i < bits.length; i++) s += bits[i].toString(16) + ',';
return cyrb53(s) + ':' + data.length;
}
function webgl() {
const c = document.createElement('canvas');
const gl = c.getContext('webgl') || c.getContext('experimental-webgl');
if (!gl) return null;
const ext = gl.getExtension('WEBGL_debug_renderer_info');
if (!ext) return {vendor: null, renderer: null};
return {vendor: String(gl.getParameter(ext.UNMASKED_VENDOR_WEBGL)),
renderer: String(gl.getParameter(ext.UNMASKED_RENDERER_WEBGL))};
}
function measure(family) {
const s = document.createElement('span');
s.style.cssText = 'position:absolute;visibility:hidden;white-space:nowrap;font-size:40px;'
+ 'font-family:' + family;
s.textContent = 'Hamburgefonstiv 0123456789 mmmmmmmmmm';
document.body.appendChild(s);
const w = s.getBoundingClientRect().width;
s.remove();
return w;
}
// The process probe: a document asked to spin keeps its process's main thread busy.
window.addEventListener('message', e => {
if (e.data && e.data.fission_busy) {
const end = performance.now() + e.data.fission_busy;
while (performance.now() < end) { /* spin */ }
}
});
async function collect(name) {
const out = {name: name, origin: location.origin};
const cv = attempt(canvasHashes);
out.canvas = typeof cv === 'string' ? cv : cv.pixels;
out.canvas_png = typeof cv === 'string' ? cv : cv.png;
try { out.audio = await audioHash(); } catch (e) { out.audio = 'error:' + e; }
const g = attempt(webgl);
out.webgl_vendor = g === null ? null : (typeof g === 'string' ? g : g.vendor);
out.webgl_renderer = g === null ? null : (typeof g === 'string' ? g : g.renderer);
out.time_zone = attempt(() => Intl.DateTimeFormat().resolvedOptions().timeZone);
out.language = attempt(() => navigator.language);
out.languages = attempt(() => navigator.languages.join('|'));
out.user_agent = attempt(() => navigator.userAgent);
out.screen_width = attempt(() => screen.width);
out.screen_height = attempt(() => screen.height);
out.screen_avail_width = attempt(() => screen.availWidth);
out.screen_avail_height = attempt(() => screen.availHeight);
out.device_pixel_ratio = attempt(() => window.devicePixelRatio);
out.fonts_check = attempt(() => document.fonts.check('16px Arial'));
out.font_width_arial = attempt(() => measure('Arial, monospace'));
out.font_width_segoe_ui = attempt(() => measure('"Segoe UI", monospace'));
out.font_width_fallback = attempt(() => measure('monospace'));
// Read, never compared: see the module docstring.
out.screen_x = attempt(() => window.screenX);
out.screen_y = attempt(() => window.screenY);
return out;
}
"""
def probe_page(name: str, child_url: str | None = None) -> bytes:
"""A document that reads the identity and sends it to the top, with an optional iframe."""
iframe = '<iframe id="child" src="%s" width="320" height="120"></iframe>' % child_url if child_url else ""
return (
"<!doctype html><html><head><meta charset=\"utf-8\"><title>%s</title></head><body>%s"
"<script>%s\n"
"collect(%s).then(r => window.top.postMessage({fission_parity: r}, '*'));</script>"
"</body></html>" % (name, iframe, PROBE_JS, json.dumps(name))
).encode("utf-8")
def top_page(port: int, hosts=(HOST_TOP, HOST_OOP, HOST_OOP_2)) -> bytes:
"""The top document: three iframes (the middle one holds a fourth) and a collector.
``window.__parity`` has one entry per context, and ``window.__parity_done`` turns true
when all of them have reported.
"""
top, oop, oop2 = hosts
nested = "http://%s:%d/probe/nested_127_0_0_1" % (top, port)
frames = (
'<iframe id="oop1" src="http://%s:%d/probe/oop_127_0_0_2?child=%s" width="400" height="260"></iframe>'
% (oop, port, nested),
'<iframe id="oop2" src="http://%s:%d/probe/oop_127_0_0_3" width="320" height="120"></iframe>'
% (oop2, port),
)
return (
"<!doctype html><html><head><meta charset=\"utf-8\"><title>fission identity parity</title>"
"<script>window.__parity = {}; window.__parity_done = false;\n"
"window.addEventListener('message', e => {\n"
" const r = e.data && e.data.fission_parity;\n"
" if (!r) return;\n"
" window.__parity[r.name] = r;\n"
" window.__parity_done = Object.keys(window.__parity).length >= %d;\n"
"});</script></head><body>%s"
"<script>%s\n"
"collect('top').then(r => window.top.postMessage({fission_parity: r}, '*'));</script>"
"</body></html>" % (len(CONTEXTS), "".join(frames), PROBE_JS)
).encode("utf-8")
# ---------------------------------------------------------------------------
# The comparison
# ---------------------------------------------------------------------------
def _absent(value) -> bool:
return value is None or (isinstance(value, str) and (value == "" or value.startswith("error:")))
def mismatches(results: dict, fields) -> list[str]:
"""Every way the iframes differ from the top document on ``fields``.
An absent value (``None``, empty, an error) in the top document is reported, because a
comparison against nothing proves nothing; the same value absent in an iframe is a
mismatch, because two empty answers are not an agreement.
"""
problems = []
top = results.get("top")
if top is None:
return ["the top document reported nothing"]
for name in CONTEXTS[1:]:
if name not in results:
problems.append("%s: the document reported nothing" % name)
for field in fields:
reference = top.get(field)
if _absent(reference):
problems.append("top: %s is absent (%r), nothing to compare against" % (field, reference))
continue
for name in CONTEXTS[1:]:
context = results.get(name)
if context is None:
continue
value = context.get(field)
if _absent(value):
problems.append("%s: %s is absent (%r), the top reads %r" % (name, field, value, reference))
elif value != reference:
problems.append("%s: %s = %r, the top reads %r" % (name, field, value, reference))
return problems
def same_persona(first: dict, second: dict) -> list[str]:
"""The contexts of ``second`` that read, on every persona field, what ``first``'s top reads.
Empty when the two seeds gave two different machines in every frame. An absent value is never
a difference (an error and an empty string are not two machines), so it is listed too.
"""
reference = tuple(first["top"].get(f) for f in PERSONA_FIELDS)
found = []
for name in CONTEXTS:
values = tuple(second[name].get(f) for f in PERSONA_FIELDS)
if any(_absent(v) for v in values) or values == reference:
found.append(name)
return found
# ---------------------------------------------------------------------------
# Unit layer: no browser
# ---------------------------------------------------------------------------
def _agreeing_results():
row = {"canvas": "abc:100", "canvas_png": "png:100", "audio": "def:5000", "webgl_vendor": "Google Inc.",
"webgl_renderer": "ANGLE", "time_zone": "America/New_York", "language": "en-US",
"languages": "en-US|en", "user_agent": "UA", "screen_width": 1920, "screen_height": 1080,
"screen_avail_width": 1920, "screen_avail_height": 1040, "device_pixel_ratio": 1,
"fonts_check": True, "font_width_arial": 503.5, "font_width_segoe_ui": 498.25,
"font_width_fallback": 600.0, "screen_x": 0, "screen_y": 0}
return {name: dict(row, name=name) for name in CONTEXTS}
ALL_FIELDS = tuple(f for group in GROUPS.values() for f in group)
@pytest.mark.unit
def test_contexts_that_agree_have_no_mismatch():
assert mismatches(_agreeing_results(), ALL_FIELDS) == []
@pytest.mark.unit
def test_an_iframe_with_another_canvas_is_reported():
"""The known-bad input: the iframe's process drew with another seed."""
results = _agreeing_results()
results["oop_127_0_0_3"]["canvas"] = "0f0f0f:100"
found = mismatches(results, GROUPS["canvas"])
assert len(found) == 1
assert found[0].startswith("oop_127_0_0_3: canvas = '0f0f0f:100'")
results["oop_127_0_0_3"]["canvas"] = "abc:100"
results["oop_127_0_0_3"]["canvas_png"] = "other-png:100"
assert [p.split(":")[0] for p in mismatches(results, GROUPS["canvas"])] == ["oop_127_0_0_3"]
@pytest.mark.unit
@pytest.mark.parametrize("field,wrong", [
("language", "it-IT"), ("time_zone", "UTC"), ("screen_width", 1366), ("device_pixel_ratio", 2),
("font_width_arial", 480.0), ("audio", "ffff:5000"), ("webgl_renderer", "llvmpipe"),
])
def test_every_field_that_differs_in_one_iframe_is_reported(field, wrong):
results = _agreeing_results()
results["nested_127_0_0_1"][field] = wrong
group = [g for g, fields in GROUPS.items() if field in fields][0]
found = mismatches(results, GROUPS[group])
assert [p.split(":")[0] for p in found] == ["nested_127_0_0_1"], found
@pytest.mark.unit
def test_an_absence_is_not_an_agreement():
"""Two empty answers are not equal values; and a top with no answer compares against nothing."""
results = _agreeing_results()
for name in CONTEXTS:
results[name]["canvas"] = "error:SecurityError"
found = mismatches(results, GROUPS["canvas"])
assert any(p.startswith("top: canvas is absent") for p in found)
results = _agreeing_results()
results["oop_127_0_0_2"]["language"] = None
results["oop_127_0_0_3"]["language"] = ""
found = mismatches(results, GROUPS["locale_and_agent"])
assert [p.split(":")[0] for p in found] == ["oop_127_0_0_2", "oop_127_0_0_3"]
@pytest.mark.unit
def test_a_document_that_never_reported_is_a_mismatch():
results = _agreeing_results()
del results["oop_127_0_0_3"]
assert mismatches(results, GROUPS["screen"]) == ["oop_127_0_0_3: the document reported nothing"]
assert mismatches({}, GROUPS["screen"]) == ["the top document reported nothing"]
@pytest.mark.unit
def test_two_seeds_that_give_the_same_machine_are_reported():
"""The known-bad input of the negative case: the iframe's process ignores the seed."""
first = _agreeing_results()
second = _agreeing_results()
for name in CONTEXTS:
second[name].update(webgl_renderer="ANGLE (NVIDIA)", screen_width=2560, screen_height=1440)
assert same_persona(first, second) == []
second["oop_127_0_0_3"].update(webgl_renderer="ANGLE", screen_width=1920, screen_height=1080)
assert same_persona(first, second) == ["oop_127_0_0_3"]
second["nested_127_0_0_1"]["screen_height"] = None
assert same_persona(first, second) == ["nested_127_0_0_1", "oop_127_0_0_3"]
@pytest.mark.unit
def test_screen_position_is_not_a_compared_field():
assert "screen_x" not in ALL_FIELDS and "screen_y" not in ALL_FIELDS
results = _agreeing_results()
results["oop_127_0_0_2"]["screen_x"] = 317
assert mismatches(results, ALL_FIELDS) == []
@pytest.mark.unit
def test_the_top_page_names_three_sites_and_a_nested_frame():
html = top_page(8123).decode("utf-8")
assert html.count("<iframe") == 2
for host in (HOST_OOP, HOST_OOP_2):
assert "http://%s:8123/probe/" % host in html
# The nested document is on the top's own site, handed to the second site's page.
assert "child=http://%s:8123/probe/nested_127_0_0_1" % HOST_TOP in html
assert "window.__parity_done" in html and "collect('top')" in html
assert "length >= %d;" % len(CONTEXTS) in html
@pytest.mark.unit
def test_a_probe_page_reads_the_documents_own_values_and_reports_to_the_top():
leaf = probe_page("oop_127_0_0_3").decode("utf-8")
assert "<iframe" not in leaf
assert "window.top.postMessage" in leaf and 'collect("oop_127_0_0_3")' in leaf
with_child = probe_page("oop_127_0_0_2", "http://127.0.0.1:1/probe/x").decode("utf-8")
assert '<iframe id="child" src="http://127.0.0.1:1/probe/x"' in with_child
for surface in ("toDataURL", "getImageData", "OfflineAudioContext", "WEBGL_debug_renderer_info",
"resolvedOptions().timeZone", "navigator.languages", "navigator.userAgent",
"screen.availHeight", "devicePixelRatio", "document.fonts.check"):
assert surface in with_child, surface
# Secure-context-only APIs are not used: 127.0.0.2 and .3 are not necessarily one.
assert "crypto.subtle" not in with_child
@pytest.mark.unit
def test_the_strategy_one_prefs_leave_the_process_count_alone():
assert STRATEGY_1_PREFS == {"fission.autostart": True, "fission.webContentIsolationStrategy": 1}
assert not any("processCount" in key for key in STRATEGY_1_PREFS)
@pytest.mark.integration
def test_the_server_answers_every_host_with_the_page_of_its_path():
server, port = _serve()
try:
import urllib.request
for host in (HOST_TOP, HOST_OOP, HOST_OOP_2):
assert urllib.request.urlopen("http://%s:%d/" % (host, port), timeout=5).read() == top_page(port)
top = urllib.request.urlopen("http://127.0.0.1:%d/" % port, timeout=5).read()
assert top == top_page(port)
leaf = urllib.request.urlopen("http://127.0.0.1:%d/probe/oop_127_0_0_3" % port, timeout=5).read()
assert leaf == probe_page("oop_127_0_0_3")
nested = urllib.request.urlopen(
"http://127.0.0.1:%d/probe/oop_127_0_0_2?child=http://127.0.0.1:%d/probe/n" % (port, port),
timeout=5).read()
assert nested == probe_page("oop_127_0_0_2", "http://127.0.0.1:%d/probe/n" % port)
finally:
server.shutdown()
# ---------------------------------------------------------------------------
# E2E layer
# ---------------------------------------------------------------------------
class _Servers:
"""The same handler on 127.0.0.1, 127.0.0.2 and 127.0.0.3, all on one port."""
def __init__(self, servers):
self.servers = servers
self.port = servers[0].server_address[1]
def shutdown(self):
for server in self.servers:
server.shutdown()
server.server_close()
def _serve():
"""One page server per host, on one port; ``(servers, port)``.
Each host gets its own socket (no ``0.0.0.0``: that would offer the pages to the network
and ask Windows Firewall about it). The kernel picks the port for the first one, which
stays bound; the other two bind the same number, and a number that is taken on one of
them is given up for a new one.
"""
class Handler(http.server.BaseHTTPRequestHandler):
timeout = 5
def do_GET(self):
url = urlsplit(self.path)
if url.path == "/":
body = top_page(self.server.server_address[1])
elif url.path.startswith("/probe/"):
name = url.path[len("/probe/"):]
child = None
for part in url.query.split("&"):
if part.startswith("child="):
child = part[len("child="):]
body = probe_page(name, child)
else:
self.send_error(404)
return
self.send_response(200)
self.send_header("Content-Type", "text/html; charset=utf-8")
self.send_header("Content-Length", str(len(body)))
self.send_header("Cache-Control", "no-store")
self.end_headers()
self.wfile.write(body)
def log_message(self, *args):
pass
last = None
for _ in range(20):
servers = []
try:
first = LocalServer((HOST_TOP, 0), Handler)
servers.append(first)
port = first.server_address[1]
for host in (HOST_OOP, HOST_OOP_2):
servers.append(LocalServer((host, port), Handler))
except OSError as error:
last = error
for server in servers:
server.server_close()
continue
for server in servers:
threading.Thread(target=server.serve_forever, daemon=True).start()
return _Servers(servers), port
raise RuntimeError("no port free on all of %s, %s, %s: %s" % (HOST_TOP, HOST_OOP, HOST_OOP_2, last))
#: Run in the top document: ask the iframe on the third site to spin, report the longest gap
#: between two ticks of a 10 ms timer. What a site can measure about its own process, with no
#: help from the driver.
SPIN_PROBE_JS = """(spin) => new Promise(resolve => {
let last = performance.now(), longest = 0;
const id = setInterval(() => {
const now = performance.now();
longest = Math.max(longest, now - last);
last = now;
}, 10);
document.getElementById('oop2').contentWindow.postMessage({fission_busy: spin}, '*');
setTimeout(() => { clearInterval(id); resolve(longest); }, 1500);
})"""
def _run(binary: str, seed: int, strategy: int) -> dict:
"""Open the page once; return what the four documents read and the longest timer gap the top saw."""
from invisible_playwright import InvisiblePlaywright
prefs = dict(STRATEGY_1_PREFS if strategy == 1 else STRATEGY_0_PREFS)
server, port = _serve()
try:
with InvisiblePlaywright(seed=seed, binary_path=binary, humanize=False, headless=True,
locale="en-US", timezone="America/New_York",
extra_prefs=prefs) as browser:
page = browser.new_context().new_page()
page.goto("http://%s:%d/" % (HOST_TOP, port), wait_until="load", timeout=60_000)
deadline = time.monotonic() + 60.0
while not page.evaluate("() => window.__parity_done"):
if time.monotonic() >= deadline:
break
page.wait_for_timeout(200)
results = page.evaluate("() => window.__parity")
longest_gap = page.evaluate(SPIN_PROBE_JS, SPIN_MS)
finally:
server.shutdown()
return {"results": results, "longest_gap_ms": longest_gap, "port": port}
@pytest.fixture(scope="module", params=[
pytest.param(0, id="strategy0"),
pytest.param(1, id="strategy1"),
])
def strategy(request):
return request.param
@pytest.fixture(scope="module")
def run(firefox_binary, strategy):
return _run(firefox_binary, SEED, strategy)
@pytest.fixture(scope="module")
def run_other_seed(firefox_binary, strategy):
return _run(firefox_binary, OTHER_SEED, strategy)
@pytest.mark.e2e
def test_every_context_reported(run):
assert sorted(run["results"]) == sorted(CONTEXTS), run["results"].keys()
@pytest.mark.e2e
def test_the_iframes_run_where_the_strategy_puts_them(run, strategy):
"""The precondition of the strategy-1 case, read by the page itself.
The iframe on the third site spins for 400 ms. In a process shared with the top the top's
10 ms timer stalls for about that long; in a process of its own it does not.
"""
gap = run["longest_gap_ms"]
if strategy == 0:
assert gap >= SHARED_PROCESS_GAP_MS, (
"strategy 0 keeps the iframes in the top's process, so a %d ms spin should stall "
"the top's timer; the longest gap was %.0f ms" % (SPIN_MS, gap))
else:
assert gap < OWN_PROCESS_GAP_MS, (
"strategy 1 gives the third site a process of its own, so a %d ms spin should not "
"stall the top's timer; the longest gap was %.0f ms" % (SPIN_MS, gap))
@pytest.mark.e2e
@pytest.mark.parametrize("group", sorted(GROUPS))
def test_the_identity_is_the_same_in_every_frame(run, group):
if group == "webgl" and run["results"].get("top", {}).get("webgl_renderer") is None:
pytest.skip("this machine gives the top document no WebGL renderer to compare against")
found = mismatches(run["results"], GROUPS[group])
assert not found, "identity differs between the top document and its iframes:\n " + "\n ".join(found)
@pytest.mark.e2e
def test_another_seed_is_another_machine_in_every_frame(run, run_other_seed):
"""The negative of the parity: equal values are only worth something if the seed moves them.
Together with the parity inside each launch this says: every frame reads the machine of ITS
seed, not one machine shared by every seed.
"""
for results in (run["results"], run_other_seed["results"]):
assert mismatches(results, PERSONA_FIELDS) == []
same = same_persona(run["results"], run_other_seed["results"])
assert not same, "seed %d and seed %d read the same machine in: %s" % (SEED, OTHER_SEED, same)
+132
View File
@@ -0,0 +1,132 @@
"""The crash of an iframe's process leaves the tab open, on a real engine with a process per site.
⛔ THE KNOWN-BAD INPUT: with Fission on (a process per site), an out-of-process iframe's BrowserParent has the TAB's
<browser> as its owner element, so the engine's `oop-frameloader-crashed` notification reaches Juggler's observer with
the tab's frameloader for the crash of one iframe. The observer answered every notification the same way: Page.crashed,
dispose the target, close the tab. A page whose only broken part was an iframe was closed under the client.
From firefox-62 the engine passes the crashed BrowsingContext's id as the notification's data
(nsFrameLoader::MaybeNotifyCrashed) and the observer takes a branch of its own for a context with a parent: the tab
stays and the client gets no Page.crashed (it is told the frame is gone with Page.frameDetached).
The process of the iframe is found, not guessed: the engine is asked (Marionette, chrome scope) for the OS pid of the
process that holds the top document and of the one that holds the iframe's; the test requires them to differ (the
iframe is out of process) and kills the iframe's.
The engine that does it is not published when this file is written: `engine_at_least` makes the test wait for it,
and on an older engine it is skipped, never passed.
"""
from __future__ import annotations
import http.server
import json
import threading
import time
import pytest
pytestmark = pytest.mark.e2e
#: the strategy of one process per site, the hosts resolved to the local server (one port: a.test:P and b.test:P are
#: two sites)
FISSION = {
"fission.autostart": True,
"fission.webContentIsolationStrategy": 1,
"dom.ipc.processCount.webIsolated": 4,
"network.dns.localDomains": "a.test,b.test",
}
#: for each browser window, each tab whose document has a child: [top pid, child pid]
PIDS = """
const out = [];
for (const win of Services.wm.getEnumerator('navigator:browser')) {
for (const tab of win.gBrowser.tabs) {
const bc = tab.linkedBrowser.browsingContext;
if (!bc || !bc.children.length) continue;
const pid = c => c.currentWindowGlobal && c.currentWindowGlobal.domProcess ? c.currentWindowGlobal.domProcess.osPid : null;
out.push([pid(bc), pid(bc.children[0])]);
}
}
return JSON.stringify(out);
"""
def _serve():
class Handler(http.server.BaseHTTPRequestHandler):
def do_GET(self):
host = (self.headers.get("Host") or "").split(":")[0]
if self.path.startswith("/frame"):
body = b"<!doctype html><title>frame</title><h1 id=h>in the iframe on " + host.encode() + b"</h1>"
else:
body = (b"<!doctype html><title>top</title><h1>top</h1>"
b"<iframe id=f src='http://b.test:%d/frame'></iframe>" % self.server.server_address[1])
self.send_response(200)
self.send_header("Content-Type", "text/html")
self.send_header("Content-Length", str(len(body)))
self.end_headers()
self.wfile.write(body)
def log_message(self, *args):
pass
server = http.server.ThreadingHTTPServer(("127.0.0.1", 0), Handler)
threading.Thread(target=server.serve_forever, daemon=True).start()
return server
def _wait(predicate, seconds):
end = time.time() + seconds
while time.time() < end:
if predicate():
return True
time.sleep(0.1)
return predicate()
def test_the_crash_of_an_iframe_s_process_leaves_the_tab(firefox_binary, engine_at_least, monkeypatch):
engine_at_least("firefox-62")
import psutil
import webfont_probe
from invisible_playwright import InvisiblePlaywright
monkeypatch.setenv("MOZ_REMOTE_ALLOW_SYSTEM_ACCESS", "1") # the chrome-scope reads below
server = _serve()
port = server.server_address[1]
marionette = None
try:
prefs = dict(FISSION, **{"marionette.port": webfont_probe.MARIONETTE_PORT})
with InvisiblePlaywright(binary_path=firefox_binary, headless=True, humanize=False,
extra_args=["-marionette"], extra_prefs=prefs) as browser:
page = browser.new_context().new_page()
crashes, closes = [], []
page.on("crash", lambda p: crashes.append(p))
page.on("close", lambda p: closes.append(p))
page.goto("http://a.test:%d/" % port, wait_until="load")
assert _wait(lambda: len(page.frames) == 2, 20), "the iframe never became a frame of the page"
# the iframe's document is not read, nor its address: what the client can see of a frame in another
# process is what the rest of Fission builds
marionette = webfont_probe._Marionette(webfont_probe.MARIONETTE_PORT)
marionette.call("WebDriver:NewSession", {"capabilities": {"alwaysMatch": {}}})
marionette.call("Marionette:SetContext", {"value": "chrome"})
pids = json.loads(marionette.call("WebDriver:ExecuteScript", {"script": PIDS, "args": []})["value"])
assert len(pids) == 1, "one tab with an iframe expected, the engine says %r" % (pids,)
top_pid, iframe_pid = pids[0]
assert top_pid and iframe_pid and top_pid != iframe_pid, \
"the iframe is not out of process (top %r, iframe %r): this engine is not running a process per site" % (top_pid, iframe_pid)
psutil.Process(iframe_pid).kill()
# The tab stays. The client is told neither that the page crashed nor that it closed; if the engine
# closed the tab, those events come within a moment, so they are waited for before they are denied.
_wait(lambda: crashes or closes or page.is_closed(), 8)
assert not crashes, "Page.crashed was sent for the crash of an iframe"
assert not closes and not page.is_closed(), "the tab was closed for the crash of an iframe"
assert page.evaluate("1 + 1") == 2
assert page.text_content("h1") == "top"
# Not asserted here: that `page.frames` drops the crashed frame. The client keeps a frame of another
# process until the Fission lifecycle work (a frame removed from the DOM stays in `page.frames` too).
finally:
if marionette is not None:
marionette.close()
server.shutdown()
+441
View File
@@ -0,0 +1,441 @@
"""The bench for firefox-62 (Fission, strategy 1): a page whose frames live in different processes.
Strategy 1 is `fission.webContentIsolationStrategy = 1` (IsolateEverything: one remote type per site) with
`fission.autostart` on. The wrapper still launches with strategy 0 (`_BASELINE`): the prefs below are an
overlay for this file only, so the product stays green while this bench is red.
Hosts `a.test`, `b.test`, `c.test` resolve to one local server through `network.dns.localDomains`, on one
port: two hosts are two SITES, so a frame of `b.test` inside a page of `a.test` is out of process, and the
`a.test` frame inside that one (a -> b -> a) is a fragment root of its own, in the process of the top.
`localhost` and `127.0.0.1` would not do for this: `127.0.0.1:P1` and `127.0.0.1:P2` are one site.
Tests 1 and 2 hold the bench itself (the sites ARE separated; the same site is NOT): green today. Every other
test says what the product does not do yet and the step that makes it green:
3 frame list with real urls step 3 (navigations)
4 evaluate in the out-of-process frame steps 2a + 1a + 1b
5 a -> b -> a parent chain steps 2a + 1b
6 content_frame() of the iframe element step 4
7 click by selector in the leaf steps 5 + 6
8 init script reaches the frame first step 1a
9 named world after the OOP frame step 1a + 2b
10 console of the OOP frame step 1a
The oracle for "another process" is the engine's own processes below the test (`-contentproc ... tab`): a
cross-site frame adds at least one, a same-site one adds none. The count is read after the browser is quiet
(the engine pre-allocates a content process and replaces it when it is used).
"""
from __future__ import annotations
import json
import os
import threading
import time
from http.server import BaseHTTPRequestHandler
from pathlib import Path
from urllib.parse import parse_qs, urlsplit
import pytest
from _servers import LocalServer
FISSION_ON = {
"fission.autostart": True,
"fission.webContentIsolationStrategy": 1, # IsolateEverything: site-origin
"dom.ipc.processCount.webIsolated": 4, # the desktop default
"network.dns.localDomains": "a.test,b.test,c.test",
}
@pytest.fixture
def cross_site_loop():
"""a.test/top -> b.test/mid -> a.test/leaf, plus a same-site frame page and the reports the pages send."""
reports = []
routes = {}
class Handler(BaseHTTPRequestHandler):
timeout = 5
def log_message(self, *args):
pass
def do_GET(self):
url = urlsplit(self.path)
host = (self.headers.get("Host") or "").split(":")[0]
if url.path.startswith("/report"):
reports.append({"host": host, "path": url.path, "query": parse_qs(url.query)})
body, ctype = b"ok", "text/plain"
elif url.path in routes:
body, ctype = routes[url.path](host).encode(), "text/html; charset=utf-8"
else:
self.send_response(404)
self.send_header("Content-Length", "0")
self.end_headers()
return
self.send_response(200)
self.send_header("Content-Type", ctype)
self.send_header("Content-Length", str(len(body)))
self.end_headers()
self.wfile.write(body)
server = LocalServer(("127.0.0.1", 0), Handler)
thread = threading.Thread(target=server.serve_forever, daemon=True)
thread.start()
port = server.server_address[1]
def at(host, path):
return "http://%s:%d%s" % (host, port, path)
# What a page reports: where it is, and the order of the scripts that ran in it (an init script pushes
# 'init' to window.__o; the page pushes 'page').
report = ("<script>(window.__o = window.__o || []).push('page');"
"console.log('hello from ' + location.pathname + ' on ' + location.host);"
"fetch('/report/loaded?path=' + location.pathname + '&order=' + encodeURIComponent(JSON.stringify(window.__o)))"
"</script>")
routes["/top"] = lambda host: ("<!doctype html><title>top</title>"
'<iframe id="b" src="%s" width="600" height="400"></iframe>' % at("b.test", "/mid") + report)
routes["/mid"] = lambda host: ("<!doctype html><title>mid</title>"
'<iframe id="a" src="%s" width="500" height="300"></iframe>' % at("a.test", "/leaf") + report)
routes["/leaf"] = lambda host: ("<!doctype html><title>leaf</title><button id=\"ok\" style=\"width:120px;height:40px\">ok</button>"
"<script>ok.addEventListener('click', e => fetch('/report/clicked?isTrusted=' + e.isTrusted))</script>" + report)
routes["/same-site"] = lambda host: ("<!doctype html><title>same-site</title>"
'<iframe id="s" src="%s" width="300" height="100"></iframe>' % at("a.test", "/leaf"))
# an iframe nested past the depth Firefox allows (nsFrameLoader::DepthTooGreat, 10), all of one origin
for n in range(0, 14):
routes["/deep%d" % n] = (lambda n: lambda host: "<!doctype html><title>deep%d</title><iframe id=\"f\" src=\"%s\"></iframe>" % (n, at(host, "/deep%d" % (n + 1))))(n)
# a page that reports each time it is shown, and whether it came out of the back-forward cache
routes["/shown"] = lambda host: ("<!doctype html><title>shown</title><script>addEventListener('pageshow', e => "
"fetch('/report/pageshow?persisted=' + e.persisted + '&top=' + (window === top)))</script>")
routes["/top-shown"] = lambda host: ('<!doctype html><title>top-shown</title><iframe id="b" src="%s"></iframe>' % at("b.test", "/shown"))
# a page and one iframe of another site, named, with nothing else in it
routes["/one-iframe"] = lambda host: ('<!doctype html><title>one</title><iframe id="f" name="f" src="%s"></iframe>' % at("b.test", "/plain"))
routes["/plain"] = lambda host: "<!doctype html><title>plain</title><p>plain"
try:
yield {"top": at("a.test", "/top"), "one_iframe": at("a.test", "/one-iframe"), "deep": at("a.test", "/deep0"), "top_shown": at("a.test", "/top-shown"), "mid": at("b.test", "/mid"), "leaf": at("a.test", "/leaf"),
"same_site": at("a.test", "/same-site"), "plain": at("a.test", "/plain"),
"reports": reports, "origin_mid": "http://b.test:%d" % port, "origin_top": "http://a.test:%d" % port}
finally:
server.shutdown()
server.server_close()
thread.join()
@pytest.fixture
def engine_dir(firefox_binary):
return str(Path(firefox_binary).resolve().parent)
def content_processes(engine_dir):
"""The pids of the engine's web content processes (`-contentproc ... tab`) below this test."""
import psutil
pids = set()
for child in psutil.Process(os.getpid()).children(recursive=True):
try:
if not os.path.normcase(child.exe()).startswith(os.path.normcase(engine_dir)):
continue
cmd = child.cmdline()
except psutil.Error:
continue
if "-contentproc" in cmd and cmd[-1] == "tab":
pids.add(child.pid)
return pids
def quiet(engine_dir, seconds=3.0, limit=30.0):
"""The set of content processes once it has not changed for `seconds`."""
end = time.time() + limit
last, since = content_processes(engine_dir), time.time()
while time.time() < end:
time.sleep(0.25)
now = content_processes(engine_dir)
if now != last:
last, since = now, time.time()
elif time.time() - since >= seconds:
break
return last
@pytest.fixture
def browser(firefox_binary):
from invisible_playwright import InvisiblePlaywright
with InvisiblePlaywright(seed=42, binary_path=firefox_binary, humanize=False, headless=True,
extra_prefs=FISSION_ON) as browser:
yield browser
@pytest.fixture
def page(browser):
page = browser.new_context().new_page()
page.set_default_timeout(3000)
page.set_default_navigation_timeout(20000)
return page
def wait_for(page, predicate, seconds=8.0):
"""Until `predicate()`, with the client's events being read: the sync client takes the engine's events
only inside its own calls, so a plain sleep would never see a frame arrive."""
end = time.time() + seconds
while time.time() < end:
if predicate():
return True
page.wait_for_timeout(100)
return predicate()
@pytest.fixture
def events(monkeypatch):
"""Every protocol event the client receives, in order (the client's own view of the page)."""
from invisible_core.juggler.connection import EventListeners
seen = []
dispatch = EventListeners.dispatch_event
def record(self, method, params, session):
seen.append({"method": method, "params": params})
return dispatch(self, method, params, session)
monkeypatch.setattr(EventListeners, "dispatch_event", record)
return seen
def frame_with_origin(page, origin):
for frame in page.frames:
if frame.url.startswith(origin):
return frame
return None
# ── 1, 2: the bench itself ─────────────────────────────────────────────────────
@pytest.mark.e2e
def test_cross_site_iframe_gets_its_own_process(page, cross_site_loop, engine_dir):
"""Green today: it says the bench separates sites. Two sites in the frame tree add at least one process."""
page.goto(cross_site_loop["plain"])
before = quiet(engine_dir)
page.goto(cross_site_loop["top"], wait_until="load")
assert wait_for(page, lambda: any(r["path"] == "/report/loaded" and r["host"] == "a.test" and
r["query"]["path"] == ["/leaf"] for r in cross_site_loop["reports"]))
after = quiet(engine_dir)
assert len(after - before) >= 1, "no new content process: before %s, after %s" % (sorted(before), sorted(after))
@pytest.mark.e2e
def test_same_site_other_port_stays_in_process(page, cross_site_loop, engine_dir):
"""Green today, the control: a frame of the page's own site adds no content process."""
page.goto(cross_site_loop["plain"])
before = quiet(engine_dir)
page.goto(cross_site_loop["same_site"], wait_until="load")
assert wait_for(page, lambda: any(r["path"] == "/report/loaded" for r in cross_site_loop["reports"]))
after = quiet(engine_dir)
assert not (after - before), "a same-site frame started a process: %s" % sorted(after - before)
# ── 3 .. 10: what the product does not do yet ──────────────────────────────────
@pytest.mark.e2e
def test_frame_list_has_real_urls(page, cross_site_loop, engine_at_least):
"""Red until step 3: the frame of another process is listed with an empty url (a placeholder)."""
engine_at_least("firefox-62")
page.goto(cross_site_loop["top"], wait_until="load")
wait_for(page, lambda: len(page.frames) >= 3)
urls = sorted(frame.url for frame in page.frames)
assert urls == sorted([cross_site_loop["top"], cross_site_loop["mid"], cross_site_loop["leaf"]])
@pytest.mark.e2e
def test_frame_evaluate_in_oop_iframe(page, cross_site_loop, engine_at_least):
"""Red until steps 2a + 1a + 1b: no execution context exists for a frame of another process."""
engine_at_least("firefox-62")
page.goto(cross_site_loop["top"], wait_until="load")
wait_for(page, lambda: len(page.frames) >= 2)
assert len(page.frames) >= 2
mid = page.frames[1]
assert mid.evaluate("location.origin") == cross_site_loop["origin_mid"]
@pytest.mark.e2e
def test_nested_a_b_a_parent_chain(page, cross_site_loop, engine_at_least):
"""Red until steps 2a + 1b: a placeholder has no parent chain."""
engine_at_least("firefox-62")
page.goto(cross_site_loop["top"], wait_until="load")
wait_for(page, lambda: len(page.frames) >= 3)
top = page.main_frame
mid = next((f for f in page.frames if f.url == cross_site_loop["mid"]), None)
leaf = next((f for f in page.frames if f.url == cross_site_loop["leaf"]), None)
assert mid is not None and leaf is not None, [f.url for f in page.frames]
assert leaf.parent_frame == mid
assert mid.parent_frame == top
@pytest.mark.e2e
def test_content_frame_resolves(page, cross_site_loop, engine_at_least):
"""Red until step 4: the element of an iframe whose document is in another process has no frame."""
engine_at_least("firefox-62")
page.goto(cross_site_loop["top"], wait_until="load")
owner = page.query_selector("#b")
try:
frame = owner.content_frame()
finally:
owner.dispose()
assert frame is not None
assert frame.url == cross_site_loop["mid"]
@pytest.mark.e2e
def test_click_in_oop_iframe_by_selector(page, cross_site_loop, engine_at_least):
"""Red until steps 5 + 6: a trusted click reaches the leaf, two frames down, in the process of the top."""
engine_at_least("firefox-62")
page.goto(cross_site_loop["top"], wait_until="load")
page.frame_locator("#b").frame_locator("#a").locator("#ok").click()
assert wait_for(page, lambda: any(r["path"] == "/report/clicked" and r["query"]["isTrusted"] == ["true"]
for r in cross_site_loop["reports"]))
@pytest.mark.e2e
def test_init_script_reaches_oop_frame_first(page, cross_site_loop, engine_at_least):
"""Red until step 1a: an init script runs in the frame of another process before the page's own scripts."""
engine_at_least("firefox-62")
page.add_init_script("(window.__o = window.__o || []).push('init')")
page.goto(cross_site_loop["top"], wait_until="load")
assert wait_for(page, lambda: len([r for r in cross_site_loop["reports"] if r["path"] == "/report/loaded"]) >= 3)
orders = {r["query"]["path"][0]: json.loads(r["query"]["order"][0])
for r in cross_site_loop["reports"] if r["path"] == "/report/loaded"}
assert orders == {"/top": ["init", "page"], "/mid": ["init", "page"], "/leaf": ["init", "page"]}
@pytest.mark.e2e
def test_named_world_declared_after_oop_iframe(page, cross_site_loop, events, engine_at_least):
"""Red until steps 1a + 2b: the utility world the client declares exists in every frame, the other
process's included (today the declaration to a frame without a docShell is lost without a word)."""
engine_at_least("firefox-62")
from invisible_core.juggler.injected import UTILITY_WORLD
page.goto(cross_site_loop["top"], wait_until="load")
wait_for(page, lambda: len(page.frames) >= 3)
page.wait_for_timeout(1000)
created = [e["params"] for e in events if e["method"] == "Runtime.executionContextCreated"]
default = {c["auxData"]["frameId"] for c in created if not c["auxData"].get("name")}
utility = {c["auxData"]["frameId"] for c in created if c["auxData"].get("name") == UTILITY_WORLD}
assert len(default) >= 3, "frames with a default context: %d" % len(default)
assert default <= utility, "frames without a utility context: %d" % len(default - utility)
# The contexts above can be those of the frame's first about:blank, which no one ever destroys: what
# counts is a read of the frame's CURRENT document through them.
mid = next((f for f in page.frames if f.url == cross_site_loop["mid"]), None)
assert mid is not None, [f.url for f in page.frames]
assert mid.locator("#a").count() == 1
@pytest.mark.e2e
def test_console_from_oop_frame_reaches_client(page, cross_site_loop, engine_at_least):
"""Red until step 1a: a console message of a frame of another process arrives."""
engine_at_least("firefox-62")
messages = []
page.on("console", lambda message: messages.append(message.text))
page.goto(cross_site_loop["top"], wait_until="load")
assert wait_for(page, lambda: any("/mid on b.test" in text for text in messages)), messages
# ── what step 1 adds to the bench ──────────────────────────────────────────────
@pytest.mark.e2e
def test_a_context_of_the_top_survives_an_oop_frame_coming_and_going(page, cross_site_loop):
"""A guard, green on every engine: the `cleared` of one process must not take the contexts of another with it.
A handle held on the top is read after a frame of another process has come and gone."""
page.goto(cross_site_loop["plain"], wait_until="load")
body = page.evaluate_handle("document.body")
page.evaluate("""url => new Promise(resolve => {
const f = document.createElement('iframe'); f.id = 'x'; f.src = url; f.onload = resolve; document.body.appendChild(f);
})""", cross_site_loop["mid"])
wait_for(page, lambda: len(page.frames) >= 2)
assert body.evaluate("b => b.tagName") == "BODY"
page.evaluate("document.getElementById('x').remove()")
assert body.evaluate("b => b.tagName") == "BODY"
@pytest.mark.e2e
def test_oop_frames_are_listed_again_after_the_top_comes_back_from_the_cache(page, cross_site_loop):
"""Red until FrameLifecycle announces again the frames below a document restored from the back-forward cache:
the content process no longer announces a frame of another process (step 1b), and the client forgets the
frames below a frame when a document commits in it."""
page.goto(cross_site_loop["top"], wait_until="load")
assert wait_for(page, lambda: len(page.frames) >= 3)
page.goto(cross_site_loop["plain"], wait_until="load")
page.go_back(wait_until="load")
assert wait_for(page, lambda: len(page.frames) >= 3), [f.url for f in page.frames]
@pytest.mark.e2e
def test_oop_frame_has_its_url_and_answers_after_the_top_comes_back_from_the_cache(page, cross_site_loop, engine_at_least):
"""Red until steps 2b + 3: the restored frames come back with their url (the parent's registry of navigations)
and with their execution contexts (announced again by the mux)."""
engine_at_least("firefox-62")
page.goto(cross_site_loop["top"], wait_until="load")
assert wait_for(page, lambda: len(page.frames) >= 3)
page.goto(cross_site_loop["plain"], wait_until="load")
page.go_back(wait_until="load")
assert wait_for(page, lambda: any(f.url == cross_site_loop["mid"] for f in page.frames))
mid = next(f for f in page.frames if f.url == cross_site_loop["mid"])
assert mid.evaluate("1") == 1
@pytest.mark.e2e
def test_removed_oop_frame_leaves_the_frame_list_and_the_page_answers(page, cross_site_loop, engine_at_least):
"""Red until PageHandler listens to the FrameLifecycle through helper.on: its own emitter calls a listener with
the event name first, so `{frameId}` was read from a string and the frame was never detached. The frame of
another process that is removed from the DOM must leave `page.frames`, and the commands that go to every
process (init scripts) must not wait for the one that is gone."""
engine_at_least("firefox-62")
page.goto(cross_site_loop["top"], wait_until="load")
assert wait_for(page, lambda: len(page.frames) >= 3)
page.evaluate("document.getElementById('b').remove()")
assert wait_for(page, lambda: len(page.frames) == 1), [f.url for f in page.frames]
page.add_init_script("window.__after = 1")
page.goto(cross_site_loop["plain"], wait_until="load")
assert page.evaluate("window.__after") == 1
@pytest.mark.e2e
def test_content_frame_of_an_iframe_nested_too_deep_is_none(page, cross_site_loop):
"""Red until step 8: past the depth Firefox allows (10) an <iframe> has a browsing context that loads
nothing and `element.browsingContext` does not apply the depth check, so the element named a frame with no
document. `contentWindow` is null there, and the client expects no content frame."""
page.goto(cross_site_loop["deep"], wait_until="load")
assert wait_for(page, lambda: len(page.frames) >= 10)
page.wait_for_timeout(1500)
last = page.frames[-1]
owner = last.frame_element()
try:
assert owner.content_frame() is None
finally:
owner.dispose()
@pytest.mark.e2e
def test_oop_frame_comes_out_of_the_back_forward_cache_with_the_top(page, cross_site_loop):
"""What the engine does, not the product: the document of a frame in another process is shown again, persisted,
when the top comes back from the cache (step 8.3 relies on it)."""
page.goto(cross_site_loop["top_shown"], wait_until="load")
assert wait_for(page, lambda: any(r["path"] == "/report/pageshow" for r in cross_site_loop["reports"]))
page.goto(cross_site_loop["plain"], wait_until="load")
page.go_back(wait_until="load")
assert wait_for(page, lambda: any(r["path"] == "/report/pageshow" and r["query"]["persisted"] == ["true"] and
r["query"]["top"] == ["false"] for r in cross_site_loop["reports"])), cross_site_loop["reports"]
@pytest.mark.e2e
def test_the_frames_have_their_urls_when_goto_returns(browser, cross_site_loop, engine_at_least):
"""Red until the load of a frame waits for the commit of the frames below it: the embedder's process says `load` of the
top while the commit of the iframe of another site waits for the name of its <iframe> (asked of that same process), and
the frames read right after `goto` had an empty url 3 times in 20 (at 50 runs the chance of seeing it is 1 - 0.85^50). Nothing here waits: the frames are read at once."""
engine_at_least("firefox-62")
empty = []
for i in range(50):
page = browser.new_context().new_page()
page.goto(cross_site_loop["one_iframe"] + "?i=%d" % i, wait_until="load")
urls = [frame.url for frame in page.frames]
if "" in urls or len(urls) < 2:
empty.append((i, urls))
page.context.close()
assert not empty, "frames with no url right after goto, in %d of 50 runs: %s" % (len(empty), empty[:3])
@@ -1,6 +1,7 @@
"""Fontconfig reads nothing of the host (e2e, Linux): no process of the browser,
parent or content, opens, stats or probes the host's fontconfig
configuration or its font directories.
"""Fontconfig reads nothing of the host (e2e, Linux): no process of the browser opens
the host's fontconfig configuration or its font files, and no content process looks at
them at all (open, stat, access, readlink). The parent's own existence probes (lstat,
stat, access, readlink) are not reads: see ``judge``.
The engine runs fontconfig on an empty configuration installed before the
first ``FcInit()`` (``StealthFcEmptyConfig``, nsLookAndFeel and the platform
@@ -8,9 +9,16 @@ font list); the fonts are the bundle's. The engine's own gtest only looks at
the final state, so it would also pass if the host's configuration had been
loaded first, by GTK, Pango or anything else, and replaced afterwards. What
sees the order is the system calls themselves: the browser runs under
``strace -f`` and a page with text is drawn, and a single look at
``strace -f`` and a page with text is drawn, and one ``open`` of
``/etc/fonts``, ``~/.config/fontconfig``, ``$FONTCONFIG_FILE`` or
``/usr/share/fonts`` by any process fails the test.
``/usr/share/fonts`` by any process, or one ``stat`` there by a content process, fails
the test.
Why the parent's existence probes pass: the parent builds the permissions of the content
sandbox (SandboxBrokerPolicyFactory::InitContentPolicy) and, for each path a content
process may be given, asks whether it exists (``lstat``, ``stat``). It opens nothing and
no byte of those files enters the process; a page cannot see the call. Fontconfig that
read the host would ``open`` its configuration, and that is what fails.
strace runs through a stand-in tree: a temporary directory with a link to
every file of the engine's directory, where the executable is a script that
@@ -156,6 +164,33 @@ def _host_lookups(log: Path, real_binary: str) -> dict:
return dict(found)
# What a call does to a path. An existence probe is the question "is it there": no byte is read.
_OPENS = ("open", "openat", "openat2", "creat")
def _call_of(line: str) -> str:
m = _LINE.match(line)
return m.group(2) if m else ""
def judge(found: dict) -> dict:
"""The part of ``_host_lookups``' result that fails the test.
- any process that OPENS a host fontconfig or font path (an open that fails with ENOENT
too: it is fontconfig trying to read its configuration);
- a content process that does anything at all there (stat, access, readlink included):
content has no reason to look, and it is the process a page runs in.
The parent's existence probes (stat, lstat, newfstatat, statx, access, faccessat, readlink)
are ignored, for the reason in the module's docstring."""
bad = {}
for who, hits in found.items():
kept = list(hits) if who == "content" else [h for h in hits if _call_of(h) in _OPENS]
if kept:
bad[who] = kept
return bad
def _kill_group(pidfile: Path) -> None:
"""Kill the stand-in's process group: strace, the browser and its children.
@@ -230,7 +265,7 @@ def test_a_killed_stand_in_leaves_neither_strace_nor_the_browser(firefox_binary,
def test_no_process_reads_the_host_fontconfig(firefox_binary, tmp_path, engine_at_least):
engine_at_least("firefox-60")
engine_at_least("firefox-64")
from invisible_playwright import InvisiblePlaywright
_require_strace_can_trace(tmp_path)
@@ -254,7 +289,7 @@ def test_no_process_reads_the_host_fontconfig(firefox_binary, tmp_path, engine_a
text = log.read_text(errors="replace")
assert "-contentproc" in text, (
"strace saw no content process, so the test could not judge one")
found = _host_lookups(log, real)
found = judge(_host_lookups(log, real))
report = []
for who, hits in sorted(found.items()):
pids = sorted({int(h.split()[0]) for h in hits})
@@ -269,5 +304,5 @@ def test_no_process_reads_the_host_fontconfig(firefox_binary, tmp_path, engine_a
report += [" " + n for n in names[:12]]
report += [" " + h[:240] for h in hits[:4]]
assert not found, (
"the browser looked at the host's fontconfig (%s):\n%s"
"the browser opened the host's fontconfig, or a content process looked at it (%s):\n%s"
% (", ".join(_host_font_paths()), "\n".join(report)))
+3
View File
@@ -1,5 +1,6 @@
"""Frame identity must travel with every selector and handle."""
import threading
from collections import OrderedDict
from types import SimpleNamespace
from unittest.mock import Mock
@@ -166,6 +167,8 @@ def test_adopt_is_one_wire_call_for_both_crossings(element, into, expected):
("payment", UTILITY_WORLD): "payment-utility"}
# What __init__ gives it: the world waits sleep on it (invisible-core 58).
injected._contexts_changed = threading.Condition()
# And the frames the engine said are detached, which the wait for a world reads (invisible-core 62).
injected._gone = OrderedDict()
assert injected.adopt("widget", element, into=into) == "adopted"
assert sent == [("Page.adoptNode", expected)]
+176
View File
@@ -0,0 +1,176 @@
"""A goto to the address the page is at ends, whatever the page is made of (firefox-62, sites isolated: strategy 1).
With sites isolated an iframe of another site is born in the process of its page and goes to the process of its site.
A goto to the address the page is already at replaces the document in the same process, and the children of the
document it replaces are detached when the new one is inserted. The page world of such an iframe is its
WindowProxy, which is a remote one by then: the Debugger refused to remove it ("argument is not a global object"),
the detach threw, and the new document was never told to the parent. The goto then ended with "load not reached in 45s
(our navigation nav-N started and has neither committed nor been aborted)", on pages of every size and header
(MDN, css-tricks, cnn), while a goto to another address, a reload and a fragment were fine.
Each goto here must end, with the response, the address and the frames it has: 20 in a row, on the kinds of page below
(a plain one, a big one, one revalidated with a 304, one fresh in the cache, one that is never stored, a page with a
frame of its own site, one with a frame of another site, one with that frame revalidated, and a -> b -> a). Hosts
`a.test`, `b.test` and `c.test` are three sites on one server (`network.dns.localDomains`).
"""
from __future__ import annotations
import asyncio
import hashlib
import threading
import time
from http.server import BaseHTTPRequestHandler
import pytest
from _servers import LocalServer
pytestmark = pytest.mark.e2e
FISSION_ON = {
"fission.autostart": True,
"fission.webContentIsolationStrategy": 1,
"dom.ipc.processCount.webIsolated": 4,
"network.dns.localDomains": "a.test,b.test,c.test",
}
GOTOS = 20
BIG = "<p>" + ("lorem ipsum dolor sit amet " * 40) + "</p>\n"
def _body(kind, port):
"""(html, how many frames the page has, the title)."""
frame = '<iframe src="http://%s:%d/%s"></iframe>'
if kind == "plain":
return "<p>plain</p>", 1
if kind == "big":
return BIG * 1200, 1 # about 1.3 MB
if kind in ("etag", "fresh", "nostore"):
return "<p>%s</p>" % kind, 1
if kind == "same-site-frame":
return "<p>top</p>" + frame % ("a.test", port, "plain"), 2
if kind == "other-site-frame":
return "<p>top</p>" + frame % ("b.test", port, "plain"), 2
if kind == "other-site-frame-etag":
return "<p>top</p>" + frame % ("b.test", port, "etag"), 2
if kind == "a-b-a":
return "<p>top</p>" + frame % ("b.test", port, "mid"), 3
if kind == "mid":
return "<p>mid</p>" + frame % ("a.test", port, "plain"), 2
raise AssertionError(kind)
KINDS = ["plain", "big", "etag", "fresh", "nostore", "same-site-frame", "other-site-frame",
"other-site-frame-etag", "a-b-a"]
@pytest.fixture
def site():
class Handler(BaseHTTPRequestHandler):
protocol_version = "HTTP/1.1"
timeout = 10
def log_message(self, *args):
pass
def do_GET(self):
kind = self.path.split("?")[0].strip("/")
port = self.server.server_address[1]
if kind == "favicon.ico":
self.send_response(404)
self.send_header("Content-Length", "0")
self.end_headers()
return
html, _ = _body(kind, port)
body = ("<!doctype html><title>%s</title>%s" % (kind, html)).encode()
headers = {"Content-Type": "text/html"}
if kind.endswith("etag"):
tag = '"%s"' % hashlib.md5(body).hexdigest()
headers["ETag"] = tag
headers["Cache-Control"] = "max-age=0, must-revalidate"
if self.headers.get("If-None-Match") == tag:
self.send_response(304)
for name, value in headers.items():
self.send_header(name, value)
self.send_header("Content-Length", "0")
self.end_headers()
return
elif kind == "fresh":
headers["Cache-Control"] = "max-age=3600"
elif kind == "nostore":
headers["Cache-Control"] = "no-store"
try:
self.send_response(200)
for name, value in headers.items():
self.send_header(name, value)
self.send_header("Content-Length", str(len(body)))
self.end_headers()
self.wfile.write(body)
except OSError:
pass
server = LocalServer(("127.0.0.1", 0), Handler)
thread = threading.Thread(target=server.serve_forever, daemon=True)
thread.start()
yield server.server_address[1]
server.shutdown()
server.server_close()
thread.join()
def _run(firefox_binary, scenario):
from invisible_playwright.async_api import InvisiblePlaywright
async def go():
async with InvisiblePlaywright(seed=42, binary_path=firefox_binary, humanize=False, headless=True,
extra_prefs=FISSION_ON) as browser:
page = await browser.new_page()
return await scenario(page)
return asyncio.run(go())
@pytest.mark.parametrize("kind", KINDS)
def test_a_goto_to_the_address_the_page_is_at_ends_every_time(firefox_binary, site, kind):
port = site
url = "http://a.test:%d/%s" % (port, kind)
_, frames = _body(kind, port)
async def scenario(page):
await page.goto(url, timeout=15000)
seen = []
for i in range(GOTOS):
began = time.monotonic()
response = await page.goto(url, timeout=15000)
took = time.monotonic() - began
title = await page.title()
seen.append((i, response.status if response else None, page.url, title, len(page.frames), round(took, 2)))
return seen
seen = _run(firefox_binary, scenario)
assert len(seen) == GOTOS
answers = (200, 304) if kind.endswith("etag") else (200,) # a revalidated page is answered 304, and says so
for i, status, address, title, count, took in seen:
assert status in answers, seen[i]
assert address == url, seen[i]
assert title == kind, seen[i]
assert count == frames, seen[i]
assert took < 10, seen[i]
def test_a_goto_to_the_same_address_with_a_query_ends_the_second_time_too(firefox_binary, site):
"""The query is another address once, and the same one after: MDN's `?x=1` twice."""
port = site
url = "http://a.test:%d/other-site-frame?x=1" % port
async def scenario(page):
await page.goto("http://a.test:%d/other-site-frame" % port, timeout=15000)
out = []
for _ in range(3):
response = await page.goto(url, timeout=15000)
out.append((response.status if response else None, page.url, len(page.frames)))
return out
out = _run(firefox_binary, scenario)
assert out == [(200, url, 2)] * 3, out
+90
View File
@@ -0,0 +1,90 @@
"""HTTP/3 behind a SOCKS5 proxy: the page reads `nextHopProtocol`, and a retail Firefox with no proxy uses h3.
⛔ THE KNOWN-BAD INPUT: the engine refuses HTTP/3 whenever a proxy is in use (AltSvcCache::UpdateAltServiceMapping, the
attempt of DnsAndConnectSocket, HttpBaseChannel), so a page behind a SOCKS5 gateway that relays UDP read `h2` where the
same Firefox with no proxy reads `h3`. With a gateway that relays UDP the QUIC connection goes through the ASSOCIATE of the
proxy (the server sees the relay, never this host); with one that does not, the QUIC handshake never completes and Firefox
falls back to h2 by itself, and nothing UDP leaves this host direct.
The server is local, reached by its address (an address of this host that is not loopback: a loopback destination goes
direct whatever the proxy), with a self-signed certificate (the context ignores certificate errors).
"""
from __future__ import annotations
import os
import socket
import pytest
pytestmark = [pytest.mark.e2e, pytest.mark.usefixtures("the_udp_line")]
def _binary():
cand = os.environ.get("STEALTHFOX_E2E_BINARY") or os.environ.get("INVPW_BINARY_PATH")
if not cand or not os.path.exists(cand):
pytest.skip("no patched binary (set STEALTHFOX_E2E_BINARY)")
return cand
def _address_of_this_host() -> str:
probe = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
try:
probe.connect(("192.0.2.1", 9))
return probe.getsockname()[0]
finally:
probe.close()
_FETCH = """async (url) => {
const seen = [];
for (let i = 0; i < 12; i++) {
const r = await fetch(url + '?n=' + i, {cache: 'no-store', mode: 'no-cors'});
await r.arrayBuffer();
const entry = performance.getEntriesByType('resource').filter(e => e.name.includes('?n=' + i)).pop();
seen.push(entry ? entry.nextHopProtocol : '?');
await new Promise(resolve => setTimeout(resolve, 500));
}
return seen;
}"""
def _protocols_behind(gateway, server, monkeypatch):
from invisible_core import _geo
from invisible_playwright import InvisiblePlaywright
monkeypatch.setattr(_geo, "discover_egress_ip", lambda *_a, **_k: gateway.tcp_exit)
with InvisiblePlaywright(headless=True, binary_path=_binary(), timezone="America/New_York",
proxy=gateway.proxy) as browser:
context = browser.new_context(ignore_https_errors=True)
page = context.new_page()
page.goto(server.url, wait_until="load", timeout=60000) # the answer that carries Alt-Svc: h3
page.wait_for_timeout(1500)
return page.evaluate(_FETCH, server.url)
def test_a_page_behind_a_gateway_that_relays_udp_reads_h3_and_the_quic_goes_by_the_relay(monkeypatch):
import aioquic # noqa: F401 - the dev extra installs it: a missing one is a failure, never a skip
from _h3_server import H3Server
from _socks_servers import coherent
host = _address_of_this_host()
with H3Server(host) as server, coherent(user="alice", password="s3cret", relay_host=host) as gateway:
protocols = _protocols_behind(gateway, server, monkeypatch)
carried = [(h, p) for h, p, _data in gateway.datagrams if (h, p) == (host, server.port)]
assert "h3" in protocols, f"nextHopProtocol of 12 fetches behind a gateway that relays UDP: {protocols}"
assert carried, "the QUIC datagrams did not go by the relay of the gateway"
assert server.quic_peers and set(server.quic_peers) == {"127.0.0.1"}, (
f"the QUIC server saw {server.quic_peers}: only the relay of the gateway (127.0.0.1) may reach it")
def test_a_page_behind_a_gateway_without_udp_falls_back_to_h2_and_nothing_goes_direct(monkeypatch):
import aioquic # noqa: F401 - the dev extra installs it: a missing one is a failure, never a skip
from _h3_server import H3Server
from _socks_servers import tcp_only
host = _address_of_this_host()
with H3Server(host) as server, tcp_only(user="alice", password="s3cret") as gateway:
protocols = _protocols_behind(gateway, server, monkeypatch)
assert "?" not in protocols and "h3" not in protocols, (
f"behind a gateway that carries no UDP every fetch is h2 (or http/1.1), never h3: {protocols}")
assert not server.quic_peers, f"a QUIC connection reached the server direct, around the proxy: {server.quic_peers}"
+6 -3
View File
@@ -56,7 +56,6 @@ _REQUIRED_PREFS_KEYS = (
"intl.accept_languages",
"intl.locale.requested",
"zoom.stealth.fpp.hw_seed",
"zoom.stealth.webrtc.host_ip",
"zoom.stealth.webgl.renderer",
"zoom.stealth.webgl.vendor",
"webgl.msaa-samples",
@@ -120,7 +119,9 @@ def test_socks5_proxy_mutates_prefs_then_pipeline_still_valid():
"network.proxy.socks_username", "network.proxy.socks_password",
"network.proxy.http", "network.proxy.ssl"):
assert name not in prefs, name
assert prefs["zoom.stealth.dns.no_local_resolution"] is True
# Names are resolved by Firefox's own DoH, through the session proxy: no gate of ours; the core declares the provider only.
assert "zoom.stealth.dns.no_local_resolution" not in prefs
assert "network.trr.mode" not in prefs and "network.trr.uri" in prefs # the provider is the core's, the state the engine's
# Profile-derived keys must still be present after proxy mutation.
#
@@ -359,7 +360,9 @@ def test_linux_xvfb_workarounds_with_socks_proxy(monkeypatch):
# The proxy layer no longer writes any endpoint, and what it does write - the
# leak-channel prefs - does not trample the Linux prefs above.
assert "network.proxy.type" not in prefs
assert prefs["zoom.stealth.dns.no_local_resolution"] is True
# Names are resolved by Firefox's own DoH, through the session proxy: no gate of ours; the core declares the provider only.
assert "zoom.stealth.dns.no_local_resolution" not in prefs
assert "network.trr.mode" not in prefs and "network.trr.uri" in prefs # the provider is the core's, the state the engine's
# ──────────────────────────────────────────────────────────────────────
+4 -2
View File
@@ -7,8 +7,10 @@ It does not break - it breaks one time in twenty.
The client is `invisible_core.juggler` and its tests without a browser are
the core's (`tests/test_juggler_actions.py` there). These need the engine,
which is where this package's e2e job is, and every one runs TWICE: with the
pointer approach drawn by the client (this package's mode, where `_cursor`
walks the cursor first) and by the engine (`engine_approach=True`, the mode
plain approach (this package's mode: the server's pointer, `_juggler/
pointer.py`, walks onto the element before calling the action, which these
tests, building `Actions` directly, do not exercise) and by the engine
(`engine_approach=True`, the mode
invisible-selenium and invisible-puppeteer drive the same client in). Those
two packages had a copy of these tests each; one place now covers both modes.
"""
+13 -3
View File
@@ -1076,11 +1076,21 @@ def test_the_launch_handler_hands_the_named_environment_to_the_engine(monkeypatc
"env": [{"name": "DISPLAY", "value": ":123"}]})
try:
env = dict(seen[-1])
# The session's own temporary directory is the server's addition, the
# one thing in the environment the caller did not name.
# The session's own temporary directory is the server's addition, and
# so are the variables of the session this unmarked launch was given
# (`server.session_for_launch`: the font manifest, the display backend,
# the crash reporter). Nothing of the server's own process comes in:
# WAYLAND_DISPLAY, set above, stays out.
tmp = env.pop("TMP")
assert env.pop("TEMP") == tmp and env.pop("TMPDIR") == tmp
assert env == {"DISPLAY": ":123"}
from invisible_playwright import _session
_, session_env = _session.default_session("x")
# The network is drawn from the seed of each session, and each unmarked
# launch is a new session: it is there.
assert env.pop("STEALTHFOX_WEBRTC_NETWORK").startswith("v4=")
session_env.pop("STEALTHFOX_WEBRTC_NETWORK")
assert env == dict(session_env, DISPLAY=":123")
assert "WAYLAND_DISPLAY" not in env
finally:
server.shutdown()
+11 -33
View File
@@ -180,45 +180,23 @@ def test_default_context_with_no_language_asked_is_en_us():
assert ip._default_context_kwargs()["locale"] == "en-US"
# ── InvisiblePlaywright._build_env - WebRTC egress auto-derive ─────────
# Locks the 2026-06-10 fix: behind a proxy the launcher feeds the discovered
# egress IP to nICEr (srflx override) + drops IPv6. Without it, a proxied
# session's WebRTC silently fell back to leaking/blocking. Runs in tests.yml.
# ── InvisiblePlaywright._build_env - the declared network ─────────────
# The session declares its host network (drawn from the seed) in one variable,
# with or without a proxy. Runs in tests.yml.
@pytest.mark.unit
def test_build_env_injects_webrtc_egress_when_discovered():
ip = InvisiblePlaywright(seed=42)
# ⛔ TWO FIELDS, and this test only exercised one. `_webrtc_egress_ip`
# is the FACT (where we exit from, read by the guard against drift);
# `_srflx_declared` is the DECISION that ends up in the env. Since
# 2026-08-25 they do not coincide: when the exit has proven, consistent
# UDP the decision is None and nothing gets declared.
ip._webrtc_egress_ip = "203.0.113.9" # what __enter__ resolves behind a proxy
ip._srflx_declared = "203.0.113.9" # and here the decision coincides with the fact
env = ip._build_env({})
assert env["STEALTHFOX_WEBRTC_PUBLIC_IP"] == "203.0.113.9"
assert env["STEALTHFOX_WEBRTC_DISABLE_IPV6"] == "1"
@pytest.mark.unit
def test_build_env_no_webrtc_keys_without_proxy(monkeypatch):
monkeypatch.delenv("STEALTHFOX_WEBRTC_PUBLIC_IP", raising=False)
ip = InvisiblePlaywright(seed=42)
ip._webrtc_egress_ip = None # no proxy → real STUN already truthful
env = ip._build_env({})
assert "STEALTHFOX_WEBRTC_PUBLIC_IP" not in env
assert "STEALTHFOX_WEBRTC_DISABLE_IPV6" not in env
def test_build_env_carries_the_declared_network():
from invisible_core import network_to_declare
env = InvisiblePlaywright(seed=42)._build_env({})
assert env["STEALTHFOX_WEBRTC_NETWORK"] == network_to_declare(42)
@pytest.mark.unit
def test_build_env_caller_env_override_wins(monkeypatch):
monkeypatch.setenv("STEALTHFOX_WEBRTC_PUBLIC_IP", "198.51.100.5")
ip = InvisiblePlaywright(seed=42)
ip._webrtc_egress_ip = "203.0.113.9" # auto-discovered
env = ip._build_env({})
assert env["STEALTHFOX_WEBRTC_PUBLIC_IP"] == "198.51.100.5" # caller wins
assert env["STEALTHFOX_WEBRTC_DISABLE_IPV6"] == "1"
monkeypatch.setenv("STEALTHFOX_WEBRTC_NETWORK", "v4=198.51.100.5;v6=1")
env = InvisiblePlaywright(seed=42)._build_env({})
assert env["STEALTHFOX_WEBRTC_NETWORK"] == "v4=198.51.100.5;v6=1" # caller wins
@pytest.mark.unit
@@ -232,7 +210,7 @@ def test_build_env_drops_the_variables_the_display_names_absent():
``None`` value and, worse, keep ``WAYLAND_DISPLAY``."""
from invisible_playwright._session import build_env
base = {"PATH": "/usr/bin", "WAYLAND_DISPLAY": "wayland-0", "DISPLAY": ":0"}
env = build_env(srflx_declared=None, base_env=base,
env = build_env(network_declared=None, base_env=base,
display_env={"DISPLAY": ":123", "GDK_BACKEND": "x11",
"WAYLAND_DISPLAY": None, "PULSE_SERVER": None})
assert env["DISPLAY"] == ":123"
@@ -87,7 +87,7 @@ def test_the_data_holds_the_inputs_that_tell_the_libraries_apart():
@pytest.mark.e2e
def test_math_sin_cos_tan_bytes_are_ucrtbase_over_a_long_hot_loop(firefox_binary, engine_at_least):
engine_at_least("firefox-60")
engine_at_least("firefox-64")
from invisible_playwright import InvisiblePlaywright
cases = _cases()
@@ -0,0 +1,151 @@
"""Mouse events reach the page and an iframe of the same process with the values they have always had.
The mouse of the engine is sent through the asynchronous (APZ) route from firefox-62 (a click on an iframe of
another site needs the hit test; see automation/input), which is also the route of the events of the page and of the
iframes in its own process. They must not change: their ORDER, whether they are trusted, the pressure, the pointer id
and type, the buttons and button, and the click count (`detail`). The sequences below are what firefox-61 delivers,
recorded with the same script (coordinates are left out: they depend on the screen's scale). The test passes on
firefox-61 and has to pass on the engine with the APZ route.
A drag is the same question for the drag session (the flag "async synthesized for tests" would send it to the native
drag loop) and is guarded by tests/test_drag_motion.py, which this test does not replace.
"""
from __future__ import annotations
import http.server
import threading
import time
import pytest
pytestmark = pytest.mark.e2e
FRAME = (b"<!doctype html><title>f</title><body style='margin:0'><button id=b "
b"style='position:absolute;left:10px;top:10px;width:120px;height:50px'>b</button>")
TOP = ("<!doctype html><title>t</title><body style='margin:0'><button id=t "
"style='position:absolute;left:10px;top:10px;width:120px;height:50px'>t</button>"
"<iframe id=f src='/frame' style='position:absolute;left:200px;top:100px;width:300px;height:200px;border:0'></iframe>"
"<script>window.__log=[];const rec=(d)=>e=>__log.push([d,e.type,e.isTrusted,"
"e.pressure===undefined?null:e.pressure,e.pointerId===undefined?null:e.pointerId,e.pointerType||null,"
"e.buttons,e.button,e.detail,e.timeStamp]);"
"const types=['pointermove','mousemove','pointerdown','mousedown','pointerup','mouseup','click','dblclick',"
"'contextmenu','auxclick'];"
"for(const t of types)document.addEventListener(t,rec('top'),true);"
"document.getElementById('f').addEventListener('load',()=>{const w=document.getElementById('f').contentWindow;"
"w.__log=window.__log;for(const t of types)w.document.addEventListener(t,rec('frame'),true);});</script>").encode()
EXPECTED = {
'top click': [
('top', 'pointermove', True, 0, 0, 'mouse', 0, -1, 0),
('top', 'mousemove', True, None, None, None, 0, 0, 0),
('top', 'pointerdown', True, 0.5, 0, 'mouse', 1, 0, 0),
('top', 'mousedown', True, None, None, None, 1, 0, 1),
('top', 'pointerup', True, 0, 0, 'mouse', 0, 0, 0),
('top', 'mouseup', True, None, None, None, 0, 0, 1),
('top', 'click', True, 0, 0, 'mouse', 0, 0, 1),
],
'frame click': [
('frame', 'pointermove', True, 0, 0, 'mouse', 0, -1, 0),
('frame', 'mousemove', True, None, None, None, 0, 0, 0),
('frame', 'pointerdown', True, 0.5, 0, 'mouse', 1, 0, 0),
('frame', 'mousedown', True, None, None, None, 1, 0, 1),
('frame', 'pointerup', True, 0, 0, 'mouse', 0, 0, 0),
('frame', 'mouseup', True, None, None, None, 0, 0, 1),
('frame', 'click', True, 0, 0, 'mouse', 0, 0, 1),
],
'top double click': [
('top', 'pointermove', True, 0, 0, 'mouse', 0, -1, 0),
('top', 'mousemove', True, None, None, None, 0, 0, 0),
('top', 'pointermove', True, 0, 0, 'mouse', 0, -1, 0),
('top', 'mousemove', True, None, None, None, 0, 0, 0),
('top', 'pointerdown', True, 0.5, 0, 'mouse', 1, 0, 0),
('top', 'mousedown', True, None, None, None, 1, 0, 1),
('top', 'pointerup', True, 0, 0, 'mouse', 0, 0, 0),
('top', 'mouseup', True, None, None, None, 0, 0, 1),
('top', 'click', True, 0, 0, 'mouse', 0, 0, 1),
('top', 'pointerdown', True, 0.5, 0, 'mouse', 1, 0, 0),
('top', 'mousedown', True, None, None, None, 1, 0, 2),
('top', 'pointerup', True, 0, 0, 'mouse', 0, 0, 0),
('top', 'mouseup', True, None, None, None, 0, 0, 2),
('top', 'click', True, 0, 0, 'mouse', 0, 0, 2),
('top', 'dblclick', True, None, None, None, 0, 0, 2),
],
'frame right click': [
('frame', 'pointermove', True, 0, 0, 'mouse', 0, -1, 0),
('frame', 'mousemove', True, None, None, None, 0, 0, 0),
('frame', 'pointermove', True, 0, 0, 'mouse', 0, -1, 0),
('frame', 'mousemove', True, None, None, None, 0, 0, 0),
('frame', 'pointerdown', True, 0.5, 0, 'mouse', 2, 2, 0),
('frame', 'mousedown', True, None, None, None, 2, 2, 1),
('frame', 'contextmenu', True, 0.5, 0, 'mouse', 2, 2, 1),
('frame', 'pointerup', True, 0, 0, 'mouse', 0, 2, 0),
('frame', 'mouseup', True, None, None, None, 0, 2, 1),
('frame', 'auxclick', True, 0, 0, 'mouse', 0, 2, 1),
],
'move with button down': [
('frame', 'pointermove', True, 0, 0, 'mouse', 0, -1, 0),
('frame', 'mousemove', True, None, None, None, 0, 0, 0),
('frame', 'pointerdown', True, 0.5, 0, 'mouse', 1, 0, 0),
('frame', 'mousedown', True, None, None, None, 1, 0, 1),
('frame', 'pointermove', True, 0, 0, 'mouse', 0, -1, 0),
('frame', 'mousemove', True, None, None, None, 0, 0, 0),
('frame', 'pointermove', True, 0, 0, 'mouse', 0, -1, 0),
('frame', 'mousemove', True, None, None, None, 0, 0, 0),
('frame', 'pointerup', True, 0, 0, 'mouse', 0, 0, 0),
('frame', 'mouseup', True, None, None, None, 0, 0, 1),
('frame', 'click', True, 0, 0, 'mouse', 0, 0, 1),
],
}
class _Handler(http.server.BaseHTTPRequestHandler):
def do_GET(self):
body = FRAME if self.path.startswith("/frame") else TOP
self.send_response(200)
self.send_header("Content-Type", "text/html")
self.send_header("Content-Length", str(len(body)))
self.end_headers()
self.wfile.write(body)
def log_message(self, *args):
pass
def _record(page, action):
page.evaluate("window.__log.length = 0")
action()
time.sleep(0.4)
return page.evaluate("window.__log.slice()")
def test_the_events_of_the_page_and_of_an_iframe_of_its_process_keep_their_order_and_values(firefox_binary):
from invisible_playwright import InvisiblePlaywright
server = http.server.ThreadingHTTPServer(("127.0.0.1", 0), _Handler)
threading.Thread(target=server.serve_forever, daemon=True).start()
try:
with InvisiblePlaywright(binary_path=firefox_binary, headless=True, humanize=False) as browser:
page = browser.new_context().new_page()
page.goto("http://127.0.0.1:%d/" % server.server_address[1], wait_until="load")
page.wait_for_function("window.__log && document.getElementById('f').contentDocument.readyState === 'complete'")
time.sleep(0.5)
actions = {
"top click": lambda: (page.mouse.move(60, 35), page.mouse.down(), page.mouse.up()),
"frame click": lambda: (page.mouse.move(260, 150), page.mouse.down(), page.mouse.up()),
"top double click": lambda: (page.mouse.move(60, 35), page.mouse.click(60, 35, click_count=2)),
"frame right click": lambda: (page.mouse.move(260, 150), page.mouse.click(260, 150, button="right")),
"move with button down": lambda: (page.mouse.move(300, 200), page.mouse.down(),
page.mouse.move(310, 205), page.mouse.move(330, 215), page.mouse.up()),
}
got = {}
for name, action in actions.items():
log = _record(page, action)
stamps = [row[-1] for row in log]
assert stamps == sorted(stamps), "%s: the time stamps go backwards" % name
assert all(stamp <= page.evaluate("performance.now()") for stamp in stamps), "%s: a time stamp in the future" % name
got[name] = [tuple(row[:-1]) for row in log]
finally:
server.shutdown()
for name, expected in EXPECTED.items():
assert got[name] == expected, "%s: expected %s, got %s" % (name, expected, got[name])
@@ -0,0 +1,196 @@
"""A navigation that changes the process (a -> b, sites isolated: strategy 1) ends the way one that does not does.
With sites isolated a navigation to another site starts in the process of the page being left and commits in a new
one. The id of the navigation is the load identifier the parent assigns; the process that commits does not know it, and
the old process's own stop of the load (it is cut when the navigation changes process) is not a failure of the
navigation. What the client must still see, whatever the process:
* a goto stopped by the page it is leaving raises NS_BINDING_ABORTED (the abort of the old process is its own);
* a goto replaced by another navigation, to another site, is "interrupted by another navigation" and the second
lands: the abort of the replaced one is told under its own id, not taken for the end of the new one;
* a goto whose response is half there when the next one starts is replaced the same way (the swap has happened);
* an iframe whose load is refused ends its load (the events a waiter needs) and its replacement error page is a
navigation of its own; an iframe removed while it loads is aborted, then detached;
* an iframe that goes to another site (its src changes) ends with the new address in the frame list: the process
it leaves cuts its load (NS_BINDING_ABORTED, its docShell being destroyed), which is not the navigation's abort;
* a frame in another process is committed with the name of its <iframe> (the embedder reads it).
Prefs: strategy 1 (`fission.webContentIsolationStrategy = 1`, `fission.autostart`) for this file only, as the bench
(`test_fission_strategy1_bench.py`); hosts a.test, b.test and c.test resolve to the local server through
`network.dns.localDomains`: two hosts are two sites.
"""
from __future__ import annotations
import asyncio
import threading
import time
from http.server import BaseHTTPRequestHandler
from urllib.parse import urlsplit
import pytest
from _servers import LocalServer
pytestmark = pytest.mark.e2e
FISSION_ON = {
"fission.autostart": True,
"fission.webContentIsolationStrategy": 1,
"dom.ipc.processCount.webIsolated": 4,
"network.dns.localDomains": "a.test,b.test,c.test",
}
@pytest.fixture
def sites():
arrived = set()
class Handler(BaseHTTPRequestHandler):
timeout = 10
def log_message(self, *args):
pass
def do_GET(self):
path = self.path.split("?")[0]
arrived.add(path)
try:
if path == "/partial":
# the headers and the start of the body arrive, the rest is held: the response is there, the
# navigation has changed process, the document is not complete
self.send_response(200)
self.send_header("Content-Type", "text/html")
self.send_header("Content-Length", "200")
self.end_headers()
self.wfile.write(b"<!doctype html><title>partial</title><p>start")
self.wfile.flush()
time.sleep(5)
self.wfile.write(b" " * 156)
return
if path == "/slow-frame":
time.sleep(3)
body = ("<!doctype html><title>%s</title><p>%s" % (path, path)).encode()
self.send_response(200)
self.send_header("Content-Type", "text/html")
self.send_header("Content-Length", str(len(body)))
self.end_headers()
self.wfile.write(body)
except OSError:
pass
server = LocalServer(("127.0.0.1", 0), Handler)
thread = threading.Thread(target=server.serve_forever, daemon=True)
thread.start()
port = server.server_address[1]
yield {"at": lambda host, path, p=None: "http://%s:%d%s" % (host, p or port, path), "arrived": arrived}
server.shutdown()
server.server_close()
thread.join()
def _run(firefox_binary, scenario):
from invisible_playwright.async_api import InvisiblePlaywright
async def go():
async with InvisiblePlaywright(seed=42, binary_path=firefox_binary, humanize=False, headless=True,
extra_prefs=FISSION_ON) as browser:
page = await browser.new_page()
return await scenario(page)
return asyncio.run(go())
def test_a_goto_to_another_site_stopped_by_the_page_it_leaves_raises_aborted(firefox_binary, sites):
async def scenario(page):
await page.goto(sites["at"]("a.test", "/plain"))
await page.evaluate("setTimeout(() => window.stop(), 1000)")
began = time.monotonic()
try:
await page.goto(sites["at"]("b.test", "/slow-frame"), wait_until="domcontentloaded", timeout=15000)
except Exception as e:
return str(e), time.monotonic() - began, page.url
return None, time.monotonic() - began, page.url
error, took, url = _run(firefox_binary, scenario)
assert error is not None and "NS_BINDING_ABORTED" in error, error
assert took < 8, took
assert url.startswith("http://a.test:"), url
def test_a_second_goto_to_a_third_site_interrupts_the_first_and_lands(firefox_binary, sites):
async def scenario(page):
await page.goto(sites["at"]("a.test", "/plain"))
async def go(url, after=None):
while after is not None and after not in sites["arrived"]:
await asyncio.sleep(0.02)
if after is not None:
# the first response has arrived and is held: the navigation has changed process
await asyncio.sleep(1.0)
try:
await page.goto(url, wait_until="domcontentloaded", timeout=15000)
return None
except Exception as e:
return str(e)
began = time.monotonic()
first, second = await asyncio.gather(
go(sites["at"]("b.test", "/partial")),
go(sites["at"]("c.test", "/second"), after="/partial"))
return first, second, time.monotonic() - began, page.url
first, second, took, url = _run(firefox_binary, scenario)
assert first is not None and "is interrupted by another navigation" in first, first
assert second is None, second
assert took < 8, took
assert url == "http://c.test:" + url.split(":")[2], url
def test_an_iframe_refused_its_load_ends_it_and_its_error_page_is_a_navigation(firefox_binary, sites):
async def scenario(page):
await page.goto(sites["at"]("a.test", "/plain"))
events = []
page.on("frameattached", lambda f: events.append("attached"))
await page.evaluate(
"(u) => { const f = document.createElement('iframe'); f.id = 'r'; f.src = u; document.body.appendChild(f); }",
sites["at"]("b.test", "/x", 9)) # a port Firefox refuses
await page.wait_for_timeout(2500)
return [(f.url, f.name) for f in page.frames], events
frames, events = _run(firefox_binary, scenario)
assert frames[1][1] == "r", frames # the error page's frame is named by its iframe, in whatever process
assert urlsplit(frames[1][0])[:2] == ("http", "b.test:9"), frames
def test_an_iframe_removed_while_it_loads_is_aborted_then_gone(firefox_binary, sites):
async def scenario(page):
await page.goto(sites["at"]("a.test", "/plain"))
await page.evaluate(
"(u) => { const f = document.createElement('iframe'); f.id = 's'; f.src = u; document.body.appendChild(f);"
" setTimeout(() => f.remove(), 1000); }", sites["at"]("b.test", "/slow-frame"))
await page.wait_for_timeout(5000)
return [f.url for f in page.frames]
urls = _run(firefox_binary, scenario)
assert len(urls) == 1 and urls[0].startswith("http://a.test:"), urls
def test_an_iframe_whose_src_goes_to_another_site_shows_the_new_address(firefox_binary, sites):
async def scenario(page):
await page.goto(sites["at"]("a.test", "/plain"))
await page.evaluate(
"(u) => { const f = document.createElement('iframe'); f.id = 'f'; f.src = u; document.body.appendChild(f); }",
sites["at"]("b.test", "/first"))
await page.wait_for_timeout(1500)
before = [f.url for f in page.frames]
await page.evaluate("(u) => { document.getElementById('f').src = u; }", sites["at"]("c.test", "/second"))
deadline = time.monotonic() + 8
while time.monotonic() < deadline and not any(f.url.endswith("/second") for f in page.frames):
await page.wait_for_timeout(100)
return before, [(f.url, f.name) for f in page.frames]
before, after = _run(firefox_binary, scenario)
assert before[1].startswith("http://b.test:") and before[1].endswith("/first"), before
assert len(after) == 2, after
assert after[1][0].startswith("http://c.test:") and after[1][0].endswith("/second"), after
assert after[1][1] == "f", after # still the frame of its <iframe>
+5 -4
View File
@@ -435,11 +435,10 @@ def test_shadow_number_input_click(firefox_binary, nested_origins, wire,
@pytest.mark.e2e
@pytest.mark.parametrize("mode", ["open", "closed"])
def test_shadow_landing_rejects_siblings_and_overlays(nested_page, nested_origins, mode):
"""The cursor's landing check, asked directly: the input's own centre is
"""The landing check of the server's pointer (`Actions.hit_target`), asked
directly through the server's `checkHitTarget`: the input's own centre is
accepted, and the padded container, a sibling laid over it and an overlay
in the frame's document are not the input."""
from invisible_playwright import _cursor
nested_page.goto(nested_origins["origin"] + "/number-top-" + mode)
frame = frames(nested_page)[1]
handle = frame.locator("input[type=number]").element_handle()
@@ -449,7 +448,9 @@ def test_shadow_landing_rejects_siblings_and_overlays(nested_page, nested_origin
x, y = box["x"] + box["width"] / 2, box["y"] + box["height"] / 2
def hits():
return handle._sync(_cursor._hits(handle._impl_obj, x, y))
return bool(handle._sync(handle._impl_obj._channel.send(
"checkHitTarget", None, {"point": {"x": x, "y": y}},
is_internal=True)))
assert hits()
handle.evaluate("""el => {
@@ -0,0 +1,288 @@
"""`goto(wait_until="networkidle")` arrives on a served browser whose context routes every request, as a stock Firefox does.
The shape of a production client: `launch_server()`, a stock Playwright client that connects to it over the WebSocket, a context
route on `**/*` that aborts images, fonts and media and continues the rest, and a page that sends a beacon (`sendBeacon`,
a POST the page does not wait for) and asks for the same font twice. Measured on real news sites through such a client: the
navigation committed, `load` came, and `networkidle` never did (timeout at 30 s on about one fetch in seven, firefox-61 and
firefox-62 alike), while a stock Firefox and Chromium reached it on the same addresses.
Red until the server, the Juggler or the core's lifecycle ends every request a routed page opens.
"""
from __future__ import annotations
import threading
import time
from http.server import BaseHTTPRequestHandler
import pytest
from _servers import LocalServer
pytestmark = pytest.mark.e2e
def _stock_client(module):
"""The stock Playwright client, as production (tf-fetch) drives the served browser. It is a pinned dev dependency
(`playwright==` in the `dev` extra), so its absence is a broken environment, not a reason to skip: a gate that skips
in CI checks nothing."""
import importlib
try:
return importlib.import_module(module)
except ImportError as exc: # pragma: no cover - only in a broken environment
pytest.fail("the stock Playwright client is missing (%s): install the wrapper with its dev extra" % exc,
pytrace=False)
PAGE = b"""<!doctype html><html><head><meta charset=utf-8><title>routed</title>
<link rel=stylesheet href=/style.css>
<link rel=preload as=font type=font/woff2 href=/font.woff2 crossorigin>
<style>@font-face{font-family:F2;src:url(/font.woff2) format('woff2')}</style>
<script src=/app.js></script>
</head><body style="font-family:F,F2"><p>text in the font</p>
<img src=/pixel.png><img src=/photo.jpg>
<script>
addEventListener('load', () => {
navigator.sendBeacon('/beacon', JSON.stringify({ev: 'load'}));
fetch('/api/data').then(r => r.text());
});
</script></body></html>"""
CSS = b"@font-face{font-family:F;src:url(/font.woff2) format('woff2')} p{color:#333}"
JS = b"window.__app = 1;"
# The other shapes a news page has: a frame of another site (another process with Fission) with its own routed
# resources, a worker that fetches, a script reached through a redirect.
EXTRA = {
"beacon": b"",
"oop_iframe": b"<iframe src='http://localhost:%(port)d/frame'></iframe>",
"worker": b"<script>new Worker('/worker.js')</script>",
"redirect": b"<script src=/moved.js></script><img src=/moved.png>",
# What a slow remote client meets: the page cancels requests while the route is still deciding.
"cancel_fetch": b"<script>for(let i=0;i<30;i++){const c=new AbortController();fetch('/api/data?i='+i,{signal:c.signal}).catch(()=>{});setTimeout(()=>c.abort(),i%7)}</script>",
"cancel_img": b"<script>for(let i=0;i<30;i++){const m=new Image();m.src='/pixel.png?a='+i;m.src='/pixel.png?b='+i}</script><script src=/slow.js></script>",
"cancel_iframe": b"<script>for(let i=0;i<6;i++){const f=document.createElement('iframe');f.src='/frame?i='+i;document.body.appendChild(f);setTimeout(()=>f.remove(),5*i)}</script>",
"cancel_navigation": b"<script>history.pushState({},'','/spa');fetch('/api/data');setTimeout(()=>{history.pushState({},'','/spa2');fetch('/api/data?x=1')},10)</script><script src=/slow.js></script>",
# Beacons the way ad and analytics scripts send them: to another origin, and while the document is being left.
"cross_beacon": b"<script>for(let i=0;i<6;i++)navigator.sendBeacon('http://localhost:%(port)d/beacon?i='+i,JSON.stringify({i}))</script>",
"unload_beacon": b"<script>addEventListener('pagehide',()=>{for(let i=0;i<4;i++)navigator.sendBeacon('/beacon?leave='+i,'x')});addEventListener('visibilitychange',()=>navigator.sendBeacon('/beacon?vis','x'))</script>",
"keepalive": b"<script>for(let i=0;i<4;i++)fetch('/api/data?k='+i,{method:'POST',keepalive:true,body:'x'}).catch(()=>{})</script>",
"many": b"<script>for(let i=0;i<50;i++){fetch('/api/data?i='+i).catch(()=>{});(new Image).src='/pixel.png?i='+i}</script>",
}
# kinds whose route handler is slow (ms). The sync client runs the handlers one after the other, so the page's 100 requests
# of `many` take 100 x (delay + one round trip); an async client (below) answers them all at once, like a Go client does.
SLOW_MS = {"cancel_fetch": 120, "cancel_img": 120, "cancel_iframe": 120, "cancel_navigation": 120, "many": 20}
FRAME = b"""<!doctype html><title>frame</title><link rel=stylesheet href=/style.css><img src=/ad.png>
<script src=/app.js></script><script>addEventListener('load',()=>{navigator.sendBeacon('/beacon','f');fetch('/api/data')})</script>"""
WORKER = b"fetch('/api/data').then(r => r.text()); setTimeout(() => fetch('/api/data'), 200);"
class _Handler(BaseHTTPRequestHandler):
hits: list = []
def log_message(self, *a):
pass
def _send(self, body, ctype, status=200):
self.send_response(status)
self.send_header("Content-Type", ctype)
self.send_header("Content-Length", str(len(body)))
self.send_header("Cache-Control", "no-store")
self.end_headers()
self.wfile.write(body)
def do_GET(self):
path = self.path.split("?")[0]
_Handler.hits.append(("GET", path))
if path == "/":
kind = (self.path.split("kind=")[1].split("&")[0]) if "kind=" in self.path else "beacon"
extra = EXTRA[kind] % {b"port": self.server.server_address[1]} if b"%(" in EXTRA[kind] else EXTRA[kind]
self._send(PAGE.replace(b"</body>", extra + b"</body>"), "text/html; charset=utf-8")
elif path == "/frame":
self._send(FRAME, "text/html; charset=utf-8")
elif path == "/slow.js":
time.sleep(0.15)
self._send(JS, "text/javascript")
elif path == "/worker.js":
self._send(WORKER, "text/javascript")
elif path in ("/moved.js", "/moved.png"):
self.send_response(302)
self.send_header("Location", "/app.js" if path.endswith(".js") else "/pixel.png")
self.send_header("Content-Length", "0")
self.end_headers()
elif path == "/style.css":
self._send(CSS, "text/css")
elif path == "/app.js":
self._send(JS, "text/javascript")
elif path == "/api/data":
self._send(b'{"ok":1}', "application/json")
else: # the font and the images: the route aborts them, they must not get here
self._send(b"x", "application/octet-stream")
def do_POST(self):
n = int(self.headers.get("Content-Length") or 0)
self.rfile.read(n)
_Handler.hits.append(("POST", self.path))
self._send(b"", "text/plain", 204)
@pytest.fixture
def site():
_Handler.hits = []
srv = LocalServer(("127.0.0.1", 0), _Handler)
threading.Thread(target=srv.serve_forever, daemon=True).start()
try:
yield "http://127.0.0.1:%d/" % srv.server_address[1]
finally:
srv.shutdown()
srv.server_close()
BLOCKED = {"image", "font", "media"}
ANSWER_ERRORS: list = []
def _router(delay_s):
def route(route):
if delay_s:
time.sleep(delay_s) # a client far away: the page can cancel the request before the answer arrives
try:
if route.request.resource_type in BLOCKED:
route.abort("blockedbyclient")
else:
route.continue_()
except Exception as e:
if "Cannot find request" not in str(e) and "Target" not in str(e):
raise
ANSWER_ERRORS.append(str(e)[:120])
return route
@pytest.mark.parametrize("kind", sorted(EXTRA))
def test_networkidle_arrives_on_a_routed_page_through_a_served_browser(firefox_binary, site, kind):
from invisible_playwright._juggler.remote import launch_server
sync_playwright = _stock_client("playwright.sync_api").sync_playwright # a stock client, as production uses
server = launch_server(headless=True, binary_path=firefox_binary, locale="en-US", timezone="Europe/Rome")
try:
with sync_playwright() as p:
browser = p.firefox.connect(server.ws_endpoint)
ctx = browser.new_context()
ANSWER_ERRORS.clear()
ctx.route("**/*", _router(SLOW_MS.get(kind, 0) / 1000.0))
page = ctx.new_page()
for attempt in range(3): # fresh pages, the way a client fetches one address after another
t0 = time.monotonic()
page.goto(site + "?kind=%s&n=%d" % (kind, attempt), wait_until="networkidle", timeout=20000)
took = time.monotonic() - t0
assert took < 15, "networkidle after %.1f s on attempt %d (answers to a closed request: %s)" % (
took, attempt, ANSWER_ERRORS[:3])
assert page.evaluate("window.__app") == 1
assert ("POST", "/beacon") in _Handler.hits, _Handler.hits
assert not any(path in ("/font.woff2", "/pixel.png", "/photo.jpg", "/ad.png") for _, path in _Handler.hits), _Handler.hits
ctx.close()
browser.close()
finally:
server.close()
@pytest.mark.parametrize("kind", ["many", "cancel_fetch", "cancel_img", "cancel_iframe", "cancel_navigation"])
def test_networkidle_arrives_when_the_client_answers_all_requests_concurrently_and_slowly(firefox_binary, site, kind):
"""An async client (the way a Go client answers: every route handler in its own task) that takes 300 ms to decide, so the
page cancels, replaces or removes a request while its answer is still on the way."""
import asyncio
from invisible_playwright._juggler.remote import launch_server
async_playwright = _stock_client("playwright.async_api").async_playwright
server = launch_server(headless=True, binary_path=firefox_binary, locale="en-US", timezone="Europe/Rome")
errors = []
async def run():
async with async_playwright() as p:
browser = await p.firefox.connect(server.ws_endpoint)
ctx = await browser.new_context()
async def route(r):
await asyncio.sleep(0.3)
try:
if r.request.resource_type in BLOCKED:
await r.abort("blockedbyclient")
else:
await r.continue_()
except Exception as e:
errors.append(str(e)[:140])
await ctx.route("**/*", route)
page = await ctx.new_page()
for attempt in range(3):
t0 = time.monotonic()
await page.goto(site + "?kind=%s&n=%d" % (kind, attempt), wait_until="networkidle", timeout=25000)
assert time.monotonic() - t0 < 20, "networkidle after %.1f s on attempt %d" % (time.monotonic() - t0, attempt)
await ctx.close()
await browser.close()
try:
asyncio.run(run())
finally:
server.close()
# an answer to a request the browser had already closed is allowed to fail, but it must not leave the page waiting
print("answers to a closed request:", errors[:3])
def test_one_page_reused_for_many_addresses_reaches_networkidle_every_time(firefox_binary, site):
"""tf-fetch's shape: ONE page for dozens of fetches. A request whose end never reaches the client (a beacon the
page closes with its document, a request the browser cancelled while the route was deciding) must not hold the
addresses that follow: the lifecycle's memory of requests in flight is per document, keyed by request id."""
from invisible_playwright._juggler.remote import launch_server
sync_playwright = _stock_client("playwright.sync_api").sync_playwright
server = launch_server(headless=True, binary_path=firefox_binary, locale="en-US", timezone="Europe/Rome")
try:
with sync_playwright() as p:
browser = p.firefox.connect(server.ws_endpoint)
ctx = browser.new_context()
ctx.route("**/*", _router(0.05))
page = ctx.new_page()
kinds = ["cancel_fetch", "cancel_img", "cancel_iframe", "beacon", "cancel_navigation", "oop_iframe"] * 2
for n, kind in enumerate(kinds):
t0 = time.monotonic()
page.goto(site + "?kind=%s&n=%d" % (kind, n), wait_until="networkidle", timeout=20000)
assert time.monotonic() - t0 < 15, "address %d (%s) reached networkidle after %.1f s" % (n, kind, time.monotonic() - t0)
ctx.close()
browser.close()
finally:
server.close()
@pytest.mark.parametrize("kind", ["cancel_fetch", "cancel_img", "cancel_iframe"])
def test_a_plain_route_handler_is_not_poisoned_by_a_request_the_page_cancelled(firefox_binary, site, kind):
"""The handler of a tf-fetch-like client is a plain function: continue_ or abort, no try. The page cancels requests
while the (slow) route is deciding; the browser has already closed them, and the engine answers the late command with
`Cannot find request`. Stock Playwright's server sends those commands as may-fail and tells the client nothing; ours
passed the error up, the client kept it as the error of the connection and raised it on the NEXT route command, which
was then never sent: the request stayed held in the engine, its handler failed too, and so on down the page (measured
on a real news page: six held requests in a row, one a beacon, and networkidle never)."""
from invisible_playwright._juggler.remote import launch_server
sync_playwright = _stock_client("playwright.sync_api").sync_playwright
server = launch_server(headless=True, binary_path=firefox_binary, locale="en-US", timezone="Europe/Rome")
try:
with sync_playwright() as p:
browser = p.firefox.connect(server.ws_endpoint)
ctx = browser.new_context()
def plain(route): # no try: the way a client is written
time.sleep(0.12)
if route.request.resource_type in BLOCKED:
route.abort("blockedbyclient")
else:
route.continue_()
ctx.route("**/*", plain)
page = ctx.new_page()
for attempt in range(3):
t0 = time.monotonic()
page.goto(site + "?kind=%s&n=%d" % (kind, attempt), wait_until="networkidle", timeout=25000)
assert time.monotonic() - t0 < 20, "attempt %d: networkidle after %.1f s" % (attempt, time.monotonic() - t0)
ctx.close()
browser.close()
finally:
server.close()
Loaded 100 of 143 files, more files were not shown because too many files have changed in this diff. Show more