Compare commits

...
Author SHA1 Message Date
feder-crandClaude Sonnet 5.5 4ea36371f5 ci: e2e.yml runs the Control+A e2e on Windows, on the published engine, as a job of its own (dispatchable alone with only=windows-control-a)
tests/test_control_a_selects_all_in_a_field_e2e.py (5 ways to press the shortcut x an <input> and a <textarea>, in-process and served to the stock
client) is red on the keyboard that held Shift for the capital A and was measured on Linux; the keyboard of a user is Windows. The new job
installs the wrapper (which pins the core of the release), fetches the published engine and runs that file on windows-latest with bash as the
shell, behind the same core-on-index gate as the Linux job: skipped with the reason in the summary until the core is on the index. The
workflow_dispatch input `only` lets it run alone (`windows-control-a`) without the 40 minutes of the Linux job.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-12 17:41:31 +01:00
feder-crandClaude Sonnet 5.5 9b0f474bc8 tests: Control+A selects all in an input and a textarea, in-process and served to the stock client (e2e, red on the keyboard that held Shift for the capital A)
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-12 17:41:30 +01:00
feder-crandClaude Sonnet 5.5 97ba055d77 Release 0.51.0: the CHANGELOG line of the process tests says only what is proven
Markdown only. The line that came with the end-to-end process tests carried a count of red runs and a cause of the extra
process that nothing saved; it now says that these are tests only and what they ask for.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-12 16:22:27 +01:00
feder-crandClaude Opus 5.5 54b2f26c69 tests: the popup process case runs its own browser in a thread of its own
The e2e of the previous commit failed at setup: the module's browser of the
matrix keeps a sync client open in the test's thread, and a second sync client
refuses to start inside its loop ("Sync API inside the asyncio loop"). The case
now opens its quiet browser in a thread with no loop and hands back its result
or its error. Same count of tests (34), still no skip on any system.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-12 16:04:14 +01:00
feder-crandClaude Opus 5.5 6d23f75229 tests: the popup process case has a browser that starts no process by itself, and asks by name on Linux
test_the_other_site_popup_runs_in_another_process counted every content process
between two reads, so a process the browser starts by itself (the pool refill,
the preloaded New Tab page and, in some countries, a process for a Mozilla
site) was taken for the popup's doing. It now has a browser of its own, on each
transport, with no preallocated processes and no preloaded New Tab page
(test-only prefs), so the count between two reads is the popup's. On Linux it
also asks by name that one of the new processes is the process of localhost.

