Compare commits

...
4 Commits
Author SHA1 Message Date
Federico ff096b4d1b screencast.start() takes an fps, and the default stays at ten (0.14.0) (#182)
* screencast.start() takes an fps, and the default stays at ten (0.14.0)

The engine has taken a frame rate all along - `fps || 25` in its own registry -
and this passed the wrapper's constant to it whatever the caller asked for. So a
live view could not go past ten frames a second no matter what it did, which is
the second half of a slow pane: the first half was the client asking every
200 ms for a source producing every 100, fixed elsewhere.

Measured on the same page, interleaved arms: asking for 10 delivers 9.6-9.8 fps
at 257 KB/s, asking for 25 delivers 23.8-24.0 at 629 KB/s.

⛔ THE DEFAULT DOES NOT MOVE, and that is the whole shape of the change. Raising
the constant would put two and a half times the bandwidth on every consumer to
serve the one that is watching a window - a batch job that never looks at a
frame would pay it too. The caller decides and the constant is what happens when
nobody does, which is how `quality` and `size` on the same call already worked.

The test that pins it caught its own weakness first. It asserted that `fps` is
in the public signature, and the mutation that deletes `fps=fps` from the
generated wrapper survived that: a parameter a caller can pass and that goes
nowhere is an inert lever, and it is worse than a missing one because it looks
like it works. It now checks that every parameter the public signature declares
is forwarded, which is the property rather than this one case.

* And an e2e that asks the engine, because the unit test cannot

The unit test proves the wrapper puts a number on the wire. Only a real engine
can say the number does anything, and a lever verified from outside the system
it moves is exactly what this project has been fooled by before: seven levers
passed as prefs on the protocol, all inert, all reported green.

Two pages of one browser, same served page, same duration, and the assertion is
on the ratio - the absolute rate is a property of the machine, and the claim is
that asking for more gets more. The floor is far from the measured numbers on
purpose: it tests that the lever is connected, not that this machine is fast.
2026-09-08 17:29:57 +02:00
Federico 84192938cb Nineteen pages show the values they describe, and twenty-four stop pointing nowhere (#181)
* Four more pages get the measurement they were describing

Each of these pages asserted something a reader has to take on trust. Each one
now carries the run that produces it, on one Windows machine, one page served
from 127.0.0.1, with the numbers computed inside the page so the figure and the
figures agree by construction.

Canvas fingerprint changes every run. Four sessions: two without a seed disagree
on both readbacks and even on the device pixel ratio, two with the same seed are
identical, 0 of 79,800 pixels apart. The drawing looks the same in all four
panels, which is the useful part: the eye cannot separate them and the hash can.
Running it also contradicted a sentence the page carried, "Different seed,
different bytes": two different identity seeds can land on the same hardware
seed and return the same readback. The direction that holds is same seed, same
bytes, and the text now says only that.

Human-like mouse movement. Three ways to reach one target, with the page
recording every pointer event. All three report isTrusted true, so the trusted
flag does not separate the driver from the engine, only both from page script.
What separates them is the deltas: 3 distinct movementX values across 41 events
for an evenly stepped driver path, 26 across 34 for the engine's. And the third
panel is not a graceful arc, which is this page's whole thesis in one image.

Detecting installed fonts by width. The article's own snippet, run over ten
families against two different fallbacks. Consolas reads absent against
monospace and present against serif on the same machine in the same session,
because Consolas is what monospace resolves to there. An invented control family
stays absent under both, which is what makes that a finding. The rule now names
its exception: an identical width means the candidate did not render, or the
candidate is the fallback.

Screen size and viewport tells. The taskbar check does not fire on this browser:
bundled Firefox headless reports a 48 pixel gap, same as headful. What is a tell
is the constant, 1366x768 at two different viewports. Also states a sharp edge of
ours: an explicit viewport leaves outerWidth on the declared window while
innerWidth follows the request, 1490 pixels of impossible chrome, and
no_viewport keeps the pair at a plausible 85.

Every PNG was opened and inspected, and carries no metadata chunks and nothing
after IEND.

* Measure the new_page default instead of describing it

The page says browser.new_page() ships Playwright's stock 1280x720, and that the
same gap was closed on this engine. Both halves are now run rather than stated.

Three headless sessions on one page served from 127.0.0.1. The bundled Firefox
opened with new_page() reports inner 1280x720 on a screen it calls 1366x768. The
same build asked for new_context(no_viewport=True) reports 1366x683, a window on
that screen instead of a number from a config file. The patched engine opened
with new_page() reports 1920x947, which is exactly what its own new_context
gives, so the convenience call is not picking up a default nobody chose.

The first panel carries a second contradiction worth naming on a page about
relationships: outerHeight reads 805 while availHeight reads 720, so the window
is taller than the space the OS says exists.

PNG opened and inspected, no metadata chunks, nothing after IEND.

* Thirteen more pages show the values they describe, and the canvas page gets two corrections

Each page now carries a card of the values it names, read from a page served
from 127.0.0.1 by two headless sessions: Playwright's bundled Firefox and a
patched engine. Every card holds that page's own values, so no two are the same
table.

Eleven pages had at least one value that differs between the two browsers, so
those carry both panels. Three had none, and there the card is a single panel
with a note that the bundled Firefox returned the same values: a difference that
does not exist is not worth two identical tables.

Four cards were built and then dropped rather than shipped. Five pages named the
same trio of userAgent, platform and oscpu, which would have put the same
three-row table on five pages, and two comparison pages would have carried the
same two-row table. Kept where that trio is the subject, dropped elsewhere.

Three probes are deliberately not in the catalogue because they reveal the host
that ran the bench: the unmasked WebGL renderer prints the real GPU, the resolved
timeZone and navigator.languages print where the machine is. Measured on this
host before they were removed.

And the canvas page carries two corrections that came out of running it:

Without a seed, what changes on every launch is the device, not necessarily the
readback. Five unseeded launches moved the screen between 1920x1080 and
2560x1440, the core count between 4 and 12 and the ratio between 1 and 1.25, and
returned the same canvas four times out of five. So two unseeded runs agreeing on
a canvas hash is the likely outcome, not evidence that a seed took effect.

And hashing toDataURL partly hashes the PNG encoder. Three launches of the
bundled Firefox drawing an identical canvas returned three different toDataURL
hashes and the same getImageData bytes every time, with
privacy.fingerprintingProtection and privacy.resistFingerprinting tested both
ways. The cards read getImageData for this reason.

All nineteen PNGs opened and inspected, no metadata chunks, nothing after IEND.

* Three questions the new measurements answer, in the block that captures them

Each of these is a question a reader types and the page could not answer until
the bench ran. One per page, and all three different: a block that grew by the
same entry on three pages would be padding.

Hash getImageData rather than toDataURL when you want to know whether the drawing
changed, because three launches of the bundled Firefox returned three data URL
hashes and the same pixel bytes.

Playwright's Firefox reports 1366x768 with availHeight 720 in headless mode, and
it did not move at two different viewports, so it is a constant rather than
something derived from the session.

And a font the probe calls absent may be the fallback: Consolas reads absent
against monospace and present against serif in the same session on Windows.

* Shorten the one alt text that ran past four hundred characters

Every other figure sits between roughly one hundred and three hundred; this one
described four things a screen reader has to hear in one breath. Same content,
fewer clauses.

* Give seven mute pages their first in-body links

linkgraph counted 24 pages in the engine corpus with zero contextual
outgoing links and named none of them, so the number had sat there for a
month with nobody able to act on it. Named now, they turn out not to be
stubs: 620 to 2600 words, six to eleven H2s, with every internal link
sitting in the See also footer or the FAQ block, which the graph excludes
on purpose because boilerplate is not equity.

Seven of them get two or three links each, written for the sentence they
sit in: the four net::ERR_* pages point at the siblings that differ only
in how far the exchange got, Anubis and Turnstile point at each other on
the proof-of-work layer they share, and the CSP page places an init
script at the page-JavaScript level of the three.

Measured before and after with the tool, on this worktree: 24 to 17.

* Eleven more mute pages, and the integrations family had none at all

The eight pages under docs/integrations had zero internal markdown
links between them: only the directory README pointed in, and nothing
pointed out. They are also the pages where a reader arrives having
already chosen a tool, which makes them the ones most worth giving a
next step.

Links are placed on the sentence that raises the subject, and the
target differs per page on purpose: eight near-identical pages that all
grew the same link in the same section would be the monotemplate
signature the checklist warns about, which is the thing the See also
block already is. So the user-agent warning points at why one string is
the weakest thing to change, Crawlee's fingerprint generator at what a
fingerprint is read as, scrapy's SOCKS route at where Playwright drops
the credentials, TestCafe's missing prefs column at the seed.

One anchor was written before checking the target and described
something that page does not cover; it names the layer stack now, which
is what the page is actually about.

Link form is the corpus convention, [x](slug.md), which build_wiki
resolves from a subdirectory through its addressable table. The
../slug.md form would read correctly on github.com and dead on the
wiki, which is the surface that ranks.

Measured with the tool against this worktree: 17 to 6, median outbound
density back to 3.4 per thousand words.

* The last six mute pages: the engine corpus is at zero

Six troubleshooting and getting-started pages get their first in-body
links, and three of them sit next to each other in the error space, so
the links say which of the neighbouring errors you would be reading
instead: force-clicking through an overlay against the not-attached
error, a leaked process against a script still holding a browser that
went away, strict mode against a click that is merely covered.

Two anchors were written before reading the target and had to be
corrected. One claimed a page covered whether content arrives in the
HTML, which it does not; it names the layer stack now. One asserted the
seed page lists two things it cannot pin, which is not the shape of that
section; it points at the section by what it is. An anchor that
describes the target wrongly is worse than no link, because a reader
follows it once and stops trusting the rest.

engine: 24 mute pages to 0, median outbound density 3.4 per thousand
words, inside the 2-5 house range. aihawk still has 2, both on the
restricted themes, handled separately.

* An anchor with an underscore left one dead link on the wiki

The link rewriter's anchor class was [A-Za-z0-9-], and a heading like
"What invisible_playwright does and does not do here" produces an anchor
carrying an underscore. The pattern then fails to match the whole link,
not just the anchor, so it shipped to the wiki as
](geetest-v4-explained.md#...) - a dead target, because the wiki has no
.md pages.

One link across 463 pages, and invisible from either side: the page
renders normally and only the destination 404s. Found by building the
wiki and grepping the output for links that still end in .md, which is
worth doing on any batch that adds internal links.

Underscore added to both classes, since a page name can carry one for
the same reason a heading can. Rebuilt: the unresolved count goes 1 to
0 and exactly one of the 463 output files differs, so nothing else
moved.

* The headful panel printed this machine's display, so it comes out

The screen figure had four panels and the third was labelled "now it is
the host's display". It was: 1365 x 853, the real geometry of the
machine the bench ran on, painted into the pixels of a page about to be
published. The alt text had carefully avoided the number, so the image
was the only place it appeared.

That is the class the house rule names by name, and it got through
because the exclusion list lives in the probe catalogue, which the
value cards go through and a bespoke bench does not. A bench written
for one page reaches straight past it.

Recomposed from the three headless panels with the harness. The
argument survives: the taskbar gap is still 48 px, the screen is still
a constant across two viewports, the patched engine still declares
1920x1080. The headful measurement is now stated in prose, with the
reason it is not shown, which is the honest version of what that panel
was for.

Renamed to three-arms, free to do because the URL has never been
published. The other four bespoke figures were opened and are clean,
and the 114 strings rendered into the fourteen value cards were scanned
for IP, host timezone, host locale, GPU model, user paths and machine
names: nothing.
2026-09-08 17:03:02 +02:00
Federico 53b7996bc3 Show the headful/headless font difference instead of only asserting it (#180)
The page opens by saying that the same page rendered both ways on one machine
is not identical, and then argues it from Linux and fontconfig. Nobody had run
it on Windows.

Four arms on one page served from 127.0.0.1, same viewport, same URL: the
bundled Firefox headful and headless, then a patched Firefox headful and
headless.

The bundled build disagrees with itself across the two modes on 8,989 of
294,400 pixels, 3.05% of the frame. The shape matters more than the number.
Every sample row keeps its exact height, so no glyph got taller; the rows drift
downward by 0, 1, 1, 2, 2, 2, 2 and 3 pixels from the first sample to the
eighth. Line boxes round differently and the error accumulates, which is why a
screenshot test can pass on a laptop and fail in CI, and why a tolerance tuned
on the first viewport does not hold at the bottom of a long page.

The patched engine returned the same frame in both modes, byte for byte, on
three repeats of the whole bench.

The figure carries the browser's own pixels: labels sit on strips added outside
the panels, since GitHub strips figcaption. It includes an amplified difference
map so the 3% is visible rather than asserted, and the text states the cost of
the trade: Arial Narrow is installed on the host, the patched engine does not
carry that face, so that row renders wide instead of narrow.
2026-09-08 07:44:18 +02:00
Federico 7567dbc52b Give every wiki page a view counter of its own (#179)
* Give every wiki page a view counter of its own

A GitHub wiki serves no per-page analytics. The traffic API reports the ten
most visited paths over fourteen days and nothing below that, so a corpus of
463 pages is invisible by construction: measured today, the whole wiki index
sits at about thirty views per fortnight and no individual page reaches the
top ten. We know which pages rank and not which ones get read.

Each page now embeds a 68-byte transparent 1x1 PNG held as an asset of an
article-views release, the way the browser launch counter has worked since
May: the asset's download count is how many times the page was loaded. The
release is created with make_latest=false, so it never becomes the
repository's Latest.

What that number is not, measured rather than assumed: four deliberate loads
produced six counts, so it carries fetches we did not make and cannot
separate, download_count being a bare integer with no provenance. It counts
fetches and not visitors, crawlers like readers, and nothing at all for a
reader who blocks images. It is for comparing pages and days.

The pixel goes into the wiki only, never back into docs/: the wiki is the
surface that ranks, while the .md in the repository is served as a JSON
payload React mounts, so a counter there would measure almost nothing and put
markup in the source tree.

build_wiki.py writes no pixel unless it is told which repository it builds
for, which is right for a local preview and silent otherwise - a wiki
published that way looks entirely normal and counts nothing. So the workflow
passes the flag and then gates on it: the checker refuses a page with no
pixel, with two, or with one addressed elsewhere, and its own eleven
known-bad cases run first.

* Pace the first upload run, and say it in English

The first run on an existing corpus uploads one asset per page - 463 here -
and GitHub throttles bursts of content-creating requests with a 403 or 429
carrying Retry-After. That burst happens before the wiki push, so a throttle
would have blocked the publish itself on the one run nobody gets to rehearse.
Honour the header, retry, and pace the loop at a tenth of a second, which puts
the whole first run under a minute of added wall clock.

The backoff has its own three known-bad cases against a fake throttling
server, because retry code that has never once retried is not retry code. A
404 stays unretried on purpose: reading one is how a missing release is found.

And the file was carrying Italian identifiers and test names into a public
repository. The language gate reads git ls-files, so running it before the
file was tracked was running it against a world where the file did not exist.
2026-09-08 07:41:16 +02:00
71 changed files with 1240 additions and 52 deletions

No files matched your search

+19 -1
View File
@@ -44,7 +44,25 @@ jobs:
python-version: "3.12"
- name: Render docs/ into a wiki build directory
run: python scripts/build_wiki.py docs wiki_build
run: python scripts/build_wiki.py docs wiki_build --pixels "${{ github.repository }}"
# The view counters. Upload BEFORE the push, never after: a page that
# reaches the wiki without its asset serves a 404 for its own pixel and
# counts nothing until the next release. Uploading only what is missing
# makes this a no-op on a run that adds no pages.
- name: Give every new page its view pixel
env:
GITHUB_TOKEN: ${{ github.token }}
run: python scripts/sync_article_pixels.py --repo "${{ github.repository }}" wiki_build
# And the gate. `build_wiki.py` writes no pixel when it is not told which
# repository it is building for, which is the right default for a local
# preview and a silent disaster here: the wiki would publish, look
# perfectly normal, and count nothing. This is the step that notices.
- name: Check every page carries its own pixel
run: |
python scripts/sync_article_pixels.py --selftest
python scripts/sync_article_pixels.py --repo "${{ github.repository }}" --check wiki_build
- name: Publish to the wiki
env:
+3 -3
View File
@@ -9,7 +9,7 @@ nav_order: 34
# Anubis: The Proof-of-Work Firewall, Explained
Every other vendor on this list is a commercial product whose internals have to be pieced together from reverse engineering, because the company that built it has no reason to publish them. Anubis is different: it is MIT-licensed, its full source is on GitHub, and its author writes publicly about why it exists and what it does not solve. This page is built almost entirely from primary material, its own repository, its own documentation, and a named security researcher's own published analysis, not practitioner reconstruction. Say that plainly, because it is the exception in this corpus, not the rule.
Every other vendor in [the survey of how websites detect bots](how-do-websites-detect-bots.md) is a commercial product whose internals have to be pieced together from reverse engineering, because the company that built it has no reason to publish them. Anubis is different: it is MIT-licensed, its full source is on GitHub, and its author writes publicly about why it exists and what it does not solve. This page is built almost entirely from primary material, its own repository, its own documentation, and a named security researcher's own published analysis, not practitioner reconstruction. Say that plainly, because it is the exception in this corpus, not the rule.
Anubis was created by Xe Iaso, a pseudonymous developer, in January 2025, after Amazon's web crawler overloaded Iaso's own Git server while ignoring `robots.txt` entirely. It is now maintained by Techaro. The name is the joke and the mechanic at once: Anubis, the Egyptian god who weighs the hearts of the dead, and the software "weighs the soul" of an incoming HTTP request before deciding whether it deserves to reach the backend at all.
@@ -27,7 +27,7 @@ Later versions moved Anubis toward something closer to a lightweight, rule-drive
## Adoption: this is not a hypothetical
Anubis is deployed in front of real infrastructure at meaningful scale, not just a research demo. Documented adopters include GNOME's GitLab instance, the Linux kernel's mailing list and Git infrastructure, FFmpeg, Wine, UNESCO, FreeCAD, ScummVM, Duke University's digital archives, OpenWRT, and the Deutsche Nationalbibliothek. Its author's own stated tradeoff is explicit rather than hidden: deploying it "will result in your website being blocked from smaller scrapers and may inhibit 'good bots' like the Internet Archive," and the project's guidance is that most sites should try Cloudflare first and reach for Anubis only when that is not an option.
Anubis is deployed in front of real infrastructure at meaningful scale, not just a research demo. Documented adopters include GNOME's GitLab instance, the Linux kernel's mailing list and Git infrastructure, FFmpeg, Wine, UNESCO, FreeCAD, ScummVM, Duke University's digital archives, OpenWRT, and the Deutsche Nationalbibliothek. Its author's own stated tradeoff is explicit rather than hidden: deploying it "will result in your website being blocked from smaller scrapers and may inhibit 'good bots' like the Internet Archive," and the project's guidance is that most sites should try Cloudflare first and reach for Anubis only when that is not an option, which in practice means the gate a visitor meets is more often [Turnstile](cloudflare-turnstile-explained.md) than this one.
## A real, named critique worth reading in full
@@ -39,7 +39,7 @@ That critique does not contradict what Anubis's own author and documentation say
This is the one detector in this whole corpus where the honest answer is: engine realness is close to irrelevant to whether the gate opens. Anubis is not testing whether a browser is lying about its fingerprint, checking canvas output, or looking for automation-framework tells. It is testing one thing: can this client execute a modern JavaScript engine fast enough to solve a SHA-256 search in a reasonable time. Any real browser, patched or unpatched, stealth or not, answers that the same way, because the puzzle does not touch fingerprint surfaces at all. A plain HTTP client with no JavaScript engine fails it regardless of how convincingly its headers are spoofed, which is the entire point: it is a liveness test for "do you run JavaScript like a browser," not a fidelity test for "are you the specific browser you claim to be."
`invisible_playwright` does not do anything specific to Anubis, and there is nothing Anubis-specific to do: a genuinely real Firefox, C++-patched or stock, solves its puzzle the same way any other real Firefox does, because the puzzle is engine-agnostic by construction. What this page is really useful for is the opposite lesson: not every gate in this space is a fingerprint problem, and treating Anubis as one would be a category error.
`invisible_playwright` does not do anything specific to Anubis, and there is nothing Anubis-specific to do: a genuinely real Firefox, C++-patched or stock, solves its puzzle the same way any other real Firefox does, because the puzzle is engine-agnostic by construction. What this page is really useful for is the opposite lesson: not every gate in this space is a fingerprint problem, and treating Anubis as one would be a category error. The gates that do read [what a browser fingerprint is made of](what-is-a-browser-fingerprint.md) are a separate family, and knowing which of the two you are behind decides whether any of that work applies at all.
## Short answers to the questions that lead here
+15
View File
@@ -89,6 +89,21 @@ as [what `navigator.vendor` and `navigator.productSub` report on Firefox](naviga
which are wrong on a Chromium base pretending to be Firefox and correct on an actual
Firefox build.
### The answer, read from a session
![One panel listing three values read from the patched engine, headless:
navigator.getBattery is undefined, navigator.vendor is an empty string, and
navigator.productSub is 20100101. A note says the bundled Firefox returned the same
values.](https://raw.githubusercontent.com/feder-cr/invisible_playwright/main/docs/img/battery-api-fingerprint-firefox-values.png)
`navigator.getBattery` is `undefined`, which is the answer to the title, and the bundled
Firefox returns the same thing.
The two Firefox constants sit next to it on purpose. A build that reports the empty
`vendor` and `20100101` for `productSub`, and then hands a page a battery object, has
contradicted itself with three property reads: the first two say Firefox and the third
says something that is not one.
## Check it yourself in two lines
Switching from stock Playwright is a two-line change, and after that every standard
@@ -81,6 +81,21 @@ a real AudioContext output, and Windows screen metrics with a plausible availabl
and device pixel ratio. Those answers are the same whether the host is your laptop or a
Linux container, because they are presented by the browser rather than read from the box.
## What each browser answers on the same page
![Two panels listing three values. navigator.webdriver differs, true against false. The
AudioContext sample rate is 48000 Hz in both. navigator.platform is Win32 in
both.](https://raw.githubusercontent.com/feder-cr/invisible_playwright/main/docs/img/can-a-website-tell-you-are-on-a-server-values.png)
Three values from one page served from `127.0.0.1`. The audio sample rate is `48000 Hz`
in both browsers and the platform string is `Win32` in both, so neither of those two is
the server tell on this host.
That is worth showing precisely because the section above is about a machine looking
like a server rather than a desktop. On a real desktop with a real audio device the
sample rate is ordinary in both, and the value that separates the two runs is the
automation flag, which is not a server signal at all.
## What invisible_playwright presents instead
The launch is two lines, and the browser you get back is a real Playwright
@@ -80,6 +80,22 @@ the folder.
This is not a bug in private mode. Private mode never promised a new identity. It
promised no leftover state, and it delivers that.
## What changes when the values change
![Two panels listing three values. localStorage is available in both browsers, and both
report that the screen and the viewport differ, so neither looks like
resistFingerprinting is on. The canvas pixel hash differs between the two
panels.](https://raw.githubusercontent.com/feder-cr/invisible_playwright/main/docs/img/can-you-be-fingerprinted-in-incognito-mode-values.png)
Three values, read from one page served from `127.0.0.1`. `localStorage` is available in
both, which is the point of the section above: private mode is about state, and this
probe is not reading state.
The line that moves is the canvas, hashed from `getImageData` bytes rather than from
`toDataURL`, and the reason for that choice is measured in
[why a canvas hash changes between runs](canvas-fingerprint-changes-every-run.md): the
encoded string moves on its own even when the pixels do not.
## Changing the values themselves, not clearing storage
If the problem is that the fingerprint values are stable and readable, the fix is to
+52 -2
View File
@@ -33,8 +33,11 @@ audio pipeline draw the same thing every time.
In this browser, those three readbacks are overwritten before they reach your code.
The value you read is a pure function of one number: an internal hardware seed the
wrapper derives from the identity seed of the session. Same seed in, same bytes out.
Different seed, different bytes.
wrapper derives from the identity seed of the session. Same seed in, same bytes out,
which is the direction you can rely on. The reverse does not hold as neatly: two
different identity seeds can land on the same hardware seed and hand you the same
readback, so a changed seed is not a guarantee of changed bytes. If you need two
sessions to look like two machines, check the readback rather than assuming it.
So when you launch without passing a seed, each session gets a new one, and the three
hashes move together in a self-consistent way. That is not the spoof failing. That is
@@ -123,6 +126,47 @@ pages is that you [assert the presence of the right value rather than the absenc
wrong one](how-to-test-bot-detection.md), and this is a case where you can measure the
right value directly.
![Four sessions of the same page served from localhost. Two sessions launched without
a seed report different canvas and WebGL readback hashes and even a different device
pixel ratio, while two sessions launched with the same seed report identical hashes and
identical
pixels.](https://raw.githubusercontent.com/feder-cr/invisible_playwright/main/docs/img/canvas-seed-vs-no-seed.png)
Four sessions above, one page served from `127.0.0.1`, hashes computed inside the page
so the numbers and the picture come from the same run. The two unseeded sessions
disagree on both readbacks. The two seeded ones agree on both, and their screenshots
are identical pixel for pixel, 0 of 79,800 differing.
The detail worth noticing is that the drawing looks the same in all four panels. Your
eye cannot separate them; the hash separates them immediately. That is the shape of
this whole surface: the readback is not the picture, and a page that hashes it is not
looking at what you are looking at.
The second unseeded panel is also physically larger, because that session drew at a
different device pixel ratio. It is not only the readbacks that get redrawn per
session: the device does.
**Two things about that panel are worth stating precisely, because guessing them wrong
sends you debugging the wrong thing.**
**What changes on every unseeded launch is the device, not necessarily the readback.**
Five unseeded launches, reading four values each: the screen alternated between
1920x1080 and 2560x1440, the core count between 4 and 12, the device pixel ratio
between 1 and 1.25. All five moved. The canvas readback, over the same five launches,
returned the same value four times. So **two unseeded runs agreeing on a canvas hash is
not evidence that your seed took effect** - it is the likelier outcome. Check a value
that varies freely, like the screen or the core count, when you want to know whether a
new identity was drawn.
**And if you hash `toDataURL()`, you are partly hashing the PNG encoder.** On the
bundled Firefox, three launches drawing the identical canvas returned three different
`toDataURL()` hashes while `getImageData()` returned the same pixel bytes all three
times. The pixels never moved; the encoded string did. A canvas hash that changes
between two runs of a *stock* browser is usually this, not a fingerprinting defence, and
it is not something `privacy.fingerprintingProtection` or `privacy.resistFingerprinting`
explains: both were tested off and on, and the encoded string kept moving either way.
Compare `getImageData` bytes when you want to know whether the drawing changed.
Draw to a canvas, read it back with
[`toDataURL()`](https://developer.mozilla.org/en-US/docs/Web/API/HTMLCanvasElement/toDataURL),
and compare the hash across two launches with the same seed:
@@ -218,6 +262,12 @@ after launch and log it. Passing that number back reproduces the same device.
same cookies but a different fingerprint is a contradiction. Keep one stable seed per
durable identity.
**Should I hash `toDataURL()` or `getImageData()`?** `getImageData`, if you want to know
whether the drawing changed. Three launches of the bundled Firefox drawing the same
canvas returned three different `toDataURL` hashes and the same pixel bytes every time:
the encoded string moves on its own, so a data URL hash reports changes the canvas never
made.
## Sources
- The project's fingerprint generator, in which the canvas, WebGL and audio readbacks
+16
View File
@@ -133,6 +133,22 @@ pixel: [`measureText()` and its ten-plus numeric fields](measuretext-textmetrics
which fail the same way for the same reason if the noise added to them accumulates
instead of staying bounded.
## Substitution, seen on one page
![Two panels listing three values. The canvas pixel hash differs between the bundled
Firefox and the patched engine. The measureText width is 115.65 px in both, and both
report that the screen and the viewport differ.](https://raw.githubusercontent.com/feder-cr/invisible_playwright/main/docs/img/canvas-fingerprint-noise-values.png)
One page served from `127.0.0.1`, three values, two browsers. The canvas pixel hash
moves and the text width does not: `measureText` returns `115.65 px` in both.
That pairing is the distinction this page is built on. A substituted readback changes
what comes out of the canvas without changing the layout metrics the same text produces,
so a detector comparing the two does not find the mismatch that per-call noise creates.
The hash comes from `getImageData` bytes on purpose: `toDataURL` output moves between
launches on the bundled browser too, for encoder reasons that have nothing to do with
the drawing.
## Checking your own
```js
+11 -3
View File
@@ -46,7 +46,9 @@ probing for web APIs, and other checks aimed at browser quirks and human behavio
family of idea as Hashcash: spend a measurable amount of CPU on something that is
cheap for the server to verify. A script that can run arbitrary JavaScript pays this
cost the same as a real browser does; a client with no JS engine at all cannot pay it
and never produces a token.
and never produces a token. A gate built on that idea alone exists in the open, and
[Anubis is readable end to end](anubis-proof-of-work-explained.md) in a way Turnstile
is not, which makes it the cheapest way to see what this layer can and cannot decide.
**Proof-of-space** is the storage-based cousin of the same idea, trading disk or
memory instead of CPU cycles.
@@ -58,7 +60,10 @@ page claims to be. Cloudflare does not publish the exact list of properties it r
and the widget script itself is not meant to be human-readable, so anyone claiming a
precise inventory of what it checks is going further than Cloudflare's own
documentation does. What is documented is the shape of the approach, not the field
names.
names. The shape is the part worth internalising: a value being wrong matters less
than two values disagreeing, which is why a mismatch like
[a platform string that contradicts the oscpu beside it](navigator-platform-oscpu-consistency.md)
is a stronger signal than either field on its own.
The point of running all of this before showing anything is stated plainly in
Cloudflare's docs too: the goal is to "fine-tune the difficulty of the challenge to
@@ -89,7 +94,10 @@ When Managed mode does decide to show something, Cloudflare's own documentation
describes it as a "simple checkbox that the visitor must click to proceed", explicitly
not an image puzzle or text to transcribe. This is the point worth being precise
about: the checkbox is not another fingerprint probe layered on top of the earlier
ones. It is a click, gated behind whatever risk score the earlier signals produced.
ones. It is a click, gated behind whatever risk score the earlier signals produced,
and a click carries its own provenance:
[a click dispatched from page JavaScript is never trusted](playwright-clicks-istrusted.md),
while one produced by the driver or the engine is.
That distinction matters for what a real engine can and cannot do about it. Everything
in the non-interactive layer, the proof-of-work, the API probing, the consistency
@@ -20,6 +20,12 @@ widget. The failure is silent in the way CSP failures usually are: no exception
Python code, a console warning in the browser you likely never read, and code that
simply never ran.
That is worth reading as a property of the layer, not an accident. An init script is
page JavaScript, and page JavaScript is the outermost of
[the three levels anything can be changed at](playwright-stealth-levels.md): it is the
level the page itself is allowed to have an opinion about, and CSP is the page
exercising that opinion.
## What CSP actually restricts
By default, a policy that sets `default-src` or `script-src` blocks inline `<script>`
@@ -74,7 +80,10 @@ that is a difference from a genuine session, not a neutral convenience. Whether
specific target's own logic could ever observe that difference from inside the page is a
separate question this page cannot answer for you, but the premise underneath
"bypassing CSP is invisible" does not hold: it is a real change to how the page executes,
not a transparent workaround.
not a transparent workaround. It belongs on the same list as every other setting that
makes a session behave unlike a visitor's, which is the list
[the checklist for a session being detected](playwright-detected-as-bot.md) works
through in order.
The practical rule: use `bypassCSP` when you are testing your own integration against
your own header and you know exactly why it is there. Treat it as a real behavioral
+36
View File
@@ -56,6 +56,36 @@ useful to a detector: it is stable for one machine, and it varies between
machines, because the installed-font set is one of the more distinctive things
about a device.
### The blind spot in that snippet, measured
The probe above is the one detectors use, and it has a false negative worth knowing
before you trust its output: **a family that IS the fallback is invisible to it.**
![The probe run on one Windows machine across three browsers, each testing ten
families against two different fallbacks. Segoe UI, Calibri, Cambria and Tahoma read
present against both fallbacks. Consolas reads absent against the monospace fallback
and present against the serif one. An invented control family reads absent
everywhere. All three browsers return the same
answer.](https://raw.githubusercontent.com/feder-cr/invisible_playwright/main/docs/img/font-presence-probe-three-arms.png)
Run that exact function over ten families with `monospace` as the fallback, on Windows,
and Consolas comes back **absent**. Consolas is installed. It is also what `monospace`
resolves to on that machine, so the candidate width and the baseline width are the same
number, and the comparison reads "fell back" when nothing fell back.
Swap the fallback to `serif` and the same family reads **present**, on the same page in
the same session. The invented control family stays absent under both, which is what
makes the Consolas row a finding, not a broken probe.
So the rule stated above holds with one exception: an identical width means the
candidate did not render *or* the candidate is the fallback. A detector that probes
against a single generic will systematically miss whichever family that generic points
at, and which family that is depends on the platform.
The other thing the three panels show is that the answer does not move. The bundled
Firefox headful, the same build headless, and an engine carrying its own font set all
return the same ten bits on this host.
## Why this is different from hashing measureText
It is easy to lump this in with `measureText` fingerprinting, but the two probe
@@ -241,6 +271,12 @@ font set is built from one manifest on every OS, and the width for a run carries
single bounded, seed-derived offset instead of the host rasterizer's metrics, so
the numbers track the seed rather than the operating system.
**Why does the probe say a font is missing when I know it is installed?** Because the
candidate is the fallback. Measured on Windows: `Consolas` reads absent against a
`monospace` fallback and present against a `serif` one, in the same session, since
`monospace` resolves to Consolas there and the two widths match. Probe against a second
generic before believing an absent.
## Sources
- This project's font architecture notes: a bundled Windows font set built from a
+13 -4
View File
@@ -13,8 +13,11 @@ nav_order: 33
failed. Chromium's own network error list defines it as "an operation was aborted
(due to user action)," and the cancelling "action" is very often something your own
page, your own script, or Playwright's own navigation handling did on purpose. This
is the one error on this page's list of siblings that is frequently not a problem at
all, and treating every occurrence as a bug wastes time chasing something that
is the one error in the `net::ERR_` family that is frequently not a problem at
all. [ERR_CONNECTION_RESET](err-connection-reset-playwright.md) and
[ERR_HTTP2_PROTOCOL_ERROR](err-http2-protocol-error-playwright.md) report a
connection that genuinely broke; this one usually reports one that was closed on
purpose, and treating every occurrence as a bug wastes time chasing something that
already worked.
## The causes that are usually fine
@@ -61,7 +64,10 @@ in-flight navigation rather than the intended third-party request.
**`page.close()` was called while a navigation was still in flight.** Closing the
page tears down whatever requests it had open; if that happens mid-navigation on
purpose or by an unrelated timeout, the abort is real and the navigation that was
racing it never gets a result.
racing it never gets a result. When the teardown came from the browser or the
context disappearing under you, the exception that surfaces first is usually
[TargetClosedError](playwright-targetclosederror-causes.md), and the abort is the
second thing you see.
**A route handler that never resolves.** A `page.route()` interceptor that neither
calls `route.continue()`, `route.fulfill()`, nor `route.abort()` leaves a request
@@ -92,7 +98,10 @@ of browser realness changes whether it fires. It is a navigation-lifecycle signa
that fires identically on a stock Playwright Chromium, a stock Firefox, and this
project's patched build, because the cancellation is decided by request-handling
logic in the engine, on your own code's instruction, not by anything about how real
the browser's identity looks to a remote site.
the browser's identity looks to a remote site. The error that does carry that
second meaning is a different one:
["Execution context was destroyed" can be a navigation you did not ask for](execution-context-destroyed.md),
which is worth reading before deciding an abort was a block.
## Short answers to the questions that lead here
+17 -2
View File
@@ -36,7 +36,10 @@ installed in the browser's trust store, that certificate is signed by an authori
nothing trusts. This is functionally identical, from the browser's point of view, to
a hostile machine-in-the-middle attack, because it is the same mechanism: someone
between you and the destination is terminating TLS you did not expect them to
terminate.
terminate. Note where in the sequence this leaves you: the tunnel was established
and the certificate on the far side of it is what failed. A proxy that refuses the
tunnel outright never gets this far and reports
[ERR_TUNNEL_CONNECTION_FAILED](err-tunnel-connection-failed-playwright.md) instead.
**An expired or misconfigured intermediate certificate.** A chain that used to
validate can stop validating the moment an intermediate CA cert expires or gets
@@ -66,6 +69,14 @@ to be adversarial. A context configured this way cannot tell the difference betw
your trusted proxy's re-signed certificate and a hostile one sitting on public
Wi-Fi, because the check that would have told them apart is the check you disabled.
Turning the check off also changes nothing about what the destination sees. A proxy
that terminates your TLS and re-establishes its own connection onward presents its
own handshake to the server, so the
[JA3 and JA4 fingerprint](ja3-ja4-tls-fingerprint.md) arriving at the destination is
the proxy's and not your browser's. Whether your browser accepted the proxy's
certificate and what the proxy's handshake looks like from the far end are two
separate questions, and only the first one is what this error is about.
The narrower, safer alternative when the actual goal is trusting one specific proxy
is installing that proxy's own root CA certificate into the browser's trust store,
so only that one issuer becomes trusted, not every issuer becoming
@@ -88,7 +99,11 @@ unexpected interception point produces.
interception.
3. **Test the same target with the proxy removed.** Validates cleanly without the
proxy: the proxy is the one re-signing TLS, confirmed. Still fails: the
destination's own certificate is broken, unrelated to the proxy at all.
destination's own certificate is broken, unrelated to the proxy at all. A proxy
that intercepts TLS is usually also deciding
[where your DNS queries go](does-a-proxy-leak-dns-doh-explained.md), which is a
separate setting with a separate way of going wrong, and worth reading once while
you have the proxy's configuration open.
4. **Check with `openssl s_client -connect host:443 -showcerts`** for the full chain
and its dates, to rule out an expired intermediate specifically rather than an
untrusted one.
+10 -2
View File
@@ -39,7 +39,10 @@ words, applies to "connections closed with the non-standard code 444," releasing
socket with a TCP reset, not a normal close. A server operator who wants to deny
a request with zero information leakage, whether the requester is a scanner, a bot, or
simply unwanted traffic, has this as a first-class, standard option: return nothing
rather than a status code that says "blocked."
rather than a status code that says "blocked." That is the one cause on this list
where the error is not a fault to repair but a decision made about your session, and
the question then moves off this page and onto
[why the script is being refused in the first place](why-does-my-playwright-script-get-blocked.md).
**A proxy-side rewrite or bypass rule interacting badly with routing.** [A real Playwright
report](https://github.com/microsoft/playwright/issues/20703) traces `ERR_EMPTY_RESPONSE`
@@ -81,7 +84,12 @@ resemblance to the Chromium string you searched for.
that closes with zero bytes, and removes the browser as a variable.
2. **Remove the proxy and retry direct.** Gone without it, the proxy or the path to it is
implicated, matching the shape in the routing-bypass report above. Persists, the origin
server or something between you and it is next.
server or something between you and it is next. If the proxy never opened the tunnel
at all you would be reading
[ERR_TUNNEL_CONNECTION_FAILED](err-tunnel-connection-failed-playwright.md), and if the
socket was torn down after some bytes had moved,
[ERR_CONNECTION_RESET](err-connection-reset-playwright.md): the three differ only in
how far the exchange got.
3. **Check whether it is one target or many.** Consistent on one specific site with
everything else loading normally is the shape of a deliberate drop; intermittent across
unrelated targets points at your own proxy or network path.
+13 -3
View File
@@ -46,7 +46,10 @@ string while driving Firefox? Look for those two names in your logs instead.
- **ALPN disagrees with what actually gets spoken.** HTTP/2 is negotiated in the TLS
handshake's ALPN extension. A proxy that terminates TLS and re-negotiates outbound can
advertise `h2` to your client while speaking something else to the origin, so the
session starts as HTTP/2 and cannot stay one.
session starts as HTTP/2 and cannot stay one. A proxy doing that also replaces the
handshake the destination sees with its own, so the
[JA3 and JA4 fingerprint](ja3-ja4-tls-fingerprint.md) arriving there is the proxy's,
which matters separately from whether the session survives.
- **A server-side HTTP/2 config problem, unrelated to your proxy.** HTTP/2 enforces
header rules HTTP/1.1 never did: no invalid bytes in a header value, a fixed
pseudo-header order, framing from RFC 9113 a lenient HTTP/1.1 stack never checked. A
@@ -55,11 +58,18 @@ string while driving Firefox? Look for those two names in your logs instead.
- **The "error" is not an error.** More than one report traces this exact code to a
server sending `RST_STREAM` deliberately, as an anti-automation response rather than a
protocol accident. The browser reports both cases identically: a stream closed with
`PROTOCOL_ERROR` before delivering anything.
`PROTOCOL_ERROR` before delivering anything. If that is what happened, the thing
worth reading is not the framing rules but
[what an HTTP/2 connection reveals about the client that opened it](http2-fingerprint-detection.md),
since the frame order and settings are themselves a fingerprint.
A smaller set of reports describe the error only in headless mode, disappearing
headful, proxy or no proxy. That is in Playwright's own tracker with no confirmed root
cause; treat it as something to test for, not an explanation to assume.
cause; treat it as something to test for, not an explanation to assume. It is also the
one shape on this page where
[the separate question of what headless changes](is-playwright-headless-detectable.md)
is worth a look, because a mode-dependent failure with no protocol explanation is the
signature of something reading the client and not the frames.
## How to actually find out which one it is
+36
View File
@@ -60,6 +60,42 @@ differs will report a different *set* of fonts as installed, even though nothing
installed or removed. Two containers from the same image can disagree if their
fontconfig caches were built at different times.
## What this looks like on one Windows machine, measured
![Four renderings of the same font sample page. Playwright's bundled Firefox in headful
mode, the same build in headless mode where 3.05% of the pixels differ, an amplified
difference map showing that the differing pixels are whole rows of text rather than
stray edges, and the patched engine, which returns an identical frame in both
modes.](https://raw.githubusercontent.com/feder-cr/invisible_playwright/main/docs/img/headless-fonts-headful-vs-headless.png)
The three causes above are usually argued from Linux and fontconfig. They show up on
Windows too, and the difference is measurable on one machine with nothing installed
or removed in between.
The bench serves a single page from `127.0.0.1` and renders it four times at the same
viewport: the bundled Firefox headful and headless, then a patched Firefox headful and
headless. Same URL, same host, same session.
The bundled build disagrees with itself between the two modes on **8,989 of 294,400
pixels, or 3.05% of the frame**. The shape of that disagreement is the useful part.
Every sample row keeps its exact height, so no glyph got taller. The rows *drift
downward* instead, by 0, 1, 1, 2, 2, 2, 2 and 3 pixels from the first sample to the
eighth.
That drift is the mechanism behind a screenshot test that passes on a laptop and fails
in CI. Line boxes round to slightly different heights, the error accumulates, and an
element halfway down a long page has moved further than one near the top. A tolerance
tuned on the first viewport will not hold at the bottom.
The patched engine returned the same frame in both modes, byte for byte, and did so on
three repeats of the whole bench. It declares its own font set instead of reading the
host's, so a headless environment has nothing left to be missing.
One row shows what that costs. `Arial Narrow` is installed on the host, so the bundled
build renders it narrow; the patched engine does not carry that face and falls back, so
the same row comes out wide. Host independence and host fidelity pull in different
directions, and this is where they part.
## Why any of it matters beyond flaky screenshots
Fonts are one of the highest-entropy signals a browser exposes, and unlike most of
@@ -238,7 +238,10 @@ itself the expensive part of the exchange, not the page wrapped around it.
Rate limits on WHOIS lookups are tighter than on most catalog pages for exactly
that reason, and a pacing scheme copied from a catalog scraper, a random gap
of a second or two, will get a lookup service returning empty answers or a
captcha well before a similar gap trips a catalog site's limiter.
captcha well before a similar gap trips a catalog site's limiter. When the
limiter does answer, the response is usually a status code and not a page, and
[the backoff that belongs in the middle of a run](how-to-handle-403-429-backoff-mid-scrape-playwright.md)
is a different piece of work from the pacing that avoids reaching it.
```python
import random
@@ -282,6 +285,12 @@ registry is doing real, expensive work for each one, because it is. The
parsing is straightforward once each value is tied to the field that names it;
the pacing is what decides whether you get to keep making requests at all.
One record per domain, with a variable set of labels and a raw block kept
alongside, is the shape
[JSON Lines handles without a schema argument](how-to-scrape-to-json-lines-playwright.md):
a ccTLD that carries three fields and a gTLD that carries twenty go into the
same file without either one padding the other.
## Short answers to the questions that lead here
**Does WHOIS only exist as a web page?** No. The original protocol answers in
+14
View File
@@ -183,6 +183,20 @@ is what this product bundles into the engine on all three platforms, so the same
identity reports the same fonts whether the machine underneath is Windows, Linux or a
container with nothing installed.
### What the two browsers report before you change anything
![Two panels listing two values. The bundled Firefox headless reports a 1366 by 768
screen with 1366 by 720 available. The patched engine reports 1920 by 1080 with 1920 by
1032 available. Both of the two values differ.](https://raw.githubusercontent.com/feder-cr/invisible_playwright/main/docs/img/how-to-scrape-headless-blocked-values.png)
Both values differ, and the shape of the difference is the thing to notice. The bundled
Firefox headless reports `1366x768`, a laptop resolution it uses whatever viewport you
asked for, so every stock headless session on any machine claims the same display. The
patched engine reports a declared `1920x1080`.
Neither browser reports the host's actual monitor, which is the part people expect and
do not get.
## Fix three: the screen and viewport numbers
A headless browser has no monitor, so every screen value it reports was decided by
@@ -37,6 +37,13 @@ downstream date is now wrong under the right label. The fix is to match on
the label text itself, normalize it through a small alias table, and only then
read the adjacent value.
Check one thing before writing any of it, because it can make the whole section
unnecessary: some patent and publication databases ship the same bibliographic
fields as machine-readable metadata in the page, and
[a JSON-LD block already carries its own labels](how-to-extract-json-ld-structured-data-playwright.md).
Where it is present it is the better read, and the selector work below is the
fallback for pages that do not have one.
```python
import re
from datetime import datetime
@@ -256,6 +263,12 @@ the shared invention-level fields once, then attaches jurisdiction-specific
fields per member, so a query for "every active family member in this
jurisdiction" does not require reconstructing the family from scratch.
The traversal underneath is the ordinary one:
[a list page whose entries each open a detail page](how-to-crawl-list-to-detail-pages-playwright.md),
with the wrinkle that here one detail page can expand into several rows. Getting
the list-to-detail walk right first makes the family expansion a step you add on
top instead of a special case tangled into the crawl.
```python
def scrape_patent_record(url, browser):
page = browser.new_page()
@@ -94,6 +94,12 @@ Store the reading exactly as the feed reported it, with its own timestamp, and s
cadence as data rather than assuming it. A downstream consumer that genuinely needs a
fixed grid can resample from the as-reported table at query time.
One row per observation, with whichever variables that station actually reports and no
padding for the ones it does not, is the case
[JSON Lines was already the right container for](how-to-scrape-to-json-lines-playwright.md):
a station reporting three variables and one reporting twenty append to the same file,
and a partial run leaves a file that still parses.
```python
def rows_from_feed(feed, variable_map):
"""Emit one row per (variable) per observation, using the feed's own timestamps.
@@ -199,6 +205,11 @@ list is. It is paginated by day or by month, so a request asks for one calendar
and gets back everything that station reported in it. A five-year pull across one
station is roughly sixty separate requests, one per month, not one long scroll.
Sixty requests is long enough that something will interrupt one of them, and a
calendar walk has the property that makes recovery cheap: the period is the key, so
[a run can pick up from the period it stopped on](how-to-resume-an-interrupted-scrape-playwright.md)
without re-reading the years already stored.
Walk the calendar explicitly and issue one request per period. `page.request` shares
the browsing context's cookies with a plain HTTP call, so an archive endpoint gated
behind a session the browser already holds answers without a second login flow.
+26 -1
View File
@@ -88,7 +88,32 @@ But consider what a behavioural check can compare, once you have a curve:
So the curve is necessary and not sufficient, which is the same shape as every other
part of this subject.
## How this project does it
## The same three layers, measured on one page
![Three panels of one target page, each drawing a dot per pointer event received. A
single driver move leaves two events and no path; a driver move with forty steps leaves
an evenly spaced line with three distinct movementX values; the patched engine's path is
unevenly spaced with twenty-six. All three report isTrusted
true.](https://raw.githubusercontent.com/feder-cr/invisible_playwright/main/docs/img/mouse-path-driver-vs-engine.png)
One page served from `127.0.0.1`, one target, three ways of reaching it. The page draws
a dot per `pointermove` and prints the fields it actually received, so the picture and
the numbers come from the same run.
The first thing the panels settle is a negative: **`isTrusted` is `true` in all three,
and so `isTrusted` does not separate the driver from the engine.** It only separates
both of them from page script. A check that stops at the trusted flag has not
distinguished anything here.
What does separate them is the deltas. The evenly stepped driver path produces **three
distinct `movementX` values across 41 events**, because a straight line walked in equal
steps reports the same delta almost every time. The engine's path produces **26 distinct
values across 34 events**. Same trusted flag, same `pointerType`, same `pressure`, and a
completely different distribution underneath.
And notice what the third panel is not: it is not a graceful arc. The dots stay roughly
on the line to the target, clustered at the start and irregular the rest of the way.
That is the point of this page in one image. The shape was never the hard part.
Two pieces, and the split is deliberate.
Binary file not shown.

After

Width:  |  Height:  |  Size: 6.9 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 14 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 16 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 17 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 45 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 50 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 73 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 12 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 32 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 17 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 10 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 18 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 16 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 32 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 10 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 10 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 29 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 32 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 13 KiB

+10 -2
View File
@@ -78,6 +78,9 @@ The helper API does not change, and that is the point of doing it at this layer.
version and from the same seeded profile as everything else. Overriding only that
string is the standard way to make a browser contradict itself, and CodeceptJS makes
it easy to do by accident because `userAgent` sits right next to the options above.
Why one string on its own is the weakest thing to change is
[its own subject](is-changing-user-agent-enough.md), and worth reading once before
deciding you need the option.
**One seed per identity, not per run.** A fixed seed makes a failing test
reproducible: you can tell the site changing from the browser changing. Rerolling per
@@ -95,7 +98,10 @@ The same two things every non-Python route gives up, and you should know them be
you pick this layer:
- **Humanised pointer motion.** The preference enables it, but the paths are drawn
by the Python driver from the seed. From CodeceptJS the pointer still teleports.
by the Python driver from the seed. From CodeceptJS the pointer still teleports,
which matters only against a site that watches behaviour:
[what a pointer event carries besides coordinates](human-mouse-movement.md) says
which half of that you keep here and which you lose.
- **Timezone and locale resolved from the proxy exit.** Those are computed at launch
by the Python wrapper. Here you get whatever `prefs.json` was generated with, so a
proxy in another country will disagree with the browser unless you regenerate per
@@ -111,7 +117,9 @@ Add a scenario that visits a fingerprint page and asserts on the user agent and
WebGL renderer. The user agent should say Firefox and the version should match
`invisible-playwright version`. If the renderer comes back as a software or basic
renderer, either the prefs did not load or the machine has no GPU, and both are worth
knowing before the suite reports green.
knowing before the suite reports green:
[which renderer strings a real machine actually reports](webgl-renderer-strings.md)
is the reference for telling one of those two from the other.
## Short answers to the questions that lead here
+9 -3
View File
@@ -78,7 +78,10 @@ one compiled into the engine and derived from the seed.
Two independent opinions do not average out. They disagree, and the disagreement
between a generated header set and an engine-level fingerprint is a stronger signal
than either being slightly unusual on its own. Turn it off and let one component own
the identity.
the identity. The reason a disagreement outweighs an oddity is
[in what a fingerprint is actually made of](what-is-a-browser-fingerprint.md): it is
read as a set of values that have to corroborate each other, not as a list of fields
scored one at a time.
The same argument applies to `userAgent` anywhere in your config: do not set it.
@@ -89,7 +92,8 @@ and `launchOptions` is typed to accept `launchPersistentContext` parameters too,
`userDataDir` belongs there. Pair a stable profile with a stable seed: the profile
keeps cookies and storage, the seed keeps the machine those cookies belong to. One
without the other is a session whose history and hardware disagree about how long it
has existed.
has existed. Which number to write down and where to keep it is
[the seed's own page](reproducible-agent-browser-identity-seed.md).
## What this route gives up
@@ -105,7 +109,9 @@ The same two things every non-Python route gives up:
That second point matters more in Crawlee than in most places, because rotating
proxies is a normal thing to do here. If your proxy pool spans countries, either
generate a `prefs.json` per region and select it per session, or accept that the
timezone will be wrong for most of them.
timezone will be wrong for most of them, which is
[a mismatch a page can check in one line](timezone-proxy-mismatch.md) and not a
subtlety anyone has to dig for.
## Checking it worked
+10 -2
View File
@@ -144,7 +144,10 @@ if __name__ == '__main__':
and matching headers, on the assumption that it controls the browser's identity.
Here it does not: the identity is compiled into the engine and derived from the
seed. Leaving the generator on produces two independent opinions about who this
browser is, and the disagreement between them is exactly what detectors read.
browser is, and the disagreement between them is exactly what detectors read. It is
the same failure a stealth plugin runs into when it patches values on top of an
engine that already reports them,
[which is the whole subject of the comparison with playwright-extra](vs-playwright-extra-stealth.md).
**The seed decides whether a failure is debuggable.** With `seed=None` every run is
a different machine, so a failing run tells you nothing: you cannot separate the
@@ -165,12 +168,17 @@ receives. A SOCKS5 endpoint has to reach `get_default_stealth_prefs` through its
engine reads, and it must not also reach Playwright: Playwright configures the
proxy itself, without the SOCKS credentials, and that configuration wins over the
preferences. HTTP and HTTPS are the other way round and go through Playwright's
own `proxy=` argument.
own `proxy=` argument. That asymmetry is not a Crawlee quirk:
[why SOCKS5 credentials have to arrive as preferences](playwright-socks5-proxy-authentication.md)
explains where Playwright drops them, and it applies to every route on this list.
If you use one, leave locale and timezone on their defaults. They resolve from the
exit IP and not from the host machine, which is what keeps the JS timezone, the
language list and the IP in agreement. Setting them by hand to your own machine's
values is how a session ends up claiming one country while leaving from another.
The resolution happens against
[a GeoIP database carried locally](offline-geoip-timezone-proxy.md), so it costs no
extra request and nothing external learns which exit you are using.
## When this is the wrong tool
+6 -2
View File
@@ -46,7 +46,9 @@ python -c "import json;from invisible_playwright import get_default_stealth_pref
Regenerate it when you upgrade the package, since the pref set moves with the engine.
Treat `prefs.json` as belonging to a specific seed and a specific version, and keep
the seed written down next to it.
the seed written down next to it. Which version it belongs to is not a convention
either: [the engine is pinned by a seal](pinning.md), and the pairing that file
describes is the one you are reproducing by hand here.
## Step two: launch
@@ -117,7 +119,9 @@ none of the extra is in the JSON:
Python.
- **The pin check.** The wrapper refuses to run a binary that does not match the
version of the config that produced the prefs. Nothing enforces that pairing here.
If you upgrade the binary and keep an old `prefs.json`, nothing will tell you.
If you upgrade the binary and keep an old `prefs.json`, nothing will tell you, and
the way that goes wrong is quiet: prefs the engine no longer reads simply
[do not apply, with no error anywhere](firefox-prefs-not-applying.md).
So this route is right when the surrounding system is already in Go or Java and
rewriting it is not on the table. When the choice is open, Python gets you the parts
+6 -2
View File
@@ -73,7 +73,9 @@ reproduce a session from.
That distinction matters more than it sounds. Sharing one identity across every user
of a build is its own signal. If you need a per-session machine, the MCP route is not
the one; drive the browser from Python with `InvisiblePlaywright(seed=...)` instead,
where the prefs are generated and applied for you.
where the prefs are generated and applied for you, or use
[an MCP server that launches through the engine](mcp-browser-server-stealth-firefox.md)
and therefore has the profile to give.
## Making the prefs work anyway
@@ -103,7 +105,9 @@ applies it over the profile's own prefs.
This is a workaround, not the supported path. It pins one identity for that profile
rather than one per session, and the profile keeps cookies and storage between runs,
which is either what you wanted or a correlation problem depending on the job.
which is either what you wanted or a correlation problem depending on the job. If it
is what you wanted, [persistent profiles have their own page](persistent-profiles.md)
covering what survives a restart and what does not.
## Checking it worked
+7 -3
View File
@@ -85,7 +85,9 @@ Open Stealth Browser
```
This has the advantage that the prefs can never drift from the installed package,
which is the failure mode a checked-in JSON file eventually produces. The cost is
which is the failure mode a checked-in JSON file eventually produces: a stale pref
name is not rejected, it is
[accepted and then never read](firefox-prefs-not-applying.md). The cost is
that `ensure_binary()` may download on the first run of a suite, so a CI job with a
short timeout wants the `invisible-playwright fetch` step separately.
@@ -99,12 +101,14 @@ version and from the same seeded profile as everything else.
`colorScheme` are all available there, and each one you set by hand is a value that
now has to agree with the profile instead of being derived from it. If you are
using a proxy, setting `timezoneId` to your own machine's zone is the classic way to
break a session that was otherwise fine.
break a session that was otherwise fine, and it breaks it in a way
[a page can check against the IP in one line](timezone-proxy-mismatch.md).
**One seed per identity, not per suite run.** A fixed seed makes a failing test
reproducible: you can separate the site changing from the browser changing. If you
need several identities in one suite, open several browsers with different seeds
rather than rerolling.
rather than rerolling. Which surfaces the number actually decides, and which it does
not, is [written out on the seed's own page](reproducible-agent-browser-identity-seed.md).
## What this route gives up
+10 -2
View File
@@ -152,7 +152,10 @@ not per request. It comes from the engine's real version and the seeded profile,
overriding only that string is the classic way to make a browser contradict itself.
**Do not run another stealth layer.** If something else patches `navigator` from
inside the page, it is now arguing with an engine that has already answered.
inside the page, it is now arguing with an engine that has already answered. The
argument is visible from the page, which is why
[a patch applied from JavaScript and a value produced by the engine](playwright-stealth-levels.md)
are not two ways of doing the same thing.
**One seed per identity, not per run.** A fixed seed makes a failure reproducible,
which is the difference between bisecting a problem and guessing at it. For many
@@ -174,6 +177,8 @@ carries are used for an HTTP 407 challenge, and the SOCKS handshake reads its
credentials from the proxy prefs, which nothing on that route writes. So on route
two an authenticated SOCKS endpoint fails to connect while an unauthenticated one
works. Use `http(s)://` there, or take route one.
[The full account of where the credentials get dropped](playwright-socks5-proxy-authentication.md)
is worth reading before assuming a working proxy is a broken one.
On route one, leave locale and timezone on `auto` so they follow the exit. On route
two they cannot follow anything, which is the main reason to prefer route one when a
@@ -183,7 +188,10 @@ proxy is involved at all.
If the target needs Chromium, use a Chromium backend. If a page does not need
JavaScript, plain Scrapy is an order of magnitude faster and no fingerprint is
involved at all.
involved at all. Reach for this backend when a fingerprint is genuinely in play, and
when it is, the order to work through
[the layers a block can come from](how-to-scrape-without-getting-blocked.md) decides
what to change first, which is rarely the setting people reach for.
## Short answers to the questions that lead here
+8 -1
View File
@@ -18,6 +18,11 @@ nothing here is a correction of somebody else's page.
| TestCafe | yes | **no** | the `path:` browser provider |
| Nightwatch | yes | **yes** | `firefox_binary` plus `moz:firefoxOptions.prefs` |
TestCafe is the one exception in that column, and it is worth reading the row before
wiring anything: a route that carries the engine and not the prefs gives you the
build's own defaults on every launch, which is a different product from
[one identity per session derived from a seed](reproducible-agent-browser-identity-seed.md).
Get the two values first, the same way for all four:
```bash
@@ -155,7 +160,9 @@ The two things no route outside the Python wrapper carries:
For test suites both are usually irrelevant, because a suite normally runs against a
known environment and does not need to convince anything. Say so out loud when
choosing: the reason to use this engine in a test runner is a realistic rendering and
font stack, not evasion.
font stack, not evasion. The font stack is the concrete half of that claim, and
[what a page can measure about the fonts a machine has](detect-installed-fonts-javascript.md)
is where the difference between a real one and a container's default shows up.
## Short answers to the questions that lead here
@@ -61,6 +61,22 @@ a Firefox user agent painted over it, or a spoofing layer that forgot to delete
property that should never have been there. Both expose `navigator.connection` and both
get caught by its mere presence.
## Three absences and one difference
![Two panels listing four values. navigator.connection, navigator.getBattery and
navigator.userAgentData are all undefined in both the bundled Firefox and the patched
engine. navigator.webdriver differs, true against
false.](https://raw.githubusercontent.com/feder-cr/invisible_playwright/main/docs/img/navigator-connection-network-information-firefox-values.png)
`navigator.connection` is `undefined` in both browsers, which is the answer this page
gives, and the panel puts two more absences next to it: `navigator.getBattery` and
`navigator.userAgentData` are `undefined` too.
Three absences in a row is the useful shape here. A build that claims Firefox and
returns a value for any of the three has contradicted itself, and the contradiction
costs a detector one property read. The only line that differs between the two panels
is `navigator.webdriver`.
## Reading it with invisible_playwright
invisible_playwright is a real Firefox patched at the C++ level and driven by stock
@@ -95,6 +95,21 @@ An empty or missing `navigator.oscpu` on a browser claiming to be Firefox is the
both worlds: absent where Firefox is present, and therefore a tell that the identity is
constructed rather than real. Presence with the right value is the only pass.
### The three, agreeing
![One panel listing three values read from the patched engine, headless:
navigator.platform Win32, navigator.oscpu Windows NT 10.0 with Win64 and x64, and the
full user agent for Firefox 151.0 on Windows. A note says the bundled Firefox returned
the same values.](https://raw.githubusercontent.com/feder-cr/invisible_playwright/main/docs/img/navigator-platform-oscpu-consistency-values.png)
All three read from one page served from `127.0.0.1`, and the bundled Firefox returned
the same three, so the panel shows the agreed state rather than a difference.
`Win32`, `Windows NT 10.0; Win64; x64` and a user agent naming Windows NT 10.0: three
different spellings of one claim. The check in this section is that they keep spelling
the same thing, and a screenshot of them agreeing is the baseline the check compares
against.
## Measuring it: read all four and check they agree
The test is short. Launch, read the four properties, and confirm they tell one story.
@@ -126,6 +126,21 @@ patched Firefox driven by stock Playwright is Firefox in exactly the way these c
test, so it inherits the correct answers without a line of spoofing code and without a
getter anyone can catch out of place.
## The two constants, read from both browsers
![Two panels listing four values. navigator.vendor is an empty string and
navigator.productSub is 20100101 in both the bundled Firefox and the patched engine.
navigator.webdriver differs, true against false. Function.prototype.toString returns
the same native-code string in both.](https://raw.githubusercontent.com/feder-cr/invisible_playwright/main/docs/img/navigator-vendor-productsub-firefox-values.png)
The two brand constants come back identical from both browsers: `navigator.vendor` is
the empty string and `navigator.productSub` is `20100101`, which is what this page says
a real Firefox reports.
That identity is the result, not a missing measurement. The only line that moves in the
panel is `navigator.webdriver`, which belongs to a different subject entirely. A tool
that had to reshape the two constants would show its work here; nothing had to.
## Reading them yourself with invisible_playwright
Do not take the table on faith - read the fields off the browser you actually run, and
+14
View File
@@ -100,6 +100,20 @@ warm local machine you can lose on a loaded CI box.
A value decided inside the engine has no race, because there is no moment before
which it was something else.
## What the two browsers actually return
![Two panels listing three values. The bundled Firefox reports navigator.webdriver
true, the patched engine reports false. Function.prototype.toString called on a native
function returns the identical native-code string in both, and navigator.platform is
Win32 in both.](https://raw.githubusercontent.com/feder-cr/invisible_playwright/main/docs/img/navigator-webdriver-explained-values.png)
Three values, one page served from `127.0.0.1`, two browsers.
Only the first line moves. `Function.prototype.toString` called on a native function
returns the identical string in both, and `navigator.platform` is `Win32` in both. That
is the whole point of the section above: the flag is the easy half, and the two
browsers are indistinguishable on the check that usually catches a patched getter.
## What a real audit checks instead
A real audit checks a whole fingerprint, not one boolean: descriptor hygiene,
+8 -1
View File
@@ -16,6 +16,11 @@ cleanup code ever runs. A clean exit never leaks a process, and an exception out
killed parent leaks, and the fix cannot live in a `finally` block: it has to be an
operating-system job object that Windows tears down when the parent dies.
Note which direction this is. A leaked process is one the script no longer holds; the
opposite case, a script still holding a browser that has gone away, surfaces as
[TargetClosedError](playwright-targetclosederror-causes.md), and the two get confused
because both start with something dying unexpectedly.
A bug report said orphaned Firefox processes were piling up on a Windows CI box, and
pointed at "any path where teardown doesn't run cleanly - a timeout, an exception out
of the `with` block, a killed test runner." That description covers several genuinely
@@ -79,7 +84,9 @@ The tempting shortcut - "anything named firefox.exe that showed up after we
started" - eventually kills a browser that belongs to a different, healthy,
concurrent session, which is a worse failure than leaving one of your own leaked
processes running: a leaked process is recoverable, a wrongly-killed one belonging
to someone else usually isn't.
to someone else usually isn't. That case is not hypothetical the moment you
[drive several browsers from one process](run-invisible-playwright-concurrently-asyncio.md),
where every one of them answers to the same binary name.
The actual identification is exact rather than heuristic. Each session generates a
random token and stamps it into its own browser's environment at launch; child
+9 -2
View File
@@ -52,7 +52,11 @@ hit-testing still applies, and whatever sits on top at that point is what
receives it. You have not reached your element; you have clicked the overlay
blind. Whatever handler fires belongs to the obstruction - or to nothing -
while your script carries on believing the button was pressed, which is how a
forced click turns one visible failure into a silent wrong path.
forced click turns one visible failure into a silent wrong path. The hit test is
the same one that
[consumed most of the humanised pointer path on the calls real scripts make](hover-mouse-movement-bug.md),
which is worth knowing because it means the check is doing real work and not
merely being cautious.
Second, and this is the part worth internalizing instead of skipping past:
clicking blind into an overlay is itself a tell, on any
@@ -78,7 +82,10 @@ except Exception:
```
**2. Check if it is timing rather than layout.** If the obstruction is a transition or an
animation, waiting for it to finish is the actual fix, not forcing through it:
animation, waiting for it to finish is the actual fix, not forcing through it. A
transition that removes and rebuilds the element instead of moving it produces
[the not-attached error rather than this one](playwright-element-not-attached-to-dom.md),
so which of the two you get already narrows what the page is doing:
```python
locator = page.get_by_role("button", name="Submit")
@@ -39,6 +39,11 @@ binary, and it is not there because that command never ran on this machine.
**How to confirm it:** check whether `playwright install` appears anywhere in your setup
script, Dockerfile, or CI workflow. If it does not, that is the fix, full stop.
This project splits the same way and for the same reason, with its own command for the
step: [the engine is fetched separately from the package](installation.md), so a fresh
environment that installed one and not the other lands on this error from the other
direction.
## Cause 2: a Docker or cross-platform build produced binaries for the wrong OS
A subtler variant: the install step did run, but it ran on a different operating system
@@ -53,6 +58,10 @@ the expected path is simply not there in a runnable form for this OS.
Dockerfile or CI job that later launches the browser, not assuming a cache
copied in from elsewhere is compatible. Playwright's official images run this step
during the image build specifically so the browsers match the container's own platform.
Once it launches, a container introduces a second and unrelated set of problems that
have nothing to do with paths:
[what an image is missing that a desktop has](how-to-use-invisible-playwright-in-docker.md)
is the next thing to read, not this page.
## Cause 3: missing system dependencies, which is a different error wearing the same clothes
@@ -98,6 +98,21 @@ the engine gives itself away in a dozen other places the header cannot reach. If
genuinely need a mobile browser, the honest answer is a WebKit or Chromium context, not a
Firefox one dressed up as a phone.
### The screen the two browsers report
![Two panels listing two values. The bundled Firefox reports a 1366 by 768 screen, the
patched engine reports 1920 by 1080. The device pixel ratio is 1 in
both.](https://raw.githubusercontent.com/feder-cr/invisible_playwright/main/docs/img/playwright-firefox-mobile-emulation-values.png)
Two values, one page served from `127.0.0.1`. The screen differs and the device pixel
ratio does not: both report `1`.
That is the section's argument in two rows. The screen is decided below the client, so
it changes when the engine changes, while `devicePixelRatio` stayed at `1` in both
because neither run asked for anything else. A mobile preset that sets a ratio on the
client cannot move the first number, and the two have to agree for the identity to hold
together.
## The engine owns the screen size, not the client
The screen size on a Firefox context belongs to the seeded engine, not to whatever a
@@ -139,6 +139,31 @@ keep doing that for those reasons. Choose between them on isolation, not on
whether the fingerprint comes out right, because now it comes out right either
way.
## The two calls, side by side, today
![Three panels listing screen, avail, outer and inner sizes. The bundled Firefox opened
with browser.new_page reports an inner size of 1280 by 720 on a 1366 by 768 screen. The
same build opened with new_context and no viewport reports 1366 by 683. The patched
engine opened with browser.new_page reports 1920 by 947, the same as its own
new_context.](https://raw.githubusercontent.com/feder-cr/invisible_playwright/main/docs/img/new-page-vs-new-context-viewport.png)
One page served from `127.0.0.1`, three sessions, headless throughout.
The first panel is the default this page is about, still there: `browser.new_page()` on
the bundled Firefox reports **1280x720** on a screen it claims is 1366x768. The second
panel is the same build asked for a context with no viewport, and the inner size becomes
1366x683, which is a window on that screen rather than a number from a config file.
The first panel also carries a second, quieter contradiction, and it is the kind this
page is really about: `outerHeight` reads **805** while `availHeight` reads **720**. The
window is taller than the space the operating system says is available. No maximised
window on a real desktop does that.
The third panel is the check on our side, which is the part we owe you rather than
Playwright: `browser.new_page()` on the patched engine reports 1920x947, the same
numbers its own `new_context` produces. The convenience call no longer picks up a
default nobody chose.
## How to check your own setup for the same shape of bug
Whatever tool you use, the check is the same three lines and it takes a session,
+7 -2
View File
@@ -81,10 +81,15 @@ recommended" for exactly this case, because a positional pick is fragile: it is
only as long as the page's element order does not change, and nothing announces when it
does. Reordering a list, adding a new row above the one you meant, or a responsive layout
that renders elements in a different sequence on a smaller viewport all silently break a
`.first()` that happened to work.
`.first()` that happened to work. A list that rebuilds itself between the pick and the
click produces
[the not-attached error instead](playwright-element-not-attached-to-dom.md), which is
the same fragility arriving as a different message.
**`{force: true}` or `strict_selectors=False`.** Neither narrows the match; both just
suppress the check. `strict_selectors=False` in particular reproduces the exact failure
suppress the check, and `force` has
[its own way of going wrong on a click that is merely covered](playwright-element-click-intercepted.md):
it delivers the click at the coordinates regardless of what is on top of them. `strict_selectors=False` in particular reproduces the exact failure
mode strict mode was built to prevent: Playwright picks one of the matches for you, and
which one it picks is not something the error message ever told you to verify. If the
count is ever wrong again after the page changes, nothing will tell you.
+14
View File
@@ -24,6 +24,20 @@ This page covers what the string has to agree with, why rotation makes things wo
rather than better, the Client Hints trap in Chromium, the one case where setting it is
correct, and what to do instead.
### The three strings, read from a real session
![One panel listing three values read from the patched engine, headless: the full user
agent string for Firefox 151.0 on Windows, navigator.platform Win32, and navigator.oscpu
Windows NT 10.0 with Win64 and x64. A note says the bundled Firefox returned the same
values.](https://raw.githubusercontent.com/feder-cr/invisible_playwright/main/docs/img/playwright-user-agent-values.png)
The three strings that have to agree, read from one page served from `127.0.0.1`. The
bundled Firefox returned the same three, so this panel is a reference rather than a
comparison: it is what agreement looks like when nobody has touched anything.
Change only the first line and the other two keep saying Windows in their own words.
That is why the rotation advice in the next section is what it is.
## What the user agent has to agree with
**Changing `navigator.userAgent` does not touch roughly eight other signals a page can
+3 -1
View File
@@ -77,7 +77,9 @@ with InvisiblePlaywright(seed=42) as browser:
This is the difference between debugging a failure and guessing at one: same seed,
same browser, so a failing run can be replayed exactly rather than hoping the next
random draw reproduces it.
random draw reproduces it. The seed reaches the browser layer and stops there, and
[what it does not pin](reproducible-agent-browser-identity-seed.md) is the half worth
reading before treating a stable fingerprint as a finished job.
## Short answers to the questions that lead here
+19
View File
@@ -56,6 +56,25 @@ the interesting shape: it does not ask a single question, it asks two and compar
answers. That pattern, cross-checking two sources that must agree, is what everything
modern is built on.
## The same properties, read from both browsers
![Two panels listing seven values read from a page served from localhost. The bundled
Firefox reports navigator.webdriver true, zero plugins and a 1366 by 768 screen. The
patched engine reports webdriver false, five plugins and a 1920 by 1080 screen. The
notification permission, user agent, colour depth and platform are identical in
both.](https://raw.githubusercontent.com/feder-cr/invisible_playwright/main/docs/img/sannysoft-explained-values.png)
Seven of the values this page describes, read from one page served from `127.0.0.1`,
first by Playwright's bundled Firefox and then by a patched engine. Three of the seven
differ.
The three that move are the three the table is really testing: `navigator.webdriver`
goes from `true` to `false`, the plugin count from `0` to `5`, and the screen from
`1366x768` to `1920x1080`. The four that do not move matter as much, because they show
what this page is arguing: `Notification.permission`, the user agent, the colour depth
and `navigator.platform` are already the same in both, so a row that agrees is not
evidence of anything either way.
## Group two: the property dump
The long list below the table is not pass/fail. It prints values:
+38
View File
@@ -50,6 +50,39 @@ The related traps:
the numbers differ from Windows and should match whatever platform you claim.
- A machine claiming Windows with a macOS-shaped available area is a contradiction.
## What the numbers actually are, on one machine
![Three panels listing screen, avail, outer and inner sizes plus device pixel ratio and
colour depth. The bundled Firefox headless reports a 1366 by 768 screen at two
different viewports without the screen changing. The patched engine reports a declared
1920 by 1080 display. All three report a 48 pixel gap between height and
availHeight.](https://raw.githubusercontent.com/feder-cr/invisible_playwright/main/docs/img/screen-values-three-arms.png)
Before applying the check above, it is worth knowing what it returns today. One
Windows machine, one page served from `127.0.0.1`, three headless sessions shown, and a
headful one measured alongside them but not printed here, because a headful window
reports the display of whichever machine it ran on.
**The taskbar check does not fire on this browser.** Playwright's bundled Firefox,
headless, reports `1366x768` with `availHeight` of `720`: a 48 pixel gap, and the
headful session measured beside it reported the same 48. So `availHeight === height` is
a real class of tell and this particular browser is not an example of it. Test the
browser you actually run rather than inheriting the example.
**What is a tell here is that the screen is a constant.** The first two panels are the
same build at viewports of 430x200 and 1000x700, and the display stays `1366x768`
through both. It is not derived from anything you asked for, and it is the same laptop
resolution in every stock headless session. A detector does not need the taskbar
comparison when the value itself never moves.
One sharp edge worth stating, because it is ours: with the patched engine, **an
explicit `viewport` leaves `outerWidth` reporting the declared window while
`innerWidth` follows what you asked for.** Measured at viewport 430x200 the pair reads
1920x1032 against 430x200, which is 1490 pixels of browser chrome and no real window
looks like that. With `no_viewport=True`, the panel above, the same pair reads 1920x1032
against 1920x947, an 85 pixel difference that is an ordinary tab strip and address bar.
If the identity matters more than the exact page size, do not pin the viewport.
## The relationships that have to hold
**The viewport cannot be bigger than the screen.** `innerWidth` greater than
@@ -156,6 +189,11 @@ platform, held stable for the identity. Rarity is the problem, not the specific
platform. It is also the value people most often set to 1 for convenience, on a
resolution where 1 is implausible.
**What screen size does Playwright's Firefox report in headless mode?** `1366x768`, with
`availHeight` at `720`. Measured at two different viewports on the same machine and it
did not move either time, so it is a constant rather than something derived from your
session, and it is the same laptop resolution in every stock headless run.
## Sources
- [MDN: `Screen.availHeight`](https://developer.mozilla.org/en-US/docs/Web/API/Screen/availHeight),
+3 -1
View File
@@ -35,7 +35,9 @@ bounded, tested, working exactly as configured.
That's the trap. A timeout on each request answers "how long do I wait for this one
server to respond." It says nothing about "how long am I willing to wait for the step
as a whole to finish." With three endpoints in the list and a ten-second timeout on
as a whole to finish." What a launch resolves from the network is the reason the
delay lands there and not on a page load, and part of it is
[deriving the timezone and locale from the proxy's exit](offline-geoip-timezone-proxy.md). With three endpoints in the list and a ten-second timeout on
each, the worst case was three sequential ten-second waits plus connection overhead -
correctly bounded per-request, and entirely unbounded as a caller-facing guarantee.
Every piece was well-behaved. Their sum was not something anyone had actually put a
+14
View File
@@ -45,6 +45,20 @@ anomaly, checkable the same way.
are altering values inside the exact runtime the opponent's code is also running in, and
the opponent always gets to look at what you changed.
## The one value that moves, and the one that does not
![Two panels listing two values. navigator.webdriver differs between the bundled
Firefox and the patched engine, true against false. Function.prototype.toString called
on a native function returns the identical native-code string in
both.](https://raw.githubusercontent.com/feder-cr/invisible_playwright/main/docs/img/vs-playwright-stealth-values.png)
Two values, read from one page served from `127.0.0.1`.
`navigator.webdriver` moves. `Function.prototype.toString` on a native function returns
the identical string from both browsers, which is the comparison that matters when the
fix is an init script: a patched getter has to survive being asked what it is, and a
value decided inside the engine is never asked.
## What it never touches, by construction
An init script cannot change what the font subsystem enumerates, what the GPU driver
+1 -1
View File
@@ -4,7 +4,7 @@ build-backend = "hatchling.build"
[project]
name = "invisible_playwright"
version = "0.13.2"
version = "0.14.0"
description = "Playwright wrapper for a patched Firefox with deterministic stealth profile."
readme = "README.md"
requires-python = ">=3.11"
+50 -3
View File
@@ -1,7 +1,7 @@
#!/usr/bin/env python3
"""Render the Jekyll docs/ tree into a GitHub wiki checkout.
Usage: build_wiki.py <docs_dir> <out_dir>
Usage: build_wiki.py <docs_dir> <out_dir> [--pixels <owner/repo>]
A GitHub wiki is a flat set of <Page>.md files with no Jekyll front matter and a
_Sidebar.md for navigation. This converter, for every docs/*.md:
@@ -9,12 +9,31 @@ _Sidebar.md for navigation. This converter, for every docs/*.md:
- rewrites internal links [x](slug.md[#a]) -> [x](slug[#a]) (wiki has no .md),
- names the page by its slug (stable URLs matching the docs site), except
index.md -> Home.md (the wiki landing page),
- and, with --pixels, gives the page its view counter (see
scripts/sync_article_pixels.py for what that number is and is not).
and then generates _Sidebar.md mirroring the parent/has_children/nav_order tree.
The pixel goes into the WIKI only, never back into docs/. The wiki is the
surface that ranks and the surface readers land on; the .md in the repository
is served as a JSON payload React mounts, and a counter there would measure
almost nothing while putting markup into the source tree.
Without --pixels (a local preview) no pixel is written at all, rather than one
addressed to a guessed repository. A wiki published that way would count
nothing while looking entirely normal, so publish-wiki.yml passes the flag AND
runs `sync_article_pixels.py --check` over the output before pushing.
"""
import os, re, sys
from sync_article_pixels import pixel_tag
DOCS = sys.argv[1]
OUT = sys.argv[2]
#: `owner/repo` the pixels address, or None. Not read from the environment
#: here: the caller that knows it is the workflow, and a fallback to
#: GITHUB_REPOSITORY would make a local run behave differently depending on
#: what happens to be exported.
PIXELS = sys.argv[sys.argv.index("--pixels") + 1] if "--pixels" in sys.argv else None
def parse(path):
t = open(path, encoding="utf-8").read()
@@ -88,13 +107,41 @@ def rewrite(body):
# `[a-z0-9/-]` and an optional `.md`: a link into a subdirectory carries the
# slash and may or may not carry the extension, and the first version of
# this pattern matched neither.
return re.sub(r'\]\(([a-z0-9/\-]+)(?:\.md)?(#[A-Za-z0-9\-]+)?\)', repl, body)
#
# The underscore is in BOTH classes because a heading like "What
# invisible_playwright does and does not do here" produces the anchor
# `#what-invisible_playwright-does-...`, and an anchor the pattern cannot
# match makes the WHOLE link fail to rewrite: it ships to the wiki as
# `](geetest-v4-explained.md#...)`, which is a dead link, not a link with a
# bad anchor. Measured on 2026-09-08: one such link across 463 pages, and it
# was invisible because the page renders fine and only the target 404s.
return re.sub(r'\]\(([a-z0-9_/\-]+)(?:\.md)?(#[A-Za-z0-9_\-]+)?\)', repl, body)
def with_pixel(name, body):
"""Put the page's view counter just under its H1.
Under and not above: the H1 is what the reader and every renderer expect
first, and a wiki page whose source starts with an <img> renders an empty
first line in some previews. Every page in both corpora starts with an H1
once the front matter is off - measured, 524 of 524 - so this is a uniform
position rather than a heuristic, and a page that ever stops starting with
one gets its pixel appended instead of silently misplaced.
"""
if not PIXELS:
return body
tag = pixel_tag(PIXELS, name)
lines = body.split("\n")
if lines and lines[0].startswith("# "):
return "\n".join([lines[0], "", tag] + lines[1:])
return body.rstrip("\n") + "\n\n" + tag
os.makedirs(OUT, exist_ok=True)
written = 0
for slug, (fm, body) in pages.items():
name = "Home" if slug == "index" else slug
open(os.path.join(OUT, name + ".md"), "w", encoding="utf-8", newline="\n").write(rewrite(body) + "\n")
open(os.path.join(OUT, name + ".md"), "w", encoding="utf-8", newline="\n").write(
with_pixel(name, rewrite(body)) + "\n")
written += 1
def title_of(slug):
+379
View File
@@ -0,0 +1,379 @@
#!/usr/bin/env python3
"""One view pixel per wiki page, and the release that holds them.
A GitHub wiki serves no per-page analytics. The repository traffic API reports
the ten most visited paths over fourteen days and nothing below that, so a
corpus of hundreds of wiki pages is invisible by construction: measured on this
repository, the whole wiki index sits at about thirty views per fortnight and
not one individual page reaches the top ten.
This gives every page a counter of its own, by the same mechanism the browser
launch counter has used since May: a release asset whose `download_count` is
incremented by GitHub on every fetch. Each wiki page embeds its own asset as a
1x1 transparent image, so one page view is one fetch is one count. The assets
live in a release tagged `article-views`, which is not a software release and
is created with `make_latest=false` so it never becomes the repository's
"Latest".
What the number is, said once so nobody reads it as more than it is:
* It counts FETCHES, not people. A reader who opens a page twice counts
twice, and there is no unique-visitor figure anywhere in it.
* It counts every client that loads images, crawlers included. Image
indexers and link unfurlers fetch it exactly like a browser does. At the
per-page volumes above, that share is not small.
* It undercounts readers who block images or read the page through a proxy
that strips them.
It is a floor with noise on top, and it is the only per-page signal available.
GitHub's own `traffic/popular/paths` is the independent instrument that can
corroborate it: a page the pixel calls the most read should, eventually, show
up in that top ten.
Usage:
python scripts/sync_article_pixels.py --repo owner/name wiki_build
python scripts/sync_article_pixels.py --repo owner/name --check wiki_build
python scripts/sync_article_pixels.py --selftest
`--check` is the gate: it refuses unless every built page carries exactly one
pixel, addressed to this repository and naming that page. It exists because
the injection happens in `build_wiki.py`, which falls back to no pixel at all
when it is not told which repository it is building for - and a wiki published
without pixels counts nothing while looking perfectly normal.
The sync NEVER deletes an asset. A page removed from `docs/` keeps its history,
and a renamed slug gets a new asset rather than inheriting the old one's count,
which is the truth: the wiki has no redirects, so a renamed page is a new URL.
"""
from __future__ import annotations
import argparse
import json
import os
import re
import struct
import sys
import time
import urllib.error
import urllib.request
import zlib
from pathlib import Path
#: The release that holds the pixels. Not a software release: `publish.yml`
#: reads `v*` tags and never looks at this one.
TAG = "article-views"
#: GitHub allows 1000 assets on a single release. Refusing well short of that
#: leaves room to notice and split into a second release, rather than finding
#: out from a failed upload on the day a page is published.
MAX_ASSETS = 1000
REFUSE_ABOVE = 950
#: `_Sidebar.md` is navigation injected into every page, not a page. A pixel
#: there would fire on every view of every page and drown its own signal.
NOT_A_PAGE = {"_Sidebar", "_Footer", "_Header"}
#: Any pixel, whichever repository or page it names. The check needs to see a
#: WRONG pixel, not only a missing one, so it matches the shape and compares
#: the parts afterwards.
PIXEL_RE = re.compile(
r'<img src="https://github\.com/([^/"]+/[^/"]+)/releases/download/'
+ TAG + r'/([^"/]+)\.png" width="1" height="1" alt="">')
def pixel_bytes() -> bytes:
"""A 1x1 fully transparent PNG, built here rather than committed.
68 bytes, and no image library on the runner. Transparent so it cannot
show through any theme, and a real PNG so a browser that sniffs content
types is not handed a text file with an image extension.
"""
def chunk(kind: bytes, data: bytes) -> bytes:
return (struct.pack(">I", len(data)) + kind + data
+ struct.pack(">I", zlib.crc32(kind + data) & 0xffffffff))
ihdr = struct.pack(">IIBBBBB", 1, 1, 8, 6, 0, 0, 0) # 1x1, 8-bit RGBA
idat = zlib.compress(b"\x00" + b"\x00\x00\x00\x00") # one filtered row
return (b"\x89PNG\r\n\x1a\n" + chunk(b"IHDR", ihdr)
+ chunk(b"IDAT", idat) + chunk(b"IEND", b""))
def pixel_tag(repo: str, page: str) -> str:
"""The exact markup a page carries.
ONE definition, imported by `build_wiki.py` which writes it and by the
check below which verifies it. Two copies of this string would agree today
and drift the first time either side is edited, and the failure would be a
wiki that silently stops counting.
`alt=""` marks it decorative, so a screen reader skips it and a broken
fetch leaves nothing visible. GitHub renders images from `github.com`
directly rather than through its camo proxy, so the reader's browser asks
GitHub for this asset and GitHub counts the request.
"""
return ('<img src="https://github.com/%s/releases/download/%s/%s.png"'
' width="1" height="1" alt="">' % (repo, TAG, page))
def page_names(wiki_dir: str | Path) -> list[str]:
"""The built wiki pages that get a pixel, by page name (no extension)."""
return sorted(p.stem for p in Path(wiki_dir).glob("*.md")
if p.stem not in NOT_A_PAGE)
def check(wiki_dir: str | Path, repo: str) -> list[str]:
"""Every page carries exactly one pixel, for THIS repo and THIS page."""
problems = []
for p in sorted(Path(wiki_dir).glob("*.md")):
found = PIXEL_RE.findall(p.read_text(encoding="utf-8"))
if p.stem in NOT_A_PAGE:
if found:
problems.append("%s is not a page and carries a pixel" % p.name)
continue
if not found:
problems.append("%s carries no pixel" % p.name)
elif len(found) > 1:
problems.append("%s carries %d pixels" % (p.name, len(found)))
else:
got_repo, got_page = found[0]
if got_repo != repo:
problems.append("%s points at %s, not %s"
% (p.name, got_repo, repo))
if got_page != p.stem:
problems.append("%s carries the pixel of %s"
% (p.name, got_page))
return problems
def _api(url: str, token: str, data: bytes | None = None,
ctype: str = "application/json", method: str | None = None,
tries: int = 5, sleep=time.sleep):
"""One API call, with the secondary rate limit handled rather than met.
The first run on an existing corpus uploads one asset per page - 463 on
the engine - and GitHub throttles bursts of content-creating requests with
a 403 or 429 carrying `Retry-After`. Without this the first run is the one
that fails, and it fails BEFORE the wiki push, so a hiccup here would block
the publish entirely. Honouring the header is also what rule 11 asks for
everywhere else this project talks to GitHub.
A 404 is raised, not retried: `release()` reads one to decide the release
has to be created.
"""
for attempt in range(tries):
req = urllib.request.Request(url, data=data, method=method)
req.add_header("Authorization", "Bearer " + token)
req.add_header("Accept", "application/vnd.github+json")
if data is not None:
req.add_header("Content-Type", ctype)
try:
with urllib.request.urlopen(req, timeout=120) as r:
return json.load(r)
except urllib.error.HTTPError as e:
last_try = attempt == tries - 1
if e.code not in (403, 429, 500, 502, 503) or last_try:
raise
wait = e.headers.get("Retry-After")
wait = int(wait) if wait and wait.isdigit() else 2 ** attempt
print("[pixels] %s from GitHub, waiting %ds (attempt %d of %d)"
% (e.code, wait, attempt + 1, tries), file=sys.stderr)
sleep(wait)
def release(repo: str, token: str) -> dict:
"""The pixel release, created on first use."""
try:
return _api("https://api.github.com/repos/%s/releases/tags/%s"
% (repo, TAG), token)
except urllib.error.HTTPError as e:
if e.code != 404:
raise
body = ("One tiny image per wiki page. The download count of each asset is"
" how many times that page was viewed. This is not a software"
" release: see scripts/sync_article_pixels.py.")
return _api("https://api.github.com/repos/%s/releases" % repo, token,
json.dumps({"tag_name": TAG, "name": "Article views",
"body": body, "draft": False, "prerelease": False,
"make_latest": "false"}).encode(), method="POST")
def existing_assets(repo: str, rel_id: int, token: str) -> dict[str, int]:
"""Asset name -> download count, ALL of them.
Paginated deliberately. The assets embedded in a release object are capped
by the API, so reading them from there would silently report a corpus of
hundreds of pages as a few dozen, and the sync would re-upload assets that
already exist (which fails) or the reader would lose pages (which is
worse, because it looks like zero views).
"""
out: dict[str, int] = {}
page = 1
while True:
batch = _api("https://api.github.com/repos/%s/releases/%d/assets"
"?per_page=100&page=%d" % (repo, rel_id, page), token)
if not batch:
return out
for a in batch:
out[a["name"]] = a["download_count"]
page += 1
def sync(wiki_dir: str | Path, repo: str, token: str) -> int:
pages = page_names(wiki_dir)
rel = release(repo, token)
have = existing_assets(repo, rel["id"], token)
missing = [p for p in pages if p + ".png" not in have]
total = len(have) + len(missing)
if total > REFUSE_ABOVE:
print("[pixels] REFUSING: %d assets would be on one release, and"
" GitHub allows %d. Split the corpus across a second release"
" before publishing more pages." % (total, MAX_ASSETS),
file=sys.stderr)
return 1
if not missing:
print("[pixels] %d pages, all already have an asset" % len(pages))
return 0
png = pixel_bytes()
upload = rel["upload_url"].split("{")[0]
for i, name in enumerate(missing, 1):
_api("%s?name=%s.png" % (upload, name), token, png, "image/png", "POST")
# Paced, not raced. A tenth of a second puts the whole first run under
# a minute of added wall clock and keeps a 463-asset burst well inside
# what GitHub serves without throttling; the retry above is what
# catches it if this is not enough.
if i % 50 == 0:
print("[pixels] uploaded %d of %d" % (i, len(missing)))
time.sleep(0.1)
print("[pixels] %d pages, uploaded %d new asset(s): %s"
% (len(pages), len(missing), ", ".join(missing[:10])
+ (" ..." if len(missing) > 10 else "")))
return 0
def selftest() -> int:
"""Known-bad inputs. A check that has only ever passed is not a check."""
import tempfile
repo = "feder-cr/invisible_playwright"
good = pixel_tag(repo, "a-page")
cases = [
("a page with its own pixel passes",
{"a-page.md": "# T\n\n" + good + "\n"}, 0),
("a page with no pixel fails",
{"a-page.md": "# T\n\nbody\n"}, 1),
("a pixel for another repo fails",
{"a-page.md": "# T\n\n" + pixel_tag("feder-cr/AIHawk", "a-page")}, 1),
("a pixel naming another page fails",
{"a-page.md": "# T\n\n" + pixel_tag(repo, "other-page")}, 1),
("two pixels on one page fail",
{"a-page.md": "# T\n\n" + good + "\n" + good}, 1),
("the sidebar without a pixel passes",
{"a-page.md": "# T\n\n" + good, "_Sidebar.md": "### nav\n"}, 0),
("the sidebar WITH a pixel fails",
{"a-page.md": "# T\n\n" + good,
"_Sidebar.md": pixel_tag(repo, "_Sidebar")}, 1),
]
bad = []
for label, files, expected in cases:
with tempfile.TemporaryDirectory() as d:
for n, t in files.items():
(Path(d) / n).write_text(t, encoding="utf-8")
got = len(check(d, repo))
ok = (got > 0) == (expected > 0)
print(" %s %s" % ("OK" if ok else "KO", label))
if not ok:
bad.append(label)
with tempfile.TemporaryDirectory() as d:
for n in ("one.md", "two.md", "_Sidebar.md", "notes.txt"):
(Path(d) / n).write_text("x", encoding="utf-8")
names = page_names(d)
# The retry, against a server that throttles. Without these three cases the
# backoff would be code that has never once run: the path only opens on a
# 403 from a burst, which is exactly the run nobody gets to rehearse.
import io
real_urlopen = urllib.request.urlopen
class _Resp(io.BytesIO):
def __enter__(self): return self
def __exit__(self, *a): return False
def _fake_opener(sequence):
left = list(sequence)
def opener(req, timeout=None):
outcome = left.pop(0)
if outcome is None:
return _Resp(b'{"ok": true}')
raise urllib.error.HTTPError(req.full_url, outcome, "throttled",
{"Retry-After": "1"}, None)
return opener
slept = []
api_cases = []
for label, sequence, must_raise in (
("a 403 with Retry-After is retried and then passes", [403, None], False),
("a 429 is retried", [429, 429, None], False),
("a 404 is NOT retried: it is how a missing release is found",
[404], True),
("the attempts run out and the error comes through", [403, 403, 403], True),
):
urllib.request.urlopen = _fake_opener(sequence)
try:
_api("https://example.invalid/x", "t", tries=3,
sleep=lambda s: slept.append(s))
raised = False
except urllib.error.HTTPError:
raised = True
finally:
urllib.request.urlopen = real_urlopen
api_cases.append((label, raised == must_raise))
api_cases.append(("l'wait viene dall'header Retry-After",
slept and all(s == 1 for s in slept)))
for label, ok in api_cases:
print(" %s %s" % ("OK" if ok else "KO", label))
if not ok:
bad.append(label)
png = pixel_bytes()
extra = (
("the pixel is a PNG", png.startswith(b"\x89PNG\r\n\x1a\n")),
("the pixel is 1x1", struct.unpack(">II", png[16:24]) == (1, 1)),
("the pixel has an alpha channel", png[25] == 6),
("page_names lists the pages", names == ["one", "two"]),
)
for label, ok in extra:
print(" %s %s" % ("OK" if ok else "KO", label))
if not ok:
bad.append(label)
print("selftest: %d cases, %d broken"
% (len(cases) + len(extra) + len(api_cases), len(bad)))
return 1 if bad else 0
def main() -> int:
ap = argparse.ArgumentParser()
ap.add_argument("wiki_dir", nargs="?")
ap.add_argument("--repo", default=os.environ.get("GITHUB_REPOSITORY"))
ap.add_argument("--check", action="store_true")
ap.add_argument("--selftest", action="store_true")
a = ap.parse_args()
if a.selftest:
return selftest()
if not a.wiki_dir or not a.repo:
ap.error("a wiki directory and --repo (or GITHUB_REPOSITORY) are needed")
if a.check:
problems = check(a.wiki_dir, a.repo)
for p in problems:
print("[pixels] " + p, file=sys.stderr)
print("[pixels] checked %d pages, %d problem(s)"
% (len(page_names(a.wiki_dir)), len(problems)))
return 1 if problems else 0
token = os.environ.get("GITHUB_TOKEN") or os.environ.get("GH_TOKEN")
if not token:
print("[pixels] no GITHUB_TOKEN", file=sys.stderr)
return 1
return sync(a.wiki_dir, a.repo, token)
if __name__ == "__main__":
raise SystemExit(main())
+24 -1
View File
@@ -2351,6 +2351,19 @@ class PageDispatcher(Dispatcher):
#: around 100 KB. Frames are never scaled up.
SCREENCAST_DEFAULT_SIZE = {"width": 1280, "height": 800}
SCREENCAST_DEFAULT_QUALITY = 80
#: Frames per second when the caller does not ask for a rate.
#:
#: ⛔ TEN AND NOT TWENTY-FIVE, and the caller can ask for either. Measured
#: 2026-09-08 on the same page, interleaved arms: asking for 10 delivers
#: 9.6-9.8 fps and 257 KB/s, asking for 25 delivers 23.8-24.0 and 629 KB/s.
#: Raising the constant would impose two and a half times the bandwidth on
#: every consumer to serve the one that is watching, and a batch job that
#: never looks at a frame would pay it too. So the default stays where it
#: is and somebody watching a window says so.
#:
#: The engine's own default is 25 (`fps || 25` in TargetRegistry.js); this
#: number is the wrapper's opinion, not the engine's.
SCREENCAST_FPS = 10
def op_screencast_start(self, params: Dict) -> Any:
@@ -2392,12 +2405,22 @@ class PageDispatcher(Dispatcher):
quality = params.get("quality")
if quality is None:
quality = self.SCREENCAST_DEFAULT_QUALITY
# ⛔ THE CALLER'S RATE, WHERE THIS IGNORED IT. The engine takes an `fps`
# and this passed the constant unconditionally, so `screencast.start()`
# had no way to ask for more - a live view got ten frames a second
# whatever it wanted, which is what made the pane feel slow after the
# client's own pause was fixed. Same shape as `quality` and `size`
# above: the caller decides, the constant is what happens when nobody
# does.
fps = params.get("fps")
if fps is None:
fps = self.SCREENCAST_FPS
result = self.send("Page.startScreencast", {
"width": int(size["width"]),
"height": int(size["height"]),
"quality": int(quality),
"fullWindow": True,
"fps": self.SCREENCAST_FPS,
"fps": int(fps),
})
self._screencast_id = result["screencastId"]
# The client's `start()` reads an optional `artifact` from the reply
@@ -76,6 +76,7 @@ class Screencast:
path: Union[str, Path] = None,
quality: int = None,
size: ScreencastSize = None,
fps: int = None,
) -> DisposableStub:
if self._started:
raise Error("Screencast is already started")
@@ -87,6 +88,7 @@ class Screencast:
{
"size": size,
"quality": quality,
"fps": fps,
"sendFrames": bool(onFrame),
"record": bool(path),
},
@@ -7809,6 +7809,7 @@ class Screencast(AsyncBase):
path: typing.Optional[typing.Union[pathlib.Path, str]] = None,
quality: typing.Optional[int] = None,
size: typing.Optional[ScreencastSize] = None,
fps: typing.Optional[int] = None,
) -> "AsyncContextManager":
"""Screencast.start
@@ -7830,6 +7831,10 @@ class Screencast(AsyncBase):
may be smaller than these bounds. If a screencast is already active (e.g. started by tracing or video recording),
the existing configuration takes precedence and the frame size may exceed these bounds or this option may be
ignored. If not specified the size will be equal to page viewport scaled down to fit into 800×800.
fps : Union[int, None]
Frames per second to ask the engine for. The wrapper's default is 10; the engine will go up to 25. Ask for
more when somebody is watching the window live, and less for a batch job that never looks at a frame - the
bandwidth follows the rate, measured at 257 KB/s for 10 and 629 KB/s for 25.
Returns
-------
@@ -7842,6 +7847,7 @@ class Screencast(AsyncBase):
path=path,
quality=quality,
size=size,
fps=fps,
)
)
@@ -7887,6 +7887,7 @@ class Screencast(SyncBase):
path: typing.Optional[typing.Union[pathlib.Path, str]] = None,
quality: typing.Optional[int] = None,
size: typing.Optional[ScreencastSize] = None,
fps: typing.Optional[int] = None,
) -> "SyncContextManager":
"""Screencast.start
@@ -7908,6 +7909,10 @@ class Screencast(SyncBase):
may be smaller than these bounds. If a screencast is already active (e.g. started by tracing or video recording),
the existing configuration takes precedence and the frame size may exceed these bounds or this option may be
ignored. If not specified the size will be equal to page viewport scaled down to fit into 800×800.
fps : Union[int, None]
Frames per second to ask the engine for. The wrapper's default is 10; the engine will go up to 25. Ask for
more when somebody is watching the window live, and less for a batch job that never looks at a frame - the
bandwidth follows the rate, measured at 257 KB/s for 10 and 629 KB/s for 25.
Returns
-------
@@ -7921,6 +7926,7 @@ class Screencast(SyncBase):
path=path,
quality=quality,
size=size,
fps=fps,
)
)
)
+126
View File
@@ -214,3 +214,129 @@ def test_a_screencast_frame_is_a_jpeg_of_the_whole_window(firefox_binary):
"the frame is %dx%d, no taller than the 800x600 viewport: the chrome "
"is not in it, so this is the page and not the window"
% (first["viewportWidth"], first["viewportHeight"]))
def test_the_caller_chooses_the_frame_rate():
"""⛔ IT IGNORED THE CALLER, and that was the second half of a slow live
view. The client's own pause was fixed first and the pane still could not
go past ten frames a second, because this passed the wrapper's constant to
the engine whatever was asked for. The engine has taken an `fps` all along.
Measured 2026-09-08 on the same page, interleaved arms: asking for 10
delivers 9.6-9.8 fps at 257 KB/s, asking for 25 delivers 23.8-24.0 at
629 KB/s. That is why the DEFAULT does not move - raising it would put two
and a half times the bandwidth on every consumer, including a batch job
that never looks at a frame - and why the caller can ask.
Known-bad: pass `self.SCREENCAST_FPS` unconditionally again. The second
assertion still holds, because the default is what it always was.
"""
conn = RecordingConnection()
page, _ = _bare_page(conn)
page.op_screencast_start({"sendFrames": True, "record": False, "fps": 25})
assert conn.sent[-1][1]["fps"] == 25, conn.sent[-1][1]
# A second start on the same page is refused, correctly: the default is
# asked of a page of its own rather than by stopping and restarting this
# one, which would be testing the stop as much as the rate.
page, _ = _bare_page(conn)
page.op_screencast_start({"sendFrames": True, "record": False})
from invisible_playwright._juggler.server import PageDispatcher
assert conn.sent[-1][1]["fps"] == PageDispatcher.SCREENCAST_FPS
assert PageDispatcher.SCREENCAST_FPS == 10, (
"the default rate moved; raising it imposes the bandwidth of a live "
"view on every consumer, which is what the parameter exists to avoid")
def test_the_rate_reaches_the_engine_from_the_public_api():
"""A parameter the wrapper honours and the public signature does not offer
is a parameter nobody outside can use.
Known-bad: drop `fps` from either generated API. The impl accepts it and no
caller can pass it.
"""
import inspect
from invisible_playwright._pw.async_api._generated import Screencast as A
from invisible_playwright._pw.sync_api._generated import Screencast as S
from invisible_playwright._pw._impl._screencast import Screencast as Impl
for cls, what in ((A, "async"), (S, "sync"), (Impl, "impl")):
assert "fps" in inspect.signature(cls.start).parameters, (
"%s screencast.start() cannot be asked for a frame rate" % what)
# ⛔ AND THAT IT IS FORWARDED, not only declared. The first version of this
# asserted the signature alone and the mutation that deletes `fps=fps` from
# the generated wrapper SURVIVED it: a parameter a caller can pass and that
# goes nowhere is the inert-lever defect this project has met before, and
# it is worse than a missing one because it looks like it works.
#
# Every parameter, not just this one: the property is that a public
# signature forwards what it declares.
for cls, what in ((A, "async"), (S, "sync")):
body = inspect.getsource(cls.start)
head, _, tail = body.partition("return")
dropped = [name for name in inspect.signature(cls.start).parameters
if name not in ("self",)
and ("%s=%s" % (name, name)) not in tail
and ("onFrame=self._wrap_handler(%s)" % name) not in tail]
assert not dropped, (
"%s screencast.start() declares parameters it never passes on, so "
"a caller setting them changes nothing: %s" % (what, dropped))
@pytest.mark.e2e
def test_asking_for_a_higher_rate_actually_delivers_more_frames(firefox_binary):
"""⛔ THE PARAMETER REACHES THE ENGINE, which the unit test cannot say. That
one proves the wrapper puts a number on the wire; only a real engine can say
the number does anything, and a lever nobody verified from inside the system
it moves is a lever this project has been fooled by before.
Interleaved is not possible here - a screencast is per page and the rate is
fixed at start - so the arms are two pages of the same browser, same page
served, same duration, and the assertion is on the RATIO rather than on
either count: the absolute rate depends on the machine, and the claim is
that asking for more gets more.
Measured 2026-09-08 on this machine: 10 asked delivered 9.6-9.8 fps, 25
asked delivered 23.8-24.0. The floor below is deliberately far from that -
it is testing that the lever is connected, not re-measuring it.
"""
srv = socketserver.TCPServer(("127.0.0.1", 0), _serve(PAGE))
threading.Thread(target=srv.serve_forever, daemon=True).start()
url = "http://127.0.0.1:%d/" % srv.server_address[1]
from invisible_playwright import InvisiblePlaywright
def count(page, fps, seconds=3.0):
got = []
def on_frame(frame):
got.append(frame)
page.goto(url)
try:
page.screencast.start(on_frame=on_frame, fps=fps)
except Exception as refused:
if "Page.startScreencast" in str(refused) and "not supported" in str(refused):
pytest.skip("this engine has no screencast (it needs "
"firefox-28 or later): %s" % refused)
raise
time.sleep(seconds)
page.screencast.stop()
return len(got)
try:
with InvisiblePlaywright(seed=42, binary_path=firefox_binary,
headless=True) as browser:
slow = count(browser.new_page(), 5)
fast = count(browser.new_page(), 25)
finally:
srv.shutdown()
assert slow and fast, "no frames at all: %d and %d" % (slow, fast)
assert fast > slow * 1.5, (
"asking for 25 frames a second delivered %d in three seconds and "
"asking for 5 delivered %d: the rate the caller asks for is not "
"reaching the engine" % (fast, slow))