It still runs on Windows, with no skip: the required suite wrapper.e2e.page
collects this file on both systems with an exact count, which is unchanged (34).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-12 16:01:53 +01:00
feder-crandClaude Sonnet 5.5 beff30e822 tests: ask for the processes of a site by its name, never count between two reads
The e2e tests that looked at content processes compared the set of
"Isolated Web Co" processes before and after an action. The browser starts
processes of its own: the pool refill, and a process for a Mozilla site
(webIsolated=https://mozgcp.net) that the New Tab page starts about a second
after its own, with any page. Under load it was born between the two reads:
the same-site control was red in 14 of 30 runs of the whole e2e suite
([P] -> [P, P2]), the cross-site test could pass on that process alone, and
the service-worker test could read it as a process left behind.

With the test-only pref fission.processSiteNames a content process that hosts
a site is named by that site (http://a.test^u on Linux, cut at 15
characters). tests/_processes.py now returns the processes of one site by that
name; the bench and the service-worker test use it. Linux only, as before.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-12 16:01:13 +01:00
feder-crandClaude Sonnet 5.5 1382a83540 tests: the fake pip of the wait test is a regular package, so the pip of the environment cannot shadow it
CI (runs 43196645121, 43196645144): 2 tests of the wait for the index failed on every Python of both systems. The shim was a directory with a
__main__.py and no __init__.py: a namespace package, which loses to the regular package `pip` of an environment that has one (a local uv venv
has none, so it passed there). The real pip ran, said "No matching distribution" for 9.9.9 and the shim was called 0 times. Reproduced in a venv with pip;
red without the __init__.py, green with it.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-12 16:00:36 +01:00
feder-crandClaude Sonnet 5.5 299fc9f5da user-install: the wait asks pip, not the JSON page of the index, and fails saying what is missing; the upgrade test installs the version its listing named
Ledger #476 of 0.50.1: the Linux job failed in test_upgrade_e2e ("the upgrade did not move the wrapper", '0.49.1' != '0.49.1') three
minutes after the upload. The step that waits for the index had asked the per-version JSON endpoint, which answered; the listing of
`pip index versions` had 0.50.1; the `pip install --upgrade` that followed was still served the 0.49.1 page.

The wait now runs `pip download --no-deps --no-cache-dir invisible-playwright==X` (the client and the index the install uses), for at most
ten minutes, and ends in "::error::the index does not have X yet, after N minutes" instead of a warning and a run that fails later. The
upgrade test takes previous and latest from one listing and installs `WRAPPER==latest`. Four unit tests run the script of the step with a
pip that fails until its Nth call; the core's install_job gate still passes.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-12 16:00:36 +01:00
feder-crandClaude Sonnet 5.5 fe5cb50ed3 Release 0.51.0: the CHANGELOG and the README say only what is proven (counter: what the package refuses and whose repository counts; the real name of the async class; the popup numbers of the register; Windows memory only; addBinding out)
Markdown only. Following the fact check of the release texts: the launch counter is refused by the package's launcher and server
(not "not optional" for the engine alone) and counted in the engine's repository; preload_newtab names the async class by its real
path and keeps only the Windows numbers that have a saved run, with the engine they were taken on; the protocol mirror line about
Page.addBinding is out (not shown for the pinned engine); the differences section no longer claims a comparison run nobody saved;
the popup known issue states where, with which client, on which engines and with how much load it was seen, with the numbers of the
register, and that the correction is in 0.51.1.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-12 15:49:06 +01:00
feder-crandClaude Sonnet 5.5 2d1bc68b26 tests: the HTTP/3 test server finds a port that TCP and UDP both bind where the system's picks fall in a refused UDP range
wrapper.e2e.web on the Windows runner (republish run 43230437094) failed three tests with "no port free for both TCP and UDP",
and the pre-push failed the same way on a work machine: Windows hands out ephemeral TCP ports in sequence and keeps excluded
ranges of a hundred ports for UDP in the same zone, so the old loop (fifty times the system's pick) got fifty consecutive numbers
inside one refused range. The first try is still the system's pick; the others are drawn at random below the dynamic range, as
the witness already does (same constants), and the refusals are named in the error.

Two tests with a fake socket layer (TCP picks 50000, 50001, ...; UDP refuses 50000-50199): the old loop is red on it, this one
finds a number outside the range; and a server that can bind nothing says so after a bounded number of tries. wrapper.unit.udp
goes from 219 to 221 tests (ci/required-suites.json).

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-12 15:12:49 +01:00
feder-crandClaude Sonnet 5.5 3b594b85ed tests: the two tests that ask the resolver trap from the test process say that the test stands for the browser
Since fc10e257ca the trap counts only the questions of a browser process, found by the process that holds the socket in
/proc/net. That is only possible on Linux; on Windows every question counts, so the pre-push (Windows) stayed green
while test_the_trap_counts_a_query_it_is_sent_and_refuses_what_it_cannot_answer failed on Linux (republish run
43230437094, wrapper.unit.udp/linux: 1 failed, 218 passed): the test asks from its own python, which is not a browser,
and the question went to `foreign`. The same holds for the resolv.conf test of the root legs.

Both tests now pass is_browser=lambda pid: True. The trap itself is unchanged, so the realness leg judges the same code.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-12 14:58:21 +01:00
feder-crandClaude Sonnet 5.5 8d1356cb69 Release 0.51.0: the served launch cannot turn the launch counter off (a client's firefoxUserPrefs, bare or marked, are refused with the core's message); the history says it is no longer possible
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-12 14:41:19 +01:00
feder-crandClaude Sonnet 5.5 0a5961270a Release 0.51.0: the README says what the launch counter is and how to turn it off; the CHANGELOG says what is known to be wrong (popups opened without a route, as measured)
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-12 14:30:14 +01:00
feder-cr 07b7b74e08 Release 0.51.0: engine firefox-63, pin invisible-core 63.66.0; CHANGELOG for the UDP line 2026-11-12 14:00:10 +01:00
feder-crandClaude Opus 5.5 710ee498ba juggler: an early download finish lives only as long as it can be read
The review of 6a50ad1 found three cases where an entry of _finished_early
stayed for the life of the browser: (a) a download announced while its
context was already closed, whose finish came after; (b) a finish after the
client released the artifact; (c) a finish of a uuid never announced.

The browser now keeps, per announced download, the context it belongs to,
until its finish or the end of that context. A finish whose download was
announced and whose artifact is gone writes nothing; only a finish of a
download not announced yet leaves an early entry, and those are bounded (64,
the oldest dropped first). The end of a context forgets its downloads that
never finished.

Tests, red on 6a50ad1 (4 of 10): (e) gone context, (f) released artifact,
(g) never-announced finishes are bounded, (h) the end of a context forgets.

NOT proven: that the engine ever sends a finish after the end of a context,
or a finish before the announcement. On one connection Juggler says a
download's creation before its end (TargetRegistry.js interceptDownloadRequest
then onDownloadComplete), so the early path is defensive. The e2e of tiny
downloads is a proof of use, not of the order; its docstring says so.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-12 13:54:42 +01:00
feder-crandClaude Sonnet 5.5 9883d3f455 juggler: a download that finished before it was announced is finished
BrowserDispatcher._on_download_finished keeps the error of a download whose
artifact does not exist yet; a successful download has no error (None), and
_on_download_created popped it with a None default and tested `is not None`,
so the artifact was never marked finished and save_as, path and failure
waited forever. A module-level sentinel tells "nothing recorded" from
"finished with no error". The entry is also popped before the
unknown-context early return, so it no longer stays in the dict.

Tests: unit file (red on the old code for the success and the gone-context
cases) and a served-browser e2e with ten 300-byte and ten 1-byte downloads.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-12 13:54:42 +01:00
feder-cr 7c79ba1ed4 Merge remote-tracking branch 'origin/main' into release/0.51.0-prep (#477, #478, #480) 2026-11-12 13:54:41 +01:00
feder-crandClaude Sonnet 5.5 fc10e257ca tests: the resolver trap counts the BROWSER (a browser process and what it starts), not the test process nor the core it runs: the core asks github.com for the latest GeoIP tag as root, the test says the browser asked
Measured on Linux: a process named firefox and its child counted 20 of 20 each; the test's own python and an orphan of the same user foreign 20 of 20 each.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-12 13:50:37 +01:00
feder-crandClaude Sonnet 5.5 78277565f5 tests: the resolver trap counts the questions of the processes of the test (the socket's inode, the process that holds it, its parents), not of a user; a question of any other process is listed with its pid and command
Runs 43188313516 and 43211837926: on the runner the agent of the runner, as root like the browser under sudo, asks for github.com, api.github.com and its orchestrator
through the trap's /etc/resolv.conf, and a user filter cannot tell it from the browser (6 realness tests red). Measured on Linux, 40 questions of a descendant and
40 of an orphan process of the same user: 40 counted, 40 foreign, each with its pid and command. One whose process cannot be traced is judged by its user, one whose
socket is gone counts as the browser's.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-12 13:38:35 +01:00
feder-crandClaude Sonnet 5.5 0a0d0d689d tests: the sandbox leg finds the tab processes (forked by the fork server, their argv has no 'tab' at the end): the kind comes from the last word, else from the Name in /proc/<pid>/status
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-12 13:14:07 +01:00
feder-crandClaude Sonnet 5.5 ff02f112fe ci: wrapper.unit.udp counts the three tests of the witness port pick (198)
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-12 12:45:34 +01:00
feder-crandClaude Opus 5.5 016eccab9e tests: the UDP witness binds TCP and UDP on one number even where the system's picks fall in a refused UDP range
Witness("127.0.0.1") failed with WinError 10013 in three unit tests of
wrapper.unit.udp on a Windows work machine, while the push before had passed
them. Windows hands out ephemeral TCP ports in sequence and keeps excluded
ranges of a hundred ports for UDP in the same zone: the witness asked the
system for a TCP port twenty times, got twenty consecutive numbers inside one
UDP range, and gave up.

Now each try binds TCP and then UDP on the same number, and if either is
refused both are released and another number is tried: the first is the
system's own pick, the others are drawn at random below both Windows'
dynamic range and Linux's ephemeral range, so they are not the next of a
sequence. 200 tries at most, then an error that names the address and the
last refusals. A port asked for is tried once and its refusal raised.

Test, red on the old code (2 of 3): a fake socket layer whose TCP picks are
sequential and whose UDP refuses 50000-50199. Real sockets on that machine,
20 runs of the witness tests each: old 19 of 20 green, new 20 of 20.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-12 12:44:58 +01:00
feder-crandClaude Sonnet 5.5 db5c7ef565 ci: the preload_newtab e2e moves to wrapper.e2e.udp (seen green on Windows, 10 runs of 10): udp 43, exit 7
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-12 12:33:18 +01:00
feder-crandClaude Sonnet 5.5 5459a6b59e ci: wrapper.e2e.udp.sandbox (Linux, a normal user, the browser's sandbox on): the socket process and a tab process must have a seccomp filter, plus the three situations of the UDP line (a proxy with UDP, no proxy, a proxy without UDP with the ICE name by DoH)
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-12 12:11:56 +01:00
feder-crandClaude Sonnet 5.5 483f9af50a tests: the constructor signature knows preload_newtab; the witness takes TCP first (Windows excluded ranges); the preload_newtab e2e (seen green as root on Linux) joins wrapper.e2e.udp.exit (9)
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-12 12:00:55 +01:00
feder-crandClaude Sonnet 5.5 1d33f56100 ci: wrapper.unit.udp counts the three tests of preload_newtab (195); its e2e is in no suite until it has been seen green
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-12 11:55:51 +01:00
Federico EliaandClaude Sonnet 5.5 285e3ba93e ci: never cancel a run of main, one run per pull request commit, and test it (#477)
e2e.yml and tests.yml already ran once per commit of a pull request (push is
filtered to main, pull_request to PRs against main), but their concurrency
group was keyed on the ref and cancelled in progress everywhere. For a push to
main the ref is always refs/heads/main, so the next push cancelled the e2e
run of the commit before it, and scripts/e2e_is_green.py refuses a release
whose e2e check-run is `cancelled`. The group is now keyed on the pull request
number and cancels only on pull_request; every other event gets a group
unique to the run, so nothing on main is cancelled or replaced while pending.

user-install.yml had a group keyed on the ref that cancelled its own weekly
run when a manual one started on main; it follows the same rule. publish-wiki
no longer cancels a publish in progress. Triggers, workflow and job names
(`e2e`, `e2e (linux, xvfb)`, `gate`) are unchanged.

tests/test_ci_runs_once_per_commit.py pins the triggers the release reads, the
cancel rule and the hunt cap (max-parallel <= 8), with known-bad inputs for
each checker. It reads the workflows with a small parser because PyYAML is
not a dependency of this package.

Co-authored-by: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-12 11:55:02 +01:00
feder-crandClaude Sonnet 5.5 966e2d6a8b launcher: preload_newtab, the option of the core that turns off the preloaded New Tab page
InvisiblePlaywright(preload_newtab=...) (sync, async and launch_server)
hands the core's option of the same name over, only when it is not None:
a wrapper paired with a core that does not know it cannot meet a
TypeError for a caller who never used it. None keeps the retail's
behaviour; False writes browser.newtab.preload false (no privileged-about
process); True says the retail's value aloud; a pref in extra_prefs wins.

Tests: the kwarg reaches the core only when asked and is a parameter of
every entry point; the e2e reads the process types from the engine's log
(MOZ_LOG=Process:5): privilegedabout exists by default and is absent with
the option, on every platform.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-12 11:54:21 +01:00
feder-crandClaude Sonnet 5.5 d13a9442c5 tests: a loss is not a drop - behind a proxy that cannot carry the UDP of a PeerConnection, nothing of the browser reaches a witness direct (suite wrapper.e2e.udp.exit)
The e2e that check 'no srflx' cannot tell the fail-closed rule from a leak: at an address nothing routes a datagram sent direct arrives nowhere, exactly as a dropped one.
A witness (_witness.py: a STUN server and a TCP listener at 198.51.100.10, held on lo, reachable by the browser directly) hears who contacts it, and the gateways leave from ANOTHER
documentation address (the exit, 198.51.100.9; the test gateway's TCP now leaves from it too, opt-in: tcp_from_exit). In each fail-closed scenario - a SOCKS5 proxy that refuses UDP, one whose UDP
leaves from another address, one whose relay never answers, an HTTP proxy - the witness hears no datagram and no connection from a source that is not the exit; a send direct is red. The controls
that make the green mean something: the same page with no proxy IS heard by the witness (datagram and connection), and behind a coherent gateway the witness hears the exit only.
Proved in the container on the giro 3 Linux binary (green, 7 tests of the suite). The witness and the gateway's source binding have unit tests (192). Counts: wrapper.e2e.udp.exit 7, wrapper.unit.udp 192.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-12 11:42:35 +01:00
feder-cr 2effeb1594 Merge remote-tracking branch 'origin/main' into udp/wrapper-r6 (0.50.1 notes, no_wait_after) 2026-11-12 11:36:56 +01:00
Federico EliaandClaude Fable 5.2 15d7608867 tests: no_wait_after is judged on the order of events, not on seconds (#478)
The test said the click must come back in under 2.5 s while /slow slept 3 s.
That measured the runner: on a loaded one the click alone took longer (2 of 30
runs of the suite, every run on one CPU) with nothing wrong in the product.

/slow is now an answer the server holds until the test lets it go. The click
with no_wait_after=True must come back while the answer is still held (the
order is: click returned, then answered; the url is still the old one). A new
test holds the other half: a plain click on the same link does not come back
until the answer is given, and returns on the new page.

Known-bad input, run before trusting it: the same test with no_wait_after
removed from the click is red on the order (answered, then click returned).

Co-authored-by: Claude Fable 5.2 <noreply@anthropic.com>
2026-11-12 11:32:43 +01:00
Federico EliaandClaude Fable 5.2 2d9cf3a82f CHANGELOG 0.50.1: the known differences from stock Playwright, and two fixes the entry had left out (#480)
Under [0.50.1], after the record of its publication:
- Fixed: a popup reaches the client as with Playwright's own Firefox (no limit
  of time, the destination's url, load reachable), and the opener's download
  event comes after the popup's page event.
- Known differences from stock Playwright, each with its measurement: the url
  of a popup that turns into a download, the url of a frame of another site at
  DOMContentLoaded, the longer click of the library client, and back/forward
  restoring the page from the back-forward cache.

Documentation only: no published byte changes.

Co-authored-by: Claude Fable 5.2 <noreply@anthropic.com>
2026-11-12 11:32:17 +01:00
feder-crandClaude Sonnet 5.5 05420d83ce tests: the resolver trap counts the questions of the user that runs the test, by the owner of the socket (/proc/net), not by name; unit.udp 189
Run 43188313516: on a runner the agent of the runner asks for github.com, api.github.com and its orchestrator through the /etc/resolv.conf the trap
rewrites, and the trap blamed the browser (6 realness tests and 1 DoH test). A question whose socket belongs to another user is answered and
listed in trap.foreign, not counted. The owner is read on receipt, before the answer: measured on Linux, 3000 questions that wait for their answer,
0 unreadable; one that cannot be read counts as the browser's.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-12 11:21:47 +01:00
feder-crandClaude Sonnet 5.5 03d18c853d tests: the DoH session built by hand launches on a virtual display too, and a test reads every direct InvisiblePlaywright(...) of the DoH and realness files (unit.udp 181)
Run 43188313516: test_a_session_without_a_proxy_resolves_with_the_system_resolver died with "no DISPLAY environment variable specified": it builds its
session by hand (not through _launch) and was not covered. The new test parses the files of the two suites and fails on a construction without headless=.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-12 11:17:40 +01:00
feder-cr 23b17c33ef Merge remote-tracking branch 'origin/main' into udp/wrapper-r6 (the ledger of 0.50.1) 2026-11-12 11:02:12 +01:00
github-actions[bot]andfeder-cr fb888c09cf record 0.50.1 as published (#476)
Co-authored-by: feder-cr <85809106+feder-cr@users.noreply.github.com>
2026-11-12 10:53:57 +01:00
feder-crandClaude Sonnet 5.5 3f56ac2e69 The old table test expects beacon for TYPE_BEACON, as the pinned driver says
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-12 10:43:22 +01:00
feder-crandClaude Sonnet 5.5 8621f0a5d6 request.resource_type agrees with the pinned driver: a beacon is beacon, a CSP report cspreport
The table that turns a Juggler cause into a Playwright resource type was a copy of the driver's and had gone stale: the pinned
driver (1.61, coreBundle.js ffNetworkManager) says `beacon` for TYPE_BEACON and `cspreport` for TYPE_CSP_REPORT; ours said `other`
for both. Measured on cnbc.com and scmp.com, our engine and Playwright's own Firefox side by side: the same POSTs (2 and about 8
per page) are `other` here and `beacon` on stock, so a client or a route filter that looks for beacons saw none.

Test (red on the old table): the driver's own table is read from the installed package and every cause it names must map to the
same type here; the next driver version that changes it fails the test, nothing is updated by hand.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-12 10:43:22 +01:00
feder-crandClaude Sonnet 5.5 9956adc386 tests: the chain by name keeps its walk on Windows (exit of the lab on loopback, with the pref) beside the one without the pref (wrapper.e2e.udp.exit, Linux)
d41ea7e moved the whole file to the Linux-only suite. Now the file holds two tests: the walk with an exit that is not loopback and no pref (wrapper.e2e.udp.exit, Linux, root), and the walk with the exit on 127.0.0.2 and media.peerconnection.ice.loopback (wrapper.e2e.udp, Linux and Windows). Selected by node id; wrapper.e2e.udp 41 again; the notes of the two suites say why.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-12 10:42:43 +01:00
feder-crandClaude Sonnet 5.5 72997c957c tests: three e2e modules of the UDP line are bound to the engine that carries it, as the others are
test_networkidle_through_a_served_browser_with_routes_e2e.py (red on firefox-61 and 62: its engine fix, 0972db59da, is in the 63), test_the_association_is_ready_when_the_peerconnection_is_born_e2e.py
and test_turn_over_tcp_is_tried_for_real_e2e.py (red before the UDP line) had only pytest.mark.e2e, so the e2e job of main, which fetches the PUBLISHED engine, would run them
against it. They now carry usefixtures(the_udp_line): they skip on an older engine and run on the candidate (REVIEW-63 #14). The collected counts do not change
(21, 1, 2); the ids stay in ci/required-suites.json, and a skip on the candidate is still red there.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-12 10:41:44 +01:00
feder-crandClaude Sonnet 5.5 bd853bc040 tests: the QUIC of the gateway test works on Windows: the relay leaves from the host's address, is told by its port, and a send that fails is said; unit tests (unit.udp 176)
On Windows the e2e read h2 on five visits and 'the server saw QUIC from []': the relay of the gateway sent from 127.0.0.1 to an address of its own
host (WinError 10051, nothing sends from loopback to the host's address there) in a timer that ignored every OSError, after logging the datagram as carried.

- the coherent gateway of the h3 test leaves from the host's address on every system (exit_host), and its fake STUN is bound there too (Windows sends
  neither from the host's address to loopback, 10049, nor the reverse); the relay is told from a client that came direct by the PORT it sends from
  (Gateway.exit_ports, H3Server.quic_peer_addrs); it forwards only to this host (forward_only_to): the browser's own QUIC to the Internet stays in the lab.
- Gateway._later records a send that raised (send_errors) and the report of the test shows it; the test asserts there is none.
- the relay's sockets turn SIO_UDP_CONNRESET off on Windows and a ConnectionResetError no longer ends the thread that reads.
- unit tests: a failing send is recorded and reported; a relay that leaves from the host's address reaches a server there, by a port in exit_ports and not
  one of a direct client; the fake STUN answers through it. Red on the old helpers (they have no exit_host/exit_ports/send_errors).

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-12 10:28:49 +01:00
feder-crandClaude Sonnet 5.5 7a0d55f4ce tests: the DoH, stress and ICE-names e2e always launch on a virtual display (headless=True, as the UDP and realness e2e); the helper that looked at the display of the host is gone; unit tests (unit.udp 177)
A test does not behave differently by the display of the machine it runs on. Replaces the helper of 302af97.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-12 10:15:10 +01:00
feder-crandClaude Sonnet 5.5 d867282c99 tests: the chain by name reads its srflx and its relay from the page with a gateway exit that is not loopback, and the loopback pref is gone
The exit of the lab is 198.51.100.9 (documentation, RFC 5737), held on lo with ip addr add for the length of the test; nICEr accepts it as a mapped
address (nr_stun_transport_addr_check rejects only wildcard, loopback and link-local), so the product's own setting is what is under test, not a pref that
is off in production. The page must read a srflx equal to the gateway's exit and the relay candidate of the TURN server it asked.
The file moves to a suite of its own, wrapper.e2e.udp.exit (Linux only, root): adding an address to an interface needs administrator and changes the network
of the host, so the Windows suite does not collect it (a skipped test would turn the verdict red). Chain takes exit_host; the TURN helper test runs for two exits.
Red on the old code: with the 127.0.0.2 exit and no pref the test fails at 0, 65 and 130 ms; green on the giro 3 Linux binary at 130 and 0 ms (container).

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-12 10:14:02 +01:00
feder-crandClaude Sonnet 5.5 302af97575 tests: the DoH, stress and ICE-names e2e ask for a virtual display on a Linux machine that has none; unit tests (unit.udp 173)
Run 43176569993: 19 of 19 of wrapper.e2e.doh on Linux died at the launch with "no DISPLAY environment variable specified". Those files launched a headed browser without a screen (the runner has none, and the suite runs under sudo). The other e2e launch with headless=True, which is a headed browser on an Xvfb the wrapper starts itself. A machine with a display, and Windows, are left as they are.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-12 10:09:13 +01:00
feder-cr 47725170de Merge remote-tracking branch 'origin/main' into udp/wrapper-r3-next (0.50.1 is on main)
# Conflicts:
#	src/invisible_playwright/_juggler/server.py
#	tests/test_a_page_is_handed_over_only_when_the_engine_says_it_is_ready.py
#	tests/test_popup_destinations_e2e.py
#	tests/test_popups_reach_the_client_e2e.py
2026-11-12 09:52:27 +01:00
feder-crandClaude Sonnet 5.5 d56ea298b4 tests: the comment of the first-datagram test says why the core's discovery of the exit fails in the lab (no echo service is reachable), not that a fixed time zone skips it
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-12 09:51:58 +01:00
b46e5a32d3 Release 0.50.1: networkidle on a reused page and on a routed served browser, a page handed over when ready (pin invisible-core 62.65.0) (#455)
* docs: the agent links and the command name the repo as it is now

Two things were broken for a reader on main, not one.

Thirteen links pointed at github.com/feder-cr/AIHawk. GitHub redirects a
NAME to the OBJECT that carried it, not to the content: after the September
swaps that name belongs to invisible_dots, which has seven wiki pages, so
AIHawk/wiki/<page> lands on its wiki Home. It answers 200 with different
content, which means a reader who clicks does not find the page and a search
engine sees a soft-404 across about 150 indexed URLs.

Seven occurrences said `uvx aihawk`, a command that does not exist. One sat
in a front-matter description, which is the snippet search engines show, and
one in a block meant to be copied: `claude mcp add stealth -- uvx aihawk`.
The command is invisible-playwright-mcp, on PyPI at 0.70.16.

All eight link targets were checked one by one and resolve to themselves with
the page title, no redirect.

Three things stay as they are, which only reading them showed. The
`pip install invisible-playwright` line matches what this engine's own README
teaches for the library, so the page is consistent rather than broken.
CHANGELOG.md keeps the old name because a changelog entry says what was true
then. And the fixture in scripts/sync_article_pixels.py keeps it because it is
the deliberate wrong case, a pixel for ANOTHER repo.

One sentence went away instead of being renamed: "shipped inside AIHawk" made
sense when AIHawk was the larger product containing the server. The server and
the repository are now the same thing, so "shipped inside itself" was circular.

(cherry picked from commit d9c8e46dce)

* test: the docs name the MCP server's repository and command as they are now

feder-cr/AIHawk now leads to an unrelated repository and answers 200, which no
link checker reports; `uvx aihawk` does not exist. The README and docs/ are
read for both.

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

* tests: the Fission bench counts the processes that host a site, not every new content process

test_same_site_other_port_stays_in_process was red on the e2e of the 0.50.0 commit ("a same-site frame
started a process: [13443]"): the bench counted every `-contentproc ... tab` pid, and the engine starts a
preallocated content process to refill its pool whenever it gets to it. On Linux the engine names a content
process by its remote type (ContentChild::SetProcessName, prctl PR_SET_NAME): "Isolated Web Co" once it
hosts a site of strategy 1, "Web Content" while preallocated. Measured on firefox-62: a cross-site frame
renames a preallocated process and a new "Web Content" refills the pool; a same-site frame changes neither.
The two tests that count processes skip off Linux, where no process carries a name.

Unit test with the measured processes: 3 red on the old bench, 3 green here. e2e on firefox-62 (candidate
#6, Linux): the bench file 17 passed; the two counting tests 15 of 15 runs green.

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

* tests: a closed context is checked for the processes of its sites, not for every content process

test_closed_contexts_with_a_never_stopping_service_worker_leave_no_process was red on the e2e of the 0.50.0
tag ([2, 2, 2, 5, 5], 5 <= 2). Measured on firefox-62 (Linux), the test's own scenario 10 times with every
process named: no "Isolated Web Co" left after any close; the 3 more are "Web Content", the engine's pool of
preallocated processes filling up behind the closed contexts (5 runs of 10, new pids each time). Not a leak:
the count read the refill.

The helper of the bench moves to tests/_processes.py and both tests use it. The context test counts the
processes that host a site: at least one while the page is open (or the count proves nothing), none a few
seconds after `close` answers (the engine waits for them inside close and kills the ones that stay). Off
Linux it skips, as the bench's two counting tests do: no other system names the process.

Unit tests (tests/unit/test_processes_counts_sites.py) from the measured processes, the closed-context case
included. e2e on firefox-62 (candidate #6, Linux): the context test 10 of 10; run_e2e.py on the two files and
the unit test 18 passed. The old counter, same scenario: 5 of 10 runs would fail.

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

* Release 0.50.1: 0.50.0 with the process-counting e2e corrected (0.50.0 never reached the index)

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

* tests: the same-site control puts its frame in the shown page; CHANGELOG: 0.50.0's entry is 0.50.1's

The e2e of #451 saw a new "Isolated Web Co" once after a.test/plain -> a.test/same-site ([10878] -> [10878,
11208]). Not a process of an earlier test: it was created after the first read and only this worker's
descendants are counted. It is the top-level navigation: when the old document may enter the back-forward
cache, the browsing context is replaced (mReplaceBrowsingContext, dom/ipc/ProcessIsolation.cpp) and the new
one may be placed in another process of the same site (dom.ipc.processCount.webIsolated = 4). Measured on
firefox-62 (candidate #6, Linux): 0 of 30 runs alone (bfcache on and off), 0 of 57 under 4 workers. The test
was written for the frame, so the frame is now added to the page already shown and the top never navigates:
20 of 20 runs green.

0.50.0 never reached the index, so the changelog gate refused its heading; its entry now opens 0.50.1.

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

* 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>
(cherry picked from commit 47182f0cd85fea08fc45e36f1c91d2d570722f14)
(cherry picked from commit e46f2dcf3eb361e6af0fedcdf6e1189f0ac330b6)

* 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 favicon of the page a goto just left). The engine takes the request out of its held set at once and the
late continue/abort/fulfill meets "Cannot find request" or NS_BINDING_ABORTED. 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; green after), and a static guard that every op of RouteDispatcher goes through _send and that _send
swallows exactly those two. The same defect was found a month earlier by richardpowellus (#351), with the favicon of the
previous page: his test is added in the next commit.

Co-authored-by: Richard Powell <1369873+richardpowellus@users.noreply.github.com>
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>

* 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>
(cherry picked from commit 91223226f5bba25edff9af0e8b1fd6b5bfea2227)
(cherry picked from commit 612b18c02b95e9b5833d62b6595d4a0ff324aac2)

* tests: answering a route the next navigation already aborted does not raise (the case of #351: the favicon of the page just left)

Sixty sequential routed gotos on a loopback page: 4-12 of them failed on the old server, every failing continue_ being
the previous document's favicon, aborted by the next navigation while the route sat with the handler. Red on main (in-process
path), green with the fix of RouteDispatcher._send.

Co-authored-by: Richard Powell <1369873+richardpowellus@users.noreply.github.com>
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>

* Release 0.50.1: pin invisible-core 62.64.0; CHANGELOG for the networkidle fixes

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
(cherry picked from commit e63ef8e61ea42e7f8df7c1bde206f3bf86fc18f7)

* A route answer the engine refuses is the engine's business, whatever its wording

The server took one wording ("Cannot find request") of an answer to a closed request as done and passed every other
protocol error up to the client. The engine also says "NS_BINDING_ABORTED
[nsIInterceptedChannel.resetInterceptionWithURI]" when the channel was cancelled while the answer was on its way: the
same event, and the client kept it as the error of the connection and raised it on its next route command.

Stock Playwright sends the three interception commands as may-fail and tells the client nothing, whatever the engine
says. So does RouteDispatcher._send now: every ProtocolError is swallowed, the route is disposed after it.

Tests: the static guard no longer allows a re-raise inside the handlers; a unit test feeds three wordings (red on the
old code for two of them).

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

* tests: the descriptors of the spawn are asserted by running it, not by reading the core's source

test_the_spawn_keeps_the_two_hardwired_descriptors asserted that the source of the core's _spawn_posix contains
`pass_fds=(its_read, its_write, 3, 4)`. Core 62.64.0 starts the engine with posix_spawn and file actions, so the words are gone
and the test failed on every Linux unit suite although the behaviour is the same (and better).

The test now runs the spawn: a parent with nothing open on 3 and 4 and its pipes far from them launches a program that reads
fd 3 and answers on fd 4 (the contract of nsRemoteDebuggingPipe.cpp), and the answer must come back and the child must hold no
descriptor above 4 of the parent's. Same shape as the core's own test
(test_the_pipe_of_the_engine_reaches_its_fixed_descriptors). No skip: the file is already POSIX-only.

The other tests of the file do not read source text (checked: no getsource/inspect/read_text left).
Ran the parent program on Linux with core 62.64.0 (image tetra-invisible:run1b-final): pong:ping:0.

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

* The page dispatcher waits for Page.ready before the page is handed over (needs invisible-core with Lifecycle.wait_for_page_ready)

Same defect and fix as in the core's page (see the core commit): a goto sent right after new_page could meet the page's initial about:blank.
The pin of invisible-core moves with the core release that carries wait_for_page_ready.

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

* Pin invisible-core==62.65.0 (a page handed over when the engine says it is ready); changelog

The core that carries Lifecycle.wait_for_page_ready is invisible-core 62.65.0 (draft PR invisible_core#238), not on the index yet:
the pin check of this push is skipped on purpose (INVISIBLE_PIN_CHECK=skip).

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

* tests: the stand-in engine of the registry test says Page.ready, as the real one does (the page is handed over on it)

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

* tests: new_page and a popup are handed over only when the engine says Page.ready (red without the wait in PageDispatcher, green with it)

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

* A page is built at once and announced when the engine says Page.ready (the wait inside the constructor held a popup's first request behind a page that did not exist yet, and lost its commit and load)

- PageDispatcher no longer waits in __init__; wait_until_ready() is called by the adoption between the construction and the announcement
  (context 'page' event, newPage answer). A detach while waiting ends the wait; a page that is not ready in time is disposed.
- The main frame's initializer carries what the lifecycle already knows (url, name, load states), as every other frame's does.
- Tests: unit (a popup exists and listens while it waits; what it does before its ready reaches its frame; red on 6a60dce) and e2e
  (a popup of a link, noopener or window.open reaches an in-process and a stock client of a served browser within 2 s, with and
  without a context route; 15 of 16 red on 6a60dce, 16 green).

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

* tests: the stand-in pages say wait_until_ready; the popup e2e reaches the stock client as the other served tests do

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

* tests: the popup reaches the client from another site too (a link, noopener, window.open: 16 more cases, in-process and through a served browser)

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

* A popup is reported on Page.ready as Playwright's is: no limit and no warning, with the address of the commit that came with the ready

- Stock Playwright 1.62 (measured): a 204 or a silent destination gives no page event, one that answers after 4 s gives it at 4 s with the
  destination already. The adoption of a popup waited 20 s and dropped it with a warning; now only a page a caller asked for
  (newPage) has the 20 s; a popup waits until the engine says Page.ready, the target goes away, or its context closes
  (BrowserDispatcher.end_waits_of), and says nothing.
- The ready and the commit of the document that made the page ready come in the same turn: the page is announced after a round trip to the
  engine (settle_events), so the frame reads the destination at the page event (3 of 4 slow popups said about:blank).
- In-process the slow popup arrived 0.9 s later than stock: it is the humanised click (1.1 s of pointer movement before the click returns),
  the popup arrives 4.02 s after the click in both modes.
- Tests: unit (limit None for a popup and 20 s for a requested page; a popup with no ready ends with its context and says nothing; the
  address at the page event is the commit's) red on b09d620; e2e (204 and silent: no event; 1.5 s: url is the destination; 25 s: reported
  then) in-process and through a served browser: the 25 s ones red on b09d620.

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

* A download started by a popup that is not announced yet is reported on its opener, as Playwright reports it

- Browser.downloadCreated names the tab the download came from. A tab opened for an attachment (a target=_blank link, a window.open) never gets
  a Page.ready and the engine closes it at once, so it is not among the announced pages and the download was lost: no download event
  anywhere (a21e1de had it, on the popup). Playwright's ffBrowser._onDownloadCreated reports it on the opener of a page that is not
  reported yet; so does this, from the opener recorded when the target was attached (BrowserDispatcher._openers). The abort of the
  navigation that became the download still goes to the page that owns the frame.
- Tests: unit (red on fbceeaf); the e2e of the destinations and of the popup matrix of the fake-web branch (73f1e8d): 16 + 34 cases against
  the reference measured on stock Playwright 1.62 - on fbceeaf 4 of the 16 were red (the download), now 50 of 50 green.

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

* A popup tells its listeners the load it reached before it was announced; an unannounced frame has no address of its own

- The popup is announced when the engine says Page.ready, which is when its document commits, so its domcontentloaded and load may be said
  before the client has the page: page.on('load') registered in the handler of the page event never fired (Playwright's does, measured by
  the independent run: destinations of 4 s and 25 s). FrameDispatcher.emit records those two states while the page is not announced and
  PageDispatcher.announce says them again right after the page event, in their order and under one lock; the first time they already set
  the state wait_for_load_state reads, so it returns at once. Only popups: a requested page is announced as before.
- The main frame is created with the address the lifecycle knows, '' if it has committed nothing (an attachment's empty tab), not
  about:blank: Playwright says '' there.
- Tests: unit (the two states after the page event, in order; red on 2f153c7); e2e: a listener registered in the handler of the page event
  hears the load of a slow popup, wait_for_load_state in the handler returns in under 2 s (in-process and a stock client over a served
  browser, window.open and link).

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

* A popup whose target goes away while its page is being built is announced and closed, not waited for for ever

A download's empty tab is closed by the engine within milliseconds; on a loaded machine its page is still being built when the detach arrives.
_handle_detach recorded it as early (nobody in _building to tell) and the adoption then waited for a Page.ready that never comes: the
popup was never announced (test_popup_destinations_e2e, the download on the opener, failed once in a full suite run). The adoption now
looks at the early detaches when it registers the page as waiting.

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

* A command of the adoption that finds the target's session gone announces and closes the popup, as a detach before the ready does

The independent run on a quiet machine lost one link-into-attachment popup in a hundred: the engine closed the tab WHILE the adoption was
initializing it, answered 'cannot find session' to Page.setInitScripts, and the popup was discarded with a warning - no page event - where
Playwright's is announced and closed. PageDispatcher._build now treats an initialization command that fails because the target or its session
is gone (one test: _target_is_gone) as the same case: the page is built, flagged gone_while_building, and the adoption announces it and closes
it right after. Test: a fake engine answers 'cannot find session' to each command of the adoption in turn (parametrised): the page event and
the close arrive, no warning; red on b05741f for Page.setInitScripts.

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

* tests: the helper of the popup destinations does not shadow the browser fixture (ruff F811)

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

* tests: the popup tests do not fail on the machine's speed (no 2 s limit)

A runner with four workers delivered a popup in 2.013 s (the limit of the test was 2 s). The verdict of these tests is that the popup arrives with
its address and its load; the wait is generous (30 s) and the check of the time is gone. The wait_for_load_state of the handler is bounded by 8 s.

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

* The adoption of a target is one explicit state machine, proved over every order of the engine's events

Four patches of the same race (a detach before the ready, during the build, between the build and the wait, a command answered 'cannot find
session') and a fifth the exhaustive test found (a detach while the adoption waits for the main frame of a tab the engine never announced:
the wait went on for 20 s and the popup was discarded; this is the order the runner produced for the download popups: 3 of 4 lost).

- _Adoption: the single record of a target between its attach and its announcement: state (attached, building, waiting, announced), gone
  (set by the engine's detach AT ANY MOMENT), page, opener, context. It replaces _adopting, _building, _openers and _detached_early.
- Every wait of the adoption looks at gone (the main-frame wait polls it), every state change is one method (_enter_building, _enter_waiting,
  _enter_announced), a command that finds the session gone ends in the same place as a detach, a closing context takes away every adoption
  of it in any state (end_waits_of).
- Invariant: an attached target that is not a page a caller asked for gives the client exactly one page event, at its ready or at its
  disappearance (and its close right after), unless its context closed first.
- Test: test_every_order_of_the_events_of_a_popup_gives_one_page_event stops the adoption thread at six points of its own and delivers the
  engine's events (frame, commit, ready, detach, in every prefix) at every one of the eight moments: 635 orders, none sampled. Mutation
  check: without the gone-aware main-frame wait 24 orders break, without the tolerance of the command error 42, without the close after the
  page 374; without the early-gone check of _enter_waiting the adoption hangs.

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

* The adoption keeps a short trace per target and writes it where a popup is dropped or fails

The log of a CI run says that a popup was not announced and not in which order the engine's events came. Each target in flight keeps (in memory,
at most 60 short strings, nothing afterwards) what the engine said (frame, commit, ready, detach) and what the adoption did (building, waiting,
announced), with the milliseconds since the attach. It is written in the warning of a failed adoption, in the error the newPage waiter gets, in
the timeout of a requested page, and in browser._dropped (the last 16 targets dropped with their context).

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

* The WebGL determinism test says why the browser could not make a context

One run in 31 of the e2e on a loaded Linux runner failed this test with "reason='gl null'" and nothing else: getContext('webgl') gave the page null. The browser
says why in the `webglcontextcreationerror` event (statusMessage: the failure list, e.g. "tryNativeGL (FEATURE_FAILURE_EGL_LOAD_3)", "Initializing WebGL backbuffer
failed.", "GL error 0x505 occurred during OpenGL context initialization"), and each of the paths that can produce null on Linux in our engine writes a different one
(library not loaded, display not initialised, context not created, GL out of memory, backbuffer not allocated). The test reads the event and puts it in the
assertion, and tries webgl2 on a fresh canvas (the old canvas already had the failed type).

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

* tests: the same-site control of the Fission bench measures the frame, not the process pool

The control counted the processes that host a site between two reads, with the default pool of three preallocated content processes: a pool
process handed to a site after the first read moved the count without the frame having asked for anything ([63248] -> [63248, 63386] on a
four-worker runner; the same family as 5402da4, ff2123e and fef0bc5). The control now runs in a browser with dom.ipc.processPrelaunch.fission.number
at 0, where a process of a site appears only because a site needed one, and says so if the page of the site has no process to compare with.

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

* The download of a tab that is not announced yet is said after the page event of the tab

The tab opened for an attachment is announced when the engine takes it away, a few milliseconds after it says the download; the download
(reported on the opener) went to the client first, the popup after: the order the other way round from Playwright's, and a client that read
the popup the moment the download arrived found none on a one-CPU machine (the 4 download cases of GitHub, 3 of 4 red; the same on a one-CPU
container: 1, 0, 2 of 50 on a90dadc). The adoption holds the download on its record and says it right after the page event (never lost: also
when the tab is dropped or fails).

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

* A download is taken with the record's removal in one step, and the opener of a target not announced is remembered: no step of the adoption can lose it

The failure branch said the pending downloads BEFORE it removed the record: a download created between the two found the record, queued on it, and
nobody said it. Taking the pending downloads and removing the record are now one step under the browser's lock, in the three branches
(announced, dropped with its context, failed); the opener of a target that ended without being announced is kept for the last 16 targets, so a
download that comes after the record is gone is still said, on the opener. Test: the download is forced into the gap of the failing adoption
(red on 65f7580: said 0 times, now once).

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

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
Co-authored-by: Richard Powell <1369873+richardpowellus@users.noreply.github.com>
2026-11-12 09:51:23 +01:00
feder-crandClaude Sonnet 5.5 e88e664a50 tests: the chain by name allows loopback in ICE, because the lab's exit is 127.0.0.2 and a retail Firefox throws away an answer whose mapped address is loopback
The giro 3 gate was red on test_a_turn_srflx_by_name_arrives_through_the_relay_before_the_tick. Measured on the giro 3 Linux binary (strace of the socket
that talks to the relay + the gateway's own log): the gateway delivers the TURN server's 401 and then its success (type 0x0103) within 5 ms, the browser
reads both, answers the 401 with credentials, and never accepts the success: it retransmits the same Allocate 5 times in the 2 s of the page. The
success carries XOR-MAPPED-ADDRESS 127.0.0.2 (where the gateway's datagrams leave from, by design of the test) and nICEr rejects a loopback mapped address as
bogus (stun_client_ctx.cpp nr_stun_transport_addr_check) unless the ICE context allows loopback (turn_client_ctx.cpp; the flag is set from
media.peerconnection.ice.loopback in nricectx.cpp). The same TURN server answers a direct browser at a non-loopback address and the allocation completes in
60 ms, so the chain is sound. With the pref the chain test passes at 130 ms of round trip on the giro 3 binary; without it it fails at 0, 65 and 130 ms.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-12 09:50:34 +01:00
feder-crandClaude Sonnet 5.5 bacf03ad21 tests: the CONNECT helper of the HTTP proxy tests reads the answer one byte at a time, so the first bytes of the tunnel are not lost with the head; unit test (unit.udp 166)
When the far side wrote and closed at once, the 200 and the first bytes of the tunnel could reach the socket in one segment, and _connect_raw dropped everything after the blank line: the caller read the end of the stream instead of the data (run 43176569993, test_a_connect_to_loopback_is_relayed_and_one_that_would_leave_it_is_refused).

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-12 09:49:01 +01:00
feder-crandClaude Sonnet 5.5 9357e790b3 tests: the first datagram of a PeerConnection is judged with the session's UDP declared coherent, and the core's own probe is not counted as the engine's association
The giro 3 gate was red on this test: with a fixed time zone the core does not discover the TCP exit, so it cannot compare it with the UDP probe's mapped
address and declares the UDP of the proxy unmeasured; the engine then treats the proxy as a router that drops UDP, asks it for no association and sends
nothing (measured on the giro 3 Linux binary: the gateway saw ONE ASSOCIATE for the whole test, the core's probe; the layer was pushed on the PC's
socket and what was sent was dropped). The test gives the core the gateway's TCP exit as every e2e of the line does (egress_by_proxy), and it no longer counts
the probe's association (the first of the gateway, made before the browser exists) as one that was ready before the PeerConnection - it passed an
engine that asked for none. Green on the giro 3 Linux binary (run 43164943499).

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-12 09:40:33 +01:00
feder-cr 1466ac6433 wrapper: the opener kept for the downloads of a target whose adoption failed lives until the engine detaches the target, and none is made for a target already detached; unit tests (unit.page 34) 2026-11-12 09:09:31 +01:00
feder-cr bf5c6dabb3 ci: wrapper.unit.page counts the popup-order test and the changed page tests of release/0.50.1 8049df3 (32) 2026-11-12 09:06:24 +01:00
feder-cr e992255d38 Merge remote-tracking branch 'origin/release/0.50.1' into udp/wrapper-r3-next 2026-11-12 09:04:57 +01:00
feder-crandClaude Sonnet 5.5 8049df3c33 A download is taken with the record's removal in one step, and the opener of a target not announced is remembered: no step of the adoption can lose it
The failure branch said the pending downloads BEFORE it removed the record: a download created between the two found the record, queued on it, and
nobody said it. Taking the pending downloads and removing the record are now one step under the browser's lock, in the three branches
(announced, dropped with its context, failed); the opener of a target that ended without being announced is kept for the last 16 targets, so a
download that comes after the record is gone is still said, on the opener. Test: the download is forced into the gap of the failing adoption
(red on 65f7580: said 0 times, now once).

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-12 08:58:48 +01:00
feder-cr e4edf5f81f ci: the realness e2e (32) is a required suite, its helpers (24) join wrapper.unit.udp (165) 2026-11-12 08:54:35 +01:00
feder-crandClaude Sonnet 5.5 7a094c3bbc tests: the realness check without a real proxy - six declared exits, the values a page reads, and the judges
The manual check drove the browser through a paid proxy and compared what a page reads with the proxy's exit. This is the
same check against a local SOCKS5 gateway that declares its exit: a local site that tells a connection the gateway opened from
a direct one, FakeDoh for the names, and the core's own geo database as the truth for the zone and the country.

* test_realness_behind_a_declared_exit_e2e.py: one launch per exit (six, in six countries), read by five tests (the address a
  site sees and no connection past the gateway; nothing of the host in the WebRTC candidates and SDP; the names reach the gateway
  and not the system resolver; the zone, the offsets read two ways and a worker; the language of the page, a worker and the
  Accept-Language header against the exit's country), plus the vendored detection page loaded behind the gateway.
* _realness_support.py: the exits, ExitGateway (remembers the ports of the connections it opened), the site, the reads, the judges.
* test_the_realness_helpers.py: the judges and the gateway/site correlation held to golden reads, no browser.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-12 08:53:37 +01:00
feder-cr 7272ea8f64 tests: the iptables fallback of the resolver trap is gone (the cause was the trap's own threads holding the port, fixed in 4933f8c); wrapper.unit.udp 141 2026-11-12 08:49:52 +01:00
feder-crandClaude Sonnet 5.5 a70f2fecaf tests: the discovery of the exit of a context stays covered now that the DoH e2e declare it away
The DoH e2e declare the exit the core asks for (their subject is the roads of the browser). The discovery itself keeps its own test: it goes
through the gateway of the context, by name, only to the services of the core, never through another context's gateway, and a gateway that
refuses them never makes the measurement say coherent. wrapper.unit.udp 140 -> 142.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-12 08:43:55 +01:00
feder-crandClaude Sonnet 5.5 65f7580182 The download of a tab that is not announced yet is said after the page event of the tab
The tab opened for an attachment is announced when the engine takes it away, a few milliseconds after it says the download; the download
(reported on the opener) went to the client first, the popup after: the order the other way round from Playwright's, and a client that read
the popup the moment the download arrived found none on a one-CPU machine (the 4 download cases of GitHub, 3 of 4 red; the same on a one-CPU
container: 1, 0, 2 of 50 on a90dadc). The adoption holds the download on its record and says it right after the page event (never lost: also
when the tab is dropped or fails).

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-12 08:42:59 +01:00
feder-crandClaude Sonnet 5.5 4933f8cdba tests: the resolver trap ends its threads before it closes its sockets, so its port is free for the next test (no more "Address already in use" on 127.0.0.1-8:53)
The answering threads sit in accept()/recvfrom(); on Linux a close() from another thread does not wake them and the kernel keeps the socket
bound until the call returns, which it never did: every trap left its address taken, and the eighth trap of a run found all eight taken
(reproduced here in a container: 19 DoH e2e, the 6 tests after the 8th trap are errors; alone, the same file passes). The loops now wake every
0.2 s to look at a flag; the teardown sets it, joins the threads, and then closes the sockets.

- test_a_closed_trap_gives_its_port_back_at_once (wrapper.unit.udp 139 -> 140): a trap on a free port is closed and a second one on the same
  port must bind 127.0.0.1 again; red on the old code on Linux.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-12 08:42:36 +01:00
feder-cr bfb67e0c2c tests: a port 53 that cannot be bound is redirected from 127.0.0.2 to a free port (iptables nat OUTPUT), the rules go with the trap 2026-11-12 08:27:48 +01:00
feder-crandClaude Sonnet 5.5 2022ecf32a tests: two connections on one page may nominate a peer-reflexive end; the road is what is judged
On the round 3 gate (Linux, run 43164943499) the nominated pair was host to prflx: the other connection's mDNS name was not resolved yet when its
connectivity check arrived, and the address the check came from is learned as peer-reflexive. That is the same direct local road, so the test accepts
host or prflx at each end, over UDP at both ends, and refuses what is a different road: a relay, a server-reflexive candidate (through the proxy or the
network), or TCP. The open time stays judged against the responder's first retry, and printed beside the retail window.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-12 08:21:06 +01:00
feder-cr 5ae6833299 tests: the DoH e2e declare the exit the UDP measurement asks for; the gateway's page is reached by an address; e2e.udp is split in e2e.udp and e2e.web; the trap says who holds port 53 2026-11-12 08:19:16 +01:00
feder-crandClaude Sonnet 5.5 a90dadc204 tests: the same-site control of the Fission bench measures the frame, not the process pool
The control counted the processes that host a site between two reads, with the default pool of three preallocated content processes: a pool
process handed to a site after the first read moved the count without the frame having asked for anything ([63248] -> [63248, 63386] on a
four-worker runner; the same family as 5402da4, ff2123e and fef0bc5). The control now runs in a browser with dom.ipc.processPrelaunch.fission.number
at 0, where a process of a site appears only because a site needed one, and says so if the page of the site has no process to compare with.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-12 07:17:52 +01:00
feder-crandClaude Sonnet 5.5 210161d9b6 The WebGL determinism test says why the browser could not make a context
One run in 31 of the e2e on a loaded Linux runner failed this test with "reason='gl null'" and nothing else: getContext('webgl') gave the page null. The browser
says why in the `webglcontextcreationerror` event (statusMessage: the failure list, e.g. "tryNativeGL (FEATURE_FAILURE_EGL_LOAD_3)", "Initializing WebGL backbuffer
failed.", "GL error 0x505 occurred during OpenGL context initialization"), and each of the paths that can produce null on Linux in our engine writes a different one
(library not loaded, display not initialised, context not created, GL out of memory, backbuffer not allocated). The test reads the event and puts it in the
assertion, and tries webgl2 on a fresh canvas (the old canvas already had the failed type).

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-12 07:16:43 +01:00
feder-crandClaude Sonnet 5.5 1542fede01 The adoption keeps a short trace per target and writes it where a popup is dropped or fails
The log of a CI run says that a popup was not announced and not in which order the engine's events came. Each target in flight keeps (in memory,
at most 60 short strings, nothing afterwards) what the engine said (frame, commit, ready, detach) and what the adoption did (building, waiting,
announced), with the milliseconds since the attach. It is written in the warning of a failed adoption, in the error the newPage waiter gets, in
the timeout of a requested page, and in browser._dropped (the last 16 targets dropped with their context).

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-12 07:16:36 +01:00
feder-crandClaude Sonnet 5.5 5426744bc6 The adoption of a target is one explicit state machine, proved over every order of the engine's events
Four patches of the same race (a detach before the ready, during the build, between the build and the wait, a command answered 'cannot find
session') and a fifth the exhaustive test found (a detach while the adoption waits for the main frame of a tab the engine never announced:
the wait went on for 20 s and the popup was discarded; this is the order the runner produced for the download popups: 3 of 4 lost).

- _Adoption: the single record of a target between its attach and its announcement: state (attached, building, waiting, announced), gone
  (set by the engine's detach AT ANY MOMENT), page, opener, context. It replaces _adopting, _building, _openers and _detached_early.
- Every wait of the adoption looks at gone (the main-frame wait polls it), every state change is one method (_enter_building, _enter_waiting,
  _enter_announced), a command that finds the session gone ends in the same place as a detach, a closing context takes away every adoption
  of it in any state (end_waits_of).
- Invariant: an attached target that is not a page a caller asked for gives the client exactly one page event, at its ready or at its
  disappearance (and its close right after), unless its context closed first.
- Test: test_every_order_of_the_events_of_a_popup_gives_one_page_event stops the adoption thread at six points of its own and delivers the
  engine's events (frame, commit, ready, detach, in every prefix) at every one of the eight moments: 635 orders, none sampled. Mutation
  check: without the gone-aware main-frame wait 24 orders break, without the tolerance of the command error 42, without the close after the
  page 374; without the early-gone check of _enter_waiting the adoption hangs.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-12 07:13:47 +01:00
feder-cr 973927fdb7 tests: the trap-policy test reads the trap fixture in conftest.py (6b moved it there with the lint of the fixtures) 2026-11-12 06:23:06 +01:00
feder-crandClaude Sonnet 5.5 071cf8d697 tests: the fixtures that several e2e files share are in conftest.py, not imported from a sibling file (ruff F811, the lint of the tests job)
A fixture imported from a twin file and then named as a test argument is a redefinition: 60 F811 in the new tests of the UDP line, the
same error that turned the 0.50.1 CI red. The collection does not change: the same 2187 tests (1422 by default), the same setup plan
(fixture order and scope per test, compared with --setup-plan before and after).

- conftest.py: doh, gateway, trap, watcher, pages (DoH e2e), socks5_tcp_only, local_https_page (WebRTC e2e) and browser (the two-transport
  fixture of the popup tests). The heavy imports are inside the bodies, so a run without the e2e extras still collects.
- _doh_support.py (ZONE, Pages) and _socks_servers.py (Socks5TcpOnly, was _Socks5TcpOnly in test_webrtc_realness.py): the plain code the
  fixtures need, in support modules, not in a test file.
- The twin files keep what is not a test argument (the autouse _hermetic_session and the helpers, imported by name); the sibling files
  stop importing the fixtures. The four `# noqa: F811` of test_popup_destinations_e2e.py are gone: ruff passes with --ignore-noqa.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-12 06:02:15 +01:00
feder-cr 7af5b84954 Merge remote-tracking branch 'origin/release/0.50.1' into udp/wrapper-r3 2026-11-12 05:47:21 +01:00
feder-crandClaude Sonnet 5.5 a18e967675 tests: the popup tests do not fail on the machine's speed (no 2 s limit)
A runner with four workers delivered a popup in 2.013 s (the limit of the test was 2 s). The verdict of these tests is that the popup arrives with
its address and its load; the wait is generous (30 s) and the check of the time is gone. The wait_for_load_state of the handler is bounded by 8 s.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-12 05:47:12 +01:00
feder-crandClaude Sonnet 5.5 64dc8d3476 tests: the popup tests do not fail on the machine's speed (no 2 s limit)
A runner with four workers delivered a popup in 2.013 s (the limit of the test was 2 s). The verdict of these tests is that the popup arrives with
its address and its load; the wait is generous (30 s) and the check of the time is gone. The wait_for_load_state of the handler is bounded by 8 s.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-12 05:44:57 +01:00
feder-cr bd46760313 ci: wrapper.e2e.udp counts 68 (the three ICE rows of test_webrtc_realness: default, content process asked, no socket process asked; the engine locks both prefs) 2026-11-12 05:29:21 +01:00
feder-crandClaude Sonnet 5.5 2283d40198 tests: a caller that asks for the ICE in the content process, or for no socket process, gets the srflx through the relay all the same (the engine locks both prefs)
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-12 05:29:12 +01:00
feder-crandClaude Sonnet 5.5 012fc862ef tests: two connections on one page are judged on the road they take, not on the clock of the machine
The test asserted a median of 30-55 ms, the time of a fast machine. On a GitHub runner the same healthy engine takes 67 ms (Windows) and
122 ms (Linux) and the gate was red on both: an absolute time is a verdict on the machine.

Every one of the five cold launches is now judged on what the machine cannot change:
* the data channel opens and echoes;
* each connection gathered a UDP host candidate named by mDNS (a run without UDP is the reserved-port failure: the socket could not bind and
  the connection fell back to TCP);
* the nominated pair, read from the browser's own statistics, is host to host over UDP at both ends (no road through TCP; a succeeded pair
  means the other connection's mDNS name was resolved);
* it opens in less than the responder's first retry (3 s): a name that does not come back opens only at the retry.
The time is printed beside the retail window, as a measure.

Run on the firefox-63 candidate engine: passes, [38, 39, 39, 73, 77] ms.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-12 05:23:06 +01:00
feder-cr 8c7e413b68 tests: the resolver trap takes the first loopback address it can bind for port 53 (a hosted runner can hold 127.0.0.1:53) and writes that address in resolv.conf 2026-11-12 05:19:56 +01:00
feder-crandClaude Sonnet 5.5 bbf4019940 tests: the helper of the popup destinations does not shadow the browser fixture (ruff F811)
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-12 05:17:48 +01:00
feder-cr 4e1f2ecf40 tests: the resolver trap says why it could not bind (the error of the socket) 2026-11-12 05:12:04 +01:00
feder-cr 6f9b87c860 ci: test_a_page_that_moves_on_e2e.py is required in wrapper.e2e.page (114): the e2e of the engine fix for a navigation the page overtook 2026-11-12 05:05:54 +01:00
feder-cr a072aa22b8 ci: the page and popup suites count the tests of release/0.50.1 6200bc2 (e2e.page 100, unit.page 24) 2026-11-12 04:40:13 +01:00
feder-cr 328ed0738e Merge remote-tracking branch 'origin/release/0.50.1' into udp/wrapper-r3 2026-11-12 04:39:51 +01:00
feder-crandClaude Sonnet 5.5 6200bc29ed A command of the adoption that finds the target's session gone announces and closes the popup, as a detach before the ready does
The independent run on a quiet machine lost one link-into-attachment popup in a hundred: the engine closed the tab WHILE the adoption was
initializing it, answered 'cannot find session' to Page.setInitScripts, and the popup was discarded with a warning - no page event - where
Playwright's is announced and closed. PageDispatcher._build now treats an initialization command that fails because the target or its session
is gone (one test: _target_is_gone) as the same case: the page is built, flagged gone_while_building, and the adoption announces it and closes
it right after. Test: a fake engine answers 'cannot find session' to each command of the adoption in turn (parametrised): the page event and
the close arrive, no warning; red on b05741f for Page.setInitScripts.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-12 04:10:00 +01:00
feder-crandClaude Sonnet 5.5 b05741f538 A popup whose target goes away while its page is being built is announced and closed, not waited for for ever
A download's empty tab is closed by the engine within milliseconds; on a loaded machine its page is still being built when the detach arrives.
_handle_detach recorded it as early (nobody in _building to tell) and the adoption then waited for a Page.ready that never comes: the
popup was never announced (test_popup_destinations_e2e, the download on the opener, failed once in a full suite run). The adoption now
looks at the early detaches when it registers the page as waiting.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-12 03:51:28 +01:00
feder-cr 95c7e156ac tests: the first visit of the h3 e2e is h2 because the fixture has no HTTPS record (the retail read h3 first in 3 sessions of 15); the FakeDoh never serves type 65 and the tests assert it 2026-11-12 03:48:26 +01:00
feder-crandClaude Sonnet 5.5 620f969655 A popup tells its listeners the load it reached before it was announced; an unannounced frame has no address of its own
- The popup is announced when the engine says Page.ready, which is when its document commits, so its domcontentloaded and load may be said
  before the client has the page: page.on('load') registered in the handler of the page event never fired (Playwright's does, measured by
  the independent run: destinations of 4 s and 25 s). FrameDispatcher.emit records those two states while the page is not announced and
  PageDispatcher.announce says them again right after the page event, in their order and under one lock; the first time they already set
  the state wait_for_load_state reads, so it returns at once. Only popups: a requested page is announced as before.
- The main frame is created with the address the lifecycle knows, '' if it has committed nothing (an attachment's empty tab), not
  about:blank: Playwright says '' there.
- Tests: unit (the two states after the page event, in order; red on 2f153c7); e2e: a listener registered in the handler of the page event
  hears the load of a slow popup, wait_for_load_state in the handler returns in under 2 s (in-process and a stock client over a served
  browser, window.open and link).

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-12 03:33:32 +01:00
feder-cr adf96a2b15 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:16:20 +01:00
feder-cr 2167538130 ci: the page and popup suites of 0.50.1 are required (wrapper.e2e.page 96, wrapper.unit.page 17), wrapper.unit.udp counts 113 after the merge 2026-11-12 02:56:16 +01:00
feder-cr 440bbb36e6 Merge branch 'release/0.50.1' into udp/wrapper-r3
# Conflicts:
#	src/invisible_playwright/_juggler/server.py
#	tests/test_every_route_command_is_answered_may_fail.py
2026-11-12 02:54:06 +01:00
feder-crandClaude Sonnet 5.5 2f153c76ff A download started by a popup that is not announced yet is reported on its opener, as Playwright reports it
- Browser.downloadCreated names the tab the download came from. A tab opened for an attachment (a target=_blank link, a window.open) never gets
  a Page.ready and the engine closes it at once, so it is not among the announced pages and the download was lost: no download event
  anywhere (a21e1de had it, on the popup). Playwright's ffBrowser._onDownloadCreated reports it on the opener of a page that is not
  reported yet; so does this, from the opener recorded when the target was attached (BrowserDispatcher._openers). The abort of the
  navigation that became the download still goes to the page that owns the frame.
- Tests: unit (red on fbceeaf); the e2e of the destinations and of the popup matrix of the fake-web branch (73f1e8d): 16 + 34 cases against
  the reference measured on stock Playwright 1.62 - on fbceeaf 4 of the 16 were red (the download), now 50 of 50 green.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-12 02:42:32 +01:00
feder-crandClaude Sonnet 5.5 fbceeafb65 A popup is reported on Page.ready as Playwright's is: no limit and no warning, with the address of the commit that came with the ready
- Stock Playwright 1.62 (measured): a 204 or a silent destination gives no page event, one that answers after 4 s gives it at 4 s with the
  destination already. The adoption of a popup waited 20 s and dropped it with a warning; now only a page a caller asked for
  (newPage) has the 20 s; a popup waits until the engine says Page.ready, the target goes away, or its context closes
  (BrowserDispatcher.end_waits_of), and says nothing.
- The ready and the commit of the document that made the page ready come in the same turn: the page is announced after a round trip to the
  engine (settle_events), so the frame reads the destination at the page event (3 of 4 slow popups said about:blank).
- In-process the slow popup arrived 0.9 s later than stock: it is the humanised click (1.1 s of pointer movement before the click returns),
  the popup arrives 4.02 s after the click in both modes.
- Tests: unit (limit None for a popup and 20 s for a requested page; a popup with no ready ends with its context and says nothing; the
  address at the page event is the commit's) red on b09d620; e2e (204 and silent: no event; 1.5 s: url is the destination; 25 s: reported
  then) in-process and through a served browser: the 25 s ones red on b09d620.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-12 02:19:46 +01:00
feder-crandClaude Sonnet 5.5 b09d620930 tests: the popup reaches the client from another site too (a link, noopener, window.open: 16 more cases, in-process and through a served browser)
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-12 01:11:02 +01:00
feder-crandClaude Sonnet 5.5 776c00afe2 tests: the stand-in pages say wait_until_ready; the popup e2e reaches the stock client as the other served tests do
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-12 00:58:07 +01:00
feder-crandClaude Sonnet 5.5 ba5b51cf91 A page is built at once and announced when the engine says Page.ready (the wait inside the constructor held a popup's first request behind a page that did not exist yet, and lost its commit and load)
- PageDispatcher no longer waits in __init__; wait_until_ready() is called by the adoption between the construction and the announcement
  (context 'page' event, newPage answer). A detach while waiting ends the wait; a page that is not ready in time is disposed.
- The main frame's initializer carries what the lifecycle already knows (url, name, load states), as every other frame's does.
- Tests: unit (a popup exists and listens while it waits; what it does before its ready reaches its frame; red on 6a60dce) and e2e
  (a popup of a link, noopener or window.open reaches an in-process and a stock client of a served browser within 2 s, with and
  without a context route; 15 of 16 red on 6a60dce, 16 green).

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-12 00:56:01 +01:00
feder-crandClaude Sonnet 5.5 14c24347c5 tests: h3 behind a proxy follows the definitive retail (never h3 at visit 1, h3 within 5 visits, h2 every visit without usable UDP)
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-12 00:38:20 +01:00
feder-crandClaude Sonnet 5.5 99c7fc93aa ci: the hosts-file e2e is required in wrapper.e2e.doh
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-12 00:33:20 +01:00
feder-crandClaude Sonnet 5.5 a61465b2be tests: the engine never reads the host's hosts file, with a proxy or without (MOZ_LOG per process, with a control)
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-12 00:33:16 +01:00
feder-crandClaude Sonnet 5.5 47536b5e64 tests: the refused-once e2e says what it measures and what it does not
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-12 00:33:16 +01:00
feder-crandClaude Sonnet 5.5 4f95aa3797 ci: the resolver-race and DoH-under-stress e2e (wrapper.e2e.doh, 17) and the FakeDoh levers unit tests (wrapper.unit.udp, 110) are required
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-12 00:27:45 +01:00
feder-crandClaude Sonnet 5.5 6a60dcebb7 tests: new_page and a popup are handed over only when the engine says Page.ready (red without the wait in PageDispatcher, green with it)
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-12 00:27:32 +01:00
feder-crandClaude Sonnet 5.5 7927e30679 tests: the refused-once e2e shortens the DNS negative cache, so it measures a temporary block and not Firefox's 60 s failure cache
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-12 00:27:13 +01:00
feder-crandClaude Sonnet 5.5 bf2a3c33b0 tests: the DoH of a proxied context when it is slow (2 s per answer) and when it refuses a name once; FakeDoh gains delay_s, delay_names and fail_first (written ahead of the engine)
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-12 00:27:13 +01:00
feder-crandClaude Sonnet 5.5 03d96a7baa tests: a context with a proxy resolves by DoH through it and a context without one never uses the DoH; the first navigation of a fresh context never asks the system resolver (written ahead of the engine)
The context-only test also asserts that the DoH log holds no name but the proxied context's, that no handshake failed and that the
default context's background lookups reach the system resolver (the trap, where it runs). New race test: eight contexts created
and navigated back-to-back, a launch-proxy variant, and a proxied context beside one without a proxy. The DoH e2e docstrings
follow the per-context rule.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-12 00:27:13 +01:00
feder-crandClaude Sonnet 5.5 7db28e4611 tests: the stand-in engine of the registry test says Page.ready, as the real one does (the page is handed over on it)
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-12 00:21:38 +01:00
feder-crandClaude Sonnet 5.5 f76240893e Pin invisible-core==62.65.0 (a page handed over when the engine says it is ready); changelog
The core that carries Lifecycle.wait_for_page_ready is invisible-core 62.65.0 (draft PR invisible_core#238), not on the index yet:
the pin check of this push is skipped on purpose (INVISIBLE_PIN_CHECK=skip).

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-12 00:14:02 +01:00
feder-crandClaude Sonnet 5.5 d5c0e410de The page dispatcher waits for Page.ready before the page is handed over (needs invisible-core with Lifecycle.wait_for_page_ready)
Same defect and fix as in the core's page (see the core commit): a goto sent right after new_page could meet the page's initial about:blank.
The pin of invisible-core moves with the core release that carries wait_for_page_ready.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-12 00:13:19 +01:00
feder-crandClaude Sonnet 5.5 422e675b86 ci: the context-only-proxy DoH e2e (wrapper.e2e.doh, 12) and the host-address helper unit tests (wrapper.unit.udp, 97) are required
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-11 23:36:39 +01:00
feder-crandClaude Sonnet 5.5 1c7bcf9dee tests: a context that is the only proxy resolves its names by DoH through it (red while TRR stays mode 0 for context-only proxies, green with engine 9bff9cf8de)
A session launched with no proxy, a context made with its own SOCKS5 gateway, a page at a name only the FakeDoh can resolve: the
name must be asked to the DoH by that gateway, the page reached by address through it, nothing to the DoH directly and no
question about the zone to the resolver of the machine. Review finding 4 (the e2e that was missing).

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-11 23:33:37 +01:00
feder-crandClaude Sonnet 5.5 84fd375562 ProxyEgressNonVerificabile: the docstring says what goes unconfirmed (timezone and locale), not an address
The engine no longer declares an egress address (the host network is drawn from the seed); only the timezone and the locale are
decided from the egress. Reworded like ProxyEgressDrifted, with a test on the text that fails on the old wording. Review
finding 30.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-11 23:33:24 +01:00
feder-crandClaude Sonnet 5.5 d596ee81c8 tests: one helper for the address of this host, computed before any server starts, a host without a default route skips
this_host_address() and its two copies connected a UDP socket to 192.0.2.1 and raised OSError on a host with no default route;
in the chain it was evaluated as an argument after the TURN server, the resolver and the page were already listening, so the
test errored and leaked three listeners instead of skipping. The helper is now tests/_host_address.py (OSError => pytest.skip),
the chain asks it first, and the three copies are gone. Review finding 29.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-11 23:33:24 +01:00
feder-crandClaude Sonnet 5.5 66d5090a0b tests: the declared-network e2e no longer sets variables the engine does not read
STEALTHFOX_WEBRTC_PUBLIC_IP and STEALTHFOX_WEBRTC_DISABLE_IPV6 are not read by the engine or the core (the unit test of the
declaration bans them in the environment); the e2e set and deleted them and imported _FAKE_EGRESS only for that. Dead setup
that said the egress still feeds WebRTC. Review finding 27.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-11 23:33:24 +01:00
feder-crandClaude Sonnet 5.5 3a1dc8df9b tests: the gather without a proxy and the ICE-name e2e wait for the engine that carries the UDP line
test_the_gather_is_real_without_a_proxy (in wrapper.e2e.udp) had no the_udp_line, unlike the other tests of its file, and the
ICE-name e2e (wrapper.e2e.doh) resolves a name through the proxy of a context, which the engine firefox-63 does. On an older
engine they skip with the reason; on the candidate (firefox-63-candidate) they run, so the exact lists of
ci/required-suites.json are unchanged. The networkidle e2e stays ungated: it needs no proxy and no UDP, and is fixed by the
Python of the core and the wrapper on any engine. Review finding 14.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-11 23:33:24 +01:00
feder-crandClaude Sonnet 5.5 5b87926543 ci: the warm-pool and the TURN-over-TCP e2e are required in wrapper.e2e.udp (61 tests)
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-11 23:29:44 +01:00
feder-crandClaude Sonnet 5.5 b396e055ce A TURN server over TCP is connected to and waited for, direct and behind SOCKS5 (e2e)
A TCP stand-in for a TURN server on this machine's address accepts, reads and closes N ms after the accept; the page asks for a
TURN allocation over TCP. A retail Firefox connects, sends the Allocate request and hears 701 when the server closes (accept
at 48 ms, 701 and the gathering complete at 850 ms with N=800). The candidate engine never connected: no accept, no bytes, 701 within
9-28 ms with the gathering complete, direct and through the gateway alike.

Red on the firefox-63 candidate build; green expected with the engine commit that binds the wildcard of the declared family.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-11 23:28:22 +01:00
feder-crandClaude Sonnet 5.5 68bb2b8e8f tests: the first datagram of a PeerConnection does not wait for a UDP association (red on the giro 2 binary: 396 ms)
The pool of UDP associations was warmed only in the process of the HTTP connections (the parent); the sockets of the PeerConnections
are made in the socket process, which found it empty and made its association from scratch: three answered steps before the first
STUN datagram. A gateway that answers every step after 130 ms makes it visible: on the giro 2 binary the first datagram leaves 396 ms
after the birth of the PeerConnection. The test asserts it leaves within 250 ms, and that an association was granted before.

The gateway of the tests now also keeps the wall-clock origin of its times and the instant of every accepted connection.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-11 23:27:55 +01:00
feder-crandClaude Sonnet 5.5 c14f2b1e9a ci: the ICE-name e2e is part of wrapper.e2e.doh (11 tests)
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-11 23:20:42 +01:00
feder-crandClaude Sonnet 5.5 bfedd53850 tests: the ICE server name of a PeerConnection is resolved in the context of its page, by the proxy of that context (red until the resolver carries the OriginAttributes)
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-11 23:20:03 +01:00
feder-crandClaude Sonnet 5.5 e868714339 tests: the h3 e2e turn off Firefox's check of third-party roots (a self-signed test server stops HTTP/3 otherwise: measured)
The Alt-Svc is learned and the QUIC handshake of validation passes with the override, then Firefox closes the connection itself because the chain
ends in a root it does not know, and every visit stays h2. With network.http.http3.disable_when_third_party_roots_found off the three visits read
h2, h3, h3 (3 runs of 3, no proxy, on the engine of the first round).

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-11 23:15:44 +01:00
feder-crandClaude Sonnet 5.5 36ecd11e99 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 80672c69a3 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 22:59:17 +01:00
feder-crandClaude Sonnet 5.5 a21e1decb9 tests: the descriptors of the spawn are asserted by running it, not by reading the core's source
test_the_spawn_keeps_the_two_hardwired_descriptors asserted that the source of the core's _spawn_posix contains
`pass_fds=(its_read, its_write, 3, 4)`. Core 62.64.0 starts the engine with posix_spawn and file actions, so the words are gone
and the test failed on every Linux unit suite although the behaviour is the same (and better).

The test now runs the spawn: a parent with nothing open on 3 and 4 and its pipes far from them launches a program that reads
fd 3 and answers on fd 4 (the contract of nsRemoteDebuggingPipe.cpp), and the answer must come back and the child must hold no
descriptor above 4 of the parent's. Same shape as the core's own test
(test_the_pipe_of_the_engine_reaches_its_fixed_descriptors). No skip: the file is already POSIX-only.

The other tests of the file do not read source text (checked: no getsource/inspect/read_text left).
Ran the parent program on Linux with core 62.64.0 (image tetra-invisible:run1b-final): pong:ping:0.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-11 22:59:15 +01:00
feder-crandClaude Sonnet 5.5 ecf384a923 ci: the no-proxy gather is a required test of wrapper.e2e.udp (58 tests)
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-11 22:58:25 +01:00
feder-crandClaude Sonnet 5.5 a8cc2c842e A keepalive fetch is a request of the page for the client, in a real browser
e2e: the page sends a plain fetch, a keepalive fetch (cors and no-cors) and a beacon; the client must hear a `request`
for each and an end for each. Measured on the firefox-62 engine: the server received the keepalive fetches and the client
heard no `request` for them (stock Playwright's Firefox reports them). Red until the engine attributes the request to
its page.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-11 22:44:20 +01:00
feder-crandClaude Sonnet 5.5 5da874d67f tests: HTTP/3 is judged on three visits of one page (h2, h3, h3 with UDP free; h2 three times without), as a retail Firefox reads them
Reference: retail 159 Linux, 15 of 15 each way (invisible_WebRTC captures/h3-fallback): with
UDP free the first visit is h2 and the second and third h3; with UDP dropped every visit is
h2 and the later loads are as fast as the first.

- _h3_server: the TCP side speaks HTTP/2 by ALPN (h2 library; HTTP/1.1 only for a client that
  offers nothing else), carrying Alt-Svc: h3; it answered HTTP/1.1 only, so the first visit
  could never read h2. One HTML document over TCP and QUIC; tcp_alpn recorded.
- test_http3_through_the_proxy_e2e: the retail method (one context, three gotos, a pause of 2 s
  after each load, nextHopProtocol of the navigation entry) on six roads: no proxy and a SOCKS5
  with coherent UDP -> h2,h3,h3 (QUIC through the relay, the server never sees this host);
  SOCKS5 that refuses UDP / leaves from another address / never answers (the declared udp is
  asserted) and an HTTP proxy -> h2,h2,h2, no QUIC at the server, no page datagram at the relay,
  visits 2 and 3 no more than 1.5 s slower than visit 1. An h3 on visit 1 is named as an error.
- _udp_line: expected_protocols / judge_visits (the sequence and the judgement, unit-tested).
- test_the_h3_line_helpers (unit): the server really negotiates h2, says Alt-Svc, answers the
  same document over h3; the judge names each mistake.
- ci/required-suites.json: wrapper.e2e.udp 53 -> 57 (the http3 file has 6 tests, was 2).

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-11 22:43:33 +01:00
feder-crandClaude Sonnet 5.5 f3e3ce164d tests: the e2e of the UDP relay hand the core the STUN server its gateway answers (udp_stun_servers), and the dropped-UDP cases expect the new behaviour
The core now MEASURES the UDP exit of a SOCKS5 proxy before declaring it; only `coherent`
makes the engine send UDP to the relay. A gateway of the tests that is not asked the right
way is declared `no` and its e2e would fail for a reason that is not the product's.

- _socks_servers: MEASURE_NUMBER (the fake STUN by a number of its own, so the measurement
  is told apart from the page's STUN_NUMBER), Gateway.measure_servers, silent_udp() (relay
  granted, STUN never answered -> unmeasured), relay_host on every factory.
- _udp_line (new): measure_servers, egress_by_proxy (the TCP exit of each gateway: a context
  proxy is measured against its own), declared_udp (what the launch measured; absent is not
  `unmeasured`), one place for every e2e.
- test_webrtc_realness: one launch helper behind a gateway; the relay tests, the two-contexts
  and the TURN-over-TCP tests use the exits of their own gateways; the dropped-UDP case is one
  helper with three roads (refused: no, another exit: no, never answered: unmeasured) that
  asserts the declared udp, no srflx, 701, and that the page's UDP never reached the relay.
- test_the_whole_udp_chain_by_name_e2e: the chain is told its own TCP exit (it was a
  documentation address the chain's UDP does not leave from, i.e. `no`) and asserts coherent.
- test_the_udp_line_helpers (unit): the real measurement of the core against each gateway
  and the chain; the helper's list is `ip:port` IPv4 literals the core takes.
- ci/required-suites.json: wrapper.e2e.udp 51 -> 53 (two new tests, listed by name).

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-11 22:38:12 +01:00
feder-crandClaude Sonnet 5.5 2329dc6c1c wrapper: the STUN servers are a launch parameter kept on the session (udp_stun_servers); the caller never declares udp
- InvisiblePlaywright(..., udp_stun_servers=None) (sync and async) and launch_server(...,
  udp_stun_servers=None) take "ip:port" IPv4 literals (None = the core's two public defaults;
  a name or a bad port raises ValueError naming the parameter) and keep them on the session.
  The launch's geo step uses them, and so does every later new_context(proxy=...): the server
  keeps the list on the browser it launches (the list rides to the server in the launcher's
  composed prefs like the session seed and is taken out before the profile is written), so the
  per-context call needs no new parameter. Nothing of it reaches the browser's environment,
  argv, prefs or pipe (tested).
- The proxy command is built by the core's context_proxy_command / launch_proxy_command: the
  `udp` field is the measurement, never what the caller wrote; configure_proxy(udp=) is gone
  and the launch's measure reaches Browser.setBrowserProxy through the core's per-proxy memory.
- The constructor-signature pin records the new keyword.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-11 22:27:14 +01:00
feder-crandClaude Sonnet 5.5 52e520dd92 wrapper: a proxy given to a context declares its measured UDP exit (udp) in Browser.setContextProxy
The core measures where a SOCKS5 proxy's UDP leaves from and the answer is the optional
field `udp` of the proxy declaration. The wrapper hands it on:

- the launcher, the async launcher and launch_server pass the udp their geo step measured
  to configure_proxy(udp=), so it reaches Browser.setBrowserProxy;
- the server's launch (a client that composed no session) declares the proxy with what the
  geo step remembered, never coherent without a measurement;
- BrowserDispatcher._apply_context_options, the one place new_context(proxy=...) of the sync,
  async and remote clients ends in, measures the context proxy BEFORE Browser.setContextProxy
  is sent (the core discovers the TCP exit through it and measures the UDP beside it, once per
  proxy, cached by endpoint and a hash of the credentials) and the result goes in `udp`.

Tests: a recorder in place of the engine, the fake SOCKS5 gateway with a UDP relay and a STUN
server only the relay reaches, declared through STEALTHFOX_UDP_STUN_SERVERS.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-11 22:27:13 +01:00
feder-crandClaude Sonnet 5.5 73c070ebb1 wrapper: every context carries the position the core declares for the session
The geo step is asked with the session seed (launcher, async_api, the served
browser, the default session) and the core's SessionGeo.geolocation_override()
(latitude, longitude, accuracy) becomes the standard `geolocation` context
option in _default_context_kwargs: the default context, each new_context /
new_page and each context of a remote client get Browser.setGeolocationOverride
through the existing path (server.py _apply_context_options). A geolocation given by the
caller wins; no coordinates, nothing is sent; the permission is never granted
here. Tests written ahead: tests/test_the_session_position_reaches_every_context.py.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-11 22:27:00 +01:00
feder-crandClaude Sonnet 5.5 1d564f5732 A route answer the engine refuses is the engine's business, whatever its wording
The server took one wording ("Cannot find request") of an answer to a closed request as done and passed every other
protocol error up to the client. The engine also says "NS_BINDING_ABORTED
[nsIInterceptedChannel.resetInterceptionWithURI]" when the channel was cancelled while the answer was on its way: the
same event, and the client kept it as the error of the connection and raised it on its next route command.

Stock Playwright sends the three interception commands as may-fail and tells the client nothing, whatever the engine
says. So does RouteDispatcher._send now: every ProtocolError is swallowed, the route is disposed after it.

Tests: the static guard no longer allows a re-raise inside the handlers; a unit test feeds three wordings (red on the
old code for two of them).

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-11 21:20:59 +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-cr 8c92c764b7 Merge #392 (docs: the agent links and the command name the MCP repo as it is now) into the 0.50.1 release 2026-11-11 20:22:43 +01:00
feder-cr 000fa7a3ad Release 0.50.1: pin invisible-core 62.64.0; CHANGELOG for the networkidle fixes
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
(cherry picked from commit e63ef8e61ea42e7f8df7c1bde206f3bf86fc18f7)
2026-11-11 20:22:42 +01:00
6a5b7e014a tests: answering a route the next navigation already aborted does not raise (the case of #351: the favicon of the page just left)
Sixty sequential routed gotos on a loopback page: 4-12 of them failed on the old server, every failing continue_ being
the previous document's favicon, aborted by the next navigation while the route sat with the handler. Red on main (in-process
path), green with the fix of RouteDispatcher._send.

Co-authored-by: Richard Powell <1369873+richardpowellus@users.noreply.github.com>
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-11 20:22:29 +01:00
feder-cr b78c5bb67c 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>
(cherry picked from commit 91223226f5bba25edff9af0e8b1fd6b5bfea2227)
(cherry picked from commit 612b18c02b95e9b5833d62b6595d4a0ff324aac2)
2026-11-11 20:22:14 +01:00
228576009b 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 favicon of the page a goto just left). The engine takes the request out of its held set at once and the
late continue/abort/fulfill meets "Cannot find request" or NS_BINDING_ABORTED. 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; green after), and a static guard that every op of RouteDispatcher goes through _send and that _send
swallows exactly those two. The same defect was found a month earlier by richardpowellus (#351), with the favicon of the
previous page: his test is added in the next commit.

Co-authored-by: Richard Powell <1369873+richardpowellus@users.noreply.github.com>
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-11 20:22:14 +01:00
feder-cr bc816cb1ae 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>
(cherry picked from commit 47182f0cd85fea08fc45e36f1c91d2d570722f14)
(cherry picked from commit e46f2dcf3eb361e6af0fedcdf6e1189f0ac330b6)
2026-11-11 20:22:14 +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-cr cbd9f5db5b Merge the process-counting e2e (#451) into the 0.50.1 release 2026-11-11 20:15:37 +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
feder-crandClaude Opus 5.5 fef0bc5ea7 tests: the same-site control puts its frame in the shown page; CHANGELOG: 0.50.0's entry is 0.50.1's
The e2e of #451 saw a new "Isolated Web Co" once after a.test/plain -> a.test/same-site ([10878] -> [10878,
11208]). Not a process of an earlier test: it was created after the first read and only this worker's
descendants are counted. It is the top-level navigation: when the old document may enter the back-forward
cache, the browsing context is replaced (mReplaceBrowsingContext, dom/ipc/ProcessIsolation.cpp) and the new
one may be placed in another process of the same site (dom.ipc.processCount.webIsolated = 4). Measured on
firefox-62 (candidate #6, Linux): 0 of 30 runs alone (bfcache on and off), 0 of 57 under 4 workers. The test
was written for the frame, so the frame is now added to the page already shown and the top never navigates:
20 of 20 runs green.

0.50.0 never reached the index, so the changelog gate refused its heading; its entry now opens 0.50.1.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-11 14:47:54 +01:00
feder-crandClaude Opus 5.5 2bc12eb80b Release 0.50.1: 0.50.0 with the process-counting e2e corrected (0.50.0 never reached the index)
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-11 13:59:28 +01:00
feder-crandClaude Opus 5.5 ff2123ef58 tests: a closed context is checked for the processes of its sites, not for every content process
test_closed_contexts_with_a_never_stopping_service_worker_leave_no_process was red on the e2e of the 0.50.0
tag ([2, 2, 2, 5, 5], 5 <= 2). Measured on firefox-62 (Linux), the test's own scenario 10 times with every
process named: no "Isolated Web Co" left after any close; the 3 more are "Web Content", the engine's pool of
preallocated processes filling up behind the closed contexts (5 runs of 10, new pids each time). Not a leak:
the count read the refill.

The helper of the bench moves to tests/_processes.py and both tests use it. The context test counts the
processes that host a site: at least one while the page is open (or the count proves nothing), none a few
seconds after `close` answers (the engine waits for them inside close and kills the ones that stay). Off
Linux it skips, as the bench's two counting tests do: no other system names the process.

Unit tests (tests/unit/test_processes_counts_sites.py) from the measured processes, the closed-context case
included. e2e on firefox-62 (candidate #6, Linux): the context test 10 of 10; run_e2e.py on the two files and
the unit test 18 passed. The old counter, same scenario: 5 of 10 runs would fail.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-11 13:40:29 +01:00
feder-crandClaude Opus 5.5 5402da4d80 tests: the Fission bench counts the processes that host a site, not every new content process
test_same_site_other_port_stays_in_process was red on the e2e of the 0.50.0 commit ("a same-site frame
started a process: [13443]"): the bench counted every `-contentproc ... tab` pid, and the engine starts a
preallocated content process to refill its pool whenever it gets to it. On Linux the engine names a content
process by its remote type (ContentChild::SetProcessName, prctl PR_SET_NAME): "Isolated Web Co" once it
hosts a site of strategy 1, "Web Content" while preallocated. Measured on firefox-62: a cross-site frame
renames a preallocated process and a new "Web Content" refills the pool; a same-site frame changes neither.
The two tests that count processes skip off Linux, where no process carries a name.

Unit test with the measured processes: 3 red on the old bench, 3 green here. e2e on firefox-62 (candidate
#6, Linux): the bench file 17 passed; the two counting tests 15 of 15 runs green.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-11 13:18:54 +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
feder-crandClaude Opus 5.5 c23612e295 test: the docs name the MCP server's repository and command as they are now
feder-cr/AIHawk now leads to an unrelated repository and answers 200, which no
link checker reports; `uvx aihawk` does not exist. The README and docs/ are
read for both.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-06 19:49:05 +01:00
feder-cr 11b9e08b1a docs: the agent links and the command name the repo as it is now
Two things were broken for a reader on main, not one.

Thirteen links pointed at github.com/feder-cr/AIHawk. GitHub redirects a
NAME to the OBJECT that carried it, not to the content: after the September
swaps that name belongs to invisible_dots, which has seven wiki pages, so
AIHawk/wiki/<page> lands on its wiki Home. It answers 200 with different
content, which means a reader who clicks does not find the page and a search
engine sees a soft-404 across about 150 indexed URLs.

Seven occurrences said `uvx aihawk`, a command that does not exist. One sat
in a front-matter description, which is the snippet search engines show, and
one in a block meant to be copied: `claude mcp add stealth -- uvx aihawk`.
The command is invisible-playwright-mcp, on PyPI at 0.70.16.

All eight link targets were checked one by one and resolve to themselves with
the page title, no redirect.

Three things stay as they are, which only reading them showed. The
`pip install invisible-playwright` line matches what this engine's own README
teaches for the library, so the page is consistent rather than broken.
CHANGELOG.md keeps the old name because a changelog entry says what was true
then. And the fixture in scripts/sync_article_pixels.py keeps it because it is
the deliberate wrong case, a pixel for ANOTHER repo.

One sentence went away instead of being renamed: "shipped inside AIHawk" made
sense when AIHawk was the larger product containing the server. The server and
the repository are now the same thing, so "shipped inside itself" was circular.

(cherry picked from commit d9c8e46dce)
2026-11-06 19:47:58 +01:00
210 changed files with 31695 additions and 3186 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
+56 -8
View File
@@ -34,18 +34,35 @@ on:
- 'docs/**'
- 'LICENSE'
workflow_dispatch:
inputs:
only:
description: "Which job. `windows-control-a` runs only the Windows job of the keyboard shortcut (after the core of a release is on the index and its engine is published); `all` runs the whole workflow."
required: false
default: "all"
type: choice
options:
- all
- windows-control-a
permissions:
contents: read
# One run of this workflow per branch at a time. A newer push cancels the older
# in-flight run as a whole, cleanly, instead of leaving its queued jobs to be
# cancelled one by one - which left the run marked failed even though nothing
# had actually failed. Keyed by workflow + ref so tests and e2e never cancel
# each other; only an older run of THIS workflow on the same branch is replaced.
# A newer push to a pull request cancels the older in-flight run of THIS
# workflow on that pull request as a whole, cleanly, instead of leaving its
# queued jobs to be cancelled one by one - which left the run marked failed even
# though nothing had actually failed. Keyed by workflow + pull request number,
# so tests and e2e never cancel each other.
#
# NEVER on main. The release gate (scripts/e2e_is_green.py) asks for the e2e
# check-run of the commit being tagged, and a cancelled one refuses the release:
# with the group keyed by ref, the next push to main cancelled the run of the
# commit before it. Outside a pull request the group is unique to the run
# (`github.run_id`), so every commit of main keeps its own finished run, and a
# pending run is not replaced by a newer one either (a group with a fixed name
# drops the older pending run, cancel or not).
concurrency:
group: ${{ github.workflow }}-${{ github.ref }}
cancel-in-progress: true
group: ${{ github.workflow }}-${{ github.event_name == 'pull_request' && format('pr-{0}', github.event.pull_request.number) || github.run_id }}
cancel-in-progress: ${{ github.event_name == 'pull_request' }}
# Engine and GeoIP downloads go through the release API with this token.
# Anonymous requests share a 60-an-hour limit per runner address and are the
@@ -67,7 +84,7 @@ jobs:
e2e:
name: e2e (linux, xvfb)
needs: core-on-index
if: needs.core-on-index.outputs.available == 'true'
if: needs.core-on-index.outputs.available == 'true' && inputs.only != 'windows-control-a'
runs-on: ubuntu-24.04
timeout-minutes: 40
steps:
@@ -163,3 +180,34 @@ jobs:
path: ${{ runner.temp }}/e2e-watchdog.log
if-no-files-found: warn
retention-days: 14
# ``Control+A`` selects all in a field, on the PUBLISHED engine and the core this package pins, on Windows, where the keyboard of a real
# user is: the shortcut letter used to reach the browser as Control+Shift+A (invisible-core 63.66.0 fixes it). The e2e is red on the
# keyboard that held Shift for the capital A (tests/test_control_a_selects_all_in_a_field_e2e.py: 5 ways to press it x an <input> and a
# <textarea>, in-process and served to the stock Playwright client). Same gate as the Linux job: it is SKIPPED, with the reason in the
# summary, until the core is on the index, and it runs unchanged after; `workflow_dispatch` with `only: windows-control-a` runs it alone.
e2e-windows-control-a:
name: e2e (windows, Control+A)
needs: core-on-index
if: needs.core-on-index.outputs.available == 'true'
runs-on: windows-latest
timeout-minutes: 20
# `run:` blocks are PowerShell on Windows unless said otherwise (e2e-hunt.yml had a ParserError on its first launch there).
defaults:
run:
shell: bash
steps:
- uses: actions/checkout@34e114876b0b11c390a56381ad16ebd13914f8d5 # v4
with: { fetch-depth: 1 }
- uses: actions/setup-python@a26af69be951a213d495a4c3e4e4022e16d87065 # v5
with: { python-version: '3.11' }
- name: Install wrapper + test deps (the stock client is in the dev extra)
run: |
python -m pip install --upgrade pip
python -m pip install ".[dev]"
- name: Fetch the published firefox binary
run: echo "FF=$(python -m invisible_playwright fetch | tail -1)" >> "$GITHUB_ENV"
- name: The keyboard shortcut selects all (the browser opens on the runner's desktop, as in e2e-hunt.yml)
env:
PYTHONUNBUFFERED: "1"
run: INVPW_BINARY_PATH="$FF" python -u -m pytest -m e2e -p no:cacheprovider -v tests/test_control_a_selects_all_in_a_field_e2e.py
+4 -1
View File
@@ -51,9 +51,12 @@ on:
permissions:
contents: write
# A publishing workflow is never cancelled half-way: the second run waits for
# the first (a newer pending run replaces an older pending one, which is
# harmless: the wiki is rebuilt in full from the repository each time).
concurrency:
group: publish-wiki
cancel-in-progress: true
cancel-in-progress: false
jobs:
publish-wiki:
+5 -2
View File
@@ -15,9 +15,12 @@ permissions:
# cancelled one by one - which left the run marked failed even though nothing
# had actually failed. Keyed by workflow + ref so tests and e2e never cancel
# each other; only an older run of THIS workflow on the same branch is replaced.
# A newer push to a pull request cancels the run it supersedes. Never on main:
# outside a pull request the group is unique to the run (`github.run_id`), so
# every commit of main keeps its own finished run (see e2e.yml for why).
concurrency:
group: ${{ github.workflow }}-${{ github.ref }}
cancel-in-progress: true
group: ${{ github.workflow }}-${{ github.event_name == 'pull_request' && format('pr-{0}', github.event.pull_request.number) || github.run_id }}
cancel-in-progress: ${{ github.event_name == 'pull_request' }}
# Engine and GeoIP downloads go through the release API with this token.
# Anonymous requests share a 60-an-hour limit per runner address and are the
+31 -24
View File
@@ -72,9 +72,11 @@ on:
permissions:
contents: read
# Only a new push to a ledger pull request cancels the run it supersedes. The
# weekly schedule and a manual run (both on main) never cancel each other.
concurrency:
group: user-install-${{ github.ref }}
cancel-in-progress: true
group: ${{ github.workflow }}-${{ github.event_name == 'pull_request' && format('pr-{0}', github.event.pull_request.number) || github.run_id }}
cancel-in-progress: ${{ github.event_name == 'pull_request' }}
jobs:
install:
@@ -107,43 +109,48 @@ jobs:
# 0.2.5. The job reported a forgotten publish that had happened two minutes
# earlier, which is the most expensive kind of red: it looks exactly like the
# real defect this workflow exists to catch.
# MEASURED AGAIN 2026-11-12 (0.50.1, ledger #476): the per-version JSON endpoint
# of PyPI answered at once, `pip index versions` listed 0.50.1, and the
# `pip install --upgrade` of the Linux job still resolved 0.49.1 (the Windows job,
# started later, was green). Those are three different pages of the index, and
# the job only needs the one pip installs from.
#
# Bounded at five minutes, so a genuinely forgotten publish still fails. The
# PER-VERSION endpoint is the authority; the aggregate `info.version` lags it
# by minutes and has its own trap, so this asks for the exact URL.
# So the question asked here is pip's own: `pip download invisible-playwright==X`,
# the same client, the same index, no cache. Bounded at ten minutes: a forgotten
# publish still fails, and it fails HERE, saying that the index does not have the
# version, instead of three steps later as a test that compares two versions.
#
# Only on the ledger pull request. A scheduled or dispatched run is not
# racing anything, and a wait there would hide a real absence behind five
# racing anything, and a wait there would hide a real absence behind ten
# minutes of polling.
- name: wait for the index to serve this version
if: github.event_name == 'pull_request'
shell: bash
run: |
python - <<'PY'
import json, os, sys, time, tomllib, urllib.error, urllib.request
import os, subprocess, sys, tempfile, time, tomllib
dist = tomllib.load(open("pyproject.toml", "rb"))["project"]["name"]
version = tomllib.load(open("pyproject.toml", "rb"))["project"]["version"]
url = f"https://pypi.org/pypi/{dist}/{version}/json"
deadline = time.monotonic() + 300
deadline = time.monotonic() + 600
deadline = min(deadline, time.monotonic() + float(os.environ.get("INDEX_WAIT_SECONDS", "600")))
poll = float(os.environ.get("INDEX_WAIT_POLL", "15"))
n = 0
said = ""
while True:
n += 1
try:
with urllib.request.urlopen(url, timeout=30) as r:
if json.load(r).get("urls"):
print(f"::notice::{dist} {version} is on the index (attempt {n})")
sys.exit(0)
except urllib.error.HTTPError as e:
if e.code != 404:
print(f"::warning::index returned HTTP {e.code}; not waiting further")
sys.exit(0)
except OSError as e:
print(f"index unreachable ({e}); retrying")
if time.monotonic() >= deadline:
print(f"::warning::{dist} {version} still not on the index after 300s; "
f"running the checks anyway so a real absence is reported")
r = subprocess.run([sys.executable, "-m", "pip", "download", "--no-deps", "--no-cache-dir",
"--disable-pip-version-check", "--quiet", "-d", tempfile.mkdtemp(),
f"{dist}=={version}"], capture_output=True, text=True)
if r.returncode == 0:
print(f"::notice::pip downloads {dist} {version} from the index (attempt {n})")
sys.exit(0)
time.sleep(10)
said = (r.stderr.strip().splitlines() or [""])[-1]
if time.monotonic() >= deadline:
minutes = int(float(os.environ.get("INDEX_WAIT_SECONDS", "600")) // 60) or 1
print(f"::error::the index does not have {dist} {version} yet, after {minutes} minutes "
f"and {n} attempts (pip said: {said})")
sys.exit(1)
time.sleep(poll)
PY
- name: Linux runtime libraries for the browser
+212 -1
View File
@@ -6,6 +6,216 @@ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/),
## [Unreleased]
## [0.51.0] - 2026-11-12
### Changed
- Engine firefox-63 through invisible-core 63.66.0, which this version pins. Behind a proxy: names are resolved by the browser's own
DNS-over-HTTPS through the proxy (not by the machine's resolver; checked with a resolver trap on Linux), WebRTC and HTTP/3 send
their UDP through the proxy's relay when its UDP was measured to leave from the same address as its TCP, and a proxy whose UDP
does not hold (including one whose UDP leaves from another address) is treated as a router that drops it (HTTP/3 falls back to
HTTP/2, ICE gathers no server-reflexive candidate). A proxy given to a context declares its own measured UDP exit. The interface
list WebRTC gathers is the network the session declares.
- A STUN server list can be given at launch (`udp_stun_servers`) for the measurement of the proxy's UDP.
- Every context carries the position the core declares for the session (the geolocation override of the context).
- The package's launcher and server refuse the two prefs that govern the launch counter, `invisible_firefox.usage_ping.enabled` and
`invisible_firefox.usage_ping.url`, in `extra_prefs` (and in the `firefoxUserPrefs` of a served launch). The engine counts launches with
an anonymous GET to the `usage-counter` release of the engine's repository (`feder-cr/firefox_antidetect_patch`).
### Added
- `preload_newtab=False` turns off the preloaded New Tab page, on request only (`InvisiblePlaywright`,
`invisible_playwright.async_api.InvisiblePlaywright` and `launch_server`): by default the browser keeps it, as a retail Firefox does.
A retail Firefox keeps the New Tab page ready in a content process of its own; with the option it is not started. `None` writes
nothing, `True` says the retail value aloud, and a `browser.newtab.preload` in `extra_prefs` wins over it. Needs invisible-core
63.66.0. Measured on Windows (run 43211271731), on an engine build of the firefox-63 candidate line (not the published engine), one
page of a site, five alternating runs: the browser's processes together take 448-454 MB as shipped and 231-239 MB with the option
(private memory 301-307 against 158-171 MB).
### Fixed
- A request the browser resumed and whose channel is replaced and cancelled before the replacement starts (a `fetch` with
`keepalive`, a beacon) is reported as failed, so it no longer keeps `networkidle` from arriving (engine firefox-63).
- A navigation the page overtakes (`location.replace`) ends, and the document that overtook it is told (engine firefox-63).
- A click in a frame under a CSS transform is mapped back to the point the frame shows, and a click in a frame scrolls the
element in even when its point is inside the main viewport (invisible-core 63.66.0).
- `request.resource_type` agrees with the pinned driver: a beacon is `beacon` and a CSP report is `cspreport` (it said `other`).
- A download whose finish is seen before its announcement is marked finished: `save_as`, `path` and `failure` used to wait for ever on it.
The early finishes the browser keeps are bounded (64) and forgotten with their context. (That the engine sends a finish before the
announcement is not proven; the path is defensive.)
- The opener kept for the downloads of a target whose adoption failed lives until the engine detaches the target, and none is
made for a target already detached.
- Tests only: the end-to-end tests that look at content processes ask for the processes of a site by its name and no longer compare two counts.
### Known differences from stock Playwright
What a script that drives the browser can observe, from the configuration of Playwright's own Firefox and of a retail Firefox (no
comparison run is saved). The result of a `window.open` (`null` or a window) is read by the page; the others are what the script sees.
- **A `window.open` from a script with no user gesture is blocked, as in a retail Firefox.** Playwright's own Firefox turns the popup
blocker off (`dom.disable_open_during_load` false in its `playwright.cfg`); a retail Firefox keeps it on, and so does this browser. So
`page.evaluate("window.open(url)")` returns `null` to the page and no `page` event comes; the same `window.open` from a click opens
the popup on both. To get stock's behaviour: open the popup from a click; or pass
`extra_prefs={"dom.disable_open_during_load": False}` for the session, knowing that a page then sees a browser that differs from a
retail Firefox.
### Known issues
- **A popup opened without a route can be announced while it is still on `about:blank`.** A popup opened with no route on the context
(a `target=_blank` link, or `window.open` from a click) can be announced to the client while it is still on `about:blank`; its `url`
then stays `about:blank`, or its `load` never arrives. Seen on a Windows runner with the library's client in the same process and four
workers running the popup tests in parallel (`test_popups_reach_the_client_e2e.py`, 20 runs): with the firefox-63 engine 17 cases of 640
in 12 of 20 runs; with the published firefox-62 engine (so also with 0.50.1) 15 cases of 640. On Linux (the firefox-63 engine) 0 red in
20 runs. In the last two runs with Playwright's own client over a served browser none was red. The defect is in the hand-over of the popup's page in this
package, not in the engine; the correction is in 0.51.1. Not measured: a served launch with numbers of its own, other machines, a run
without parallel workers, macOS.
## [0.50.1] - 2026-11-12
0.50.0 was tagged and never published: its end-to-end gate was red on two tests that counted processes.
0.50.1 is 0.50.0 with those tests corrected.
### 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
- `goto(wait_until="networkidle")` arrives on a page that is reused for many addresses, and on a served browser whose
context routes every request, as with a stock Firefox. Two causes, both ours. A route answered after the browser had
already closed its request (a fetch the page aborted, an image it replaced, an iframe it removed, a beacon cancelled
with its document) came back to the client as an error, which the client kept for the whole connection and raised on the
next route command; that command was never sent, its request stayed held in the engine, and so on down the page. The
server now takes such an answer as done, whatever wording the engine gives it ("Cannot find request", or "NS_BINDING_ABORTED"
when the channel was cancelled while the answer was on its way), as Playwright's own server does. The same defect was found a month earlier by richardpowellus
(#351), on the favicon of the page a `goto` had just left; his test is part of this release. And the core counted the requests in flight
with one integer per page, never reset by a navigation, so one request whose end never arrived kept every later address
from going idle (invisible-core 62.64.0 keeps them by request id, per document, and does not keep the requests of a
frame that already left: a beacon sent at `pagehide` is announced after its frame is gone).
- A `goto` sent right after `new_page` is no longer "interrupted by another navigation to about:blank" on a loaded machine. The page was
handed to the caller as soon as its main frame was announced, while the engine had not yet committed the page's own initial
`about:blank`; a navigation answered before that commit lost to it. The page is now handed over when the engine says it is
ready (`Page.ready`), as Playwright's own page is (invisible-core 62.65.0, `Lifecycle.wait_for_page_ready`; a page closed before
it was ready ends the wait with an error at once).
- 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.
- The end-to-end tests that count content processes count the ones that host a site, not every content
process that is new. The engine keeps a pool of preallocated processes and refills it whenever it gets
to it, so a refill landing between two reads looked like a process the test had caused (a same-site
frame, a closed context with a service worker that never stops). Measured on firefox-62: a closed context
leaves no process of its site. On Linux the process is named by the site it hosts; elsewhere these
tests skip.
- A popup (a `target=_blank` link, `window.open`) reaches the client as it does with Playwright's own Firefox: when its
destination answers, with no limit of time, with the destination's address as its url, and with `load` reachable on
it. It used to be given up on after 20 s, could be announced with `about:blank` as its url, and about one in a
hundred was never announced. A destination that never becomes a page (a 204, a server that never answers) is not
announced, as on stock. Measured against stock destination by destination, with answers after 4 s and after 25 s: 18
cases of 18; and 128 popups announced of 128 across the two transports (the library client, a stock client over
`launch_server`).
- For a popup whose answer is a download, the opener's `download` event comes after the popup's `page` event, as on
stock. With little CPU the download could arrive and the page never be announced. Measured on a runner limited to
one CPU: 8 runs red of 10 before, 0 of 10 after.
### Known differences from stock Playwright
Measured against Playwright's own Firefox with the same script, on this version. None of them is a value a page
reads; they are what a script that drives the browser can observe.
- **The url of a popup that turns into a download.** A link or a `window.open` whose answer is an attachment gives, as on
stock, a `page` event, a `download` event on the opener, and a popup that closes at once. The popup's `url` at the `page`
event is `about:blank` here and the empty string on stock. Measured: 8 cases of 8 (link and `window.open`, the library
client and a stock client over `launch_server`), against 4 of 4 on stock.
- **The url of a frame of another site at the page's `DOMContentLoaded`.** A frame of another site runs in another process,
as in a retail Firefox, and commits its navigation after the page's `DOMContentLoaded`; stock Playwright keeps frames in
the page's process. So `frame.url` read right after `goto(..., wait_until="domcontentloaded")` can be the empty string.
After `load` it is always set. Measured, 30 runs each: after `load` the url was there 30 times here and 30 on stock; at
`DOMContentLoaded` once here and 30 times on stock. Wait for `load`, or for the frame's own navigation, before reading it.
- **A click takes longer with the library client.** From `click()` on a link to the `page` event of the popup it opens:
0.8 to 1.7 s more than stock with the library client, and the same as stock (within 0.1 s) with a stock client over
`launch_server`. Measured on 64 popups per transport and on destinations that answer after 4 s and after 25 s. The
same run with `humanize=False` was not measured.
- **Back and forward restore the page from the back-forward cache.** As in a retail Firefox, `go_back` and `go_forward`
bring the page back as it was; Playwright's own Firefox loads it again. So a script that runs when the page loads does
not run again here. Measured on a 17-step journey with the same script on both: on its three back and forward steps
the page's load-time requests were sent again on stock (6 beacons each) and not here (0, 2 and 0, the two being the
ones a page sends when it is left); every step ended on the same page, and the other 14 steps sent the same requests.
## [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
@@ -2020,7 +2230,8 @@ browser reads that decision.
repository that builds and ships the engine. The engine's compiled default
says the same from the next build. Engines older than firefox-21 do not read
the pref and are not counted. To opt out of the ping, set
`invisible_firefox.usage_ping.enabled` to `False` in `extra_prefs`.
`invisible_firefox.usage_ping.enabled` to `False` in `extra_prefs`. (Since 0.51.0 this is no longer possible: the
counter cannot be turned off or redirected.)
- **The `browser launches` badge is back.** It was removed in 0.7.2 because the
counter behind it lived on a repository that had been deleted, so the badge
would have redrawn a frozen number every morning. The counter has lived on
+2436
View File
File diff suppressed because it is too large. Load diff
+60 -8
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=`:
@@ -165,6 +214,11 @@ not carry raises, and the error lists the ones it does.
Full list of pinnable keys, how pinning interacts with the Bayesian sampler, and common patterns are in **[docs/pinning.md](docs/pinning.md)**.
### Launch counter
The engine counts launches with an anonymous GET to the `usage-counter` release of the engine's repository (`feder-cr/firefox_antidetect_patch`) on GitHub. This package's launcher and server refuse the two prefs that govern it, `invisible_firefox.usage_ping.enabled` and `invisible_firefox.usage_ping.url`, in `extra_prefs`.
---
## CLI
@@ -184,11 +238,11 @@ invisible-playwright version # wrapper, core and engine versions, and where the
**If you would rather prompt than script.** This page is the engine, as a Python
library. Two ways to use it without writing code, both one line: from an MCP client
you already have (Claude Code, Claude Desktop, Cursor),
`claude mcp add stealth -- uvx aihawk`, see
[the MCP server page](https://github.com/feder-cr/AIHawk/wiki/mcp-server); or with an
`claude mcp add stealth -- uvx invisible-playwright-mcp`, see
[the MCP server page](https://github.com/feder-cr/invisible_playwright_mcp/wiki/mcp-server); or with an
interface and a model included, needing only an OpenRouter key,
`uvx aihawk ui --openrouter-key sk-or-...`, see
[AIHawk](https://github.com/feder-cr/AIHawk). Same engine underneath, and the second
`uvx invisible-playwright-mcp ui --openrouter-key sk-or-...`, see
[invisible_playwright_mcp](https://github.com/feder-cr/invisible_playwright_mcp). Same engine underneath, and the second
is a client of the first.
All of it reads better, and is searchable, in
@@ -232,8 +286,8 @@ two around it are how most people reach it:
- **[invisible_core](https://github.com/feder-cr/invisible_core)** - seed to
fingerprint to preferences, plus proxy and geolocation. This package pins it.
- **[AIHawk](https://github.com/feder-cr/AIHawk)** - this engine as an MCP
server (`uvx aihawk`, for any client that brings its own
- **[invisible_playwright_mcp](https://github.com/feder-cr/invisible_playwright_mcp)** - this engine as an MCP
server (`uvx invisible-playwright-mcp`, for any client that brings its own
model) and, in the same package, an interface with a model included, from
one command. The interface is a client of the server, with no private path
to the browser.
@@ -323,6 +377,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>
+11
View File
@@ -0,0 +1,11 @@
[
{"id": "wrapper.e2e.udp", "giro": "G2", "os": ["linux", "windows"], "min_tests": 43, "exact": true, "tests": ["tests/test_preload_newtab_turns_the_privileged_about_process_off_e2e.py", "tests/test_the_association_is_ready_when_the_peerconnection_is_born_e2e.py", "tests/test_turn_over_tcp_is_tried_for_real_e2e.py", "tests/test_webrtc_realness.py::test_the_gather_is_real_without_a_proxy", "tests/test_the_whole_udp_chain_by_name_e2e.py::test_a_turn_srflx_by_name_arrives_through_the_relay_when_the_exit_of_the_lab_is_loopback", "tests/test_declared_host_network_e2e.py", "tests/test_a_page_over_ipv6_gathers_on_a_machine_declared_without_it_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", "tests/test_webrtc_realness.py::test_a_proxy_whose_udp_leaves_from_another_address_gives_no_srflx_at_all", "tests/test_webrtc_realness.py::test_a_proxy_whose_relay_never_answers_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. 57 = 1+7+6+1+21 from the five files + 21 from the 10 UDP-line tests of test_webrtc_realness.py (parametrized). The chain by name is here in its variant with the lab's exit on loopback (127.0.0.2) and the pref `media.peerconnection.ice.loopback`, on Linux and Windows: the exit of the lab is loopback, and a loopback mapped address is thrown away by nICEr unless the ICE context allows it. The variant without the pref (an exit that is not loopback) is the suite wrapper.e2e.udp.exit, Linux only; the address added to the interface of the Windows runner is work of the release after firefox-63. The preload_newtab test (2) is here: seen green on Linux as root (Docker) and on Windows 10 runs of 10 (windows-2022, round 5 engine); it reads the engine's own process log."},
{"id": "wrapper.e2e.udp.exit", "giro": "G2", "os": ["linux"], "min_tests": 7, "exact": true, "tests": ["tests/test_the_whole_udp_chain_by_name_e2e.py::test_a_turn_srflx_by_name_arrives_through_the_relay_before_the_tick", "tests/test_a_proxy_that_cannot_carry_udp_leaks_nothing_direct_e2e.py"], "marker": "e2e", "needs_root": ["linux"], "note": "Linux only, and not collected on Windows: the exit of the lab is a documentation address (198.51.100.9) added to lo with `ip addr add`, which needs root and iproute2; a mapped address in 127/8 would be thrown away by nICEr as bogus (stun_client_ctx.cpp nr_stun_transport_addr_check) and the pref that allows it is off in a product. The page reads a srflx equal to the gateway exit and the relay of the TURN server, the TURN name resolved by the DoH through the proxy, in the tick of 2 s. On the Windows runner of GitHub (administrator, the network of the runner) it could run too: not yet. A skipped test would turn the verdict red, hence a suite of its own. Its twin with the lab's exit on loopback and the pref stays in wrapper.e2e.udp on both systems, so that Windows keeps the walk of the chain by name."},
{"id": "wrapper.e2e.udp.sandbox", "giro": "G2", "os": ["linux"], "min_tests": 13, "exact": true, "tests": ["tests/test_the_socket_process_is_sandboxed_e2e.py", "tests/test_webrtc_realness.py::test_the_gather_is_real_without_a_proxy", "tests/test_webrtc_realness.py::test_a_gateway_with_coherent_udp_gives_the_page_a_srflx_born_through_its_relay", "tests/test_ice_names_by_the_context_proxy_e2e.py::test_a_gateway_without_udp_resolves_the_ice_name_then_ends_in_701"], "marker": "e2e", "needs_root": false, "note": "The browser WITH its sandbox, run by a normal user, as on any Linux that allows user namespaces. On the Ubuntu 24.04 runner AppArmor refuses them to a user, so every other non-root suite runs a browser WITHOUT the sandbox of its socket and content processes; the gate turns the restriction off for this leg (sysctl kernel.apparmor_restrict_unprivileged_userns=0) and the first test fails unless the socket and a tab process have a seccomp filter (Seccomp: 2). The three situations of the UDP line: A (a proxy that carries UDP: the srflx born through the relay), B (no proxy: the gather is real), C (a proxy with no UDP: the ICE server name goes by DoH through the proxy and the gather ends in 701). No root and no resolver trap needed."},
{"id": "wrapper.e2e.web", "giro": "G2", "os": ["linux", "windows"], "min_tests": 27, "exact": true, "tests": ["tests/test_networkidle_through_a_served_browser_with_routes_e2e.py", "tests/test_http3_through_the_proxy_e2e.py"], "marker": "e2e", "needs_root": false, "note": "The networkidle e2e with routes and the HTTP/3 e2e, split from wrapper.e2e.udp (about 260 s of 500 on Linux; the whole suite did not fit the 15 minutes of Windows)."},
{"id": "wrapper.e2e.doh", "giro": "G2", "os": ["linux", "windows"], "min_tests": 19, "exact": true, "tests": ["tests/test_the_hosts_file_of_the_host_is_never_read_e2e.py", "tests/test_resolver_race_e2e.py", "tests/test_doh_under_stress_e2e.py", "tests/test_context_proxy_only_resolves_by_doh_e2e.py", "tests/test_doh_through_the_proxy_e2e.py", "tests/test_ice_names_by_the_context_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.e2e.realness", "giro": "G2", "os": ["linux", "windows"], "min_tests": 32, "exact": true, "tests": ["tests/test_realness_behind_a_declared_exit_e2e.py"], "marker": "e2e", "needs_root": ["linux"], "note": "The realness check without a real proxy: six declared exits, the values a page reads, and the roads. Linux runs as root without xdist like the DoH suite (the resolver trap); on Windows the trap does not exist and the assertion on the system resolver is the only one omitted."},
{"id": "wrapper.unit.udp", "giro": "G1", "os": ["linux", "windows"], "min_tests": 221, "exact": true, "tests": ["tests/test_a_served_launch_cannot_turn_the_launch_counter_off.py", "tests/test_the_witness_picks_a_port_both_sockets_bind.py", "tests/test_preload_newtab_reaches_the_core_only_when_asked.py", "tests/test_the_resolver_trap_counts_its_own_users.py", "tests/test_the_doh_e2e_launch_on_a_virtual_display.py", "tests/test_the_realness_helpers.py", "tests/test_the_h3_line_helpers.py", "tests/test_the_fake_doh_delays_and_refuses.py", "tests/test_the_host_address_helper.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", "tests/test_the_exit_of_a_context_is_discovered_through_its_own_gateway.py", "tests/test_the_witness_hears_a_direct_send.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."},
{"id": "wrapper.e2e.page", "giro": "G2", "os": ["linux", "windows"], "min_tests": 115, "exact": true, "tests": ["tests/test_a_tiny_download_on_a_served_browser_is_saved_e2e.py", "tests/test_a_page_that_moves_on_e2e.py", "tests/test_a_popup_is_reported_when_the_engine_says_it_is_ready_as_playwright_does_e2e.py", "tests/test_a_popup_of_a_link_reaches_the_client_e2e.py", "tests/test_popup_destinations_e2e.py", "tests/test_popups_reach_the_client_e2e.py", "tests/test_route_superseded_e2e.py"], "marker": "e2e", "needs_root": false, "note": "114 = 100 + the 14 of test_a_page_that_moves_on_e2e.py (a navigation the page overtook with location.replace ends; the engine fix 860ef8a6d9 is proved by it). 100 counted at the collection; was 96 = 10+32+16+34+4 before the popup tests of 6200bc2). A page is handed over when the engine says Page.ready; a popup reaches the client (link, noopener, window.open; own site and another; with and without a route; in-process and over launch_server) as Playwright's does; a superseded route. Needs the candidate binary, and the stock Playwright client of the dev extra."},
{"id": "wrapper.unit.page", "giro": "G1", "os": ["linux", "windows"], "min_tests": 44, "exact": true, "tests": ["tests/test_a_download_finished_before_it_was_announced_is_finished.py", "tests/test_every_order_of_the_events_of_a_popup_gives_one_page_event.py", "tests/test_ci_drive_gate_goes_through_the_core.py", "tests/test_a_page_is_handed_over_only_when_the_engine_says_it_is_ready.py", "tests/test_a_new_page_waits_for_the_engine.py", "tests/test_page_number_follows_the_call.py"], "marker": "unit", "needs_root": false, "note": "24 (counted at the collection; was 20 = 3+8+1+8 before 6200bc2). The page dispatcher's wait for Page.ready and what it hands over; the drive gate goes through the core (the engine waits for the session's road)."}
]
+3 -3
View File
@@ -1,6 +1,6 @@
---
title: "AI agent retry loops trip rate limits, not fingerprints"
description: "Retry and re-plan loops multiply requests into a volume signal; throttling belongs in the agent loop. This page moved to the AIHawk wiki."
description: "Retry and re-plan loops multiply requests into a volume signal; throttling belongs in the agent loop. This page moved to the invisible_playwright_mcp wiki."
parent: "AI Agents and Frameworks"
grand_parent: "Guides"
nav_order: 17
@@ -9,10 +9,10 @@ nav_order: 17
# AI agent retry loops trip rate limits, not fingerprints
This page moved to the AIHawk wiki, where the agent-experience content now
This page moved to the invisible_playwright_mcp wiki, where the agent-experience content now
lives:
**[Agent retry loops trip rate limits, not fingerprints](https://github.com/feder-cr/AIHawk/wiki/agent-retry-loops-rate-limits)**
**[Agent retry loops trip rate limits, not fingerprints](https://github.com/feder-cr/invisible_playwright_mcp/wiki/agent-retry-loops-rate-limits)**
The one-paragraph version: an agent that retries and re-plans multiplies its
requests, and volume is scored server-side against your address and account.
+3 -3
View File
@@ -1,6 +1,6 @@
---
title: "Why AI browser agents have their own timing signal"
description: "An LLM loop emits machine-regular action gaps and instant pointer jumps - a behavioral signal no fingerprint fixes. This page moved to the AIHawk wiki."
description: "An LLM loop emits machine-regular action gaps and instant pointer jumps - a behavioral signal no fingerprint fixes. This page moved to the invisible_playwright_mcp wiki."
parent: "AI Agents and Frameworks"
grand_parent: "Guides"
nav_order: 10
@@ -9,10 +9,10 @@ nav_order: 10
# Why AI browser agents have their own timing signal
This page moved to the AIHawk wiki, where the agent-experience content now
This page moved to the invisible_playwright_mcp wiki, where the agent-experience content now
lives:
**[The timing signal AI agents give off](https://github.com/feder-cr/AIHawk/wiki/ai-agent-timing-signal)**
**[The timing signal AI agents give off](https://github.com/feder-cr/invisible_playwright_mcp/wiki/ai-agent-timing-signal)**
The short version it still owes you here: a think-act loop pauses for model
latency, and that pause repeats with a regularity no human produces. The
+1 -1
View File
@@ -224,7 +224,7 @@ this whole page is about.
one. Pick on the agent loop, then fix the machine, then consider the engine.
**Is there any agent route to an engine-level fingerprint?** Two, and they are not
equivalent. `uvx aihawk` launches through the engine, so the
equivalent. `uvx invisible-playwright-mcp` launches through the engine, so the
seeded profile and the humanised pointer come with it. Microsoft's own Playwright
MCP server takes a browser and an executable path, which runs the engine but
carries no `firefox_user_prefs`, so every session on a given build shares one
+3 -3
View File
@@ -1,6 +1,6 @@
---
title: "browser-use gets detected: what you can and cannot change"
description: "browser-use drives Chrome over CDP. What BrowserProfile lets you change and what stays out of reach. This page moved to the AIHawk wiki."
description: "browser-use drives Chrome over CDP. What BrowserProfile lets you change and what stays out of reach. This page moved to the invisible_playwright_mcp wiki."
parent: "AI Agents and Frameworks"
grand_parent: "Guides"
nav_order: 2
@@ -9,10 +9,10 @@ nav_order: 2
# browser-use gets detected: what you can and cannot change
This page moved to the AIHawk wiki, where the agent-experience content now
This page moved to the invisible_playwright_mcp wiki, where the agent-experience content now
lives:
**[browser-use getting blocked: what you can and cannot change](https://github.com/feder-cr/AIHawk/wiki/browser-use-getting-blocked)**
**[browser-use getting blocked: what you can and cannot change](https://github.com/feder-cr/invisible_playwright_mcp/wiki/browser-use-getting-blocked)**
The unchanged short answer: browser-use exposes a real set of levers
(`executable_path`, `user_data_dir`, `proxy`, `headless`, `args`), all of
@@ -1,6 +1,6 @@
---
title: "Computer-use agents and browser fingerprint detection"
description: "Clicking by pixel makes driver flags moot; the engine fingerprint and action rhythm stay checkable. This page moved to the AIHawk wiki."
description: "Clicking by pixel makes driver flags moot; the engine fingerprint and action rhythm stay checkable. This page moved to the invisible_playwright_mcp wiki."
parent: "AI Agents and Frameworks"
grand_parent: "Guides"
nav_order: 6
@@ -9,10 +9,10 @@ nav_order: 6
# Computer-use agents and browser fingerprint detection
This page moved to the AIHawk wiki, retargeted at the question people
This page moved to the invisible_playwright_mcp wiki, retargeted at the question people
actually search:
**[Claude computer use detected as a bot](https://github.com/feder-cr/AIHawk/wiki/claude-computer-use-detected-as-bot)**
**[Claude computer use detected as a bot](https://github.com/feder-cr/invisible_playwright_mcp/wiki/claude-computer-use-detected-as-bot)**
The core of it, kept here in brief: a coordinate-clicking agent never
generates the DOM-automation tells, so `navigator.webdriver` advice mostly
+5 -5
View File
@@ -20,7 +20,7 @@ Playwright, or not to touch Firefox, at all.
These pages are for developers wiring an agent to this engine. The
agent-experience side - what to run, which agent products compare how, what to
check when an agent gets blocked - lives on the
[AIHawk wiki](https://github.com/feder-cr/AIHawk/wiki), the agent built on this
[invisible_playwright_mcp wiki](https://github.com/feder-cr/invisible_playwright_mcp/wiki), the agent built on this
same engine.
## Framework integrations
@@ -34,15 +34,15 @@ same engine.
## Computer-use and screenshot agents
- [Back a computer-use agent with a real browser engine](back-computer-use-agent-real-browser.md) - implement the screenshot-and-click Computer interface over an invisible_playwright page, and its honest limits.
- [Computer-use agents and browser fingerprint detection](computer-use-agents-browser-detection.md) - clicking by pixel makes driver flags moot; the engine fingerprint and action rhythm stay checkable. (Moved to the AIHawk wiki; the page here points across.)
- [Computer-use agents and browser fingerprint detection](computer-use-agents-browser-detection.md) - clicking by pixel makes driver flags moot; the engine fingerprint and action rhythm stay checkable. (Moved to the invisible_playwright_mcp wiki; the page here points across.)
- [DOM-reading vs screenshot agents: which stealth helps](dom-reading-vs-screenshot-agents.md) - which stealth signal helps depends on whether the agent reads DOM or clicks pixels.
## How AI agents get detected
- [AI browser agents and stealth: what fits and what does not](ai-browser-agents-stealth.md) - most agents drive Chromium over CDP, so a stealth Firefox does not drop in.
- [browser-use gets detected: what you can and cannot change](browser-use-detection.md) - browser-use drives Chrome over CDP: what BrowserProfile changes, what stays out of reach. (Moved to the AIHawk wiki; the page here points across.)
- [Why AI browser agents have their own timing signal](ai-agent-timing-signal.md) - a think-act loop emits machine-regular gaps and instant pointer jumps no fingerprint fixes. (Moved to the AIHawk wiki; the page here points across.)
- [AI agent retry loops trip rate limits, not fingerprints](agent-retry-loops-rate-limits.md) - retry and re-plan loops multiply requests into a volume signal; throttle in the agent loop. (Moved to the AIHawk wiki; the page here points across.)
- [browser-use gets detected: what you can and cannot change](browser-use-detection.md) - browser-use drives Chrome over CDP: what BrowserProfile changes, what stays out of reach. (Moved to the invisible_playwright_mcp wiki; the page here points across.)
- [Why AI browser agents have their own timing signal](ai-agent-timing-signal.md) - a think-act loop emits machine-regular gaps and instant pointer jumps no fingerprint fixes. (Moved to the invisible_playwright_mcp wiki; the page here points across.)
- [AI agent retry loops trip rate limits, not fingerprints](agent-retry-loops-rate-limits.md) - retry and re-plan loops multiply requests into a volume signal; throttle in the agent loop. (Moved to the invisible_playwright_mcp wiki; the page here points across.)
- [Playwright 1.62 Ships MCP In the Box](playwright-162-built-in-mcp.md) - the MCP server and a new playwright-cli are now bundled into core, runnable via `npx playwright mcp` with no separate install.
## Running agents at scale and on servers
+2 -2
View File
@@ -22,8 +22,8 @@ the thing it describes, and several of them record something we got wrong first.
- **[Integrations](integrations/)** - running this inside Scrapy, Crawlee, Robot
Framework, CodeceptJS, test runners and Playwright MCP, including which frameworks
it does not fit and why.
- **[The agent on top](https://github.com/feder-cr/AIHawk/wiki)** - this engine also
drives [AIHawk](https://github.com/feder-cr/AIHawk), an AI agent you instruct in
- **[The agent on top](https://github.com/feder-cr/invisible_playwright_mcp/wiki)** - this engine also
drives [invisible_playwright_mcp](https://github.com/feder-cr/invisible_playwright_mcp), an AI agent you instruct in
plain language; its wiki covers the agent layer the way this one covers the
browser: comparisons, blocked agents, and task guides.
+5 -6
View File
@@ -1,6 +1,6 @@
---
title: "Using invisible_playwright with Microsoft's Playwright MCP"
description: "There is a server for this engine, inside AIHawk: uvx aihawk. This page is for people already committed to Microsoft's playwright-mcp, and says exactly what that route costs."
description: "There is a server for this engine: uvx invisible-playwright-mcp. This page is for people already committed to Microsoft's playwright-mcp, and says exactly what that route costs."
parent: "Integrations"
nav_order: 7
---
@@ -8,13 +8,12 @@ nav_order: 7
# Using invisible_playwright with Microsoft's Playwright MCP
**There is a server for this engine:**
[`aihawk`](https://github.com/feder-cr/AIHawk/wiki/mcp-server),
shipped inside AIHawk.
[`invisible-playwright-mcp`](https://github.com/feder-cr/invisible_playwright_mcp/wiki/mcp-server).
One line, and it carries the seeded profile and the humanised pointer that the
route on this page cannot:
```bash
claude mcp add stealth -- uvx aihawk
claude mcp add stealth -- uvx invisible-playwright-mcp
```
This page is for the other case: you are already committed to Microsoft's
@@ -122,8 +121,8 @@ knowing before you trust the session.
## Short answers to the questions that lead here
**Is there an MCP server for this project?** Yes:
[`aihawk`](https://github.com/feder-cr/AIHawk/wiki/mcp-server),
`uvx aihawk`. It launches through the engine, so the seeded
[`invisible-playwright-mcp`](https://github.com/feder-cr/invisible_playwright_mcp/wiki/mcp-server),
`uvx invisible-playwright-mcp`. It launches through the engine, so the seeded
profile and the humanised pointer come with it.
Microsoft's own `playwright-mcp` also accepts `--browser firefox` together with
+2 -2
View File
@@ -189,8 +189,8 @@ supply a clean IP, human pacing, and session reuse for the layers a browser cann
[how to test whether the browser itself is the problem](how-to-test-bot-detection.md), and
[rate limiting your scraper so volume stops being the signal](how-to-rate-limit-your-scraper-playwright.md).
If the traffic is produced by an AI agent rather than a script, the pacing and
retry layers have their own failure modes, mapped on the AIHawk wiki:
[why does my AI agent get blocked?](https://github.com/feder-cr/AIHawk/wiki/why-does-my-ai-agent-get-blocked)
retry layers have their own failure modes, mapped on the invisible_playwright_mcp wiki:
[why does my AI agent get blocked?](https://github.com/feder-cr/invisible_playwright_mcp/wiki/why-does-my-ai-agent-get-blocked)
---
+4 -3
View File
@@ -4,7 +4,7 @@ build-backend = "hatchling.build"
[project]
name = "invisible_playwright"
version = "0.47.1"
version = "0.51.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==63.66.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
+14 -3
View File
@@ -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):
@@ -179,7 +189,8 @@ def _headers_array(raw) -> List[Dict[str, str]]:
#: Juggler's `cause` and `internalCause` are `nsIContentPolicy` constant names
#: (`causeTypeToString` in NetworkObserver.js), so they arrive as
#: `TYPE_XMLHTTPREQUEST`, never `xmlhttprequest`. This is the table the
#: Playwright driver's ffNetworkManager uses for the same event.
#: Playwright driver's ffNetworkManager uses for the same event (the pinned driver's table is read by
#: tests/test_resource_types_match_the_pinned_driver.py: a beacon is `beacon`, a CSP report `cspreport`).
_CAUSE_TO_RESOURCE_TYPE = {
"TYPE_INVALID": "other", "TYPE_OTHER": "other",
"TYPE_SCRIPT": "script", "TYPE_IMAGE": "image",
@@ -188,8 +199,8 @@ _CAUSE_TO_RESOURCE_TYPE = {
"TYPE_REFRESH": "document", "TYPE_XBL": "other", "TYPE_PING": "other",
"TYPE_XMLHTTPREQUEST": "xhr", "TYPE_OBJECT_SUBREQUEST": "other",
"TYPE_DTD": "other", "TYPE_FONT": "font", "TYPE_MEDIA": "media",
"TYPE_WEBSOCKET": "websocket", "TYPE_CSP_REPORT": "other",
"TYPE_XSLT": "other", "TYPE_BEACON": "other", "TYPE_FETCH": "fetch",
"TYPE_WEBSOCKET": "websocket", "TYPE_CSP_REPORT": "cspreport",
"TYPE_XSLT": "other", "TYPE_BEACON": "beacon", "TYPE_FETCH": "fetch",
"TYPE_IMAGESET": "image", "TYPE_WEB_MANIFEST": "manifest",
}
_INTERNAL_CAUSE_TO_RESOURCE_TYPE = {
+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")
+875
View File
@@ -0,0 +1,875 @@
"""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, seed=session.seed,
udp_stun_servers=session._udp_stun_servers)
session._timezone = geo.timezone
session._locale = geo.locale
session._webrtc_egress_ip = geo.egress_ip
session._geolocation = geo.geolocation_override()
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,
preload_newtab: 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,
udp_stun_servers: Optional[List[str]] = 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).
udp_stun_servers where a SOCKS5 proxy's UDP exit is measured from: "ip:port" IPv4 literals, None for the
two public defaults. Kept on the session, so the launch and every context proxy a client
later gives measure from the same list. Python only: nothing reaches the browser.
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, udp_stun_servers=udp_stun_servers,
preload_newtab=preload_newtab)
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))
File diff suppressed because it is too large. Load diff
+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()
+111 -31
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, UDP_STUN_PREF
from typing import Any, Dict, Optional
from invisible_core import compose_session_prefs, context_geometry, make_virtual_display
@@ -65,6 +65,52 @@ __all__ = ["build_prefs", "true_headless_requested", "TRUE_HEADLESS_ENV",
TRUE_HEADLESS_ENV = "INVPW_TRUE_HEADLESS"
def udp_stun_list(servers: Optional[Any]) -> Optional[list]:
"""The `udp_stun_servers=` of a launch, validated by the core ("ip:port" IPv4 literals; a name or a bad port
raises ValueError naming the parameter) and normalised to "ip:port" strings; None for the two public defaults."""
if servers is None:
return None
from invisible_core._udp_exit import stun_servers
return ["%s:%d" % server for server in stun_servers(servers)]
def session_geo(timezone: str, proxy: Optional[Dict[str, str]], locale: Any,
seed: Optional[int] = None):
"""`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.
The seed places the session on the map (the declared position)."""
from invisible_core import prepare_session_geo
return prepare_session_geo(timezone, proxy, locale, seed=seed)
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,
seed=session.seed)
session._timezone, session._locale = geo.timezone, geo.locale
session._geolocation = geo.geolocation_override()
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 +119,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 +182,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)
@@ -156,6 +198,8 @@ def build_prefs(
humanize: Any,
show_cursor: Optional[bool] = None,
session_seed: Optional[int] = None,
udp_stun_servers: Optional[Any] = None,
preload_newtab: Optional[bool] = None,
) -> Dict[str, Any]:
"""Fingerprint prefs plus the humanize toggle, which is always set explicitly.
@@ -203,6 +247,9 @@ def build_prefs(
humanize=(_cursor_max_seconds(humanize)
if cursor_engine == ENGINE_BINARY else False),
show_cursor=show_cursor,
# Handed to the core only when asked: a core that does not know the option is never called with it,
# so a caller who does not use it cannot meet a TypeError from a pairing with an older core.
**({} if preload_newtab is None else {"preload_newtab": preload_newtab}),
).prefs
# ⛔ THE TYPING SEED RIDES IN THE PREFS AND NEVER REACHES THE PROFILE.
#
@@ -217,24 +264,35 @@ 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
# ⛔ THE STUN SERVERS OF THE UDP-EXIT MEASUREMENT ride here for the server only (`UDP_STUN_PREF`): `op_launch`
# takes the key out before the profile is written, as it does the seed. Not written when the launch named none.
if udp_stun_servers:
prefs[UDP_STUN_PREF] = ",".join(udp_stun_servers)
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 +304,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
@@ -269,9 +325,9 @@ class ProxyEgressNonVerificabile(RuntimeError):
This is not drift and it is not parity: it is absence of measurement. A
proxy that does not answer the probe for several checks in a row is not a
proxy that holds, it is a proxy we are flying blind on while the engine
keeps declaring to every page an address that nobody is confirming any
more.
proxy that holds, it is a proxy we are flying blind on while the timezone
and the locale, decided from the egress at launch, go on being declared
to every page with nobody confirming the egress they came from any more.
"""
@@ -351,10 +407,22 @@ 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
`__init__`. They already did, identically, which is why this works at all.
`_network_declared`, `_timezone` and `_virtual_display` in their own
`__init__`; `_geolocation` (the position the session declares, the
``geolocation`` object of a context, None until `__enter__` decides it
and when the exit has no point) is the class default below. They already did, identically, which is why this works at all.
"""
#: The position this session declares to the engine
#: (``SessionGeo.geolocation_override()``: latitude, longitude, accuracy),
#: or None. Set by `__enter__` from the egress, like `_timezone`.
_geolocation: Optional[Dict[str, float]] = None
#: Where this session measures a SOCKS5 proxy's UDP exit from: the ``udp_stun_servers=`` of the launch, as
#: "ip:port" strings (validated by the core), or None for the two public defaults. Kept on the session so the
#: launch geo step and the browser's later context proxies use the same list.
_udp_stun_servers: Optional[list] = None
def _resolve_headless(self) -> bool:
"""Translate the user's ``headless`` flag.
@@ -410,13 +478,23 @@ class CommonLaunch:
# None before __enter__ has decided.
if self._locale is not None:
kwargs["locale"] = self._locale.primary
# The position the core declares for this machine. It travels as the
# standard `geolocation` context option, so the engine gets
# `Browser.setGeolocationOverride` for EVERY context (the default one
# and each `new_context`/`new_page`), a caller's own `geolocation=`
# wins like any other default, and the PERMISSION is not granted here:
# the page's grant (the caller's `grant_permissions`) is what makes the
# engine answer. The override belongs to each context (Juggler keys it
# by `browserContextId`), so a context that closes takes its own with it.
if self._geolocation is not None:
kwargs["geolocation"] = dict(self._geolocation)
return kwargs
def _build_env(self, prefs: Dict[str, Any]) -> Dict[str, str]:
"""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 +503,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))
@@ -448,6 +526,8 @@ class CommonLaunch:
humanize=self._humanize,
show_cursor=self._show_cursor,
session_seed=self.seed,
udp_stun_servers=self._udp_stun_servers,
preload_newtab=self._preload_newtab,
)
def _arm_cursor_engine(self, owner: Any) -> None:
+24 -29
View File
@@ -4,7 +4,7 @@ from __future__ import annotations
import asyncio
import time
from pathlib import Path
from typing import Any, Dict, Optional, Union
from typing import Any, Dict, Optional, Sequence, Union
from invisible_playwright._pw.async_api import Browser, BrowserContext, Playwright, async_playwright
from invisible_playwright._pw._impl._browser_context import page_number_reserved
@@ -37,6 +37,8 @@ class InvisiblePlaywright(_session.CommonLaunch):
profile_dir: Optional[Union[str, Path]] = None,
prep_recaptcha: bool = False,
show_cursor: Optional[bool] = None,
udp_stun_servers: Optional[Sequence[str]] = None,
preload_newtab: Optional[bool] = None,
) -> None:
# See sync launcher: `zoom.stealth.fpp.hw_seed` is int32_t - clamp.
# One place decides the seed, and a profile directory remembers it
@@ -45,6 +47,8 @@ class InvisiblePlaywright(_session.CommonLaunch):
self._pin = pin
self._headless = headless
self._proxy = proxy
# See the sync launcher: validated now, kept for the launch and for every context proxy.
self._udp_stun_servers = _session.udp_stun_list(udp_stun_servers)
self._extra_args = list(extra_args or [])
self._humanize = humanize
# See the sync launcher: who draws the cursor path (this package by
@@ -59,6 +63,8 @@ class InvisiblePlaywright(_session.CommonLaunch):
# it.
self._show_cursor = (None if show_cursor is None
else bool(show_cursor))
self._preload_newtab = (None if preload_newtab is None
else bool(preload_newtab))
# What the caller ASKED for: "auto" or a tag. The decision is the
# core's, made in __enter__ from the egress (prepare_session_geo),
# and there is none before it.
@@ -88,13 +94,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
@@ -111,22 +115,13 @@ class InvisiblePlaywright(_session.CommonLaunch):
# session keeps the core's DECISION (a SessionLocale). See the sync
# launcher.
_geo = await asyncio.to_thread(
prepare_session_geo, self._timezone, self._proxy, self._locale_requested
prepare_session_geo, self._timezone, self._proxy, self._locale_requested,
seed=self.seed, udp_stun_servers=self._udp_stun_servers,
)
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()
self._geolocation = _geo.geolocation_override()
# 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 +186,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 +205,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 +225,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
+42 -44
View File
@@ -3,7 +3,7 @@ from __future__ import annotations
import time
from pathlib import Path
from typing import Any, Dict, Optional, Union
from typing import Any, Dict, Optional, Sequence, Union
from invisible_playwright._pw.sync_api import Browser, BrowserContext, Playwright, sync_playwright
@@ -101,6 +101,8 @@ class InvisiblePlaywright(_session.CommonLaunch):
profile_dir: Optional[Union[str, Path]] = None,
prep_recaptcha: bool = False,
show_cursor: Optional[bool] = None,
udp_stun_servers: Optional[Sequence[str]] = None,
preload_newtab: Optional[bool] = None,
) -> None:
"""
Args:
@@ -157,6 +159,13 @@ class InvisiblePlaywright(_session.CommonLaunch):
page = ctx.new_page()``. First run creates the dir;
subsequent runs reuse it. Pair with a stable ``seed=`` to
also pin the fingerprint identity across runs.
preload_newtab: The New Tab page a retail Firefox keeps preloaded in a
process of its own (about 200 MB, and a Mozilla site's process
beside it). Default ``None``: the core writes nothing and the
retail's behaviour stays. ``False`` is a declaration of yours:
the core writes ``browser.newtab.preload`` false and neither
process is born. ``True`` says the retail's value aloud. A
``browser.newtab.preload`` in ``extra_prefs`` wins over it.
show_cursor: Draw the pointer where the automation is, so a
person watching the screen can follow the session - the
Windows arrow, with the package logo's green halo around it.
@@ -185,6 +194,10 @@ class InvisiblePlaywright(_session.CommonLaunch):
self._pin = pin
self._headless = headless
self._proxy = proxy
# Where a SOCKS5 proxy's UDP exit is measured from ("ip:port" IPv4 literals; None = the two public
# defaults). Validated now, kept on the session for the launch AND for every context proxy; a parameter of
# this Python launch only: nothing of it is put in the browser's environment, argv, prefs or pipe.
self._udp_stun_servers = _session.udp_stun_list(udp_stun_servers)
self._extra_args = list(extra_args or [])
self._humanize = humanize
# Who draws the cursor path: this package (default), the browser
@@ -205,6 +218,8 @@ class InvisiblePlaywright(_session.CommonLaunch):
# it.
self._show_cursor = (None if show_cursor is None
else bool(show_cursor))
self._preload_newtab = (None if preload_newtab is None
else bool(preload_newtab))
# What the caller ASKED for: "auto" or a tag. The decision is the
# core's, made in __enter__ from the egress (prepare_session_geo),
# and there is none before it.
@@ -235,14 +250,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
@@ -260,21 +272,12 @@ class InvisiblePlaywright(_session.CommonLaunch):
# The language is decided in the same call, from the same egress: the
# core resolves "auto" and applies Firefox's language table, and this
# session keeps the DECISION (a SessionLocale), never a tag of its own.
_geo = prepare_session_geo(self._timezone, self._proxy, self._locale_requested)
_geo = prepare_session_geo(self._timezone, self._proxy, self._locale_requested,
seed=self.seed, udp_stun_servers=self._udp_stun_servers)
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()
self._geolocation = _geo.geolocation_override()
# 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 +412,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 +436,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 +446,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 +516,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
+731
View File
@@ -0,0 +1,731 @@
"""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.errors
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, QTYPE_HTTPS = 1, 28, 65
RCODE_OK, RCODE_SERVFAIL, RCODE_NXDOMAIN, RCODE_REFUSED = 0, 2, 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", 503: "Service Unavailable"}
class DohQuery(NamedTuple):
name: str
qtype: int
via: str
#: The ways :class:`FakeDoh` can refuse a query (``fail_first``). All three are failures of the lookup for Firefox's TRR:
#: ``close`` ends the exchange with no answer (an h2 stream reset, or a closed connection over HTTP/1.1): a failure of
#: the CHANNEL, the kind ``TRRService::ConfirmationContext::RecordTRRStatus`` counts (``NS_FAILED(channelStatus)``);
#: ``http503`` answers an HTTP error (``TRR_SERVER_RESPONSE_ERR``); ``servfail`` answers a well-formed DNS message with
#: rcode 2 (``TRR_RCODE_FAIL``).
FAILURE_KINDS = ("close", "http503", "servfail")
class DohAnswer(NamedTuple):
"""What the FakeDoh did with one query: ``outcome`` is ``"answered"`` or a failure kind, ``delay`` the seconds
between the arrival of the query and the moment its answer (or its refusal) was sent."""
name: str
qtype: int
via: str
outcome: str
delay: float
class _Reply(NamedTuple):
status: int
body: bytes
content_type: str
delay: float = 0.0
close: bool = False # no answer at all: reset the stream / close the connection
record: Optional[Tuple[str, int, str, str]] = None # (name, qtype, via, outcome), logged when it is sent
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,
delay_s: float = 0.0, delay_names: Optional[Dict[str, float]] = None,
fail_first: Optional[Dict[str, str]] = 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)
#: Latency of EVERY answer, in seconds (each response is held that long after its query arrived, not only the
#: connection set-up); ``delay_names`` overrides it per name (a name or any name under it). Both can be changed
#: while the server runs. Over h2 the answers are held independently, so the A and the AAAA of one lookup come
#: back together after the delay, not one after the other.
self.delay_s = delay_s
self.delay_names: Dict[str, float] = {k.lower().rstrip("."): v for k, v in (delay_names or {}).items()}
#: ``{name: kind}`` (kind in :data:`FAILURE_KINDS`): the FIRST query of each type (A, AAAA...) for ``name`` is
#: refused in that way; every later one is served as usual. Can be changed while the server runs.
self.fail_first: Dict[str, str] = {k.lower().rstrip("."): v for k, v in (fail_first or {}).items()}
for kind in self.fail_first.values():
if kind not in FAILURE_KINDS:
raise ValueError("unknown failure kind %r, expected one of %s" % (kind, FAILURE_KINDS))
#: What was done with every query, in the order it was SENT (see :class:`DohAnswer`).
self.answers: List[DohAnswer] = []
self._failed: Set[Tuple[str, int]] = set()
#: Every query, in order.
self.queries: List[DohQuery] = []
#: The names for which this server answered a type 65 (HTTPS) query WITH DATA. It never does: the retail Firefox reads
#: h3 at its first visit when the DNS answer carries that record, so a test that expects h2 first (the h3 e2e) asserts
#: that this stays empty, and says so if the server learns to serve it.
self.https_served: List[str] = []
#: 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 answers_for(self, name: str, qtype: Optional[int] = None) -> List[DohAnswer]:
name = name.lower().rstrip(".")
with self._lock:
return [a for a in self.answers if a.name == name and (qtype is None or a.qtype == 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 _delay_of(self, name: str) -> float:
for key, seconds in self.delay_names.items():
if name == key or name.endswith("." + key):
return seconds
return self.delay_s
def _record(self, record: Optional[Tuple[str, int, str, str]], received: float) -> None:
"""Log that an answer is being sent now (``received`` is the monotonic time its query arrived)."""
if record is not None:
with self._lock:
self.answers.append(DohAnswer(*record, time.monotonic() - received))
def _answer(self, via: str, method: str, target: str, content_type: str, body: bytes) -> _Reply:
"""What to send for one HTTP request, recording the DNS query it carries."""
def bad(status: int) -> _Reply:
with self._lock:
self.bad_requests.append((via, method, target, status))
return _Reply(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)
kind = self.fail_first.get(query.name)
if kind is not None and (query.name, query.qtype) in self._failed:
kind = None
elif kind is not None:
self._failed.add((query.name, query.qtype))
delay = self._delay_of(query.name)
record = (query.name, query.qtype, via, kind or "answered")
if kind == "close":
return _Reply(0, b"", "", delay, True, record)
if kind == "http503":
return _Reply(503, b"", "text/plain", delay, False, record)
if kind == "servfail":
return _Reply(200, build_response(query, RCODE_SERVFAIL), "application/dns-message", delay, False, record)
message = answer_for(names, query)
if query.qtype == QTYPE_HTTPS and struct.unpack("!H", message[6:8])[0] > 0:
with self._lock:
self.https_served.append(query.name)
return _Reply(200, message, "application/dns-message", delay, False, record)
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:]
received = time.monotonic()
reply = self._answer(via, method, target, headers.get("content-type", ""), body)
if reply.delay:
time.sleep(reply.delay)
self._record(reply.record, received)
if reply.close:
return
status, payload, content_type = reply.status, reply.body, reply.content_type
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] = {}
#: Answers being held back: (due monotonic time, stream id, reply, monotonic time the query arrived). One thread
#: reads, holds and writes, so the TLS socket never has a reader and a writer at once, and the answers of one
#: connection are held independently of each other (the A and the AAAA of a lookup both wait ``delay``).
held: List[Tuple[float, int, _Reply, float]] = []
tls.settimeout(0.05)
last_activity = time.monotonic()
def send(stream_id: int, reply: _Reply, received: float) -> None:
self._record(reply.record, received)
try:
if reply.close:
connection.reset_stream(stream_id, error_code=h2.errors.ErrorCodes.INTERNAL_ERROR)
else:
connection.send_headers(stream_id, [
(":status", str(reply.status)), ("content-type", reply.content_type),
("content-length", str(len(reply.body))), ("cache-control", "max-age=%d" % DOH_TTL)])
connection.send_data(stream_id, reply.body, end_stream=True)
except h2.exceptions.H2Error: # the client reset the stream while its answer was held
pass
while True:
now = time.monotonic()
for item in [h for h in held if h[0] <= now]:
held.remove(item)
send(item[1], item[2], item[3])
pending = connection.data_to_send()
if pending:
tls.sendall(pending)
try:
data = tls.recv(65536)
except (socket.timeout, ssl.SSLWantReadError):
if not held and time.monotonic() - last_activity > 60:
return
continue
if not data:
return
last_activity = time.monotonic()
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"]
received = time.monotonic()
reply = self._answer(
via, headers.get(":method", ""), headers.get(":path", ""),
headers.get("content-type", ""), request["body"])
if reply.delay:
held.append((received + reply.delay, event.stream_id, reply, received))
else:
send(event.stream_id, reply, received)
elif isinstance(event, h2.events.StreamReset):
streams.pop(event.stream_id, None)
held[:] = [h for h in held if h[1] != event.stream_id]
elif isinstance(event, h2.events.ConnectionTerminated):
return
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", "QTYPE_HTTPS", "RCODE_NXDOMAIN", "RCODE_OK", "RCODE_REFUSED", "RCODE_SERVFAIL", "DohAnswer", "DohGateway", "DohQuery",
"FAILURE_KINDS", "FakeDoh", "Query",
"answer_for", "build_response", "encode_query", "is_loopback", "make_certificate", "parse_query", "pump",
"relay", "wait_until",
]
+44
View File
@@ -0,0 +1,44 @@
"""Support of the DoH e2e files and of the fixtures of conftest.py that serve them (no pytest in here)."""
from __future__ import annotations
import http.server
import threading
from _servers import LocalServer
#: 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"}
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()
+259
View File
@@ -0,0 +1,259 @@
"""A local HTTPS server that speaks HTTP/3 as well, reached by its address.
The same port answers TCP (TLS, HTTP/2 by ALPN with an `Alt-Svc: h3` header, HTTP/1.1 for a client that offers nothing
else) and UDP (QUIC, HTTP/3, aioquic), with a self-signed certificate for the address it is given. The TCP side speaks HTTP/2
because that is what a real site does: the FIRST visit of a page reads `h2`, and only after the Alt-Svc it carries may a
later one read `h3` (retail Firefox 159, native DNS in loopback: h2, h3, h3; behind a proxy h3 within a few visits, and at the first one when the DNS answer carries the HTTPS record: 3 sessions of 15 in the third run). 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` and `h2` (pip install aioquic h2; the dev extra installs both).
"""
from __future__ import annotations
import asyncio
import datetime
import ipaddress
import random
import socket
import socketserver
import ssl
import tempfile
import threading
from pathlib import Path
from typing import List, Tuple
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
#: The one document every path answers, over TCP and over QUIC.
PAGE = b"<!doctype html><meta charset=utf-8><title>h3</title><p>ok</p>"
# How many port numbers are tried, and where the ones after the system's own pick are drawn from: the same as the witness's.
from _witness import DRAW_FROM as _WITNESS_DRAW_FROM, TRIES as _WITNESS_TRIES # noqa: E402
class _TcpServer(socketserver.ThreadingTCPServer):
allow_reuse_address = True
daemon_threads = True
def _tcp_server_on_a_port_udp_binds(address: str):
"""A TCP server on a port number that UDP can bind too, as ``(server, port)``.
The first try is the system's own pick (port 0); the others are drawn at random below the dynamic range. Windows hands out
ephemeral TCP ports in sequence and keeps excluded ranges of a hundred ports for UDP inside the same zone, so asking the
system again lands in the same refused range again and again (run 43230437094, ``wrapper.e2e.web`` on Windows: fifty
consecutive picks refused, three tests red; the witness had the same defect and the same remedy,
``test_the_witness_picks_a_port_both_sockets_bind.py``)."""
draw = random.Random()
refusals: List[str] = []
for attempt in range(_WITNESS_TRIES):
wanted = 0 if attempt == 0 else draw.randint(*_WITNESS_DRAW_FROM)
try:
tcp = _TcpServer((address, wanted), _TcpHandler)
except OSError as exc:
refusals.append("%s: %s" % (wanted or "system pick", exc))
continue
port = tcp.server_address[1]
probe = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
try:
probe.bind((address, port))
return tcp, port
except OSError as exc:
refusals.append("%s: %s" % (port, exc))
tcp.server_close()
finally:
probe.close()
raise RuntimeError("no port free for both TCP and UDP on %s after %d tries; the last refusals: %s"
% (address, _WITNESS_TRIES, "; ".join(refusals[-3:])))
class _TcpHandler(socketserver.BaseRequestHandler):
"""One TCP connection: the TLS handshake here (not in the accept loop), then HTTP/2 or HTTP/1.1 by the ALPN."""
def handle(self):
owner = self.server.owner
try:
self.request.settimeout(10)
tls = owner._tls.wrap_socket(self.request, server_side=True)
except (ssl.SSLError, OSError):
return
try:
tls.settimeout(60)
alpn = tls.selected_alpn_protocol() or "http/1.1"
owner.tcp_alpn.append(alpn)
if alpn == "h2":
self._h2(tls, owner)
else:
self._http1(tls, owner)
except (ssl.SSLError, OSError):
pass
finally:
try:
tls.close()
except OSError:
pass
@staticmethod
def _h2(tls, owner):
import h2.config
import h2.connection
import h2.events
import h2.exceptions
conn = h2.connection.H2Connection(config=h2.config.H2Configuration(client_side=False, header_encoding="utf-8"))
conn.initiate_connection()
tls.sendall(conn.data_to_send())
while True:
data = tls.recv(65536)
if not data:
return
try:
events = conn.receive_data(data)
except h2.exceptions.ProtocolError:
tls.sendall(conn.data_to_send())
return
for event in events:
if isinstance(event, h2.events.RequestReceived):
owner.tcp_requests.append(dict(event.headers).get(":path", ""))
conn.send_headers(event.stream_id, [
(":status", "200"), ("content-type", "text/html; charset=utf-8"),
("content-length", str(len(PAGE))), ("alt-svc", owner.alt_svc),
("access-control-allow-origin", "*")])
conn.send_data(event.stream_id, PAGE, end_stream=True)
elif isinstance(event, h2.events.DataReceived):
conn.acknowledge_received_data(event.flow_controlled_length, event.stream_id)
elif isinstance(event, h2.events.ConnectionTerminated):
return
out = conn.data_to_send()
if out:
tls.sendall(out)
@staticmethod
def _http1(tls, owner):
head = b""
while b"\r\n\r\n" not in head:
chunk = tls.recv(4096)
if not chunk:
return
head += chunk
parts = head.split(b"\r\n", 1)[0].split(b" ")
owner.tcp_requests.append(parts[1].decode("latin-1") if len(parts) > 1 else "")
tls.sendall(b"HTTP/1.1 200 OK\r\nContent-Type: text/html; charset=utf-8\r\nContent-Length: %d\r\n"
b"Alt-Svc: %s\r\nAccess-Control-Allow-Origin: *\r\nConnection: close\r\n\r\n%s"
% (len(PAGE), owner.alt_svc.encode(), PAGE))
class H3Server:
"""TCP+TLS (HTTP/2) and QUIC (HTTP/3) 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 same peers with the port they sent from: (address, port). On a machine where a gateway's relay sends from an address of
#: this host (Windows cannot send from 127.0.0.1 to it) the address cannot tell the relay from a client that came direct; its port can.
self.quic_peer_addrs: List[Tuple[str, int]] = []
#: The paths of the requests that were answered over HTTP/3, and over TCP.
self.h3_requests: List[str] = []
self.tcp_requests: List[str] = []
#: The ALPN each TCP connection negotiated ("h2", or "http/1.1").
self.tcp_alpn: List[str] = []
self._dir = tempfile.TemporaryDirectory()
cert, key = _certificate(address, Path(self._dir.name))
server = self
# One port for both: the TCP port first, then the same number for UDP.
tcp, port = _tcp_server_on_a_port_udp_binds(address)
self.port = port
#: What the TCP answer says about HTTP/3: the same port, for an hour.
self.alt_svc = 'h3=":%d"; ma=3600' % port
self._tls = ssl.SSLContext(ssl.PROTOCOL_TLS_SERVER)
self._tls.load_cert_chain(str(cert), str(key))
self._tls.set_alpn_protocols(["h2", "http/1.1"])
tcp.owner = self
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)
peer = self._quic._network_paths[0].addr
server.quic_peers.append(peer[0])
server.quic_peer_addrs.append((peer[0], peer[1]))
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/html; charset=utf-8"),
(b"access-control-allow-origin", b"*")])
self._http.send_data(http_event.stream_id, PAGE, 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()
+22
View File
@@ -0,0 +1,22 @@
"""The address of this host that a relay or a server of an e2e test binds to: ONE helper for every test that needs it."""
import socket
import pytest
def this_host_address() -> str:
"""The IPv4 address this host sends from (the one of its default route, as a real gateway's relay has a routable one:
a loopback relay only suits a client whose UDP socket is not bound to an interface, and an engine's ICE sockets are).
No packet is sent.
A host with no default route (a container or a CI runner without a network, a laptop offline) has no such address: the
test cannot pass by design there, so it SKIPS. Call it BEFORE starting any server of the test, so that nothing is left
listening when it skips."""
probe = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
try:
probe.connect(("192.0.2.1", 9))
return probe.getsockname()[0]
except OSError:
pytest.skip("no default route: no LAN address to bind the relay")
finally:
probe.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"]
+565
View File
@@ -0,0 +1,565 @@
"""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 (or the first of 127.0.0.2... it can bind: see TRAP_ADDRESSES) (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, ""
#: The loopback addresses the trap tries for port 53, in order. A hosted runner can have something on 127.0.0.1:53 or on the
#: wildcard of that port (systemd-resolved holds 127.0.0.53 and 127.0.0.54): every 127.x.x.x is loopback on Linux, so the trap
#: takes the first one it can bind and writes THAT address into /etc/resolv.conf (a resolv.conf names no port). With a free
#: port (port=0) only 127.0.0.1 is used.
TRAP_ADDRESSES = ("127.0.0.1", "127.0.0.2", "127.0.0.3", "127.0.0.4", "127.0.0.5", "127.0.0.6", "127.0.0.7", "127.0.0.8")
def _who_holds(port: int) -> str:
"""What the machine says about the sockets of `port` (Linux: ss), for the message of a trap that could not bind."""
import subprocess
for command in (["ss", "-H", "-lntup"], ["netstat", "-lntup"]):
try:
done = subprocess.run(command, capture_output=True, text=True, timeout=10)
except (OSError, subprocess.SubprocessError):
continue
lines = [line for line in done.stdout.splitlines() if (":%d " % port) in line]
return "; held by: " + (" | ".join(lines) if lines else "nothing listed by %s" % command[0])
return "; no ss or netstat to say who holds it"
class Asker(NamedTuple):
"""Who sent a question to the trap: the user, the process (None when its socket could not be traced) and its command."""
uid: int
pid: Optional[int]
command: str
def row_from_proc_net(text: str, port: int) -> Optional[Tuple[int, int]]:
"""``(uid, inode)`` of the socket bound to local port ``port`` in the text of one of /proc/net/{udp,udp6,tcp,tcp6}, or None.
A row is ``sl local_address rem_address st tx:rx tr:tm retrnsmt uid timeout inode ...``; the local address is
``HEX_ADDRESS:HEX_PORT``. The client of a DNS question is a socket still open (it waits for the answer), on an
ephemeral port of its own."""
for line in text.splitlines()[1:]:
fields = line.split()
if len(fields) < 10 or ":" not in fields[1]:
continue
try:
if int(fields[1].rsplit(":", 1)[1], 16) == port:
return int(fields[7]), int(fields[9])
except ValueError:
continue
return None
def uid_from_proc_net(text: str, port: int) -> Optional[int]:
"""The uid of that socket (see :func:`row_from_proc_net`)."""
row = row_from_proc_net(text, port)
return None if row is None else row[0]
def pid_of_socket_inode(inode: int, proc: str = "/proc") -> Optional[int]:
"""The pid of a process that holds the socket with this inode open (root sees every process), or None."""
needle = "socket:[%d]" % inode
try:
entries = os.listdir(proc)
except OSError:
return None
for name in entries:
if not name.isdigit():
continue
fd_dir = os.path.join(proc, name, "fd")
try:
for fd in os.listdir(fd_dir):
try:
if os.readlink(os.path.join(fd_dir, fd)) == needle:
return int(name)
except OSError:
continue
except OSError:
continue
return None
def parent_of(pid: int, proc: str = "/proc") -> Optional[int]:
"""The parent of a process, from /proc/<pid>/stat (the name between parentheses may hold spaces), or None."""
try:
with open(os.path.join(proc, str(pid), "stat"), encoding="utf-8", errors="replace") as handle:
return int(handle.read().rsplit(")", 1)[1].split()[1])
except (OSError, ValueError, IndexError):
return None
def command_of(pid: int, proc: str = "/proc") -> str:
"""What a process is, for a message: its name and the start of its command line."""
try:
with open(os.path.join(proc, str(pid), "comm"), encoding="utf-8", errors="replace") as handle:
name = handle.read().strip()
with open(os.path.join(proc, str(pid), "cmdline"), "rb") as handle:
line = b" ".join(handle.read().split(b"\0")).decode("utf-8", "replace").strip()
return ("%s: %s" % (name, line))[:120]
except OSError:
return "(gone)"
def descends_from(pid: int, root: int, parent=parent_of) -> bool:
"""Whether ``pid`` is ``root`` or one of its descendants, going up the parents (at most 64 steps)."""
for _ in range(64):
if pid == root:
return True
up = parent(pid)
if up is None or up <= 1 or up == pid:
return False
pid = up
return False
def is_a_browser_process(pid: int, proc: str = "/proc") -> bool:
"""Whether a process is the browser's own (the main process, ``firefox``, or ``firefox-bin``), by its name in /proc/<pid>/comm.
Its children (content, socket, forkserver) are found by their parents."""
try:
with open(os.path.join(proc, str(pid), "comm"), encoding="utf-8", errors="replace") as handle:
return handle.read().strip() in ("firefox", "firefox-bin", "firefox.exe")
except OSError:
return False
def under_a_browser(pid: int, root: int, parent=parent_of, is_browser=is_a_browser_process) -> bool:
"""Whether ``pid`` is a browser process or one of its descendants, going up the parents and stopping at ``root`` (the test
process: it is NOT the browser, and neither is anything it runs that is not a browser, like the core's own download of a
database) or at a process with no parent known (at most 64 steps)."""
for _ in range(64):
if is_browser(pid):
return True
if pid == root:
return False
up = parent(pid)
if up is None or up <= 1 or up == pid:
return False
pid = up
return False
def who_asked(protocol: str, peer) -> Optional[Asker]:
"""Who sent a question to the trap, read where the kernel says it (Linux): the row of the client's socket in /proc/net
gives the user and the inode, and the inode gives the process that holds it. None off Linux or when the socket is
gone. ``peer`` is the (address, port...) of the client."""
if not sys.platform.startswith("linux"):
return None
six = ":" in str(peer[0])
names = ("udp6" if six else "udp",) if protocol == "udp" else ("tcp6" if six else "tcp",)
for name in names:
try:
with open("/proc/net/" + name, encoding="utf-8") as table:
row = row_from_proc_net(table.read(), int(peer[1]))
except OSError:
continue
if row is not None:
uid, inode = row
pid = pid_of_socket_inode(inode) if inode else None
return Asker(uid, pid, command_of(pid) if pid is not None else "")
return None
def owner_of_the_peer(protocol: str, peer) -> Optional[int]:
"""The uid of the process that sent a question to the trap (see :func:`who_asked`), or None."""
asker = who_asked(protocol, peer)
return None if asker is None else asker.uid
class ResolverTrap:
"""A resolver on loopback that counts what it is asked. See the module docstring.
It counts what the BROWSER asks, and the test says "the browser asked the resolver of the machine". The browser is found from
the socket the question came from (its inode, the process that holds it, its parents up to ``root_pid``, by default the
test process): a question counts if that process is the browser or descends from it. A question from any other process is
answered and listed in :attr:`foreign` with its pid and command, not counted: /etc/resolv.conf is the machine's, and on a
CI runner the agent of the runner, even as root, asks for github.com through it; and the test process's own python (the
core, which asks github.com for the latest GeoIP tag when no database is given) is not the browser either (runs
43188313516, 43211837926: the browser was blamed for names it never asked, and a user filter cannot tell them apart). There
is no list of names. A question whose process cannot be traced is judged by its user (``only_uid``, by default the
effective uid), and one whose socket cannot be found any more counts as the browser's."""
available, reason = _trap_capability()
def __init__(self, answers: Optional[Dict[str, str]] = None, *, port: int = 53,
rewrite_resolv_conf: bool = True, only_uid: Optional[int] = None, owner_of=None,
root_pid: Optional[int] = None, parent_of_pid=None, is_browser=None):
self.answers = {k.lower(): v for k, v in (answers or {}).items()}
self.port = port
#: The loopback address the trap listens on once it is bound (see TRAP_ADDRESSES).
self.address = "127.0.0.1"
self.rewrite_resolv_conf = rewrite_resolv_conf
#: Every question: (name, qtype, "udp"|"tcp").
self.queries: List[DohQuery] = []
#: The questions of other users' processes: (query, uid). Answered, not counted.
self.foreign: List[Tuple[DohQuery, Asker]] = []
self.root_pid = root_pid if root_pid is not None else os.getpid()
self._parent_of = parent_of_pid or parent_of
self._is_browser = is_browser or is_a_browser_process
self.only_uid = only_uid if only_uid is not None else (os.geteuid() if hasattr(os, "geteuid") else None)
self._owner_of = owner_of or who_asked
self._lock = threading.Lock()
self._sockets: List[socket.socket] = []
#: The threads that answer on `_sockets`, and the flag that ends them: see `_restore`.
self._threads: List[threading.Thread] = []
self._ending = threading.Event()
self._original: Optional[bytes] = None
self._running = False
#: Why the last bind attempt failed (the error of the socket), for the message when none succeeds.
self._bind_error: Optional[OSError] = None
# --- 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:
seen = ", ".join("%s/%d (%s)" % q for q in self.queries) or "nothing"
if self.foreign:
seen += " [and %d question(s) of other processes, not counted: %s]" % (
len(self.foreign), "; ".join(sorted({"%s from pid %s (uid %d) %s" % (
q.name, a.pid if a.pid is not None else "?", a.uid, a.command or "") for q, a in self.foreign})))
return seen
# --- 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(("nameserver %s\noptions timeout:1 attempts:1\n" % self.address).encode("ascii"))
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
# ⛔ THE THREADS END BEFORE THE SOCKETS ARE CLOSED. A thread blocked in accept() or recvfrom() is not woken by a close()
# of its socket from another thread (Linux): the kernel keeps the socket, still bound, until the call returns, and the
# call never returns. The port stayed taken after the test, and the NEXT trap found 127.0.0.1-8:53 "already in use"
# one address per test, until all eight were gone (run 43164943499; here: the eighth trap of a run of 19 tests).
# The answering loops therefore wake up every 0.2 s to look at `_ending`, and the socket is closed once they are gone.
self._ending.set()
for t in self._threads:
t.join(2.0)
self._threads = []
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:
addresses = TRAP_ADDRESSES if self.port != 0 else TRAP_ADDRESSES[:1]
for address in addresses:
for attempt in range(200):
made = self._bind_once(discarded, address)
if made:
break
if self.port != 0:
break
if made:
self.address = address
break
if not made:
raise OSError("the resolver trap found no port it could bind for TCP and UDP (port %d on %s; the last error: %s)%s"
% (self.port, ", ".join(addresses), self._bind_error, _who_holds(self.port)))
finally:
for s in discarded:
s.close()
self._sockets += made
for s in made:
s.settimeout(0.2)
target = self._serve_udp if s.type == socket.SOCK_DGRAM else self._serve_tcp
t = threading.Thread(target=target, args=(s,), daemon=True)
self._threads.append(t)
t.start()
def _bind_once(self, discarded: List[socket.socket], address: str = "127.0.0.1") -> 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, address, 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 as exc:
self._bind_error = exc
discarded += pair
if required:
discarded += made
return []
continue
made += pair
self.port = port
return made
# --- answering -----------------------------------------------------------------------------------------------
def _respond(self, message: bytes, protocol: str, peer=None) -> Optional[bytes]:
try:
query = parse_query(message)
except ValueError:
return None
asker = self._owner_of(protocol, peer) if peer is not None else None
if isinstance(asker, int): # an owner given as a bare uid
asker = Asker(asker, None, "")
ours = True
if asker is not None:
if asker.pid is not None:
ours = under_a_browser(asker.pid, self.root_pid, self._parent_of, self._is_browser)
elif self.only_uid is not None:
ours = asker.uid == self.only_uid
with self._lock:
if ours:
self.queries.append(DohQuery(query.name, query.qtype, protocol))
else:
self.foreign.append((DohQuery(query.name, query.qtype, protocol), asker))
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 not self._ending.is_set():
try:
data, peer = sock.recvfrom(4096)
except socket.timeout:
continue
except OSError:
return
response = self._respond(data, "udp", peer)
if response is not None:
try:
sock.sendto(response, peer)
except OSError:
pass
def _serve_tcp(self, listener: socket.socket) -> None:
while not self._ending.is_set():
try:
conn, peer = listener.accept()
except socket.timeout:
continue
except OSError:
return
threading.Thread(target=self._tcp_conversation, args=(conn, peer), daemon=True).start()
def _tcp_conversation(self, conn: socket.socket, peer=None) -> 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", peer)
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)
+88
View File
@@ -0,0 +1,88 @@
"""Which of the engine's processes host a site, told by the name of the site: what the e2e tests that look at processes read.
Counting processes between two reads does not tell a site's process from the browser's own. The browser starts
content processes for itself: it refills the pool of preallocated ones (`dom.ipc.processPrelaunch.fission.number`)
whenever it gets to it, and the New Tab page starts a process for a Mozilla site of its own (remote type
`webIsolated=https://mozgcp.net`, born about a second after the process of the New Tab page, with any page, even
about:blank). Under load that process arrives after the first read of a test, and "the set of processes changed"
read it as the effect of the frame under test: the same-site control was red in 14 of 30 runs of the whole e2e suite
(`[P] -> [P, P2]`), and "at least one new process" for a cross-site frame was satisfied by that process alone.
So a test asks for the processes of ONE site, by name. With the pref `fission.processSiteNames` on (`NAMED_BY_SITE`,
test-only: the product never sets it) a content process that hosts a site is named by that site
(`ContentChild::SetProcessName`, dom/ipc/ContentChild.cpp: a leading `https://` is dropped), and on Linux
`prctl(PR_SET_NAME)` keeps 15 characters (ipc/glue/ProcessUtils_linux.cpp). Measured on firefox-62 (Linux):
- the process of `http://a.test` in a Playwright context is named `http://a.test^u`: the site, then the start of
`^userContextId=N`, cut at 15 characters;
- the process the New Tab page starts is named `mozgcp.net`;
- a process with no site keeps its type: `Web Content`, `Privileged Cont`, `WebExtensions`.
The process gets its name before any document loads in it, so when a page of the site has run, its process already
answers to the site. Windows names no process (ProcessUtils_none.cpp): a test that looks at sites skips there and
says so.
"""
from __future__ import annotations
import os
import sys
import pytest
#: The pref overlay that names a content process by the site it hosts. Test-only.
NAMED_BY_SITE = {"fission.processSiteNames": True}
#: What PR_SET_NAME keeps of a process name on Linux.
NAME_LENGTH = 15
def name_of_site(site):
"""What the process name of `site` starts with: the site without a leading `https://`, cut at 15 characters."""
if site.startswith("https://"):
site = site[len("https://"):]
return site[:NAME_LENGTH]
def hosts_site(name, site):
"""True when a process called `name` is a process of `site`.
The name is the prefix itself, or the prefix followed by `^` (the start of `^userContextId=N`). When the prefix is
shorter than 15 characters the next character has to be `^`, so `http://a.test` does not match a process of
`http://a.testing.example`."""
prefix = name_of_site(site)
if name == prefix:
return True
if not name.startswith(prefix):
return False
return len(prefix) >= NAME_LENGTH or name[len(prefix)] == "^"
def site_pids(processes, site, engine_dir=None):
"""The pids, among `processes` (psutil-like), of the content processes (`-contentproc ... tab`) that host `site`;
with `engine_dir`, only those of the engine in that directory."""
import psutil
pids = set()
for proc in processes:
try:
if engine_dir is not None and not os.path.normcase(proc.exe()).startswith(os.path.normcase(engine_dir)):
continue
name, cmd = proc.name(), proc.cmdline()
except psutil.Error:
continue
if "-contentproc" in cmd and cmd and cmd[-1] == "tab" and hosts_site(name, site):
pids.add(proc.pid)
return pids
def site_processes_below(root_pid, site, engine_dir=None):
"""The pids of the processes below `root_pid` that host `site`. Off Linux the test skips: no name says it."""
import psutil
if not sys.platform.startswith("linux"):
pytest.skip("only Linux names a content process by the site it hosts; %s names none" % sys.platform)
try:
children = psutil.Process(root_pid).children(recursive=True)
except psutil.Error:
return set()
return site_pids(children, site, engine_dir)
+392
View File
@@ -0,0 +1,392 @@
"""What the tests of "the page behind a declared exit" share: the exits, a gateway that tells a local site which of its
connections came through it, the page's reads, and the judges that turn what was read into sentences.
THE QUESTION. A person who buys a proxy expects every site to see ONE place: the address of its exit, the time zone of that
address, the language of that country, no trace of the machine the browser runs on. The check used to be made by hand, through a
paid proxy, against pages on the internet. Here the proxy is a local SOCKS5 gateway that DECLARES its exit
(``Gateway.tcp_exit``, the address it answers to "what is my address"), and the pages are local ones that read the same values a
page on the internet reads.
THE TRUTH FOR THE ZONE AND THE COUNTRY is the core's own offline geo database (``invisible_core._geo.ip_to_timezone`` and
``ip_to_country``), not a second service: the tests ask whether the browser's pages say what the core's database says about the
declared exit, which is the path ``prepare_session_geo`` takes. Whether the database is right about the world is not asked here.
THE ADDRESSES BELOW ARE PUBLIC, and each one is an address whose zone and country the geo database knows (the tests need that:
a documentation address has no zone). They are built from parts so that no dotted public address stands in a file.
Nothing here opens a browser. ``test_the_realness_helpers.py`` holds the judges and the gateway to what they say.
"""
from __future__ import annotations
import http.server
import ipaddress
import re
import socket
import threading
from dataclasses import dataclass, field
from datetime import datetime
from typing import Any, Dict, Iterable, List, Optional, Sequence, Set, Tuple
from zoneinfo import ZoneInfo
from _doh_servers import DOH_TARGETS, DohGateway, is_loopback, relay
from _servers import LocalServer
from _socks_servers import WEB_NAME, WHOAMI4, WHOAMI6
from test_webrtc_realness import candidates, host_candidates, is_mdns, srflx_candidates
def _address(*parts: int) -> str:
return ".".join(str(part) for part in parts)
#: Six declared exits, each an address whose zone and country the geo database knows, on four continents: a zone west of UTC
#: with daylight saving, a zone with a half-hour offset, one east of the date line's neighbours, a southern-hemisphere zone whose
#: daylight saving runs the other way, and two in Europe/South America. The zone the tests expect is asked of the database at
#: test time; only the address is fixed here.
EXITS: Dict[str, str] = {
"germany": _address(1, 178, 10, 5),
"japan": _address(1, 0, 16, 5),
"india": _address(1, 6, 0, 5),
"australia": _address(1, 0, 4, 5),
"brazil": _address(1, 178, 32, 5),
"united_states": _address(1, 32, 239, 5),
}
#: The names the pages are reached by. The FakeDoh answers them with the loopback where the site is, so the only way to the site
#: is a name resolved by DoH through the gateway and a CONNECT by address.
SITE_NAME = "exit-site.test"
ZONE_NAMES = {SITE_NAME: "127.0.0.1"}
#: Two instants a page reads its offset at: 15 January and 15 July 2025, noon UTC, in milliseconds. One is in the northern
#: winter and one in the northern summer, so a zone whose daylight saving is wrong in one hemisphere reads a wrong offset at one
#: of them.
INSTANTS_MS = (1736942400000, 1752580800000)
#: What a retail Firefox reports as the name of a zone for which ICU keeps an older canonical name. The database says the first,
#: a retail browser in that zone prints the second (or the first): either is the zone of the exit.
ZONE_NAMES_OF_A_RETAIL_FIREFOX: Dict[str, Tuple[str, ...]] = {
"Asia/Kolkata": ("Asia/Kolkata", "Asia/Calcutta"),
}
#: The primary language subtags that are plausible for the country of an exit: the national language of the country and
#: English, which a Firefox of any country can carry (the English build is the commonest one everywhere). A country that is not
#: in the table is checked for the agreement of the reads with one another only.
PLAUSIBLE_PRIMARY: Dict[str, Set[str]] = {
"US": {"en", "es"}, "GB": {"en"}, "CA": {"en", "fr"}, "AU": {"en"}, "NZ": {"en"}, "IE": {"en"}, "ZA": {"en", "af"},
"IN": {"en", "hi"}, "SG": {"en", "zh"}, "DE": {"de", "en"}, "AT": {"de", "en"}, "CH": {"de", "fr", "it", "en"},
"FR": {"fr", "en"}, "BE": {"fr", "nl", "en"}, "NL": {"nl", "en"}, "IT": {"it", "en"}, "ES": {"es", "ca", "en"},
"PT": {"pt", "en"}, "BR": {"pt", "en"}, "MX": {"es", "en"}, "AR": {"es", "en"}, "CL": {"es", "en"}, "CO": {"es", "en"},
"JP": {"ja", "en"}, "KR": {"ko", "en"}, "CN": {"zh", "en"}, "TW": {"zh", "en"}, "PL": {"pl", "en"}, "SE": {"sv", "en"},
"NO": {"nb", "nn", "no", "en"}, "DK": {"da", "en"}, "FI": {"fi", "en"}, "RU": {"ru", "en"}, "UA": {"uk", "ru", "en"},
"TR": {"tr", "en"},
}
# ---------------------------------------------------------------------------------------------------------- the gateway
class ExitGateway(DohGateway):
"""A gateway that declares an exit AND remembers the local port of every connection it opened for a page.
A real proxy's exit is the address a site sees as the peer of its connection. On loopback every peer is 127.0.0.1, so the
gateway says which connections are its own instead: ``upstream_ports`` holds the source port of each connection it opened
to a loopback server, recorded BEFORE it answers the CONNECT, so the server (which is asked only after the browser has the
answer) always finds it. A connection of the browser that did not come through the gateway has a port that is not there:
to the site it is a direct connection, a leak."""
def __init__(self, *args: Any, **kwargs: Any):
self.upstream_ports: Set[int] = set()
self._ports_lock = threading.Lock()
super().__init__(*args, **kwargs)
def came_through(self, source_port: int) -> bool:
with self._ports_lock:
return source_port in self.upstream_ports
def _connect(self, c: socket.socket, host: str, port: int) -> None:
special = (host, port) in DOH_TARGETS or (host, port) in (WHOAMI4, WHOAMI6, (WEB_NAME, 80))
if special or not is_loopback(host):
super()._connect(c, host, port)
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)
with self._ports_lock:
self.upstream_ports.add(upstream.getsockname()[1])
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 reads
#: What a page and a worker read, as ONE function: the worker's source is made from it, so the two cannot drift. The offset is
#: read two ways: from the clock of the page (``getTimezoneOffset``) and from the wall clock ``Intl`` prints for the zone the
#: page itself names (the difference with UTC). ``0 - x`` and not ``-x``, so that a zero is +0 on the wire.
READ_JS = """() => {
const instants = %s;
const zone = new Intl.DateTimeFormat().resolvedOptions().timeZone;
const ahead = (t) => {
const p = {};
for (const x of new Intl.DateTimeFormat('en-US', {timeZone: zone, hourCycle: 'h23', year: 'numeric', month: 'numeric',
day: 'numeric', hour: 'numeric', minute: 'numeric', second: 'numeric'}).formatToParts(new Date(t))) p[x.type] = x.value;
return Math.round((Date.UTC(+p.year, +p.month - 1, +p.day, +p.hour %% 24, +p.minute, +p.second) - t) / 60000);
};
return {
zone,
offsets_by_date: instants.map((t) => 0 - new Date(t).getTimezoneOffset()),
offsets_by_intl: instants.map(ahead),
language: navigator.language,
languages: [...navigator.languages],
intl: new Intl.DateTimeFormat().resolvedOptions().locale,
};
}""" % list(INSTANTS_MS)
#: The page: asks the site what address it sees, makes one fetch (the header the site receives from a fetch), reads, and has a
#: dedicated worker read the same and fetch once (the header of a worker's request).
PAGE_JS = """async () => {
const read = %s;
const ip = (await (await fetch('/ip', {cache: 'no-store'})).text()).trim();
await (await fetch('/fetch', {cache: 'no-store'})).text();
const own = read();
const worker = await new Promise((resolve, reject) => {
const timer = setTimeout(() => reject(new Error('the worker never answered')), 20000);
const w = new Worker('/worker.js');
w.onmessage = (e) => { clearTimeout(timer); resolve(e.data); };
w.onerror = (e) => { clearTimeout(timer); reject(new Error('worker error: ' + e.message)); };
w.postMessage(0);
});
return {ip, page: own, worker};
}""" % READ_JS
WORKER_JS = ("const read = %s;\nonmessage = async () => {\n await (await fetch('/worker-fetch', {cache: 'no-store'})).text();\n"
" postMessage(read());\n};\n" % READ_JS)
# --------------------------------------------------------------------------------------------------------------- the site
@dataclass(frozen=True)
class Arrival:
"""One request the site received: the path, the source port of the connection, and whether the gateway opened it."""
path: str
source: str
via_gateway: bool
accept_language: Optional[str]
class Site:
"""The local site: ``/ip`` says which address the site sees (the exit the gateway declares, or ``DIRECT <address>`` for a
connection the gateway did not open), ``/fetch`` and ``/worker-fetch`` only count, ``/worker.js`` is the worker."""
def __init__(self, gateway: ExitGateway):
outer = self
self.gateway = gateway
self.arrivals: List[Arrival] = []
self._lock = threading.Lock()
class Handler(http.server.BaseHTTPRequestHandler):
def do_GET(self) -> None: # noqa: N802
path = self.path.split("?")[0]
host, port = self.client_address[:2]
through = outer.gateway.came_through(port)
with outer._lock:
outer.arrivals.append(Arrival(path, "%s:%d" % (host, port), through, self.headers.get("Accept-Language")))
if path == "/ip":
body, kind = (outer.gateway.tcp_exit if through else "DIRECT %s" % host).encode(), "text/plain"
elif path == "/worker.js":
body, kind = WORKER_JS.encode(), "text/javascript"
elif path == "/":
body, kind = b"<!doctype html><title>exit</title><body>exit</body>", "text/html; charset=utf-8"
else:
body, kind = b"ok", "text/plain"
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: Any) -> None:
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: str = SITE_NAME, path: str = "/") -> str:
return "http://%s:%d%s" % (name, self.port, path)
def headers_of(self, *paths: str) -> Dict[str, Optional[str]]:
"""The Accept-Language of the LAST request of each path (None when the request carried none or never came)."""
with self._lock:
seen = list(self.arrivals)
return {path: next((a.accept_language for a in reversed(seen) if a.path == path), None) for path in paths}
def close(self) -> None:
self._server.shutdown()
self._server.server_close()
# ------------------------------------------------------------------------------------------------------- the host's own
def host_addresses() -> Set[str]:
"""Every address of every interface of this machine, normalised (loopback and link-local included). ``psutil`` is a
dependency of the package, and answers the same on Linux and on Windows."""
import psutil
found: Set[str] = set()
for addresses in psutil.net_if_addrs().values():
for entry in addresses:
if entry.family in (socket.AF_INET, socket.AF_INET6):
try:
found.add(ipaddress.ip_address(entry.address.split("%")[0]).compressed)
except ValueError:
continue
return found
_IPV4_WORD = re.compile(r"(?<![0-9A-Za-z.])(?:\d{1,3}\.){3}\d{1,3}(?![0-9A-Za-z.])")
_IPV6_WORD = re.compile(r"(?<![0-9A-Za-z:])(?:[0-9A-Fa-f]{0,4}:){2,7}[0-9A-Fa-f]{0,4}(?![0-9A-Za-z:])")
def addresses_in(text: str) -> List[ipaddress._BaseAddress]:
"""Every IPv4 and IPv6 address written in ``text`` (a name such as ``<uuid>.local`` is none)."""
found = []
for token in _IPV4_WORD.findall(text) + _IPV6_WORD.findall(text):
try:
found.append(ipaddress.ip_address(token))
except ValueError:
continue
return found
# -------------------------------------------------------------------------------------------------------------- the judges
def ip_problems(ip_seen: str, arrivals: Sequence[Arrival], direct: Sequence[str], exit_ip: str, connects: Sequence[Tuple[str, int]],
site_port: int) -> List[str]:
"""What is wrong with "the site sees the exit and nothing reached it, or the network, directly"."""
problems: List[str] = []
if ip_seen != exit_ip:
problems.append("the page was told its address is %r, the gateway's declared exit is %r" % (ip_seen, exit_ip))
if not arrivals:
problems.append("the site received no request at all")
outside = [a for a in arrivals if not a.via_gateway]
if outside:
problems.append("the site received %d request(s) on connections the gateway did not open (a direct connection): %s"
% (len(outside), [(a.path, a.source) for a in outside]))
if ("127.0.0.1", site_port) not in connects:
problems.append("the gateway never saw a CONNECT to the site, it saw %s" % list(connects))
if direct:
problems.append("the browser opened connections past the gateway: %s" % list(direct))
return problems
def webrtc_problems(probe: Dict[str, Any], exit_ip: str, host: Iterable[str]) -> List[str]:
"""What of this machine, or what incoherent with the exit, the candidates and the SDP of a gather show."""
lines = list(probe.get("candidates") or [])
sdp = probe.get("sdp") or ""
cands = candidates(lines)
problems: List[str] = []
if not cands:
return ["the gather produced no candidate at all (%s)" % probe.get("errors")]
raw = [c["address"] for c in host_candidates(cands) if not is_mdns(c["address"])]
if raw:
problems.append("host candidates that are not mDNS names: %s" % raw)
six = [c["address"] for c in cands if ":" in c["address"] and not is_mdns(c["address"])]
if six and ipaddress.ip_address(exit_ip).version == 4:
problems.append("IPv6 candidates behind an IPv4 exit: %s" % six)
reflexive = sorted({c["address"] for c in srflx_candidates(cands)})
if reflexive and reflexive != [exit_ip]:
problems.append("the server-reflexive candidate is %s, the exit is %s" % (reflexive, exit_ip))
written = addresses_in(sdp + "\n" + "\n".join(lines))
private = sorted({str(a) for a in written if a.version == 4 and not a.is_unspecified and (a.is_private or a.is_link_local
or a.is_loopback)})
if private:
problems.append("private or loopback IPv4 addresses in the SDP or the candidates: %s" % private)
mine = set(host)
own = sorted({a.compressed for a in written if a.compressed in mine})
if own:
problems.append("addresses of this machine's interfaces in the SDP or the candidates: %s" % own)
return problems
def acceptable_zones(zone: str) -> Tuple[str, ...]:
return ZONE_NAMES_OF_A_RETAIL_FIREFOX.get(zone, (zone,))
def expected_offsets(zone: str) -> List[int]:
"""The minutes a zone is ahead of UTC at each of :data:`INSTANTS_MS`, from the system tz database (``zoneinfo``)."""
info = ZoneInfo(zone)
return [int(datetime.fromtimestamp(t / 1000, tz=info).utcoffset().total_seconds() // 60) for t in INSTANTS_MS]
def timezone_problems(reads: Dict[str, Dict[str, Any]], zone: str) -> List[str]:
"""``reads`` maps a scope name (page, worker) to what :data:`READ_JS` returned there; every scope must say ``zone`` and the
offsets of ``zone`` at both instants, read both ways."""
problems: List[str] = []
want = expected_offsets(zone)
for scope, read in reads.items():
if read.get("zone") not in acceptable_zones(zone):
problems.append("%s: Intl says the zone is %r, the exit's is %s" % (scope, read.get("zone"), zone))
for way in ("offsets_by_date", "offsets_by_intl"):
if read.get(way) != want:
problems.append("%s: %s are %s, the offsets of %s at the two instants are %s" % (scope, way, read.get(way), zone, want))
return problems
def _tags(header: str) -> List[str]:
return [part.split(";")[0].strip() for part in header.split(",") if part.strip()]
def language_problems(reads: Dict[str, Dict[str, Any]], headers: Dict[str, Optional[str]], country: Optional[str]) -> List[str]:
"""The language of a session as everything a site can read says it: ``reads`` (page, worker), the Accept-Language of the
requests (``headers``, by path), and the plausibility of the primary language for ``country``."""
problems: List[str] = []
page = reads["page"]
languages = page.get("languages") or []
if not languages:
return ["navigator.languages is empty"]
primary = languages[0]
if page.get("language") != primary:
problems.append("navigator.language is %r, navigator.languages starts with %r" % (page.get("language"), primary))
for scope, read in reads.items():
if read.get("intl") != primary:
problems.append("%s: the Intl locale is %r, the language is %r" % (scope, read.get("intl"), primary))
if scope != "page":
for key in ("language", "languages"):
if read.get(key) != page.get(key):
problems.append("%s: %s is %r, the page's is %r" % (scope, key, read.get(key), page.get(key)))
for path, header in headers.items():
if header is None:
problems.append("%s: the request carried no Accept-Language" % path)
elif _tags(header) != languages:
problems.append("%s: Accept-Language is %r, navigator.languages is %s" % (path, header, languages))
table = PLAUSIBLE_PRIMARY.get(country or "")
if table is not None and primary.split("-")[0].lower() not in table:
problems.append("the language %r is not plausible for %s (plausible: %s)" % (primary, country, sorted(table)))
return problems
@dataclass
class Observation:
"""Everything one launch behind one declared exit showed, as plain data (the browser and the servers are closed)."""
label: str
exit_ip: str
zone: str
country: Optional[str]
ip_seen: str = ""
reads: Dict[str, Dict[str, Any]] = field(default_factory=dict)
arrivals: List[Arrival] = field(default_factory=list)
headers: Dict[str, Optional[str]] = field(default_factory=dict)
probe: Dict[str, Any] = field(default_factory=dict)
connects: List[Tuple[str, int]] = field(default_factory=list)
site_port: int = 0
direct: List[str] = field(default_factory=list)
watched: int = 0
host: Set[str] = field(default_factory=set)
doh_vias: Dict[str, Set[str]] = field(default_factory=dict)
doh_connects: List[Tuple[str, int]] = field(default_factory=list)
gateway_name: str = ""
trap_ran: bool = False
trap_queries: List[str] = field(default_factory=list)
datagrams: List[Tuple[str, int]] = field(default_factory=list)
+637
View File
@@ -0,0 +1,637 @@
"""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 gateways are the 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.
* :func:`silent_udp` - UDP ASSOCIATE is granted and the relay carries datagrams, but
no STUN server ever answers (a router that drops UDP behind a working handshake): the core's
measurement ends in ``unmeasured``.
THE CORE MEASURES THE UDP EXIT of a SOCKS5 proxy before it declares it to the browser (``invisible_core._udp_exit``: a STUN
Binding through the proxy's ASSOCIATE, compared with the TCP exit). A test that wants the relay to be used hands the core
this gateway's measurement server, ``udp_stun_servers=gw.measure_servers`` (``MEASURE_NUMBER``: the fake STUN server by a
documentation NUMBER of its own, so the datagrams of the measurement are told apart from those of the page, which asks
``STUN_NUMBER``). The measurement is a UDP ASSOCIATE of its own: :attr:`Gateway.associates` and :attr:`Gateway.datagrams` count it.
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 select
import socket
import struct
import threading
import time
from typing import List, Optional, Set, 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"
#: The same fake STUN server by ANOTHER number: where the core's own measurement of the UDP exit asks (``udp_stun_servers``),
#: so that what the measurement sent through the relay is never mistaken for what the page sent. Documentation address too.
MEASURE_NUMBER = "198.51.100.6"
#: 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 same page by an address (RFC 5737 TEST-NET-3): since the browser resolves names itself and connects by address, a
#: test that loads the gateway's page through a SOCKS gateway names it by this one.
WEB_ADDRESS = "203.0.113.80"
#: 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, bind_host: str = "127.0.0.1"):
self.mapped_ip = mapped_ip
self.mapped_port = mapped_port
self.requests = 0
self._sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
# On the address the relay sends from: Windows sends neither from an address of the host to loopback (WinError 10049) nor
# from loopback to an address of the host (10051), so a relay that leaves from the host's address needs its STUN there too.
self._sock.bind((bind_host, 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, stun_answers: bool = True,
tcp_from_exit: bool = False):
assert udp in ("relay", "refuse")
self.udp = udp
#: False: the relay carries the datagrams but the fake STUN server is mute (its requests are dropped).
self.stun_answers = stun_answers
#: 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 the TCP connections the gateway opens for a CONNECT also leave from ``exit_host`` (as its datagrams do): a server that
#: is reachable DIRECT then tells a connection of the proxy from a connection of the browser by the source.
self.tcp_from_exit = tcp_from_exit
#: 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, bind_host="127.0.0.1" if exit_host.startswith("127.") else exit_host)
#: 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()
#: The same instant on the wall clock (seconds since the epoch), to compare with what a page reads from Date.now().
self.wall0 = time.time()
#: Every TCP connection the gateway accepted (a SOCKS handshake starts with one), as seconds from t0.
self.accepted: List[float] = []
#: 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]] = []
#: The local port of the socket each granted association sends from: what a server behind the gateway sees as the port
#: of the relay, and what tells a datagram that went by the relay from one that came direct from this host.
self.exit_ports: List[int] = []
#: A datagram the relay could not send (a socket that raised): said here and in the report of a test, never mute.
self.send_errors: List[str] = []
#: The hosts the relay forwards a datagram to (the fake STUN server aside); None: any host. A test that sends from an
#: address of this host keeps its lab closed: the browser's own background QUIC does not leave the machine.
self.forward_only_to: Optional[Set[str]] = None
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 measure_servers(self) -> List[str]:
"""The ``udp_stun_servers`` of a launch behind this gateway: where the core measures its UDP exit, in the
form the parameter takes (``"ip:port"``, an IPv4 literal)."""
return ["%s:%d" % (MEASURE_NUMBER, STUN_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
self.accepted.append(time.monotonic() - self.t0)
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 _open_upstream(self, target: Tuple[str, int]) -> socket.socket:
"""The TCP connection of a CONNECT: from ``exit_host`` when ``tcp_from_exit``, else from wherever the system chooses."""
if not self.tcp_from_exit:
return socket.create_connection(target, timeout=10)
up = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
try:
up.settimeout(10)
up.bind((self.exit_host, 0))
up.connect(target)
except OSError:
up.close()
raise
return up
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) in ((WEB_NAME, 80), (WEB_ADDRESS, 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 = self._open_upstream(self._target(host, port))
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, what: str = "a datagram") -> None:
"""Run ``fn`` after half the round trip (at once on loopback). A send that fails is RECORDED in ``send_errors`` (a
silent one hid that Windows cannot send from 127.0.0.1 to an address of its own host: WinError 10051), except on a gateway
that is already closed."""
def run() -> None:
try:
fn()
except OSError as e:
if not self._closed:
self.send_errors.append("%s: %s %s" % (what, type(e).__name__, e))
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), "the answer to the client")
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), (MEASURE_NUMBER, STUN_PORT)):
if not self.stun_answers:
return None
# 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)
if self.forward_only_to is not None and host not in self.forward_only_to:
return 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))
self.exit_ports.append(out.getsockname()[1])
if hasattr(socket, "SIO_UDP_CONNRESET"):
# Windows: an ICMP "port unreachable" to a send makes the NEXT recvfrom raise WinError 10054 and, uncaught, ends the
# thread that reads: a relay that stops carrying answers because one datagram found nobody. Off, as a real relay has it.
for sock in (relay, out):
sock.ioctl(socket.SIO_UDP_CONNRESET, False)
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 ConnectionResetError:
continue
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), "the datagram to %s:%d" % target)
def outbound() -> None: # world -> client
while True:
try:
d, src = out.recvfrom(65536)
except ConnectionResetError:
continue
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,
exit_host: str = "127.0.0.1") -> 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, exit_host=exit_host)
def tcp_only(*, exit_ip: str = EXIT, user: Optional[str] = None,
password: Optional[str] = None, relay_host: str = "127.0.0.1", exit_host: str = "127.0.0.1") -> 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, relay_host=relay_host, exit_host=exit_host)
def mismatched(*, tcp_exit: str = EXIT, udp_exit: str = OTHER_EXIT,
user: Optional[str] = None, password: Optional[str] = None, relay_host: str = "127.0.0.1",
exit_host: str = "127.0.0.1") -> 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, relay_host=relay_host, exit_host=exit_host)
def silent_udp(*, exit_ip: str = EXIT, user: Optional[str] = None, password: Optional[str] = None,
relay_host: str = "127.0.0.1", exit_host: str = "127.0.0.1") -> Gateway:
"""TCP works and UDP ASSOCIATE is granted, but no STUN request is ever answered: the core's measurement is
``unmeasured``."""
return Gateway(udp="relay", tcp_exit=exit_ip, udp_exit=exit_ip, user=user, password=password,
relay_host=relay_host, exit_host=exit_host, stun_answers=False)
# ----------------------------------------------------------------------------------------------------------------
# A tiny TCP-only SOCKS5 server for the e2e tests (the fixture `socks5_tcp_only` of conftest.py makes one).
# ----------------------------------------------------------------------------------------------------------------
class Socks5TcpOnly:
"""Minimal SOCKS5: no-auth, CONNECT (TCP) relayed, UDP ASSOCIATE refused.
Reproduces a residential TCP-only proxy: pages load over TCP, but WebRTC's
UDP path is dead - which (for a no-camera page in default_address_only mode)
is exactly what made the default-route probe fail and ICE return zero
candidates before Fix C.
"""
def __init__(self):
self._srv = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
self._srv.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
self._srv.bind(("127.0.0.1", 0))
self._srv.listen(16)
self.port = self._srv.getsockname()[1]
self.udp_associate_attempts = 0
self._stop = False
self._t = threading.Thread(target=self._serve, daemon=True)
self._t.start()
def _serve(self):
while not self._stop:
try:
conn, _ = self._srv.accept()
except OSError:
break
threading.Thread(target=self._handle, args=(conn,), daemon=True).start()
def _recv_exact(self, sock, n):
buf = b""
while len(buf) < n:
chunk = sock.recv(n - len(buf))
if not chunk:
return None
buf += chunk
return buf
def _handle(self, conn):
try:
head = self._recv_exact(conn, 2)
if not head or head[0] != 0x05:
conn.close()
return
nmethods = head[1]
self._recv_exact(conn, nmethods)
conn.sendall(b"\x05\x00") # no-auth
req = self._recv_exact(conn, 4)
if not req:
conn.close()
return
ver, cmd, _, atyp = req
if atyp == 0x01:
addr = socket.inet_ntoa(self._recv_exact(conn, 4))
elif atyp == 0x03:
ln = self._recv_exact(conn, 1)[0]
addr = self._recv_exact(conn, ln).decode("ascii", "ignore")
elif atyp == 0x04:
addr = socket.inet_ntop(socket.AF_INET6, self._recv_exact(conn, 16))
else:
conn.close()
return
port = struct.unpack("!H", self._recv_exact(conn, 2))[0]
if cmd != 0x01: # not CONNECT (e.g. UDP ASSOCIATE) → refuse
self.udp_associate_attempts += 1
conn.sendall(b"\x05\x07\x00\x01\x00\x00\x00\x00\x00\x00") # cmd not supported
conn.close()
return
try:
upstream = socket.create_connection((addr, port), timeout=15)
except OSError:
conn.sendall(b"\x05\x04\x00\x01\x00\x00\x00\x00\x00\x00") # host unreachable
conn.close()
return
conn.sendall(b"\x05\x00\x00\x01\x00\x00\x00\x00\x00\x00") # success
self._relay(conn, upstream)
except Exception:
try:
conn.close()
except Exception:
pass
def _relay(self, a, b):
try:
while True:
r, _, _ = select.select([a, b], [], [], 30)
if not r:
break
for s in r:
data = s.recv(65536)
if not data:
return
(b if s is a else a).sendall(data)
finally:
for s in (a, b):
try:
s.close()
except Exception:
pass
def close(self):
self._stop = True
try:
self._srv.close()
except Exception:
pass
+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
+350
View File
@@ -0,0 +1,350 @@
"""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 contextlib
import hashlib
import hmac
import json
import socket
import struct
import subprocess
import threading
import time
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
from typing import Dict, List, Optional, Tuple
from _doh_servers import DohGateway, FakeDoh
from _host_address import this_host_address
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"
#: The exit of a lab that a browser accepts as a real one: a documentation address (RFC 5737, TEST-NET-2, like the TURN server's) that
#: the host holds on its loopback interface (`lab_exit_address`). A mapped address in 127/8 is thrown away by nICEr as bogus.
LAB_EXIT = "198.51.100.9"
MAGIC = 0x2112A442
PASSWORD = "qwerty"
REALM = "hermetic"
NONCE = "6e6f6e6365"
@contextlib.contextmanager
def lab_exit_address(address: str = LAB_EXIT):
"""Hold ``address`` on the loopback interface for the length of the block (Linux, root: ``ip addr add``), so that a gateway can send
from it and a browser reads it as a real exit. It FAILS, never skips, when it cannot (a missing root is a failure of the host the
suite was given): the suite that uses it is listed for Linux only."""
listing = subprocess.run(["ip", "-4", "-o", "addr", "show", "dev", "lo"], capture_output=True, text=True, check=False)
held = (" %s/" % address) in listing.stdout
if not held:
done = subprocess.run(["ip", "addr", "add", "%s/32" % address, "dev", "lo"], capture_output=True, text=True, check=False)
if done.returncode != 0:
raise RuntimeError("cannot hold %s on lo (needs root and iproute2 on Linux): %s" % (address, (done.stderr or done.stdout).strip()))
try:
yield address
finally:
if not held:
subprocess.run(["ip", "addr", "del", "%s/32" % address, "dev", "lo"], capture_output=True, text=True, check=False)
# ── 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, exit_host: str = EXIT_HOST) -> None:
# The address of this host first: on a host with no default route the test skips, with no server started yet.
relay_host = relay_host or this_host_address()
#: Where the gateway's datagrams and connections leave from: what the TURN server hears and what the page must read as its srflx.
self.exit_ip = exit_host
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, 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(self.exit_ip, 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 == chain.exit_ip
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()
+173
View File
@@ -0,0 +1,173 @@
"""What the e2e tests of the UDP line share: the STUN servers the core measures from, the TCP exit of each gateway, what the
launch declared, and the sequence of protocols a page reads on each road.
THE CORE MEASURES THE UDP EXIT of a SOCKS5 proxy before it declares it (``invisible_core._udp_exit``): a STUN Binding sent
through the ASSOCIATE of the proxy to a list of servers, compared with the TCP exit it discovers through the same proxy. Only
``udp: coherent`` makes the engine send UDP to the relay; ``no`` and ``unmeasured`` are "a router that drops UDP" (HTTP/3
too). The list of servers is the explicit launch parameter ``udp_stun_servers`` (``"ip:port"``, IPv4 literals), so a hermetic
test points the measurement at the fake STUN server only its gateway's relay reaches. The caller never declares ``udp``.
Nothing here opens a browser; the unit test ``test_the_udp_line_helpers.py`` holds it to what it says.
"""
from __future__ import annotations
import ipaddress
from typing import Any, Callable, Dict, List, Optional, Sequence
#: How much slower than the first visit a later visit may load, in milliseconds, on the roads where UDP does not work. A
#: retail Firefox on a network that drops UDP loads the later visits as fast as the first (15 of 15 sessions, h2/h2/h2): an h3
#: attempt that waits for a timeout before it falls back to h2 would be seconds.
LOAD_MARGIN_MS = 1500
#: The visits of one page in one context, by kind of road. With NO proxy and the native DNS the retail is measured in loopback
#: and is exact: h2, h3, h3 over three visits. BEHIND A PROXY the names are resolved by DoH, the browser learns the Alt-Svc
#: from the first answer and the retail (Windows 159, DoH forced like our core, 15 sessions per condition) takes its time to
#: move to h3: with UDP free h2/h2/h3 in 9 sessions, h2/h2/h2 in 4 and h2/h3/h3 in 2 in the first runs, and h3 already on the
#: first visit (h3, h2, h2) in 3 sessions of 15 in the third, when the DNS answer carried the HTTPS record; so the page is
#: visited up to ``PROXY_VISITS`` times, and every proxy road makes the same number of visits (a road where UDP is dropped
#: reads h2 on all of them, as the retail does in 15 of 15: the one outcome that repeats). The fixture's first visit is h2
#: because it is reached by an address (no HTTPS record exists), not because the retail never reads h3 first.
DIRECT_VISITS = 3
PROXY_VISITS = 5
#: The roads. ``direct``: no proxy, native DNS. ``socks5_coherent``: a SOCKS5 proxy whose UDP the core measured coherent (UDP
#: free behind the proxy). The others are "a router that drops UDP": a SOCKS5 proxy that refuses UDP, whose UDP leaves
#: elsewhere or that never answers; or an HTTP proxy.
_DIRECT_ROAD = "direct"
_H3_PROXY_ROAD = "socks5_coherent"
_H2_ROADS = ("socks5_no_udp", "socks5_mismatched", "socks5_unmeasured", "http_proxy")
ROADS = (_DIRECT_ROAD, _H3_PROXY_ROAD) + _H2_ROADS
def _literal(entry: Any) -> str:
"""``"ip:port"`` of an IPv4 literal and a port, or ValueError (the form the launch parameter takes)."""
host, sep, port = str(entry).rpartition(":")
if not sep or ipaddress.ip_address(host).version != 4 or not 1 <= int(port) <= 65535:
raise ValueError("%r is not an \"ip:port\" IPv4 literal" % (entry,))
return "%s:%s" % (ipaddress.ip_address(host), int(port))
def measure_servers(gateway: Any) -> List[str]:
"""The ``udp_stun_servers=`` of a launch behind ``gateway``: the server its relay answers for the core's measurement.
One place, so that no test writes a list of its own."""
return [_literal(entry) for entry in gateway.measure_servers]
def egress_by_proxy(*gateways: Any, direct: Optional[str] = None) -> Callable[..., str]:
"""A replacement for ``invisible_core._geo.discover_egress_ip``: the TCP exit of the proxy it is asked about, which is
the one the gateway reports (no local gateway can answer the product's HTTPS question as itself). One gateway or
several (a session proxy and a context proxy have each their own); the UDP probe that follows is NOT replaced, it runs
through the relay for real. ``direct`` answers the discovery made with no proxy. An unknown proxy fails loudly."""
exits = {gateway.server: gateway.tcp_exit for gateway in gateways}
def discover(proxy: Optional[Dict[str, Any]] = None, *_args: Any, **_kwargs: Any) -> str:
if not proxy:
if direct is None:
raise AssertionError("the TCP exit was asked with no proxy and the test gave none")
return direct
server = proxy.get("server") if isinstance(proxy, dict) else None
if server not in exits:
raise AssertionError("the TCP exit of %r was asked and no gateway of the test owns it: %s" % (server, sorted(exits)))
return exits[server]
return discover
def declared_udp(proxy: Dict[str, Any], servers: Sequence[str]) -> str:
"""The ``udp`` the launch measured for ``proxy`` with ``servers``: ``coherent``, ``no`` or ``unmeasured``. It is what the
core remembered for the proxy (and declares to the engine); an AssertionError when the launch measured nothing, so
``unmeasured`` cannot be mistaken for an absent measurement."""
from invisible_core import _udp_exit
from invisible_core._proxy import parse_proxy
endpoint = parse_proxy(proxy)
key = _udp_exit.cache_key(endpoint, _udp_exit.stun_servers(list(servers)))
entry = _udp_exit._cache.get(key)
if entry is None:
raise AssertionError("the launch measured nothing for %r with %s" % (proxy.get("server"), list(servers)))
return entry[1]
def visits_for(road: str) -> int:
"""How many times the page is visited on ``road``: three with no proxy, :data:`PROXY_VISITS` behind any proxy."""
if road == _DIRECT_ROAD:
return DIRECT_VISITS
if road in ROADS:
return PROXY_VISITS
raise KeyError("no such road: %r (roads: %s)" % (road, ", ".join(ROADS)))
def expected_protocols(road: str) -> str:
"""What a retail Firefox reads (``nextHopProtocol`` of the document) over the visits of ``road``, as a sentence."""
visits = visits_for(road)
if road == _DIRECT_ROAD:
return "h2, h3, h3 over %d visits (no proxy, native DNS)" % visits
if road == _H3_PROXY_ROAD:
return ("h2 on the first visit, then h3 from a later visit on and h3 on every one after it, within %d visits "
"(retail with DoH and UDP free: h2/h2/h3 in 9 of 15, h2/h2/h2 in 4, h2/h3/h3 in 2, and h3 first in 3 of 15 in the "
"third run when the DNS answer carries the HTTPS record; this fixture has none: h2 first)" % visits)
return "h2 on every one of %d visits, as fast as the first (retail with UDP dropped: h2/h2/h2 in 15 of 15)" % visits
def no_https_record(host: str, doh: Any = None) -> List[str]:
"""What is wrong with the claim "the first visit of this fixture is h2", as sentences; an empty list when nothing is.
The retail reads h3 at the first visit when the DNS answer for the site carries the HTTPS record (type 65): the third
retail run did in 3 sessions of 15. The fixture reads h2 first only if no such record can reach the browser: the server
is reached by an ADDRESS (no name, no lookup), and the FakeDoh, when one is in the path, has never served a type 65 with
data (``FakeDoh.https_served``)."""
problems: List[str] = []
try:
ipaddress.ip_address(host.strip("[]"))
except ValueError:
problems.append("the server is reached by the name %r: its DNS answer could carry an HTTPS record, and the retail "
"reads h3 at the first visit when it does" % host)
served = list(getattr(doh, "https_served", ())) if doh is not None else []
if served:
problems.append("the FakeDoh served an HTTPS record (type 65) for %s: the first visit may read h3, as the retail does"
% sorted(set(served)))
return problems
def judge_visits(road: str, protocols: Sequence[str], walls_ms: Sequence[float]) -> List[str]:
"""What is wrong with the visits of one page on ``road``, as sentences; an empty list when nothing is.
``protocols`` is the ``nextHopProtocol`` of each visit and ``walls_ms`` the time ``page.goto`` took to the load event;
both have :func:`visits_for` entries. The rules, from the retail:
* ``direct``: exactly h2, h3, h3.
* ``socks5_coherent``: the first visit is h2 (the fixture is reached by an address: no HTTPS record exists, so nothing
tells the browser about h3 before the first connection; the retail itself reads h3 first when the DNS answer carries
the record, so this is a rule of the fixture, checked with :func:`no_https_record`); every later visit is h2 or h3, but once one is h3 all the following are (h3 never goes back to h2); and at
least one visit is h3 (it is NOT required at the second: h2/h2/h3 is the commonest retail sequence).
* the roads where UDP is dropped: h2 on every visit, and no visit loads more than :data:`LOAD_MARGIN_MS` slower than the
first (a fallback that waits for a timeout is a tell)."""
problems: List[str] = []
protocols, walls_ms = list(protocols), list(walls_ms)
visits = visits_for(road)
said = "a retail Firefox reads %s on this road" % expected_protocols(road)
if len(protocols) != visits:
problems.append("%d protocols for %d visits: %s" % (len(protocols), visits, protocols))
if len(walls_ms) != visits:
problems.append("%d load times for %d visits: %s" % (len(walls_ms), visits, walls_ms))
if protocols and protocols[0] == "h3":
problems.append("visit 1 read h3: in this fixture nothing had told the browser yet that the server speaks h3 (no "
"name, no HTTPS record): something told it, or the fixture changed")
if len(protocols) == visits:
if road == _DIRECT_ROAD:
if protocols != ["h2", "h3", "h3"]:
problems.append("the protocols of the %d visits are %s, %s" % (visits, protocols, said))
elif road == _H3_PROXY_ROAD:
first = protocols.index("h3") if "h3" in protocols else None
if first is None:
problems.append("none of the %d visits read h3: %s, %s" % (visits, protocols, said))
elif set(protocols) - {"h2", "h3"} or protocols[0] != "h2" or "h2" in protocols[first:]:
problems.append("the protocols of the %d visits are %s, %s" % (visits, protocols, said))
elif protocols != ["h2"] * visits:
problems.append("the protocols of the %d visits are %s, %s" % (visits, protocols, said))
if len(walls_ms) == visits and road in _H2_ROADS:
for number in range(2, visits + 1):
if walls_ms[number - 1] > walls_ms[0] + LOAD_MARGIN_MS:
problems.append("visit %d loaded in %d ms against %d ms for visit 1 (more than %d ms slower): an h3 attempt "
"that waited for a timeout before the fallback" % (number, walls_ms[number - 1], walls_ms[0], LOAD_MARGIN_MS))
return problems
+135
View File
@@ -0,0 +1,135 @@
"""A witness: a STUN server (UDP) and a TCP listener on ONE local address and port, that writes down who contacted it.
What it is for: a datagram or a connection a browser sends DIRECT, around its proxy, is invisible in a laboratory whose servers sit at
documentation addresses that nothing routes (a leak and a drop look the same: nothing arrives). The witness stands at an address the
browser can reach directly (a documentation address held on ``lo``, see ``_turn_chain.lab_exit_address``), so a leak ARRIVES, from a
source that is not the exit of the proxy, and a test can tell a leak from a drop. It answers a STUN Binding Request with the source it
saw, so a road that works also gives the page a server-reflexive candidate.
``udp`` is every datagram as (source ip, source port, length); ``tcp`` is every connection as (source ip, source port).
"""
from __future__ import annotations
import random
import socket
import sys
import struct
import threading
from typing import Dict, Iterable, List, Tuple
_MAGIC = b"\x21\x12\xa4\x42"
#: How many port numbers the witness tries before it gives up, and where it draws them from after the system's own pick.
TRIES = 200
#: Below the start of Windows' dynamic range (49152), where its excluded ranges are reserved in blocks of a hundred, and
#: below Linux's ephemeral range (32768): a number drawn here is not the next of a sequence the system hands out.
DRAW_FROM = (20000, 32767)
class Witness:
def __init__(self, address: str, port: int = 0) -> None:
self.address = address
self.udp: List[Tuple[str, int, int]] = []
self.tcp: List[Tuple[str, int]] = []
self._lock = threading.Lock()
self._closed = False
# One port number for both, TCP and UDP. Each try binds TCP and then UDP on the same number; if either is refused, both
# are released and another number is tried. The first try is the system's own pick (TCP, port 0). The others are drawn
# at random: Windows hands out ephemeral TCP ports in sequence and keeps excluded ranges of a hundred ports for UDP
# inside the same zone, so "the next pick" lands in the same refused range again and again (WinError 10013, twenty
# tries in a row on a work machine). A given ``port`` is tried once and its refusal is raised as it is.
self._udp, self._tcp, self.port = self._bind_both(address, port)
threading.Thread(target=self._serve_udp, daemon=True).start()
threading.Thread(target=self._serve_tcp, daemon=True).start()
@staticmethod
def _bind_both(address: str, port: int):
refusals: List[str] = []
draw = random.Random()
for attempt in range(1 if port else TRIES):
wanted = port if port else (0 if attempt == 0 else draw.randint(*DRAW_FROM))
tcp = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
udp = None
try:
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((address, wanted))
chosen = tcp.getsockname()[1]
udp = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
udp.bind((address, chosen))
tcp.listen(16)
return udp, tcp, chosen
except OSError as exc:
if port:
tcp.close()
if udp is not None:
udp.close()
raise
refusals.append("%s: %s" % (wanted or "system pick", exc))
tcp.close()
if udp is not None:
udp.close()
raise OSError("the witness found no port number on %s where both TCP and UDP bind, after %d tries; the last refusals: %s"
% (address, TRIES, "; ".join(refusals[-3:])))
# --- what a test reads ------------------------------------------------------------------------------------------
def heard(self) -> Dict[str, list]:
with self._lock:
return {"udp": list(self.udp), "tcp": list(self.tcp)}
def heard_from_other_than(self, allowed: Iterable[str]) -> Dict[str, list]:
"""What the witness heard from a source that is not one of ``allowed`` (the exit of the proxy): a direct send."""
ok = set(allowed)
heard = self.heard()
return {"udp": [h for h in heard["udp"] if h[0] not in ok], "tcp": [h for h in heard["tcp"] if h[0] not in ok]}
@property
def target(self) -> str:
return "%s:%d" % (self.address, self.port)
# --- serving ----------------------------------------------------------------------------------------------------
def close(self) -> None:
self._closed = True
for s in (self._udp, self._tcp):
try:
s.close()
except OSError:
pass
def __enter__(self) -> "Witness":
return self
def __exit__(self, *exc) -> None:
self.close()
def _serve_udp(self) -> None:
while not self._closed:
try:
data, peer = self._udp.recvfrom(2048)
except ConnectionResetError:
continue
except OSError:
return
with self._lock:
self.udp.append((peer[0], peer[1], len(data)))
if len(data) >= 20 and data[0:2] == b"\x00\x01" and data[4:8] == _MAGIC:
xport = struct.pack("!H", peer[1] ^ 0x2112)
xaddr = bytes(a ^ b for a, b in zip(socket.inet_aton(peer[0]), _MAGIC))
attr = struct.pack("!HH", 0x0020, 8) + b"\x00\x01" + xport + xaddr
try:
self._udp.sendto(b"\x01\x01" + struct.pack("!H", len(attr)) + _MAGIC + data[8:20] + attr, peer)
except OSError:
pass
def _serve_tcp(self) -> None:
while not self._closed:
try:
conn, peer = self._tcp.accept()
except OSError:
return
with self._lock:
self.tcp.append((peer[0], peer[1]))
try:
conn.close()
except OSError:
pass
+180 -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).
@@ -312,3 +343,149 @@ def fixture_server():
finally:
httpd.shutdown()
httpd.server_close()
# ======================================================================================================================
# Fixtures shared by several e2e files. They live here, not in one file that the others import from: an imported fixture
# that a test then names as an argument is a redefinition (ruff F811, the lint of the `tests` job).
# ======================================================================================================================
@pytest.fixture
def doh():
import h2 # noqa: F401 - the dev extra installs it: a missing one is a failure, never a skip
from _doh_servers import FakeDoh
from _doh_support import ZONE
server = FakeDoh(ZONE)
yield server
server.close()
@pytest.fixture
def gateway(doh):
from _doh_servers import DohGateway
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."""
import _trap_policy
from _leaks import ResolverTrap
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."""
from pathlib import Path
from _leaks import Watcher
w = Watcher(match=("firefox", Path(firefox_binary).stem.lower())).start()
yield w
w.stop()
@pytest.fixture
def pages():
from _doh_support import Pages
server = Pages()
yield server
server.close()
@pytest.fixture
def socks5_tcp_only():
from _socks_servers import Socks5TcpOnly
srv = Socks5TcpOnly()
yield srv
srv.close()
@pytest.fixture
def local_https_page():
"""A trivial localhost page (used by the no-proxy srflx test)."""
import threading
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
class H(BaseHTTPRequestHandler):
#: A silent socket no longer pins a thread down: after five seconds it drops.
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), H)
httpd.daemon_threads = True
threading.Thread(target=httpd.serve_forever, daemon=True).start()
yield f"http://127.0.0.1:{httpd.server_address[1]}/"
httpd.shutdown()
@pytest.fixture(scope="module", params=["in-process", "stock-client"])
def browser(request, firefox_binary):
"""One browser per transport for the whole file (the popup tests of two files use it)."""
import importlib
if request.param == "in-process":
from invisible_playwright import InvisiblePlaywright
with InvisiblePlaywright(binary_path=firefox_binary, headless=True) as b:
yield b
return
try: # the stock client (a pinned dev dependency), imported by name: the fork's guard forbids a static import
sync_playwright = importlib.import_module("playwright.sync_api").sync_playwright
except ImportError as exc:
pytest.fail("the stock Playwright client is missing (%s): install the wrapper with its dev extra" % exc,
pytrace=False)
from invisible_playwright._juggler.remote import launch_server
server = launch_server(headless=True, binary_path=firefox_binary, locale="en-US", timezone="Europe/Rome")
try:
with sync_playwright() as p:
b = p.firefox.connect(server.ws_endpoint)
try:
yield b
finally:
b.close()
finally:
server.close()
@@ -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
@@ -20,15 +20,21 @@ Known-bad inputs, each run against this file before it was trusted:
* click and press without `_waiting_after` -> the form and the Enter tests go
red on a 157 engine (no request, the old URL);
* `_waiting_after` that ignores `noWaitAfter` -> the last test goes red: the
click waits for the slow page.
* `_waiting_after` that ignores `noWaitAfter` -> the `no_wait_after` test goes
red: the click comes back after the held answer, not before it.
**No clock in the last two tests.** `/slow` is an answer the server HOLDS until
the test lets it go, and what is asserted is the order of two events: the click
coming back, and the server answering. A limit in seconds (the click "in under
2.5 s") measured the runner: on a loaded one the click alone took longer and
the test went red with nothing wrong (2 of 30 suite runs, and every run on one
CPU).
"""
from __future__ import annotations
import http.server
import socket
import threading
import time
import pytest
@@ -38,7 +44,18 @@ FORM = (b"<form method='POST' action='/post'>"
b"<a id='slow' href='/slow'>slow</a>")
def _serve():
class _Held:
"""The answer to `/slow`, held by the server until `release` is set, and the order in which things happened."""
GIVES_UP_AFTER = 25 # seconds; only so that a click that wrongly waits ends, and the test fails on the order
def __init__(self):
self.arrived = threading.Event()
self.release = threading.Event()
self.order = []
def _serve(held=None):
sock = socket.socket()
sock.bind(("127.0.0.1", 0))
port = sock.getsockname()[1]
@@ -55,8 +72,10 @@ def _serve():
self.wfile.write(body)
def do_GET(self):
if self.path == "/slow":
time.sleep(3)
if self.path == "/slow" and held is not None:
held.arrived.set()
held.release.wait(held.GIVES_UP_AFTER)
held.order.append("answered")
self._page(FORM if self.path == "/" else b"<title>%s</title>" % self.path.encode())
def do_POST(self):
@@ -101,18 +120,55 @@ def test_a_click_that_submits_a_form_returns_on_the_posted_page(firefox_binary):
@pytest.mark.e2e
def test_no_wait_after_returns_without_waiting_for_the_navigation(firefox_binary):
"""The click comes back while the server is still holding the answer of the page it navigates to."""
from invisible_playwright import InvisiblePlaywright
srv, url = _serve()
held = _Held()
srv, url = _serve(held)
try:
with InvisiblePlaywright(seed=4242, binary_path=firefox_binary,
headless=True) as browser:
page = browser.new_context().new_page()
page.goto(url, wait_until="load", timeout=30_000)
started = time.monotonic()
page.click("#slow", no_wait_after=True, timeout=30_000)
assert time.monotonic() - started < 2.5, (
"no_wait_after=True waited for the navigation")
held.order.append("click returned")
assert held.order == ["click returned"], (
"no_wait_after=True waited for the navigation: %r" % held.order)
assert page.url == url, "the page moved on with its answer still held: %s" % page.url
held.release.set()
page.wait_for_url(url + "slow", timeout=30_000)
assert held.order == ["click returned", "answered"], held.order
finally:
held.release.set()
srv.shutdown()
@pytest.mark.e2e
def test_a_plain_click_on_the_same_link_stays_until_the_held_answer_is_given(firefox_binary):
"""The other half, which makes the test above mean something: without `no_wait_after` the same click does NOT come
back while the answer is held. The answer is let go only once the request has reached the server, from another
thread, and the click returns after it, already on the new page."""
from invisible_playwright import InvisiblePlaywright
held = _Held()
srv, url = _serve(held)
def let_go_once_asked():
if held.arrived.wait(30):
held.order.append("let go")
held.release.set()
threading.Thread(target=let_go_once_asked, daemon=True).start()
try:
with InvisiblePlaywright(seed=4242, binary_path=firefox_binary,
headless=True) as browser:
page = browser.new_context().new_page()
page.goto(url, wait_until="load", timeout=30_000)
page.click("#slow", timeout=30_000)
held.order.append("click returned")
assert held.order == ["let go", "answered", "click returned"], (
"a plain click came back before the answer of its navigation: %r" % held.order)
assert page.url == url + "slow", page.url
finally:
held.release.set()
srv.shutdown()
@@ -0,0 +1,208 @@
"""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)
# the real engine says so once the page's initial about:blank is done; the page is handed over on it
self.dispatch_event("Page.ready", {}, 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,249 @@
"""A proxy given to a context declares where its UDP leaves from, MEASURED before the command is sent.
The core measures the UDP exit of a SOCKS5 proxy (`invisible_core._udp_exit`: UDP ASSOCIATE, then a STUN Binding request
with ICE's retransmissions, compared with the TCP exit it discovers through the same proxy) and the answer is the
optional field ``udp`` of ``Browser.setContextProxy``: ``coherent``, ``no`` or ``unmeasured``. Without it the engine
drops the UDP of every SOCKS5 proxy, so a context that is given its own proxy would never get a server-reflexive
candidate. The caller never declares it: a ``udp`` key in the dict of a proxy is not read.
``new_context(proxy=...)`` of the sync client, of the async client and of a remote one all end in
``BrowserDispatcher._apply_context_options``: one place, tested here with a recorder in place of the engine. The
gateway is the fake of ``_socks_servers`` (a SOCKS5 server with a UDP relay and a STUN server only the relay reaches).
THE STUN SERVERS ARE A PARAMETER OF THE LAUNCH: ``InvisiblePlaywright(..., udp_stun_servers=[...])`` and
``launch_server(..., udp_stun_servers=[...])`` ("ip:port" IPv4 literals; None = the two public defaults). The session
keeps the list, the launch's geo step and every later context proxy use it, and none of it reaches the browser: not its
environment, argv, prefs or pipe.
"""
from __future__ import annotations
import logging
import os
import sys
import pytest
from _socks_servers import EXIT, STUN_NUMBER, STUN_PORT, coherent, mismatched, tcp_only
from invisible_core import _geo, _udp_exit
from invisible_core.juggler.connection import EventListeners
from invisible_playwright import _session
from invisible_playwright._juggler.server import (BrowserDispatcher, Server, UDP_STUN_PREF,
session_udp_stun_servers, take_session_motion)
pytestmark = pytest.mark.unit
#: The fake STUN server only the gateway's relay reaches, in the form the launch parameter takes.
STUN = ["%s:%d" % (STUN_NUMBER, STUN_PORT)]
class _Connection(EventListeners):
def __init__(self, gateways=()):
super().__init__()
self.sent = []
self.datagrams_before = {}
self._gateways = gateways
def startup_send(self, method, params=None):
return self.send(method, params, timeout=None)
def send(self, method, params=None, session=None, timeout=30):
# How many datagrams the relays had carried when each command was sent: the measure comes BEFORE it.
self.datagrams_before[len(self.sent)] = sum(len(g.datagrams) for g in self._gateways)
self.sent.append((method, params))
return {"browserContextId": "CTX"}
@pytest.fixture(autouse=True)
def _fresh(monkeypatch):
monkeypatch.setattr(_udp_exit, "_cache", {})
# The fake gateway answers the exit question the way the product asks it (api.ipify.org through socks5h), but
# these tests are about the measurement, so the TCP exit is the gateway's own declaration.
monkeypatch.setattr(_geo, "discover_egress_ip", lambda proxy=None, **kw: EXIT)
def _apply(options, gateways=(), stun=STUN):
conn = _Connection(gateways)
dispatcher = BrowserDispatcher(Server(), None, conn, "151.0", udp_stun_servers=stun)
conn.sent.clear()
dispatcher._apply_context_options("CTX", options)
return conn
def _context_proxy(conn):
found = [(i, p) for i, (m, p) in enumerate(conn.sent) if m == "Browser.setContextProxy"]
assert len(found) == 1, conn.sent
return found[0]
def test_a_coherent_socks5_context_proxy_declares_coherent_after_it_was_measured():
with coherent() as gw:
conn = _apply({"proxy": gw.proxy}, [gw])
index, params = _context_proxy(conn)
assert params["udp"] == "coherent"
assert params["type"] == "socks" and params["browserContextId"] == "CTX"
assert conn.datagrams_before[index] >= 1, "the Binding request was sent before the command"
assert gw.associates == 1
def test_a_udp_that_leaves_from_another_address_declares_no():
with mismatched() as gw:
assert _context_proxy(_apply({"proxy": gw.proxy}, [gw]))[1]["udp"] == "no"
def test_a_proxy_that_refuses_udp_declares_no():
with tcp_only() as gw:
assert _context_proxy(_apply({"proxy": gw.proxy}, [gw]))[1]["udp"] == "no"
@pytest.mark.parametrize("scheme", ["http", "https", "socks4"])
def test_a_proxy_that_is_not_socks5_declares_no_field_and_opens_no_connection(scheme):
with coherent() as gw:
proxy = {"server": "%s://127.0.0.1:%d" % (scheme, gw.port)}
params = _context_proxy(_apply({"proxy": proxy}, [gw]))[1]
assert "udp" not in params
assert gw.associates == 0 and not gw.connects
def test_the_caller_never_declares_udp_on_a_context_proxy():
"""Red on the code that read the key: a caller-written `coherent` for a proxy whose UDP exits elsewhere (or
is refused) must come out as what was MEASURED."""
with tcp_only() as gw:
assert _context_proxy(_apply({"proxy": dict(gw.proxy, udp="coherent")}, [gw]))[1]["udp"] == "no"
with mismatched() as gw:
assert _context_proxy(_apply({"proxy": dict(gw.proxy, udp="coherent")}, [gw]))[1]["udp"] == "no"
def test_one_proxy_is_measured_once_however_many_contexts_are_given_it():
with coherent() as gw:
for _ in range(3):
assert _context_proxy(_apply({"proxy": dict(gw.proxy)}, [gw]))[1]["udp"] == "coherent"
assert gw.associates == 1
def test_the_cache_is_keyed_without_the_secret():
with coherent(user="a", password="hunter2-zzz") as gw:
_apply({"proxy": gw.proxy}, [gw])
assert _udp_exit._cache
for key in _udp_exit._cache:
assert "hunter2-zzz" not in repr(key)
def test_the_credentials_are_used_on_the_socket_and_nowhere_else(caplog):
user, password = "u-7c1e4b9a02", "p-3d5f8a6e41"
env_before = dict(os.environ)
with coherent(user=user, password=password) as gw:
with caplog.at_level(logging.DEBUG):
params = _context_proxy(_apply({"proxy": gw.proxy}, [gw]))[1]
assert params["udp"] == "coherent"
text = "\n".join(r.getMessage() + repr(r.args) + str(r.exc_info) for r in caplog.records)
assert user not in text and password not in text
assert dict(os.environ) == env_before
assert not [a for a in sys.argv if user in a or password in a]
def test_a_context_without_its_own_proxy_measures_nothing():
with coherent() as gw:
conn = _apply({}, [gw])
assert not [m for m, _ in conn.sent if m == "Browser.setContextProxy"]
assert gw.associates == 0
def test_a_context_proxy_that_cannot_be_read_is_refused_and_nothing_is_measured():
from invisible_playwright._juggler.server import ProtocolException as Refusal
with coherent() as gw:
with pytest.raises(Refusal):
_apply({"proxy": {"server": "ftp://127.0.0.1:%d" % gw.port}}, [gw])
assert gw.associates == 0
def test_a_browser_built_without_a_list_measures_from_the_two_defaults():
conn = _Connection()
assert BrowserDispatcher(Server(), None, conn, "151.0").udp_stun_servers is None
# the launch: the list is a parameter of the session, kept on it, never given to the browser ------------------
def test_the_session_keeps_the_list_the_launch_named_and_the_server_gets_it():
from invisible_playwright import InvisiblePlaywright
from invisible_playwright.async_api import InvisiblePlaywright as AsyncInvisiblePlaywright
expected = ["198.51.100.5:19302", "203.0.113.9:3478"]
for cls in (InvisiblePlaywright, AsyncInvisiblePlaywright):
session = cls(seed=1, udp_stun_servers=["198.51.100.5:19302", ("203.0.113.9", 3478)])
assert session._udp_stun_servers == expected
assert cls(seed=1)._udp_stun_servers is None
def test_a_bad_list_is_refused_by_every_public_entry_point():
import inspect
from invisible_playwright import InvisiblePlaywright
from invisible_playwright._juggler.remote import launch_server
from invisible_playwright.async_api import InvisiblePlaywright as AsyncInvisiblePlaywright
for cls in (InvisiblePlaywright, AsyncInvisiblePlaywright):
with pytest.raises(ValueError, match="udp_stun_servers"):
cls(seed=1, udp_stun_servers=["stun.example.org:3478"])
assert "udp_stun_servers" in inspect.signature(launch_server).parameters
def test_the_server_takes_the_list_out_of_the_prefs_before_the_profile():
prefs = {"a.b": 1, UDP_STUN_PREF: "198.51.100.5:19302,203.0.113.9:3478"}
assert session_udp_stun_servers(prefs) == ["198.51.100.5:19302", "203.0.113.9:3478"]
rest, _seed, _budget = take_session_motion(prefs)
assert UDP_STUN_PREF not in rest and rest == {"a.b": 1}
assert session_udp_stun_servers({"a.b": 1}) is None
def test_op_launch_reads_the_list_before_the_prefs_are_cleaned_and_writes_a_profile_without_it():
import inspect
from invisible_playwright._juggler import server
source = inspect.getsource(server.BrowserTypeDispatcher.op_launch)
assert source.index("session_udp_stun_servers(launch_prefs)") < source.index("take_session_motion(launch_prefs)")
assert source.index("take_session_motion(launch_prefs)") < source.index("write_user_js(")
assert "launch_proxy_command(params[\"proxy\"], udp_stun_servers)" in source
assert "parse_proxy(params[\"proxy\"]).as_engine_command()" not in source
def test_every_entry_point_hands_the_list_to_the_geo_step():
"""The sync launcher, the async launcher and `launch_server` call `prepare_session_geo` with the session's list."""
import ast
import importlib
import inspect
for module in ("launcher", "async_api", "_juggler.remote"):
source = inspect.getsource(importlib.import_module("invisible_playwright." + module))
tree = ast.parse(source)
calls = [n for n in ast.walk(tree) if isinstance(n, ast.Call)
and getattr(n.func, "id", None) == "prepare_session_geo"]
# (the async launcher passes the function to `asyncio.to_thread`: its keywords are on that call)
calls += [n for n in ast.walk(tree) if isinstance(n, ast.Call)
and getattr(n.func, "attr", None) == "to_thread"
and any(getattr(a, "id", None) == "prepare_session_geo" for a in n.args)]
assert calls, module
for call in calls:
assert "udp_stun_servers" in [k.arg for k in call.keywords], module
def test_no_stun_address_reaches_the_browsers_environment_argv_prefs_or_pipe():
from invisible_core import decide_session_locale
from invisible_playwright import InvisiblePlaywright
servers = ["198.51.100.5:19302", "203.0.113.9:3478"]
session = InvisiblePlaywright(seed=7, udp_stun_servers=servers, binary_path="firefox")
session._timezone, session._locale = "Asia/Tokyo", decide_session_locale("en-US")
prefs = session._build_prefs()
assert session_udp_stun_servers(prefs) == servers # the server's own key is there...
env = _session.build_env(network_declared="v4=198.51.100.7;v6=0", profile=session._profile,
executable=None, base_env={})
# ...and what the engine is given: the prefs after the server took its own keys out, the environment, the pipe.
browser_prefs, _seed, _budget = take_session_motion(prefs)
pipe = repr(_udp_exit.launch_proxy_command({"server": "socks5://10.0.0.1:1080"}, servers))
given = repr(browser_prefs) + repr(env) + pipe
for needle in servers + ["198.51.100.5", "203.0.113.9"]:
assert needle not in given, needle
assert not [k for k in env if "STUN" in k.upper()]
# the launch of a client that composed no session ----------------------------------------------------------
def test_a_hand_made_launch_proxy_cannot_claim_a_coherent_udp():
"""`launch(proxy={..., "udp": "coherent"})` through a bare client: nothing was measured, so `unmeasured`."""
with mismatched() as gw:
command = _udp_exit.launch_proxy_command(dict(gw.proxy, udp="coherent"), STUN)
assert command["udp"] == "unmeasured"
@@ -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,134 @@
"""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. While each page is open it counts the processes that host a site
(at least one: the page's, or the count would prove nothing), and once `close` has answered it waits a few
seconds for them to be gone: none may be left (on the old engine every context leaves its own, one more each
time). Only the processes of the page's site are counted, asked for by name (tests/_processes.py): the browser is
launched with `fission.processSiteNames`, which names a content process by the site it hosts (the page is served
from `http://127.0.0.1:<port>`; a site never includes the port). The browser starts processes of its own, and
counting every content process, or every one that hosts any site, read them as a leak ([2, 2, 2, 5, 5] on the e2e
of the 0.50.0 commit, three "Web Content" and no site left; a process for a Mozilla site started by the New Tab
page). If the name were not what the test expects, the count while the page is open would be 0 and the first assert
says so. Off Linux the test skips: no other system names the process.
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 _processes import NAMED_BY_SITE, site_processes_below # noqa: E402
from _servers import LocalServer # noqa: E402
pytestmark = pytest.mark.e2e
ENGINE_WITH_THE_FIX = "firefox-61"
SITE = "http://127.0.0.1" # the site of the served page; a site never includes the port
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]
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,
extra_prefs=NAMED_BY_SITE)
def sites():
return site_processes_below(launched.process.pid, SITE)
async def drive():
opened, left = [], []
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
opened.append(len(sites()))
await client.call(context, "close") # the engine waits for the context's processes, then kills
deadline = time.time() + 5
while sites() and time.time() < deadline:
await asyncio.sleep(0.25)
left.append(len(sites()))
return opened, left
try:
opened, left = asyncio.run(drive())
finally:
launched.close()
server.shutdown()
assert all(opened), "a page with no process for its site: the count proves nothing (%r)" % (opened,)
assert left == [0] * 5, "processes of a site left after each closed context: %r" % (left,)
@@ -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"})]
@@ -0,0 +1,148 @@
"""A download the engine finished BEFORE it announced it is finished once it is announced.
`BrowserDispatcher._on_download_finished` keeps the error of a download whose artifact does not exist yet, and
`_on_download_created` hands it to the artifact later. A download that succeeded has no error (`None`), and the old
code read that as "nothing was kept": the artifact was never marked finished, so `save_as`, `path` and `failure`
waited forever on a complete file (seen on tiny downloads, where the transfer ends before the announcement is handled).
No browser and no socket: the two real methods run on a stand-in that carries the attributes they read, and the
artifact is a fake that records what it was told.
Known-bad input: the code before 6a50ad1 -> (a) and (d) are red; the code of 6a50ad1 -> (e), (f) and (g) are red.
"""
from __future__ import annotations
import threading
import types
import pytest
from invisible_playwright._juggler import server as juggler_server
from invisible_playwright._juggler.server import BrowserDispatcher
pytestmark = pytest.mark.unit
CONTEXT = "ctx-1"
class FakeArtifact:
"""What `ArtifactDispatcher` is to the two methods: built with (server, context, uuid, path), told once."""
def __init__(self, server, context, uuid, path):
self.uuid = uuid
self.path = path
self.channel = {"guid": "artifact@" + uuid}
self.finished = threading.Event()
self.reports = []
def report_finished(self, error):
self.reports.append(error)
self.finished.set()
@pytest.fixture
def browser(monkeypatch, tmp_path):
monkeypatch.setattr(juggler_server, "ArtifactDispatcher", FakeArtifact)
return types.SimpleNamespace(
contexts=[types.SimpleNamespace(context_id=CONTEXT)],
_targets_lock=threading.Lock(),
_page_targets={},
_adoptions={},
_gone_openers={},
_artifacts={},
_finished_early={},
_download_contexts={},
server=object(),
_downloads_dir=lambda context_id: str(tmp_path),
)
def _created(browser, uuid, context=CONTEXT):
BrowserDispatcher._on_download_created(
browser, {"uuid": uuid, "browserContextId": context, "pageTargetId": "t1",
"url": "http://x/f", "suggestedFileName": "f.bin"})
def _finished(browser, uuid, **extra):
BrowserDispatcher._on_download_finished(browser, dict({"uuid": uuid}, **extra))
def test_a_download_that_succeeded_before_it_was_announced_is_finished(browser):
_finished(browser, "u1")
_created(browser, "u1")
artifact = browser._artifacts["u1"]
assert artifact.finished.wait(2), "the artifact was never marked finished: save_as would wait forever"
assert artifact.reports == [None]
assert browser._finished_early == {}
def test_a_download_canceled_before_it_was_announced_is_finished_with_the_reason(browser):
_finished(browser, "u2", canceled=True)
_created(browser, "u2")
artifact = browser._artifacts["u2"]
assert artifact.finished.wait(2)
assert artifact.reports == ["canceled"]
assert browser._finished_early == {}
def test_a_download_that_failed_before_it_was_announced_keeps_its_error(browser):
_finished(browser, "u3", error="NS_ERROR_NET_RESET")
_created(browser, "u3")
assert browser._artifacts["u3"].reports == ["NS_ERROR_NET_RESET"]
def test_a_download_announced_and_then_finished_is_finished(browser):
_created(browser, "u4")
artifact = browser._artifacts["u4"]
assert not artifact.finished.is_set()
_finished(browser, "u4")
assert artifact.finished.wait(2)
assert artifact.reports == [None]
assert browser._finished_early == {}
def test_a_download_announced_and_not_finished_stays_open(browser):
_created(browser, "u5")
assert not browser._artifacts["u5"].finished.is_set()
assert browser._finished_early == {}
def test_an_early_finish_of_a_context_that_does_not_exist_is_not_kept(browser):
_finished(browser, "u6")
assert "u6" in browser._finished_early
_created(browser, "u6", context="gone")
assert "u6" not in browser._artifacts
assert browser._finished_early == {}
def test_e_a_finish_after_the_announcement_of_a_gone_context_keeps_nothing(browser):
"""(e) The context was already closed when the download was announced: no artifact, and the finish that follows has no
reader. It used to be kept as an early finish for the life of the browser."""
_created(browser, "u7", context="ctx-gone")
_finished(browser, "u7")
assert browser._finished_early == {} and browser._download_contexts == {}
def test_f_a_finish_after_the_artifact_was_released_keeps_nothing(browser):
"""(f) The client released the artifact (its index entry is gone) before the engine said the download ended."""
_created(browser, "u8")
browser._artifacts.pop("u8") # what ArtifactDispatcher.released() does
_finished(browser, "u8")
assert browser._finished_early == {} and browser._download_contexts == {}
def test_g_finishes_never_announced_are_bounded(browser):
"""(g) uuids the engine never announced: their early finishes are dropped once newer ones push them out."""
for n in range(juggler_server._EARLY_FINISHES_KEPT + 10):
_finished(browser, "never-%d" % n)
assert len(browser._finished_early) == juggler_server._EARLY_FINISHES_KEPT
assert "never-0" not in browser._finished_early and "never-%d" % (juggler_server._EARLY_FINISHES_KEPT + 9) in browser._finished_early
def test_h_the_end_of_a_context_forgets_its_unfinished_downloads(browser):
"""(h) A download announced and never finished: the end of its context forgets it (no growth across contexts)."""
browser._forget_downloads_of = lambda context_id: BrowserDispatcher._forget_downloads_of(browser, context_id)
_created(browser, "u9")
_created(browser, "u10", context="ctx-gone")
BrowserDispatcher._forget_downloads_of(browser, CONTEXT)
assert list(browser._download_contexts) == ["u10"]
@@ -40,7 +40,7 @@ def display(monkeypatch):
geo = types.SimpleNamespace(timezone="Europe/Rome",
locale=SessionLocale.of("it-IT"),
egress_ip=None,
srflx_to_declare=lambda: None)
geolocation_override=lambda: None)
def refuse(**_kw):
raise FontManifestMismatch("the engine does not carry these faces")
@@ -53,7 +53,7 @@ def display(monkeypatch):
monkeypatch.setattr(_session, "resolve_executable", lambda _p: "firefox")
monkeypatch.setattr(_session, "build_env", refuse)
for mod in (launcher, async_api):
monkeypatch.setattr(mod, "prepare_session_geo", lambda *_a: geo)
monkeypatch.setattr(mod, "prepare_session_geo", lambda *_a, **_k: geo)
monkeypatch.setattr(mod, "resolve_executable", lambda _p: "firefox")
monkeypatch.setattr(launcher, "sync_playwright", no_playwright)
monkeypatch.setattr(async_api, "async_playwright", no_playwright)
@@ -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,84 @@
"""A `fetch(..., {keepalive: true})` is a request of the page: the client hears `request` and its end.
Stock Playwright's Firefox reports the keepalive fetch of a page like any other request: `page.on("request")` fires, and
`requestfinished` follows. Here the server saw the request and the client heard nothing, so a client that follows the page's
network by those events (tf-fetch's network recorder does) never knew the request existed.
The page asks for the same address four ways. `plain` is the control (a fetch without keepalive), `keepalive` and
`beacon` are the two that the engine runs in the parent process, and each must give exactly one `request` and one end.
"""
from __future__ import annotations
import threading
from http.server import BaseHTTPRequestHandler
import pytest
from _servers import LocalServer
pytestmark = pytest.mark.e2e
PAGE = b"""<!doctype html><title>keepalive</title><script>
addEventListener('load', () => {
fetch('/seen/plain', {method: 'POST', body: 'x'});
fetch('/seen/keepalive', {method: 'POST', body: 'x', keepalive: true});
fetch('/seen/keepalive-nocors', {keepalive: true, mode: 'no-cors'});
navigator.sendBeacon('/seen/beacon', 'x');
});
</script>"""
class _Handler(BaseHTTPRequestHandler):
def log_message(self, *a):
pass
def _answer(self, body, ctype="text/plain"):
self.send_response(200)
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):
if self.path == "/":
self._answer(PAGE, "text/html; charset=utf-8")
else:
self._answer(b"ok")
def do_POST(self):
self.rfile.read(int(self.headers.get("Content-Length") or 0))
self._answer(b"ok")
@pytest.fixture
def site():
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()
@pytest.mark.parametrize("route", [False, True])
def test_every_request_of_the_page_reaches_the_client_with_its_end(firefox_binary, site, route):
from invisible_playwright import InvisiblePlaywright
started, ended = [], []
with InvisiblePlaywright(seed=4261, binary_path=firefox_binary, headless=True) as browser:
context = browser.new_context()
if route:
context.route("**/*", lambda r: r.continue_())
page = context.new_page()
page.on("request", lambda r: started.append(r.url.replace(site, "")))
page.on("requestfinished", lambda r: ended.append(r.url.replace(site, "")))
page.on("requestfailed", lambda r: ended.append(r.url.replace(site, "")))
page.goto(site + "/", wait_until="load")
page.wait_for_timeout(2000) # the client is a sync one: events are delivered while it calls the browser
seen = sorted(u for u in started if u.startswith("/seen/"))
assert seen == ["/seen/beacon", "/seen/keepalive", "/seen/keepalive-nocors", "/seen/plain"], \
"the client heard these requests: %r" % started
assert sorted(u for u in ended if u.startswith("/seen/")) == seen, \
"requests without an end for the client: %r" % sorted(set(seen) - set(ended))
@@ -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,153 @@
"""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 _socks_servers import Socks5TcpOnly
from test_webrtc_realness import _PROBE_JS, candidates, host_is_mdns
egress = "203.0.113.7"
monkeypatch.delenv("STEALTHFOX_WEBRTC_NETWORK", raising=False)
measured = []
def through_the_proxy(timezone, proxy, locale, **_kw):
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"
+12 -1
View File
@@ -51,11 +51,22 @@ class _SlowEngine(EventListeners):
class _Page:
def __init__(self, server, context, session, target_id, number, opener=None):
def __init__(self, server, context, session, target_id, number, opener=None, is_gone=None):
self.target_id = target_id
self.number = number
self.channel = {"guid": "page-" + target_id}
gone_while_building = False
def wait_until_ready(self, timeout=20.0):
pass # the engine of this test says Page.ready at once
def settle_events(self):
pass
def announce(self, context, replay):
context.emit("page", {"page": self.channel})
def announce_closed(self):
pass
@@ -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,581 @@
"""A page is handed over to the client only once the engine says Page.ready.
NO BROWSER HERE: the real dispatchers over a scripted Juggler connection (the one of the registry test) whose pages announce their
frame at birth and say `Page.ready` only when the test tells them to, as the real engine does after its transient about:blank
navigations.
⛔ THE KNOWN-BAD INPUT. The engine commits the page's initial about:blank AFTER it announces the frame; a `goto` sent in between is
'interrupted by another navigation to about:blank'. A wrapper that hands the page over on the main frame alone (no wait for
Page.ready) returns `new_page()` while the engine is still in that window; so does the adoption of a popup.
Known-bad: with the wait for Page.ready removed (a21e1de), the first two tests fail - the page is delivered before Page.ready; with
the wait INSIDE the constructor (7db28e4..6a60dce), the last two fail - a popup opened by a link has its first request held by a
route until its page answers, so a page that is only built once it is ready never becomes ready, and what the engine says between
the commit and the ready (the commit itself, the `load`) is said to a page that does not exist yet and is lost; the client's popup
then has no `load` to wait for. The page is BUILT at once and ANNOUNCED when ready.
"""
from __future__ import annotations
import threading
import time
import pytest
from invisible_playwright._juggler import remote
from invisible_playwright._juggler.server import FrameDispatcher, LocalUtilsDispatcher
from test_a_closed_context_leaves_nothing_in_the_registry import ScriptedJuggler
pytestmark = pytest.mark.unit
#: how long a page that must NOT be delivered yet is watched
WATCH = 0.4
class LateReadyJuggler(ScriptedJuggler):
"""The engine of the registry test, except that Page.ready is held back until `say_ready(session)`."""
def __init__(self):
super().__init__()
self.held = {}
self.released = set()
self.queued = []
def dispatch_event(self, method, params, session=None):
if method == "Page.ready" and session not in self.released:
self.held[session] = (method, params)
return None
return super().dispatch_event(method, params, session)
def send(self, method, params=None, session=None, timeout=30):
if method == "Browser.getInfo":
# a reply comes after everything the engine sent before it: the events queued as "sent with the ready" arrive first
queued, self.queued = self.queued, []
for event, event_params, event_session in queued:
super().dispatch_event(event, event_params, event_session)
return {}
return super().send(method, params, session, timeout)
def say_ready(self, session):
self.released = set(self.released) | {session}
method, params = self.held.pop(session)
super().dispatch_event(method, params, session)
def popup_born(self, opener_target, context_id, n):
"""A target the opener opened: attached and framed, but not ready."""
target, session = "p%d" % n, "ps%d" % n
self.sessions[target] = session
self.dispatch_event("Browser.attachedToTarget", {
"sessionId": session,
"targetInfo": {"targetId": target, "type": "page", "openerId": opener_target,
"browserContextId": context_id}}, 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)
self.dispatch_event("Page.ready", {}, session)
return target, session
@pytest.fixture
def late_browser():
server = remote._SharedServer()
browser_type = remote.SharedBrowserType(server)
LocalUtilsDispatcher(server)
conn = LateReadyJuggler()
browser = remote.SharedBrowserDispatcher(server, browser_type, conn, "firefox/1")
yield browser
for session in list(conn.held):
conn.say_ready(session)
time.sleep(0.1)
for context in list(browser.contexts):
try:
server.handle({"guid": context.guid, "method": "close", "params": {}})
except Exception:
pass
server.shutdown()
def _new_context(browser):
server = browser.server
return server.object(server.handle(
{"guid": browser.guid, "method": "newContext", "params": {}})["context"]["guid"])
def test_new_page_returns_only_after_page_ready(late_browser):
server, conn = late_browser.server, late_browser.conn
context = _new_context(late_browser)
answer = {}
def new_page():
answer["reply"] = server.handle(
{"guid": context.guid, "method": "newPage", "params": {"pageNumber": 1}})
worker = threading.Thread(target=new_page, daemon=True)
worker.start()
deadline = time.monotonic() + 5
while not conn.held and time.monotonic() < deadline:
time.sleep(0.01)
assert conn.held, "the page was never born in the scripted engine"
worker.join(WATCH)
assert worker.is_alive() and "reply" not in answer, (
"new_page() returned before the engine said Page.ready: the page would be handed over inside the window where a goto is "
"interrupted by the engine's own about:blank")
assert not context.pages, "the page was registered before it was ready"
(session,) = conn.held
conn.say_ready(session)
worker.join(5)
assert not worker.is_alive() and "reply" in answer, "new_page() did not return after Page.ready"
assert len(context.pages) == 1
def test_a_popup_is_announced_only_after_page_ready(late_browser):
server, conn = late_browser.server, late_browser.conn
context = _new_context(late_browser)
# the opener: ready at once
conn.released = {"s1"}
server.handle({"guid": context.guid, "method": "newPage", "params": {"pageNumber": 1}})
assert len(context.pages) == 1
opener_target = next(iter(conn.sessions))
announced = []
original = context.emit
def spy(event, params=None):
if event == "page":
announced.append(time.monotonic())
return original(event, params)
context.emit = spy
target, session = conn.popup_born(opener_target, context.context_id, 1)
time.sleep(WATCH)
assert not announced and len(context.pages) == 1, (
"the popup was announced before the engine said Page.ready for it")
conn.say_ready(session)
deadline = time.monotonic() + 5
while not announced and time.monotonic() < deadline:
time.sleep(0.01)
assert announced, "the popup was never announced after Page.ready"
assert len(context.pages) == 2
def _unannounced_page(browser, session):
return next(o for o in browser.server._objects.values()
if o.TYPE == "Page" and getattr(o, "session", None) == session)
def test_a_popup_exists_and_listens_while_it_waits_for_its_ready(late_browser):
"""The first request of a popup opened by a link is held by a route until its page answers: the page must be built to answer."""
server, conn = late_browser.server, late_browser.conn
context = _new_context(late_browser)
conn.released = {"s1"}
server.handle({"guid": context.guid, "method": "newPage", "params": {"pageNumber": 1}})
opener_target = next(iter(conn.sessions))
target, session = conn.popup_born(opener_target, context.context_id, 1)
deadline = time.monotonic() + 5
page = None
while page is None and time.monotonic() < deadline:
try:
page = _unannounced_page(late_browser, session)
except StopIteration:
time.sleep(0.01)
assert page is not None, "the popup was not built while the engine had not said Page.ready: nothing answers its first request"
time.sleep(0.2)
assert page._held is None, "the popup is built but does not listen: the events of its birth are held"
assert len(context.pages) == 1, "and it was announced before it was ready"
def test_what_a_popup_does_before_its_ready_reaches_its_frame(late_browser, monkeypatch):
"""The engine says Page.ready at the commit of the popup's first document; the `load` follows at once. Both reach the client."""
server, conn = late_browser.server, late_browser.conn
context = _new_context(late_browser)
conn.released = {"s1"}
server.handle({"guid": context.guid, "method": "newPage", "params": {"pageNumber": 1}})
opener_target = next(iter(conn.sessions))
said = []
original = FrameDispatcher.emit
def spy(self, event, params=None):
said.append((self.frame_id, event, params))
return original(self, event, params)
monkeypatch.setattr(FrameDispatcher, "emit", spy)
target, session = conn.popup_born(opener_target, context.context_id, 1)
frame_id = "f" + target
url = "http://127.0.0.1/popup"
conn.dispatch_event("Page.navigationStarted", {"frameId": frame_id, "navigationId": "n1", "url": url}, session)
conn.dispatch_event("Page.navigationCommitted", {"frameId": frame_id, "navigationId": "n1", "url": url, "name": ""}, session)
conn.dispatch_event("Page.eventFired", {"frameId": frame_id, "name": "DOMContentLoaded"}, session)
conn.dispatch_event("Page.eventFired", {"frameId": frame_id, "name": "load"}, session)
conn.say_ready(session)
deadline = time.monotonic() + 5
while len(context.pages) < 2 and time.monotonic() < deadline:
time.sleep(0.01)
assert len(context.pages) == 2, "the popup was never announced"
popup = context.pages[1]
assert popup.frame.url == url, "the frame of the popup was told about:blank: its commit was said to a page that did not exist"
heard = set(popup.frame.initializer["loadStates"])
heard |= {params["add"] for fid, event, params in said
if fid == frame_id and event == "loadstate" and params and "add" in params}
assert "load" in heard, ("the client's frame never heard `load` of the popup (heard %s): wait_for_url(until=load) would wait for ever"
% sorted(heard))
def test_a_popup_waits_for_its_ready_without_a_limit_and_a_requested_page_for_twenty_seconds(late_browser, monkeypatch):
"""Playwright's popup is reported on Page.ready with no limit (a destination that answers after 25 s gives the event at 25 s); the
page a caller asked for waits 20 s and fails."""
from invisible_playwright._juggler.server import PageDispatcher
waited = []
original = PageDispatcher.wait_until_ready
def spy(self, timeout=20.0):
waited.append(timeout)
return original(self, timeout)
monkeypatch.setattr(PageDispatcher, "wait_until_ready", spy)
server, conn = late_browser.server, late_browser.conn
context = _new_context(late_browser)
conn.released = {"s1"}
server.handle({"guid": context.guid, "method": "newPage", "params": {"pageNumber": 1}})
opener_target = next(iter(conn.sessions))
conn.popup_born(opener_target, context.context_id, 1)
deadline = time.monotonic() + 5
while len(waited) < 2 and time.monotonic() < deadline:
time.sleep(0.01)
assert waited == [20.0, None], "a requested page waits 20 s, a popup without a limit: %r" % (waited,)
def test_a_popup_that_never_gets_its_ready_ends_with_its_context_and_says_nothing(late_browser):
"""204, a server that never answers: no ready, no `page` event, no warning; closing the context ends the wait."""
import warnings
server, conn = late_browser.server, late_browser.conn
context = _new_context(late_browser)
conn.released = {"s1"}
server.handle({"guid": context.guid, "method": "newPage", "params": {"pageNumber": 1}})
opener_target = next(iter(conn.sessions))
announced = []
original = context.emit
context.emit = lambda event, params=None: (announced.append(event) if event == "page" else None, original(event, params))[1]
with warnings.catch_warnings(record=True) as caught:
warnings.simplefilter("always")
conn.popup_born(opener_target, context.context_id, 1)
time.sleep(0.5)
assert not announced, "a popup with no ready was announced"
assert any(a.state == "waiting" for a in late_browser._adoptions.values()), "the popup is not waiting"
server.handle({"guid": context.guid, "method": "close", "params": {}})
deadline = time.monotonic() + 5
while late_browser._adoptions and time.monotonic() < deadline:
time.sleep(0.01)
assert not late_browser._adoptions, "closing the context did not end the wait of the popup"
time.sleep(0.2)
assert not announced, "a popup of a closed context was announced"
assert not [w for w in caught if "adoption" in str(w.message)], [str(w.message) for w in caught]
def test_a_popup_is_announced_with_the_address_of_the_commit_that_came_with_its_ready(late_browser):
"""The engine says Page.ready and, in the same turn, the commit of the document: the client is told the page after the commit, so
the url it reads at the `page` event is the destination, as Playwright's is (3 of 4 popups said about:blank)."""
server, conn = late_browser.server, late_browser.conn
context = _new_context(late_browser)
conn.released = {"s1"}
server.handle({"guid": context.guid, "method": "newPage", "params": {"pageNumber": 1}})
opener_target = next(iter(conn.sessions))
urls = []
original = context.emit
def spy(event, params=None):
if event == "page":
page = next(o for o in server._objects.values() if o.TYPE == "Page" and o.channel == params["page"])
urls.append(page.frame.url)
return original(event, params)
context.emit = spy
target, session = conn.popup_born(opener_target, context.context_id, 1)
frame_id = "f" + target
url = "http://127.0.0.1/slow"
deadline = time.monotonic() + 5
while not any(o.TYPE == "Page" and getattr(o, "session", None) == session for o in server._objects.values()) and time.monotonic() < deadline:
time.sleep(0.01)
conn.queued.append(("Page.navigationStarted", {"frameId": frame_id, "navigationId": "n1", "url": url}, session))
conn.queued.append(("Page.navigationCommitted", {"frameId": frame_id, "navigationId": "n1", "url": url, "name": ""}, session))
conn.say_ready(session) # the commit follows in the stream: it is delivered with the round trip that comes back after it
deadline = time.monotonic() + 5
while not urls and time.monotonic() < deadline:
time.sleep(0.01)
assert urls == [url], "the popup was announced with %r, not with the address of the commit that came with its ready" % (urls,)
def test_a_download_started_by_a_popup_that_is_not_announced_is_reported_on_its_opener_after_the_popup(late_browser):
"""`<a target=_blank href=file>` with `Content-Disposition: attachment`: the new tab never gets a Page.ready and the engine closes it at
once. Playwright reports the download on the OPENER (ffBrowser._onDownloadCreated) and the popup before it; looking only among the
announced pages lost the download, and saying it at once put it before the popup (a client that read the popup the moment the
download arrived found none on a loaded machine)."""
server, conn = late_browser.server, late_browser.conn
context = _new_context(late_browser)
conn.released = {"s1"}
server.handle({"guid": context.guid, "method": "newPage", "params": {"pageNumber": 1}})
opener_target = next(iter(conn.sessions))
opener = next(o for o in server._objects.values() if o.TYPE == "Page" and o.target_id == opener_target)
order = []
original_opener = opener.emit
opener.emit = lambda event, params=None: (order.append(event), original_opener(event, params))[1]
original_context = context.emit
context.emit = lambda event, params=None: (order.append("context:" + event), original_context(event, params))[1]
target, session = conn.popup_born(opener_target, context.context_id, 1)
deadline = time.monotonic() + 5
while not (target in late_browser._adoptions and late_browser._adoptions[target].state == "waiting") and time.monotonic() < deadline:
time.sleep(0.01)
conn.dispatch_event("Browser.downloadCreated", {
"uuid": "u1", "browserContextId": context.context_id, "pageTargetId": target, "frameId": "f" + target,
"url": "http://127.0.0.1/file", "suggestedFileName": "f.bin"}, None)
assert "download" not in order, "the download was said before the popup it came from: %r" % (order,)
conn.dispatch_event("Browser.detachedFromTarget", {"targetId": target, "sessionId": session}, None) # the tab is closed
deadline = time.monotonic() + 5
while "download" not in order and time.monotonic() < deadline:
time.sleep(0.01)
assert "download" in order, "the download of the popup was not reported on its opener: %r" % (order,)
assert order.index("context:page") < order.index("download"), "the download came before the popup: %r" % (order,)
def test_the_load_of_a_popup_said_before_its_announcement_is_said_again_right_after_it(late_browser, monkeypatch):
"""A listener registered in the handler of the `page` event (`page.on("load")`) hears the load of a popup in Playwright, because the
page is reported after its ready and the load follows. Here the document may have loaded before the client hears of the page: the
two states are said again after the announcement, in order, and the first time they already set the state `wait_for_load_state`
reads."""
from invisible_playwright._juggler import dispatcher as base
trace = []
original = base.Dispatcher.emit
def spy(self, method, params=None):
if method == "page":
trace.append("page")
elif getattr(self, "TYPE", "") == "Frame" and method == "loadstate" and params and "add" in params:
trace.append(params["add"])
return original(self, method, params)
monkeypatch.setattr(base.Dispatcher, "emit", spy)
server, conn = late_browser.server, late_browser.conn
context = _new_context(late_browser)
conn.released = {"s1"}
server.handle({"guid": context.guid, "method": "newPage", "params": {"pageNumber": 1}})
opener_target = next(iter(conn.sessions))
target, session = conn.popup_born(opener_target, context.context_id, 1)
deadline = time.monotonic() + 5
while not (target in late_browser._adoptions and late_browser._adoptions[target].state == "waiting") and time.monotonic() < deadline:
time.sleep(0.01)
frame_id, url = "f" + target, "http://127.0.0.1/slow"
conn.dispatch_event("Page.navigationStarted", {"frameId": frame_id, "navigationId": "n1", "url": url}, session)
conn.dispatch_event("Page.navigationCommitted", {"frameId": frame_id, "navigationId": "n1", "url": url, "name": ""}, session)
conn.dispatch_event("Page.eventFired", {"frameId": frame_id, "name": "DOMContentLoaded"}, session)
conn.dispatch_event("Page.eventFired", {"frameId": frame_id, "name": "load"}, session)
del trace[:] # what is said from here on: the ready, the announcement, the replay
conn.say_ready(session)
deadline = time.monotonic() + 5
while trace.count("load") < 1 and time.monotonic() < deadline:
time.sleep(0.01)
time.sleep(0.2)
assert "page" in trace, trace
after = trace[trace.index("page") + 1:]
assert after == ["domcontentloaded", "load"], "after the announcement the client heard %r" % (after,)
def test_a_popup_whose_target_goes_away_while_its_page_is_being_built_is_announced_and_closed(late_browser, monkeypatch):
"""A download's empty tab closes within milliseconds; on a loaded machine the page of the popup is still being built when the engine
detaches it. That detach went by with nobody to tell, and the wait for a ready that never comes went on for ever: the popup was never
announced (the full suite failed once on it)."""
from invisible_playwright._juggler.server import PageDispatcher
original_init = PageDispatcher.__init__
def slow_init(self, *args, **kwargs):
time.sleep(0.4) # the build is slower than the detach
return original_init(self, *args, **kwargs)
monkeypatch.setattr(PageDispatcher, "__init__", slow_init)
server, conn = late_browser.server, late_browser.conn
context = _new_context(late_browser)
conn.released = {"s1"}
monkeypatch.undo() # the opener is built at normal speed
server.handle({"guid": context.guid, "method": "newPage", "params": {"pageNumber": 1}})
monkeypatch.setattr(PageDispatcher, "__init__", slow_init)
opener_target = next(iter(conn.sessions))
announced, closed = [], []
original = context.emit
context.emit = lambda event, params=None: (announced.append(event) if event == "page" else None, original(event, params))[1]
target, session = conn.popup_born(opener_target, context.context_id, 1)
conn.dispatch_event("Browser.detachedFromTarget", {"targetId": target, "sessionId": session}, None)
deadline = time.monotonic() + 5
while "page" not in announced and time.monotonic() < deadline:
time.sleep(0.01)
assert "page" in announced, "the popup that went away while its page was being built was never announced"
@pytest.mark.parametrize("command", ["Page.setInitScripts", "Browser.getInfo"])
def test_a_command_of_the_adoption_that_finds_the_session_gone_announces_and_closes_the_popup(late_browser, command, monkeypatch):
"""The tab goes away WHILE the adoption initializes it: the engine answers 'cannot find session' to a command of the adoption. Like a
detach before the ready, that ends in the page announced and closed (Playwright's does), never in a discard with a warning: the
download of a link into a new tab was lost one time in a hundred (independent run, quiet machine)."""
import warnings
from invisible_core.juggler.connection import ProtocolError
server, conn = late_browser.server, late_browser.conn
context = _new_context(late_browser)
conn.released = {"s1"}
server.handle({"guid": context.guid, "method": "newPage", "params": {"pageNumber": 1}})
opener_target = next(iter(conn.sessions))
original_send = conn.send
def send(method, params=None, session=None, timeout=30):
if method == command and session not in (None, "s1"):
raise ProtocolError('%s: ERROR: cannot find session with id "%s"' % (method, session))
return original_send(method, params, session, timeout)
monkeypatch.setattr(conn, "send", send)
announced = []
original = context.emit
context.emit = lambda event, params=None: (announced.append(event) if event == "page" else None, original(event, params))[1]
with warnings.catch_warnings(record=True) as caught:
warnings.simplefilter("always")
target, session = conn.popup_born(opener_target, context.context_id, 1)
if command == "Browser.getInfo":
conn.say_ready(session) # this one is asked once the page is ready
else:
conn.dispatch_event("Browser.detachedFromTarget", {"targetId": target, "sessionId": session}, None)
deadline = time.monotonic() + 5
while "page" not in announced and time.monotonic() < deadline:
time.sleep(0.01)
time.sleep(0.2)
assert "page" in announced, "the popup whose session was gone was discarded instead of announced"
assert not [w for w in caught if "adoption" in str(w.message)], [str(w.message) for w in caught]
def test_a_popup_that_is_dropped_or_fails_leaves_the_trace_of_what_the_engine_said(late_browser, monkeypatch):
"""The log of a red run on a machine nobody can look at does not say in which order the events came: the adoption keeps a short trace
per target and writes it in the warning of a failed adoption and in the record of the dropped ones."""
import warnings
from invisible_playwright._juggler.server import PageDispatcher
server, conn = late_browser.server, late_browser.conn
context = _new_context(late_browser)
conn.released = {"s1"}
server.handle({"guid": context.guid, "method": "newPage", "params": {"pageNumber": 1}})
opener_target = next(iter(conn.sessions))
# 1. dropped with its context
target, session = conn.popup_born(opener_target, context.context_id, 1)
deadline = time.monotonic() + 5
while not (target in late_browser._adoptions and late_browser._adoptions[target].state == "waiting") and time.monotonic() < deadline:
time.sleep(0.01)
server.handle({"guid": context.guid, "method": "close", "params": {}})
deadline = time.monotonic() + 5
while not late_browser._dropped and time.monotonic() < deadline:
time.sleep(0.01)
assert late_browser._dropped, "a popup dropped with its context left no trace"
dropped_target, text = late_browser._dropped[-1]
assert dropped_target == target
for word in ("attached", "frameAttached", "building", "waiting", "dropped: its context closed"):
assert word in text, "the trace of the dropped popup lacks %r: %s" % (word, text)
# 2. a failed adoption writes it in its warning
context2 = _new_context(late_browser)
def boom(self, *args, **kwargs):
raise ValueError("boom")
conn.released = {"s1", "s2"}
monkeypatch.setattr(PageDispatcher, "__init__", boom)
with warnings.catch_warnings(record=True) as caught:
warnings.simplefilter("always")
conn.popup_born(opener_target, context2.context_id, 2)
deadline = time.monotonic() + 5
while not [w for w in caught if "adoption" in str(w.message)] and time.monotonic() < deadline:
time.sleep(0.01)
messages = [str(w.message) for w in caught if "adoption" in str(w.message)]
assert messages and "events of the target" in messages[0] and "attached" in messages[0], messages
def test_a_download_that_comes_while_the_adoption_fails_is_said_once_on_the_opener(late_browser, monkeypatch):
"""The adoption of a popup fails; the engine says the download of that tab in the step between the moment the adoption looks for its
pending downloads and the moment it removes its record (forced here: right after the first time the adoption thread lets go of the
browser's lock once it has failed). The download queued on a record that is about to vanish was said by nobody. It is said, once, on the
opener: taking the pending ones and removing the record are ONE step, and the opener of a target not announced is remembered."""
import warnings
from invisible_playwright._juggler.server import PageDispatcher
server, conn = late_browser.server, late_browser.conn
context = _new_context(late_browser)
conn.released = {"s1"}
server.handle({"guid": context.guid, "method": "newPage", "params": {"pageNumber": 1}})
opener_target = next(iter(conn.sessions))
opener = next(o for o in server._objects.values() if o.TYPE == "Page" and o.target_id == opener_target)
said = []
original_emit = opener.emit
opener.emit = lambda event, params=None: (said.append(event), original_emit(event, params))[1]
state = {"failing": False, "delivered": False}
target = "p1"
def deliver():
state["delivered"] = True
late_browser._on_download_created({
"uuid": "u9", "browserContextId": context.context_id, "pageTargetId": target, "frameId": "f" + target,
"url": "http://127.0.0.1/file", "suggestedFileName": "f.bin"})
class Tracked:
def __init__(self, inner):
self.inner = inner
def __enter__(self):
self.inner.acquire()
return self
def __exit__(self, *exc):
self.inner.release()
if state["failing"] and not state["delivered"] and threading.current_thread().name.startswith("invpw-adopt-p1"):
deliver()
def acquire(self, *a, **k):
return self.inner.acquire(*a, **k)
def release(self):
return self.inner.release()
def boom(self, *args, **kwargs):
state["failing"] = True
raise ValueError("boom")
monkeypatch.setattr(PageDispatcher, "__init__", boom)
monkeypatch.setattr(late_browser, "_targets_lock", Tracked(late_browser._targets_lock))
with warnings.catch_warnings(record=True):
warnings.simplefilter("always")
conn.popup_born(opener_target, context.context_id, 1)
deadline = time.monotonic() + 5
while not state["delivered"] and time.monotonic() < deadline:
time.sleep(0.01)
time.sleep(0.2)
assert state["delivered"], "the adoption never failed"
assert said.count("download") == 1, "the download that came while the adoption failed was said %d times: %r" % (said.count("download"), said)
def test_the_opener_of_a_target_the_engine_already_took_away_is_not_remembered(late_browser):
"""A download cannot come from a target that is detached: no entry is made for it (the table of openers is for the targets the
engine still has when their adoption ends without announcing them)."""
from types import SimpleNamespace
gone = SimpleNamespace(target_id="t-gone", opener="o-1", gone=True)
with late_browser._targets_lock:
late_browser._remember_opener(gone)
assert "t-gone" not in late_browser._gone_openers
def test_the_opener_of_a_failed_adoption_lives_until_the_target_detaches_and_the_cap_holds(late_browser):
from types import SimpleNamespace
alive = SimpleNamespace(target_id="t-alive", opener="o-2", gone=False)
with late_browser._targets_lock:
late_browser._remember_opener(alive)
assert late_browser._gone_openers.get("t-alive") == "o-2", "the opener of a failed adoption was not remembered"
late_browser._handle_detach("t-alive", "s-alive")
assert "t-alive" not in late_browser._gone_openers, "the entry outlived the detach of its target"
for number in range(20):
with late_browser._targets_lock:
late_browser._remember_opener(SimpleNamespace(target_id="t%d" % number, opener="o", gone=False))
assert len(late_browser._gone_openers) == 16 and "t0" not in late_browser._gone_openers and "t19" in late_browser._gone_openers
@@ -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,176 @@
"""A popup is reported on Page.ready, as Playwright's own is: with no limit, and with the destination's address already.
Measured against stock Playwright 1.62 and its Firefox (in-process, 2 runs of each, never in disagreement):
* a destination that answers 204, or never answers: NO `page` event in 30 s (nothing commits, the engine never says Page.ready);
* a destination that answers after 4 s: the event at 4.08 s, with `url` already the destination and `load` in the same millisecond.
Here: the same two, in-process and through a served browser driven by a stock client, and a destination that answers after 25 s (the
wrapper dropped a popup that was not ready in 20 s, with a warning); the address read at the `page` event is the destination.
Red on b09d620: the popup of the slow destination reads `about:blank` at the event (the commit comes in the same turn as the ready and
was applied after the page was announced), and the one that answers after 25 s was dropped at 20 s.
"""
from __future__ import annotations
import threading
import time
from http.server import BaseHTTPRequestHandler
import pytest
from _servers import LocalServer
pytestmark = pytest.mark.e2e
class _Handler(BaseHTTPRequestHandler):
def log_message(self, *a):
pass
def do_GET(self):
path, _, query = self.path.partition("?")
if path == "/nocontent":
self.send_response(204)
self.send_header("Content-Length", "0")
self.end_headers()
return
if path == "/slow":
ms = int(query.split("ms=")[1].split("&")[0]) if "ms=" in query else 0
time.sleep(ms / 1000.0)
body = b"<!doctype html><html><head><title>slow</title></head><body>slow</body></html>"
else:
body = (b"<!doctype html><html><head><title>opener</title></head><body>"
b"<button id=open204 onclick=\"window.open('/nocontent','_blank')\">open</button>"
b"<a id=link204 href=/nocontent target=_blank>link</a>"
b"<button id=open1500 onclick=\"window.open('/slow?ms=1500','_blank')\">open</button>"
b"<a id=link1500 href='/slow?ms=1500' target=_blank>link</a>"
b"<button id=open25000 onclick=\"window.open('/slow?ms=25000','_blank')\">open</button>"
b"</body></html>")
try:
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)
except OSError: # the browser left before a slow answer
pass
@pytest.fixture
def site():
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()
def _stock_client(module):
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)
def _drive(mode, firefox_binary, body):
"""Run body(context, page) in-process or through a served browser driven by a stock client."""
if mode == "in-process":
from invisible_playwright import InvisiblePlaywright
with InvisiblePlaywright(seed=42, binary_path=firefox_binary, headless=True, humanize=False) as b:
ctx = b.new_context()
body(ctx, ctx.new_page())
ctx.close()
return
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()
body(ctx, ctx.new_page())
ctx.close()
browser.close()
finally:
server.close()
MODES = ["in-process", "served"]
@pytest.mark.parametrize("mode", MODES)
@pytest.mark.parametrize("opener", ["#open204", "#link204"])
def test_a_destination_that_commits_nothing_gives_no_popup_event(firefox_binary, site, mode, opener):
def body(ctx, page):
page.goto(site, wait_until="load", timeout=30000)
seen = []
ctx.on("page", lambda p: seen.append(p))
page.click(opener)
time.sleep(6)
assert not seen, "a popup whose destination commits nothing was reported (Playwright's is not)"
assert len(ctx.pages) == 1
_drive(mode, firefox_binary, body)
@pytest.mark.parametrize("mode", MODES)
@pytest.mark.parametrize("opener", ["#open1500", "#link1500"])
def test_a_slow_popup_is_reported_with_the_address_of_its_destination(firefox_binary, site, mode, opener):
def body(ctx, page):
page.goto(site, wait_until="load", timeout=30000)
with page.expect_popup(timeout=20000) as info:
page.click(opener)
assert info.value.url == site + "slow?ms=1500", "the popup was reported with %r" % info.value.url
info.value.close()
_drive(mode, firefox_binary, body)
@pytest.mark.parametrize("mode", MODES)
def test_a_popup_whose_destination_answers_after_25_seconds_is_reported_then(firefox_binary, site, mode):
def body(ctx, page):
page.goto(site, wait_until="load", timeout=30000)
t0 = time.monotonic()
with page.expect_popup(timeout=45000) as info:
page.click("#open25000")
took = time.monotonic() - t0
assert 24.0 < took < 40.0, "reported after %.1f s" % took
assert info.value.url == site + "slow?ms=25000"
info.value.close()
_drive(mode, firefox_binary, body)
@pytest.mark.parametrize("mode", MODES)
@pytest.mark.parametrize("opener", ["#open1500", "#link1500"])
def test_a_listener_registered_in_the_page_handler_hears_the_load_of_the_popup(firefox_binary, site, mode, opener):
"""Stock Playwright: `context.on("page", lambda p: p.on("load", ...))` fires for a popup that loads after the event (4 s and 25 s
destinations); the popup is reported when its ready comes, which is when its document commits, so the load may be said before the
client has the page. `wait_for_load_state` in the same handler returns at once."""
def body(ctx, page):
page.goto(site, wait_until="load", timeout=30000)
heard, waited = [], []
def on_page(popup):
popup.on("load", lambda p: heard.append(time.monotonic()))
t = time.monotonic()
popup.wait_for_load_state("load", timeout=10000)
waited.append(time.monotonic() - t)
ctx.on("page", on_page)
with page.expect_popup(timeout=20000) as info:
page.click(opener)
deadline = time.monotonic() + 5
while not heard and time.monotonic() < deadline:
page.wait_for_timeout(50)
assert heard, "the listener registered in the handler of the page event never heard the load of the popup"
assert waited and waited[0] < 8.0, "wait_for_load_state in the handler took %r" % (waited,) # at once; the limit is the machine's
info.value.close()
_drive(mode, firefox_binary, body)
@@ -0,0 +1,136 @@
"""A tab opened by a link (`target=_blank`, with or without `noopener`) or by `window.open` reaches the client, in-process and
through a served browser driven by a stock Playwright client, with and without a context route holding the requests.
⛔ THE KNOWN-BAD INPUT. The page is handed to the client when the engine says `Page.ready`; the engine says it at the commit of the
popup's first document. Waiting for it INSIDE the construction of the page (7db28e4..6a60dce) broke two ways, each found by a run:
* the first request of a popup is held by the context's route until the page answers it, and a page that is built only once it is
ready never answers: `adoption of target ... failed: the page was not ready in 20s` on the server, `Timeout 15000ms exceeded while
waiting for event "page"` on the client (a stock client, a served browser, a route that continues every request);
* in-process, the commit and the `load` that come with the ready were said to a page that did not exist: `popup.wait_for_url(url)`
timed out on `load` (5 tests of test_popup_pages.py).
The page is now BUILT at once and ANNOUNCED when ready.
"""
from __future__ import annotations
import threading
import time
from http.server import BaseHTTPRequestHandler
import pytest
from _servers import LocalServer
pytestmark = pytest.mark.e2e
POPUP = b"<!doctype html><html><head><title>popup</title></head><body><h1>popup</h1></body></html>"
class _Handler(BaseHTTPRequestHandler):
def log_message(self, *a):
pass
def do_GET(self):
path = self.path.split("?")[0]
if path == "/popup":
body = POPUP
else:
# the same server by another NAME is another site: the document lands in another process (Fission)
port = self.server.server_address[1]
other = ("http://localhost:%d/popup" % port).encode()
body = (b"<!doctype html><html><head><title>opener</title></head><body>"
b"<a id=link href=/popup target=_blank>link</a>"
b"<a id=noopener href=/popup target=_blank rel=noopener>noopener</a>"
b"<button id=open onclick=\"window.open('/popup','_blank')\">open</button>"
b"<button id=open-noopener onclick=\"window.open('/popup','_blank','noopener')\">open</button>"
b"<a id=xlink href=" + other + b" target=_blank>cross-site link</a>"
b"<a id=xnoopener href=" + other + b" target=_blank rel=noopener>cross-site noopener</a>"
b"<button id=xopen onclick=\"window.open('" + other + b"','_blank')\">open</button>"
b"<button id=xopen-noopener onclick=\"window.open('" + other + b"','_blank','noopener')\">open</button>"
b"</body></html>")
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)
@pytest.fixture
def site():
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()
def _stock_client(module):
"""The stock Playwright client, a pinned dev dependency: its absence is a broken environment, not a reason to skip."""
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)
OPENERS = ["#link", "#noopener", "#open", "#open-noopener", "#xlink", "#xnoopener", "#xopen", "#xopen-noopener"]
def _router(delay_s):
def route(route):
time.sleep(delay_s) # a client that decides: the popup's first request waits for it
route.continue_()
return route
def _check(page, popup_of, site, opener):
page.goto(site, wait_until="load", timeout=30000)
# The verdict is that the popup arrives, with its address and its load: how long it takes depends on the machine (a runner with four
# workers took 2.0 s once), so no time limit here beyond a generous wait.
with page.expect_popup(timeout=30000) as info:
page.click(opener)
popup = info.value
popup.wait_for_load_state("load", timeout=5000)
expected = (site.replace("127.0.0.1", "localhost") if opener.startswith("#x") else site) + "popup"
assert popup.url == expected
assert popup.title() == "popup"
assert popup in page.context.pages
popup.close()
@pytest.mark.parametrize("routed", [False, True], ids=["plain", "routed"])
@pytest.mark.parametrize("opener", OPENERS)
def test_a_popup_reaches_an_in_process_client(firefox_binary, site, opener, routed):
from invisible_playwright import InvisiblePlaywright
with InvisiblePlaywright(seed=42, binary_path=firefox_binary, headless=True, humanize=False) as b:
ctx = b.new_context()
if routed:
ctx.route("**/*", _router(0.05))
page = ctx.new_page()
_check(page, None, site, opener)
ctx.close()
@pytest.mark.parametrize("routed", [False, True], ids=["plain", "routed"])
@pytest.mark.parametrize("opener", OPENERS)
def test_a_popup_reaches_a_stock_client_of_a_served_browser(firefox_binary, site, opener, routed):
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()
if routed:
ctx.route("**/*", _router(0.05))
page = ctx.new_page()
_check(page, None, site, opener)
ctx.close()
browser.close()
finally:
server.close()
@@ -0,0 +1,154 @@
"""A LOSS IS NOT A DROP: behind a proxy that cannot carry the UDP of a PeerConnection, nothing of the browser reaches a server direct.
The fail-closed rule of the UDP line is "the UDP of a PeerConnection behind a proxy that carries none goes NOWHERE: not to the relay, and
never direct, around the proxy". The e2e that check "no srflx" cannot tell the rule from a leak: in a laboratory whose servers sit at
documentation addresses nothing routes, a datagram sent direct arrives nowhere, exactly as a dropped one. Here the STUN server and the TCP
TURN listener of the page (a WITNESS, ``_witness.py``) stand at an address the browser CAN reach directly (a documentation address held
on ``lo``: root, Linux, the suite ``wrapper.e2e.udp.exit``), and the gateways leave from ANOTHER such address, the exit. So:
* in each fail-closed scenario - a proxy that refuses UDP, one whose UDP leaves from another address than its TCP, one whose relay never
answers, an HTTP proxy - the witness hears NO datagram from anyone and NO connection from a source that is not the exit; a send direct
fails this test;
* the controls, which are what makes the green mean something: the same page with NO proxy is heard by the witness (the laboratory does
see a direct send), and behind a coherent gateway the witness hears the datagrams from the EXIT only (the relay is seen too).
"""
from __future__ import annotations
import pytest
import _turn_chain as chain_mod
from _doh_servers import FakeDoh
from _host_address import this_host_address
from _http_proxy import HttpProxy
from _socks_servers import EXIT, OTHER_EXIT, Gateway
from _udp_line import declared_udp, egress_by_proxy, measure_servers
from _witness import Witness
from test_webrtc_realness import _e2e_binary, _launch, _launch_behind # noqa: F401
pytestmark = [pytest.mark.e2e, pytest.mark.usefixtures("the_udp_line")]
#: Where the witness stands: a documentation address (RFC 5737, TEST-NET-2) held on lo, reachable by the browser directly.
WITNESS_ADDRESS = "198.51.100.10"
#: The exit of the gateways (the address their datagrams and connections leave from): another documentation address on lo.
EXIT_ADDRESS = chain_mod.LAB_EXIT
#: How long the page waits after the offer: the first retransmissions of STUN and TURN (0, 0.1, 0.3, 0.7, 1.5, 3.1 s) have all been sent.
WAIT_MS = 5000
_PROBE_JS = """async (target) => {
const pc = new RTCPeerConnection({iceServers: [
{urls: ['stun:' + target]},
{urls: ['turn:' + target + '?transport=udp'], username: 'u', credential: 'p'},
{urls: ['turn:' + target + '?transport=tcp'], username: 'u', credential: 'p'}]});
pc.createDataChannel('x');
const found = [];
pc.onicecandidate = (e) => { if (e.candidate) found.push(e.candidate.candidate); };
await pc.setLocalDescription(await pc.createOffer());
await new Promise((resolve) => setTimeout(resolve, %d));
return found;
}""" % WAIT_MS
@pytest.fixture
def witness():
with chain_mod.lab_exit_address(EXIT_ADDRESS), chain_mod.lab_exit_address(WITNESS_ADDRESS):
w = Witness(WITNESS_ADDRESS)
try:
yield w
finally:
w.close()
def _gateway(**kw) -> Gateway:
"""A SOCKS5 gateway whose datagrams and connections leave from the exit address, with a relay on this host's address."""
kw.setdefault("tcp_exit", EXIT)
kw.setdefault("udp_exit", EXIT)
return Gateway(relay_host=this_host_address(), exit_host=EXIT_ADDRESS, tcp_from_exit=True, **kw)
def _gather(page_launcher, w: Witness):
with page_launcher() as browser:
page = browser.new_context().new_page()
page.goto("about:blank")
return page.evaluate(_PROBE_JS, w.target)
# (id, how the gateway is made, what the core must have declared for its UDP)
SOCKS_SCENARIOS = [
("the_proxy_refuses_udp", lambda: _gateway(udp="refuse"), "no"),
("the_udp_of_the_proxy_leaves_from_another_address", lambda: _gateway(udp="relay", udp_exit=OTHER_EXIT), "no"),
("the_relay_never_answers", lambda: _gateway(udp="relay", stun_answers=False), "unmeasured"),
]
@pytest.mark.parametrize("make,declared", [(m, d) for _i, m, d in SOCKS_SCENARIOS], ids=[i for i, _m, _d in SOCKS_SCENARIOS])
def test_behind_a_socks5_proxy_that_cannot_carry_the_udp_nothing_is_sent_direct(monkeypatch, witness, make, declared):
binary = _e2e_binary()
if not binary:
pytest.skip("no patched binary (set STEALTHFOX_E2E_BINARY)")
from invisible_core import _geo
gateway = make()
try:
monkeypatch.setattr(_geo, "discover_egress_ip", egress_by_proxy(gateway))
found = _gather(lambda: _launch_behind(gateway, binary_path=binary), witness)
assert declared_udp(gateway.proxy, measure_servers(gateway)) == declared, "the scenario is not the one it says"
finally:
gateway.close()
leaked = witness.heard_from_other_than([EXIT_ADDRESS])
assert not witness.heard()["udp"], (
"the witness heard a datagram behind a proxy that carries no UDP: %s (the exit is %s)" % (witness.heard()["udp"], EXIT_ADDRESS))
assert not leaked["tcp"], "a connection to the witness did not come from the proxy's exit: %s" % (leaked["tcp"],)
assert not [c for c in found if " typ srflx " in c or " typ relay " in c], "a candidate that nothing allocated: %s" % (found,)
def test_behind_an_http_proxy_nothing_is_sent_direct(monkeypatch, witness):
binary = _e2e_binary()
if not binary:
pytest.skip("no patched binary (set STEALTHFOX_E2E_BINARY)")
from invisible_core import _geo
doh = FakeDoh({})
proxy = HttpProxy("http-proxy", doh)
try:
monkeypatch.setattr(_geo, "discover_egress_ip", lambda *a, **k: EXIT)
found = _gather(lambda: _launch(proxy=proxy.proxy, binary_path=binary), witness)
finally:
proxy.close()
doh.close()
assert not witness.heard()["udp"], "the witness heard a datagram behind an HTTP proxy: %s" % (witness.heard()["udp"],)
assert not witness.heard()["tcp"], (
"the witness heard a connection behind an HTTP proxy that refuses it (the proxy never connected): %s" % (witness.heard()["tcp"],))
assert not [c for c in found if " typ srflx " in c or " typ relay " in c], "a candidate that nothing allocated: %s" % (found,)
def test_the_control_with_no_proxy_the_witness_hears_the_browser_direct(monkeypatch, witness):
"""Without this the green above proves nothing: the laboratory must SEE a direct datagram and a direct connection."""
binary = _e2e_binary()
if not binary:
pytest.skip("no patched binary (set STEALTHFOX_E2E_BINARY)")
from invisible_core import _geo
monkeypatch.setattr(_geo, "discover_egress_ip", lambda *a, **k: EXIT) # the world has no network: nothing to wait for
_gather(lambda: _launch(binary_path=binary), witness)
heard = witness.heard()
assert heard["udp"], "the witness heard no datagram of a browser with no proxy: the laboratory does not see a direct send"
assert heard["tcp"], "the witness heard no connection of a browser with no proxy: the laboratory does not see a direct connection"
assert not [h for h in heard["udp"] + heard["tcp"] if h[0] == EXIT_ADDRESS], "a direct send came from the exit of the gateways"
def test_the_control_behind_a_coherent_gateway_the_witness_hears_the_exit_only(monkeypatch, witness):
"""The relay is seen too: the datagrams and the connections of a proxy that carries UDP arrive FROM ITS EXIT, and from nowhere else."""
binary = _e2e_binary()
if not binary:
pytest.skip("no patched binary (set STEALTHFOX_E2E_BINARY)")
from invisible_core import _geo
gateway = _gateway(udp="relay")
try:
monkeypatch.setattr(_geo, "discover_egress_ip", egress_by_proxy(gateway))
_gather(lambda: _launch_behind(gateway, binary_path=binary), witness)
assert declared_udp(gateway.proxy, measure_servers(gateway)) == "coherent"
finally:
gateway.close()
heard = witness.heard()
assert heard["udp"], "the witness heard no datagram through a coherent relay"
assert not witness.heard_from_other_than([EXIT_ADDRESS])["udp"], (
"a datagram came from a source that is not the exit of the relay: %s" % (witness.heard_from_other_than([EXIT_ADDRESS])["udp"],))
assert not witness.heard_from_other_than([EXIT_ADDRESS])["tcp"], (
"a connection came from a source that is not the exit of the proxy: %s" % (witness.heard_from_other_than([EXIT_ADDRESS])["tcp"],))
@@ -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
+1 -1
View File
@@ -27,7 +27,7 @@ from invisible_playwright._juggler._marshal import _resource_type
("TYPE_MEDIA", "media"),
("TYPE_WEBSOCKET", "websocket"),
("TYPE_WEB_MANIFEST", "manifest"),
("TYPE_BEACON", "other"),
("TYPE_BEACON", "beacon"),
("TYPE_OTHER", "other"),
])
def test_the_cause_juggler_sends_names_the_resource(cause, expected):
@@ -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,50 @@
"""A client of the server cannot turn the launch counter off or point it elsewhere (no browser).
The core refuses the two prefs of the counter in ``extra_prefs``; the server takes ``firefoxUserPrefs`` from a client and, for a launch
that names no session, puts them on top of the session it composes, and for a marked launch takes them as they come. Both roads are
closed here, at ``session_for_launch``, with the core's own refusal.
"""
from __future__ import annotations
import pytest
from invisible_core.prefs import USAGE_PING_PREFS, USAGE_PING_REFUSAL, USAGE_PING_URL
from invisible_playwright._juggler import server
pytestmark = pytest.mark.unit
ENABLED, URL = USAGE_PING_PREFS
@pytest.fixture(autouse=True)
def composed_session(monkeypatch):
"""The session the server composes for an unmarked launch, without composing one (that needs an engine)."""
import invisible_playwright._session as session
monkeypatch.setattr(session, "default_session", lambda executable, proxy=None: ({URL: USAGE_PING_URL, "x": 1}, {}))
@pytest.mark.parametrize("pref,value", [(ENABLED, False), (ENABLED, True), (ENABLED, None), (URL, "https://example.invalid/x"), (URL, None)])
@pytest.mark.parametrize("marked", [False, True], ids=["bare launch", "marked launch"])
def test_a_client_cannot_send_the_counter_prefs(pref, value, marked):
prefs = {pref: value}
if marked:
prefs[server.COMPOSED_PREF] = True
with pytest.raises(ValueError) as refused:
server.session_for_launch(prefs, "firefox")
assert pref in str(refused.value) and USAGE_PING_REFUSAL in str(refused.value)
def test_the_address_the_core_wrote_travels_in_a_marked_launch():
prefs, _env = server.session_for_launch({server.COMPOSED_PREF: True, URL: USAGE_PING_URL, "y": 2}, "firefox")
assert prefs[URL] == USAGE_PING_URL and prefs["y"] == 2 and ENABLED not in prefs
def test_a_bare_launch_gets_the_core_address_and_the_clients_other_prefs():
prefs, _env = server.session_for_launch({"z": 3}, "firefox")
assert prefs[URL] == USAGE_PING_URL and prefs["z"] == 3 and ENABLED not in prefs
def test_the_same_address_in_a_bare_launch_is_still_refused():
"""Only the address the CORE wrote, inside a composed launch, is let through: a bare client that names it is refused too."""
with pytest.raises(ValueError):
server.session_for_launch({URL: USAGE_PING_URL}, "firefox")
@@ -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,92 @@
"""A proof of use, not of the order: on one connection the engine says a download's creation before its end, so this test does not force a finish before the announcement (the unit test test_a_download_finished_before_it_was_announced_is_finished.py does). It shows that tiny downloads, the case where the end comes soonest, are saved whole through a served browser.
Tiny downloads through a served browser are saved by a stock client, every one.
One served browser, a stock Playwright client, a page that links to a 300-byte attachment and to a 1-byte one:
ten downloads of each, each saved and compared byte for byte.
Not a known-bad input for the order: it is not expected to be red on the server before the fix (the unit test is the proof of
the fix); it guards the use.
"""
from __future__ import annotations
import http.server
import importlib
import threading
import pytest
pytestmark = pytest.mark.e2e
BODIES = {"big": bytes(range(256)) + b"\x01" * 44, "one": b"Z"}
COUNT = 10
def _serve():
class H(http.server.BaseHTTPRequestHandler):
def log_message(self, *a):
pass
def do_GET(self):
kind = self.path.strip("/").split("/")[0].split("?")[0]
if kind in BODIES:
body = BODIES[kind]
self.send_response(200)
self.send_header("content-type", "application/octet-stream")
self.send_header("content-disposition", 'attachment; filename="%s.bin"' % kind)
self.send_header("content-length", str(len(body)))
self.end_headers()
self.wfile.write(body)
return
links = "".join('<a id="%s%d" href="/%s?n=%d">%s</a> ' % (k, i, k, i, k)
for k in BODIES for i in range(COUNT))
page = ("<!doctype html><title>d</title>" + links).encode()
self.send_response(200)
self.send_header("content-type", "text/html")
self.send_header("content-length", str(len(page)))
self.end_headers()
self.wfile.write(page)
srv = http.server.ThreadingHTTPServer(("127.0.0.1", 0), H)
srv.daemon_threads = True
threading.Thread(target=srv.serve_forever, daemon=True).start()
return srv, "http://127.0.0.1:%d/" % srv.server_address[1]
@pytest.fixture
def served():
srv, url = _serve()
try:
yield url
finally:
srv.shutdown()
srv.server_close()
def test_ten_tiny_downloads_of_each_size_are_saved_through_a_served_browser(firefox_binary, served, tmp_path):
try: # the stock client (a pinned dev dependency), imported by name: the fork's guard forbids a static import
sync_playwright = importlib.import_module("playwright.sync_api").sync_playwright
except ImportError as exc:
pytest.fail("the stock Playwright client is missing (%s): install the wrapper with its dev extra" % exc,
pytrace=False)
from invisible_playwright._juggler.remote import launch_server
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)
try:
page = browser.new_context(accept_downloads=True).new_page()
page.goto(served, timeout=30_000)
for kind, body in BODIES.items():
for i in range(COUNT):
with page.expect_download(timeout=20_000) as info:
page.click("#%s%d" % (kind, i))
target = tmp_path / ("%s%d.bin" % (kind, i))
info.value.save_as(target)
assert target.read_bytes() == body, (kind, i)
assert info.value.failure() is None
finally:
browser.close()
finally:
server.close()
Loaded 100 of 210 files, more files were not shown because too many files have changed in this diff. Show more