S024: privacy mode that holds up (R1-16)
Firefox-consistent anti-fingerprinting script (canvas/WebGL/audio/font noise per run and site; common screen, CPU, platform, touch and WebGL values; frames covered), paused per site, on in incognito. Privacy mode also switches third-party cookie blocking and a Firefox-style Accept-Language in the vendored servo-net; document.cookie is emptied in cross-site frames. Engine gaps fixed on the way: screen geometry (was 0x0), document.fonts.check, a pass-through DynamicsCompressorNode. Settings sub-page and shield flyout explain it. Tests: unit tests, privacy-mode/incognito/net smokes, Cover Your Tracks run recorded in docs/engine/privacy-mode.md. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
parent
2bac58769c
commit
68346f0edb
25 changed files with 815 additions and 55 deletions
|
|
@ -73,6 +73,7 @@ Never modify: `~/Documents/Apps/Nacre` (the original Python Nacre, reference onl
|
|||
| `SMOKE_SIZE=1280x1600 tools/smoke.sh tests/smoke/sliders.txt` | controls hold still (R1-21): Interface size drag (value label while held, applied on release), Contrast live, Style chip pick; `SMOKE_VISIBLE=1 tools/smoke.sh tests/smoke/sliders-visible.txt` the same plus scrolling for the user's window (~772 px). Selftest `press`/`drag`/`release`, `scroll x y dy`; read the PNGs | now (R1-21) |
|
||||
| `python3 tests/smoke/net/server.py &` + `tools/smoke.sh tests/smoke/net-{privacy,adblock,downloads}.txt` | network pass, offline: secure DNS through a local DoH stub (`*.nacre.test` → 127.0.0.1), HTTPS-only + certificate warning, tracking params, ad blocker with a local list, downloads + download manager stubs; the server's `/log` has requests, DNS names, Range headers, manager calls. `cache-restart.txt` with `SMOKE_HOME=<cache.txt outdir>/home`: disk cache. `net-real.txt` needs internet. `@HOME@` in scripts = the throwaway home | now (S007) |
|
||||
| `tools/smoke.sh tests/smoke/mse.txt` | MSE: MediaSource + one SourceBuffer plays chunk-appended fMP4 and WebM (offline); passes only on a build with the MSE patches (branch `s022-mse-proto`, see docs/engine/mse-spike.md) | S022 prototype |
|
||||
| `tools/smoke.sh tests/smoke/privacy-mode.txt` (+ `SMOKE_ARGS=--incognito … privacy-incognito.txt`) | privacy mode: `pages/fingerprint.html` read off/on, `fp-off.json`/`fp-on.json` + shots (offline); `privacy-net.txt` (needs `tests/smoke/net/server.py`) frame cookies, per-site pause, Accept-Language; `SMOKE_TIMEOUT=700 … coveryourtracks.txt` EFF's test off/on (internet, direct). Selftest `save <name> <js>` writes a JS string result to `<name>.json`; `SMOKE_ARGS` passes browser arguments | now (S024) |
|
||||
| `python tools/icons.py` | rebuilds the icon font subset and `src/ui/icons.rs` from `tools/icons.txt` (needs fontTools and Arch's ttf-material-symbols-variable) | now (S015) |
|
||||
| appimagetool, wine + Inno Setup, VM "Windows 10" | packaging and Windows checks | see the user's global CLAUDE.md "Building" |
|
||||
|
||||
|
|
|
|||
|
|
@ -11,13 +11,13 @@ R1-16: privacy mode must be genuinely useful: anti-fingerprinting (canvas, WebGL
|
|||
- `src/inject.rs` (how scripts are injected per page and frame), the Protection flyout in `src/ui/menus.rs`
|
||||
|
||||
## Steps
|
||||
- [ ] List the fingerprint surfaces Servo 0.7 exposes (a local test page printing each value) and pick per surface: normalise (common value) or randomise per session/site
|
||||
- [ ] Inject the spoofing script at document start in every frame when privacy mode is on (per site and global), consistent across APIs (UA ↔ platform ↔ timezone ↔ language)
|
||||
- [ ] Switch on S023's third-party cookie blocking and privacy headers with privacy mode; incognito windows start with privacy mode on
|
||||
- [ ] Protection flyout and Settings show what privacy mode does and what's limited by the engine
|
||||
- [ ] Verify: local fingerprint page before/after (smoke shots + JSON); then one run on coveryourtracks.eff.org (needs internet, no Tor/proxy) and record the result
|
||||
- [ ] Unit tests for pure logic (value choice, consistency); regression: common sites (heavy-web.txt) still work with privacy mode on
|
||||
- [ ] PROGRESS entry, INDEX line, commit `S024: …` and push
|
||||
- [x] List the fingerprint surfaces Servo 0.7 exposes (a local test page printing each value) and pick per surface: normalise (common value) or randomise per session/site
|
||||
- [x] Inject the spoofing script at document start in every frame when privacy mode is on (per site and global), consistent across APIs (UA ↔ platform ↔ timezone ↔ language)
|
||||
- [x] Switch on S023's third-party cookie blocking and privacy headers with privacy mode; incognito windows start with privacy mode on
|
||||
- [x] Protection flyout and Settings show what privacy mode does and what's limited by the engine
|
||||
- [x] Verify: local fingerprint page before/after (smoke shots + JSON); then one run on coveryourtracks.eff.org (needs internet, no Tor/proxy) and record the result
|
||||
- [x] Unit tests for pure logic (value choice, consistency); regression: common sites (heavy-web.txt) still work with privacy mode on
|
||||
- [x] PROGRESS entry, INDEX line, commit `S024: …` and push
|
||||
|
||||
## End criteria
|
||||
- Local fingerprint page shows the normalised values with privacy mode on and real ones off; Cover Your Tracks result recorded; heavy-web smoke still passes with privacy mode on.
|
||||
|
|
|
|||
|
|
@ -43,5 +43,5 @@ Tracker: https://claude.ai/artifact/9AD7fPfwJ4ASFzVTJGKU4h
|
|||
|
||||
## 06 Privacy
|
||||
- [x] [S023 — Request headers and third-party cookies in servo-net](06%20Privacy/S023-net-headers-cookies.md) · Opus medium
|
||||
- [ ] [S024 — Privacy mode that holds up](06%20Privacy/S024-privacy-mode.md) · Opus high
|
||||
- [x] [S024 — Privacy mode that holds up](06%20Privacy/S024-privacy-mode.md) · Opus high
|
||||
- [ ] [S025 — Cookies encrypted at rest](06%20Privacy/S025-cookie-encryption.md) · Opus medium
|
||||
|
|
|
|||
|
|
@ -21,3 +21,4 @@
|
|||
- D-016 — 2026-11-12 — Patched gst_mse loading (S026). Nacre ships its own `libgstmse-1.0.so.0` and `mse` plugin built from `vendor/gst-mse` (`tools/gst-mse.sh`). Release layout: library in `<exe dir>/lib/`, plugin in `<exe dir>/lib/gstreamer-1.0/`; a dev build uses `target/gst-mse/{lib,gstreamer-1.0}`. The binary's RUNPATH (`$ORIGIN/lib:$ORIGIN/../gst-mse/lib`, from `build.rs`) finds the library ahead of the system copy (same soname), and `main.rs` prepends the plugin dir to `GST_PLUGIN_PATH` before GStreamer starts (paths in GST_PLUGIN_PATH beat the system plugin of the same name). Windows: the DLLs sit next to `nacre.exe` / in `lib\gstreamer-1.0` (unverified). — RUNPATH needs no wrapper script or re-exec; LD_LIBRARY_PATH would have to be set before the process starts. — S030 packaging (AppImage, tarball, Windows), S028 merge
|
||||
- D-017 — 2026-11-12 — Request headers and third-party cookie blocking are Nacre patches in the vendored servo-net (S023): new module `nacre.rs` holds embedder-set state (extra headers, block switch, top-level site per webview); `http_loader.rs` and `websocket_loader.rs` read it. A request is third-party when its host's registrable domain differs from its webview's top-level site; blocking is on when the setting or privacy mode is on (`App::refresh_hub_config`). — Servo 0.7 has neither; the user wants engine fixes. `document.cookie` in cross-site frames stays uncovered (script isn't vendored). — S024 (privacy mode only needs `privacy_mode_on`), any Servo upgrade (re-apply from DESIGN.md "Vendored servo-net patches", re-run `privacy-net.txt`)
|
||||
- D-017 — 2026-11-12 — MSE DOM design (S027). (1) `dom_media_source_enabled` is not a servo-config pref: adding a field to `Preferences` means vendoring servo-config, which rebuilds nearly every Servo crate. Instead the three interfaces carry `[Func="MediaSource::enabled"]`, which reads `NACRE_DOM_MEDIA_SOURCE_ENABLED` once (`0`/`false` = off, default on; `servo_media_player::mse::enabled`). A settings switch, if wanted, sets that variable before Servo starts. (2) The DOM owns the spec state (readyState, updating, both lists, events, always queued as media element tasks); gst_mse owns parsing, buffering and removal. Only `sourceopen` after attaching, update-end/error, duration and active-list changes come from the backend. (3) The backend's event sink names its MediaSource by id through a thread-local map of weak references (no `Trusted`, so a dropped MediaSource is collected). (4) MediaSource object URLs live in a per-global map (`GlobalScope::media_source_urls`), revoked one task later (pages revoke right after setting `src`), cleared on unload. (5) gst_mse defects found here are fixed in vendor/gst-mse like D-016 (patches 5–9 in docs/engine/gst-mse-patches.md). — Keeps rebuilds to servo-script and the media crates; matches Servo's own direction (#22416). — S028 (player integration, merge), S029, any Servo upgrade
|
||||
- D-018 — 2026-11-12 — Privacy mode looks like desktop Firefox (S024): values that can't be hidden are made consistent with the Firefox user agent (platform, oscpu, appVersion, WebGL "Mozilla", no touch points, Firefox's language list in both `navigator.languages` and Accept-Language); canvas/WebGL/audio/fonts get noise seeded per run and top-level site; time zone and locale stay real; the TouchEvent globals stay (removing them broke Wikipedia). Engine gaps that stop fingerprint or site scripts get a small always-on JS layer (`FONTS_CHECK_JS`, `COMPRESSOR_JS`). — Inconsistent spoofing is itself a fingerprint; Firefox is the UA Nacre sends. — S025 and later privacy or UA work: keep the navigator values in step with any user agent change (`inject::firefox_navigator`).
|
||||
|
|
|
|||
|
|
@ -143,6 +143,10 @@ picture-in-picture, extensions, password capture, printing.
|
|||
video" (and PiP finds no video). Plain `<video>` files (WebM, MP4 through GStreamer) play.
|
||||
- Inline `<svg>` is painted from its own markup, so `currentColor` misses the CSS colour; `SVG_COLOR_JS`
|
||||
(`inject.rs`) copies each icon's computed colour into its `color` attribute (hover colours not followed).
|
||||
- Fingerprinting: Servo has no IndexedDB, plugins list, WebRTC or DynamicsCompressorNode, and its user agent is a
|
||||
rare Firefox version, so Cover Your Tracks still finds Nacre unique with privacy mode on (bits per metric in
|
||||
`docs/engine/privacy-mode.md`). `document.fonts.check()` and a pass-through compressor are Nacre's own layer
|
||||
(`FONTS_CHECK_JS`, `COMPRESSOR_JS` in `inject.rs`); the screen size comes from `Hub::screen_geometry`.
|
||||
- CSS `mask-image` icons (e.g. Wikipedia's) paint as solid squares. HTTP/2 header limit: see D-012.
|
||||
|
||||
## Vendored servo-net patches
|
||||
|
|
@ -159,6 +163,7 @@ picture-in-picture, extensions, password capture, printing.
|
|||
| `http_loader.rs` `http_network_or_cache_fetch` (step 8.15) | appends the embedder's extra headers (`DNT`, `Sec-GPC`, `Save-Data`) unless the request already has them; records a `Document` request's site as its webview's top-level site; skips the `Cookie` header for a third-party request (S023) | `privacy-net.txt` |
|
||||
| `http_loader.rs` `http_network_fetch` (step 15) | doesn't store `Set-Cookie` from a third-party response (S023) | `privacy-net.txt` |
|
||||
| `websocket_loader.rs` `create_handshake_request`, `process_ws_response` | the same third-party rule for WebSocket handshakes (S023) | unit tests only |
|
||||
| `fetch/methods.rs` `main_fetch` (step 12) | privacy mode's Firefox-style Accept-Language ("en-US,en;q=0.5", `nacre::append_accept_language`) replaces Servo's single locale; a page's own value stays (S024) | `privacy-net.txt` |
|
||||
|
||||
Third-party rule (S023): a request is third-party when its host's site (registrable domain, eTLD+1; an IP address
|
||||
or a single-label host stands for itself) differs from the top-level site of its webview. Scheme and port don't
|
||||
|
|
@ -166,8 +171,15 @@ count, so `a.example.com` on `example.com` stays first-party. The top-level site
|
|||
request of that webview (net sees it before any subresource) and from the hub's `notify_url_changed` (history
|
||||
navigations without a request, downloads that didn't replace the page); `notify_closed` forgets it. Requests with no
|
||||
webview or no known top-level site are never blocked. `Document` requests are never blocked; `IFrame` documents are
|
||||
checked like any subresource. Not covered: `document.cookie` and the Cookie Store API in a third-party frame
|
||||
(script sends those to net with no webview id; servo-script isn't vendored).
|
||||
checked like any subresource. `document.cookie` and the Cookie Store API in a third-party frame go to net with no
|
||||
webview id (servo-script isn't vendored); Nacre's `FRAME_COOKIE_JS` (`inject.rs`, S024) empties them in a frame
|
||||
whose top page is another site.
|
||||
|
||||
## Privacy mode (S024)
|
||||
|
||||
Page script `PRIVACY_JS` (`inject.rs`) plus the servo-net switches (third-party cookies, Accept-Language list);
|
||||
every surface, the choice made for it and the Cover Your Tracks result are in `docs/engine/privacy-mode.md`.
|
||||
Paused per site (`privacy.mode_off`); on in incognito windows by default (`privacy.mode_incognito`).
|
||||
|
||||
## UI system (S015)
|
||||
|
||||
|
|
|
|||
|
|
@ -79,14 +79,14 @@ written.
|
|||
| Setting | State |
|
||||
|---|---|
|
||||
| VPN: Tor (system, Tor Browser, or started) or custom SOCKS5/HTTP, kill switch while connecting | written (`net/bridge.rs`, `net/tor.rs`); S007 verified the bridge with the VPN off (net-privacy.txt: route Direct, every connection through it, traffic counted live); Tor and proxies never run in tests (user rule), kill switch not checked |
|
||||
| Privacy mode (+ in incognito) | written (PRIVACY_JS) |
|
||||
| Privacy mode (+ in incognito) | verified S024 (privacy-mode.txt, privacy-incognito.txt, privacy-net.txt, coveryourtracks.txt): canvas/WebGL/audio/font noise, common screen/CPU/platform/touch/WebGL values, Firefox-style languages and Accept-Language, third-party cookies blocked incl. frames' document.cookie, paused per site, on in incognito; details `docs/engine/privacy-mode.md` |
|
||||
| Secure DNS (Cloudflare, Quad9, Google, Mullvad, AdGuard, custom) | verified S007 with a custom endpoint on a local stub (net-privacy.txt: names only the stub knows load); the public providers not contacted in tests |
|
||||
| HTTPS-only mode with fallback prompt and exceptions | verified S007 (net-privacy.txt: upgrade via the `location.replace()` page, certificate warning "Open anyway" (fixed: servo-net patch), fallback prompt + Open anyway, site stays http this session, local addresses never upgraded); "Always for this site" not tapped |
|
||||
| Site settings (defaults and per-site) | verified S008 (site-memory*.txt, restart): stored per site, applied again after a restart. Enforced: pop-ups, notifications, images (hub blocks image requests), sound (tab muted on load), Servo's own requests, open-other-apps. Shown as "Not available" (Servo 0.7): location (navigator.geolocation never answers), camera, microphone, device list (no navigator.mediaDevices), persistent storage (no navigator.storage), clipboard, JavaScript. Per-site privacy-mode flag does not exist (privacy mode is global; S024) |
|
||||
| Site settings (defaults and per-site) | verified S008 (site-memory*.txt, restart): stored per site, applied again after a restart. Enforced: pop-ups, notifications, images (hub blocks image requests), sound (tab muted on load), Servo's own requests, open-other-apps. Shown as "Not available" (Servo 0.7): location (navigator.geolocation never answers), camera, microphone, device list (no navigator.mediaDevices), persistent storage (no navigator.storage), clipboard, JavaScript. Privacy mode is paused per site from the shield menu (S024) |
|
||||
| Delete browsing data (+ on exit) | written |
|
||||
| Send Do Not Track and GPC | verified S023 (privacy-net.txt): `DNT: 1` + `Sec-GPC: 1` on every request (vendored servo-net), plus the JS properties |
|
||||
| Remove tracking parameters | verified S007 (net-privacy.txt: utm_*/fbclid removed, other parameters kept, off keeps all) |
|
||||
| Block third-party cookies | verified S023 (privacy-net.txt): cross-site requests send and store no cookies (vendored servo-net), same-site subdomains keep theirs, on in privacy mode. `document.cookie` in a cross-site frame isn't covered |
|
||||
| Block third-party cookies | verified S023 (privacy-net.txt): cross-site requests send and store no cookies (vendored servo-net), same-site subdomains keep theirs, on in privacy mode. `document.cookie` in a cross-site frame: empty (S024, script layer) |
|
||||
| Google sign-in quirk | written (UA switch + JS) |
|
||||
| Sites where ad blocking is paused | verified S007 (net-adblock.txt), persisted S008 (site-memory*.txt) |
|
||||
| Remote debugging, user agent | written |
|
||||
|
|
|
|||
|
|
@ -295,6 +295,16 @@ Later: S010 list: user checks the Discord icon with their own client (the Discor
|
|||
- Handoff to S024: privacy mode already turns third-party cookie blocking on; S024 only extends `App::privacy_mode_on` if it adds per-window/per-site modes.
|
||||
- Later: a test server left by an older session held ports 8766/8767 with stale code; stop old ones before net smokes.
|
||||
|
||||
## S024 — Privacy mode that holds up (2026-11-12)
|
||||
- Done: `PRIVACY_JS` rewritten after the original privacy.py (Firefox-consistent; per-run + per-site noise; frames incl. script-made ones; native-looking functions); paused per site from the shield menu (`privacy.mode_off`); third-party cookie blocking + Firefox-style Accept-Language/`navigator.languages` switched by privacy mode (servo-net `nacre::set_language_list`, methods.rs step 12); `FRAME_COOKIE_JS` empties `document.cookie` in cross-site frames whenever third-party cookies are blocked; incognito on by default (verified).
|
||||
- Engine gaps fixed on the way: `Hub::screen_geometry` (screen was 0 x 0), `document.fonts.check()` and a pass-through DynamicsCompressorNode (both always on; without them Cover Your Tracks never got a result).
|
||||
- UI: Settings → Privacy → Privacy mode sub-page (what it hides, what not, paused sites, "Test it"); shield flyout explains and has "On <site>".
|
||||
- Tests: 3 new unit tests (navigator values from UA, script filling, language list), 67 green. Smokes: `privacy-mode.txt` (fingerprint page off/on JSON + shots), `privacy-incognito.txt` (`SMOKE_ARGS=--incognito`), `privacy-net.txt` extended (frame cookies, pause, Accept-Language; 1 flaky `EvaluationFailure(None)` in 5 runs), launch, net-privacy green. Selftest `save <name> <js>`; smoke.sh `SMOKE_ARGS`.
|
||||
- Cover Your Tracks (`coveryourtracks.txt`, direct): per-metric bits ~124 → ~58; canvas/audio "randomized", touch/platform/WebGL tells gone; headline still unique (UA, time zone, no IndexedDB). Table in `docs/engine/privacy-mode.md`.
|
||||
- heavy-web with privacy on: DuckDuckGo + Wikipedia pass (removing TouchEvent globals broke Wikipedia search and WebM playback: kept them); YouTube part fails, as in the baseline without privacy mode (which also crashed there once and hit DuckDuckGo's rate limit once).
|
||||
- Not done: plugins list, IndexedDB, DOM-measured fonts, web workers (engine/coverage limits); real sign-ins with privacy mode on (for the user).
|
||||
- Later: normal mode still shows Servo's "Linux"/"4.0" platform values next to the Firefox UA; the YouTube results step of heavy-web crashes/times out on main.
|
||||
|
||||
## Later
|
||||
- Turnstile widget paints as a black half-disc (Servo painting of its iframe/shadow DOM, S006 site doctor).
|
||||
- Google sign-in past the email step: press Next with a real account, by the user (S006).
|
||||
|
|
|
|||
66
docs/engine/privacy-mode.md
Normal file
66
docs/engine/privacy-mode.md
Normal file
|
|
@ -0,0 +1,66 @@
|
|||
# Privacy mode (S024, R1-16)
|
||||
|
||||
Privacy mode hides what makes Nacre stand out, so sites can't recognise the browser without cookies. It is on
|
||||
when Settings → Privacy → Privacy mode is on, and in incognito windows unless "Always on in incognito windows" is
|
||||
off. It can be paused per site from the shield menu (`privacy.mode_off`). Changes apply from each page's next load.
|
||||
|
||||
## How it works
|
||||
|
||||
| Layer | Where | What |
|
||||
|---|---|---|
|
||||
| Page script | `inject.rs` `PRIVACY_JS` (`privacy_script`) | runs at document start in every document Servo parses (frames too), and reaches same-origin frames made by script through `contentWindow` / `contentDocument` |
|
||||
| Network | `vendor/servo-net/nacre.rs` | third-party cookies blocked (S023), Accept-Language as Firefox's list (`set_language_list`) |
|
||||
| Frame cookies | `inject.rs` `FRAME_COOKIE_JS` | `document.cookie` empty and not stored in a frame whose top page is another site (on whenever third-party cookies are blocked) |
|
||||
|
||||
Noise is seeded by a random value per run (`Shared::seed`) plus the top-level site (last two host labels; a
|
||||
cross-origin frame reads it from its referrer), so values differ on every site and after every restart but are
|
||||
stable within a site. Replaced functions print as native code (`Function.prototype.toString`).
|
||||
|
||||
## Surfaces (Servo 0.7, `tests/smoke/pages/fingerprint.html`)
|
||||
|
||||
| Surface | Off (engine) | On | Choice |
|
||||
|---|---|---|---|
|
||||
| Canvas (`toDataURL`, `toBlob`, `getImageData`) | real | low-bit noise on ~1 in 40 colour values | randomise per site/run |
|
||||
| WebGL `readPixels` | real | same noise | randomise |
|
||||
| WebGL vendor / renderer | "Mozilla/Servo" | "Mozilla"; `WEBGL_debug_renderer_info` exists and answers "Mozilla" | normalise (Firefox's values) |
|
||||
| Audio (`getChannelData`, `getFloatFrequencyData`) | real | ~1e-7 noise | randomise |
|
||||
| Fonts via canvas `measureText` | real (7 of 32 probed fonts found here) | every probed font "installed" (width ± 0.001 px) | normalise |
|
||||
| Screen size, avail size, colour depth, position | real (after the `screen_geometry` fix: was 0 x 0) | smallest of 1366x768, 1536x864, 1920x1080, 2560x1440, 3840x2160 holding the window; 24 bit; 0,0 | normalise |
|
||||
| `hardwareConcurrency` | real | 8 | normalise |
|
||||
| `deviceMemory` | absent | absent | Firefox has none either |
|
||||
| `platform`, `oscpu`, `appVersion` | "Linux", none, "4.0" | from the user agent: "Linux x86_64", "Linux x86_64", "5.0 (X11)" (Windows: "Win32", "5.0 (Windows)") | normalise (consistent with the UA) |
|
||||
| `maxTouchPoints`, `createEvent('TouchEvent')` | absent, works | 0, NotSupportedError | normalise (desktop Firefox); the TouchEvent globals stay, removing them broke Wikipedia's search and media documents |
|
||||
| `navigator.languages`, Accept-Language | `["en-US"]`, "en-US" | `["en-US", "en"]`, "en-US,en;q=0.5" | normalise (Firefox's form), the same everywhere |
|
||||
| Time zone, locale | real | real | kept: changing them breaks clocks and calendars; both come from the system and agree |
|
||||
| User agent | Firefox form of Servo's (`mainstream_ua`) | same | kept |
|
||||
| Plugins, `pdfViewerEnabled` | 0, false | same | engine limit (Firefox lists 5 PDF plugins) |
|
||||
| IndexedDB, WebRTC, battery, `userAgentData` | absent | absent | engine limits |
|
||||
| Fonts measured by DOM layout, web workers | real | real | not covered |
|
||||
|
||||
## Compatibility layers added on the way (always on)
|
||||
|
||||
- `FONTS_CHECK_JS`: Servo's `document.fonts` has no `check()`; Cover Your Tracks' script stopped there.
|
||||
- `COMPRESSOR_JS`: Servo has no DynamicsCompressorNode; a pass-through stand-in lets audio fingerprint scripts
|
||||
run (EFF's server answers 500 to the error string Fingerprint2 reports otherwise).
|
||||
- `Hub::screen_geometry`: Servo reported a 0 x 0 screen because Nacre gave it none.
|
||||
|
||||
## Cover Your Tracks (2026-11-12, direct connection, `tests/smoke/coveryourtracks.txt`)
|
||||
|
||||
Both runs: tracking ads and invisible trackers blocked. Headline: off "nearly-unique" (17.55 bits, one in
|
||||
191,498), on "unique" (18.55 bits) — the headline is set by the rarest values, which privacy mode can't change:
|
||||
the user agent (Servo's Firefox 153), time zone, the supercookie test (no IndexedDB in Servo).
|
||||
Identifying bits per metric, off → on:
|
||||
|
||||
| Metric | Off | On |
|
||||
|---|---|---|
|
||||
| Canvas hash | 17.55 | 0.90 (randomized by first party domain) |
|
||||
| AudioContext | 17.55 | 1.39 (randomized by first party domain) |
|
||||
| Touch support | 9.69 | 0.99 |
|
||||
| Platform | 9.71 | 2.42 |
|
||||
| WebGL vendor & renderer | 7.56 ("None") | 3.63 ("Mozilla~Mozilla") |
|
||||
| HTTP Accept headers | 5.93 | 4.06 |
|
||||
| Screen size and colour depth | 5.77 | 4.98 |
|
||||
| Hardware concurrency | 2.10 | 2.00 |
|
||||
| Unchanged | UA 5.68, time zone 5.02 + 4.69, supercookies 8.3, plugins 2.93, fonts 3.77, WebGL hash 3.59 ("randomized" even off), DNT 2.02, language 0.91 | same |
|
||||
|
||||
Sum of the per-metric bits: about 124 off, 58 on.
|
||||
|
|
@ -2451,6 +2451,8 @@ impl App {
|
|||
}
|
||||
let scripts_changed = old.privacy.mode != new.privacy.mode
|
||||
|| old.privacy.mode_incognito != new.privacy.mode_incognito
|
||||
|| old.privacy.mode_off != new.privacy.mode_off
|
||||
|| old.privacy.block_third_party != new.privacy.block_third_party
|
||||
|| old.privacy.dnt != new.privacy.dnt
|
||||
|| old.privacy.save_data != new.privacy.save_data
|
||||
|| old.privacy.google_signin != new.privacy.google_signin
|
||||
|
|
@ -2478,6 +2480,8 @@ impl App {
|
|||
servo.set_preference("user_agent", servo::PrefValue::Str(ua.clone()));
|
||||
*self.shared.user_agent.borrow_mut() = ua.clone();
|
||||
crate::net::fetch::set_user_agent(&ua);
|
||||
// Privacy mode's navigator values follow the user agent.
|
||||
self.install_page_scripts();
|
||||
}
|
||||
if old.spell.langs != new.spell.langs || (!old.spell.enabled && new.spell.enabled) {
|
||||
self.load_speller();
|
||||
|
|
|
|||
23
src/app.rs
23
src/app.rs
|
|
@ -399,6 +399,19 @@ impl App {
|
|||
// Request headers and the cookie policy live in the vendored servo-net (S023).
|
||||
net::nacre::set_extra_request_headers(&crate::hub::privacy_headers(&settings));
|
||||
net::nacre::set_block_third_party_cookies(settings.privacy.block_third_party || self.privacy_mode_on(&settings));
|
||||
net::nacre::set_language_list(self.privacy_mode_on(&settings));
|
||||
}
|
||||
|
||||
/// What pages see as the screen and their window (`window.screen`, `outerWidth`, `screenX`): the monitor and
|
||||
/// window of the last focused, moved or resized window. Wayland doesn't tell windows where they are (0, 0).
|
||||
fn update_screen(&self, window_id: WindowId) {
|
||||
let Some(win) = self.windows.get(&window_id) else { return };
|
||||
let outer = win.window.outer_size();
|
||||
let pos = win.window.outer_position().unwrap_or_default();
|
||||
let monitor = win.window.current_monitor().map(|m| m.size()).filter(|s| s.width > 0 && s.height > 0).unwrap_or(outer);
|
||||
let size = servo::DeviceIntSize::new(monitor.width as i32, monitor.height as i32);
|
||||
let window_rect = servo::DeviceIntRect::from_origin_and_size(servo::DeviceIntPoint::new(pos.x, pos.y), servo::DeviceIntSize::new(outer.width as i32, outer.height as i32));
|
||||
*self.hub.screen.borrow_mut() = Some(servo::ScreenGeometry { size, available_size: size, window_rect });
|
||||
}
|
||||
|
||||
/// Privacy mode: on everywhere, or in incognito windows when the user chose that.
|
||||
|
|
@ -418,6 +431,10 @@ impl App {
|
|||
token: &self.hub.token,
|
||||
privacy_mode: privacy,
|
||||
seed: &self.shared.seed,
|
||||
user_agent: &self.shared.user_agent.borrow(),
|
||||
privacy_paused: &s.privacy.mode_off,
|
||||
languages: &net::nacre::languages(&net::nacre::locale()),
|
||||
block_third_party: s.privacy.block_third_party || privacy,
|
||||
dnt: s.privacy.dnt,
|
||||
force_dark: s.web.force_dark,
|
||||
smooth_scroll: s.web.smooth_scroll && !crate::perf::lite(&s),
|
||||
|
|
@ -1359,6 +1376,7 @@ impl App {
|
|||
self.start_servo();
|
||||
}
|
||||
self.windows.insert(id, win);
|
||||
self.update_screen(id);
|
||||
if kind == Kind::Normal {
|
||||
self.last_window = Some(id);
|
||||
}
|
||||
|
|
@ -1770,7 +1788,9 @@ impl ApplicationHandler<AppEvent> for App {
|
|||
WindowEvent::CloseRequested => {
|
||||
self.close_window(window_id);
|
||||
},
|
||||
WindowEvent::Moved(_) => self.update_screen(window_id),
|
||||
WindowEvent::Resized(size) => {
|
||||
self.update_screen(window_id);
|
||||
let pip = self.windows.get(&window_id).and_then(|w| if let Kind::Pip { window, tab } = w.kind { Some((window, tab)) } else { None });
|
||||
if let Some(win) = self.windows.get_mut(&window_id) {
|
||||
win.resized(*size);
|
||||
|
|
@ -1792,6 +1812,9 @@ impl ApplicationHandler<AppEvent> for App {
|
|||
self.redraw(window_id);
|
||||
},
|
||||
WindowEvent::Focused(focused) => {
|
||||
if *focused {
|
||||
self.update_screen(window_id);
|
||||
}
|
||||
if let Some(win) = self.windows.get_mut(&window_id) {
|
||||
win.focused = *focused;
|
||||
let _ = win.egui.on_window_event(&win.window, &event);
|
||||
|
|
|
|||
19
src/hub.rs
19
src/hub.rs
|
|
@ -117,6 +117,9 @@ pub struct Hub {
|
|||
/// Whether the Firefox user agent is in use (Google sign-in quirk).
|
||||
pub ua_quirk_on: RefCell<bool>,
|
||||
pub servo: RefCell<Option<servo::Servo>>,
|
||||
/// The screen and window for `window.screen` and `outerWidth`; the app keeps it current. Without it Servo
|
||||
/// reports a 0 x 0 screen.
|
||||
pub screen: RefCell<Option<servo::ScreenGeometry>>,
|
||||
}
|
||||
|
||||
/// Tracking parameters removed from links when "strip tracking parameters" is on.
|
||||
|
|
@ -171,6 +174,7 @@ impl Hub {
|
|||
net_log: RefCell::new(HashMap::new()),
|
||||
ua_quirk_on: RefCell::new(false),
|
||||
servo: RefCell::new(None),
|
||||
screen: RefCell::new(None),
|
||||
})
|
||||
}
|
||||
|
||||
|
|
@ -316,6 +320,10 @@ impl Hub {
|
|||
}
|
||||
|
||||
impl WebViewDelegate for Hub {
|
||||
fn screen_geometry(&self, _webview: WebView) -> Option<servo::ScreenGeometry> {
|
||||
*self.screen.borrow()
|
||||
}
|
||||
|
||||
fn notify_url_changed(&self, webview: WebView, url: Url) {
|
||||
// Covers pages shown without a request (history) and downloads that kept the old page.
|
||||
net::nacre::set_top_level_url(webview.id(), &servo::ServoUrl::from_url(url.clone()));
|
||||
|
|
@ -436,7 +444,16 @@ mod tests {
|
|||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn privacy_headers_follow_the_settings_and_reach_requests() {
|
||||
fn privacy_language_list_is_firefox_style() {
|
||||
assert_eq!(net::nacre::languages("en-US"), vec!["en-US", "en"]);
|
||||
assert_eq!(net::nacre::languages("pt-BR"), vec!["pt-BR", "pt"]);
|
||||
assert_eq!(net::nacre::languages("en"), vec!["en"]);
|
||||
assert_eq!(net::nacre::accept_language(&net::nacre::languages("en-US")), "en-US,en;q=0.5");
|
||||
assert_eq!(net::nacre::accept_language(&net::nacre::languages("de")), "de");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn privacy_headers_follow_the_settings_and_reach_requests() {
|
||||
let mut settings = Settings::default();
|
||||
settings.privacy.dnt = true;
|
||||
settings.privacy.save_data = false;
|
||||
|
|
|
|||
277
src/inject.rs
277
src/inject.rs
|
|
@ -8,7 +8,7 @@
|
|||
//! Servo injects user scripts into every document before the page's own scripts run. Settings
|
||||
//! that change them take effect on the next page load (Servo's rule for user content).
|
||||
|
||||
use serde::Deserialize;
|
||||
use serde::{Deserialize, Serialize};
|
||||
use serde_json::Value;
|
||||
|
||||
use crate::util;
|
||||
|
|
@ -33,6 +33,14 @@ pub struct Options<'a> {
|
|||
pub token: &'a str,
|
||||
pub privacy_mode: bool,
|
||||
pub seed: &'a str,
|
||||
/// The user agent pages see, for privacy mode's matching `navigator` values.
|
||||
pub user_agent: &'a str,
|
||||
/// Sites where privacy mode is paused.
|
||||
pub privacy_paused: &'a [String],
|
||||
/// `navigator.languages` in privacy mode, matching its Accept-Language (`net::nacre::languages`).
|
||||
pub languages: &'a [String],
|
||||
/// Third-party cookies are blocked (the setting or privacy mode): `document.cookie` in cross-site frames too.
|
||||
pub block_third_party: bool,
|
||||
pub dnt: bool,
|
||||
pub force_dark: bool,
|
||||
pub smooth_scroll: bool,
|
||||
|
|
@ -51,12 +59,15 @@ pub struct Options<'a> {
|
|||
/// Nacre's own scripts run inside one closure with the private `__send`, so pages can call the
|
||||
/// functions on `window.__nacre` (find, media controls, ...) but can never send a message as Nacre.
|
||||
pub fn page_scripts(o: &Options) -> Vec<String> {
|
||||
let mut modules: Vec<String> = vec![MEDIA_JS.to_owned(), FIND_JS.to_owned(), PIP_JS.to_owned(), META_JS.to_owned(), SVG_COLOR_JS.to_owned()];
|
||||
let mut modules: Vec<String> = vec![MEDIA_JS.to_owned(), FIND_JS.to_owned(), PIP_JS.to_owned(), META_JS.to_owned(), SVG_COLOR_JS.to_owned(), FONTS_CHECK_JS.to_owned(), COMPRESSOR_JS.to_owned()];
|
||||
if o.dnt {
|
||||
modules.push(DNT_JS.to_owned());
|
||||
}
|
||||
if o.privacy_mode {
|
||||
modules.push(PRIVACY_JS.replace("__SEED__", &util::js_string(o.seed)));
|
||||
modules.push(privacy_script(o.seed, o.user_agent, o.languages, o.privacy_paused));
|
||||
}
|
||||
if o.block_third_party {
|
||||
modules.push(FRAME_COOKIE_JS.to_owned());
|
||||
}
|
||||
if o.force_dark {
|
||||
modules.push(FORCE_DARK_JS.to_owned());
|
||||
|
|
@ -339,38 +350,200 @@ const DNT_JS: &str = r#"(() => { try {
|
|||
} catch (e) {} })();"#;
|
||||
|
||||
/// Privacy mode: fingerprint noise seeded per site and per run, common values for the rest.
|
||||
const PRIVACY_JS: &str = r#"(() => { if (window.__nacrePriv) return; window.__nacrePriv = 1;
|
||||
const SEED = __SEED__ + location.hostname;
|
||||
let h = 2166136261; for (let i = 0; i < SEED.length; i++) { h ^= SEED.charCodeAt(i); h = Math.imul(h, 16777619); }
|
||||
const rnd = () => { h ^= h << 13; h ^= h >>> 17; h ^= h << 5; return ((h >>> 0) % 1000) / 1000; };
|
||||
const def = (o, k, v) => { try { Object.defineProperty(o, k, { get: () => v, configurable: true }); } catch (e) {} };
|
||||
def(Navigator.prototype, 'hardwareConcurrency', 8);
|
||||
def(Navigator.prototype, 'deviceMemory', 8);
|
||||
const round = (v, step) => Math.ceil(v / step) * step;
|
||||
try { const s = screen; const w = round(s.width, 200), hgt = round(s.height, 100);
|
||||
def(Screen.prototype, 'width', w); def(Screen.prototype, 'height', hgt);
|
||||
def(Screen.prototype, 'availWidth', w); def(Screen.prototype, 'availHeight', hgt);
|
||||
def(Screen.prototype, 'colorDepth', 24); def(Screen.prototype, 'pixelDepth', 24); } catch (e) {}
|
||||
// Canvas: flip the lowest bit of a few pixels, the same pixels every time on this site.
|
||||
const noise = (ctx, w, hh) => { try { if (!w || !hh) return; const img = ctx.getImageData(0, 0, w, hh);
|
||||
for (let i = 0; i < 12; i++) { const p = Math.floor(rnd() * w * hh) * 4; img.data[p] ^= 1; img.data[p + 1] ^= 1; }
|
||||
ctx.putImageData(img, 0, 0); } catch (e) {} };
|
||||
const toURL = HTMLCanvasElement.prototype.toDataURL;
|
||||
HTMLCanvasElement.prototype.toDataURL = function () { const c = this.getContext && this.getContext('2d');
|
||||
if (c) noise(c, this.width, this.height); return toURL.apply(this, arguments); };
|
||||
const toBlob = HTMLCanvasElement.prototype.toBlob;
|
||||
if (toBlob) HTMLCanvasElement.prototype.toBlob = function () { const c = this.getContext && this.getContext('2d');
|
||||
if (c) noise(c, this.width, this.height); return toBlob.apply(this, arguments); };
|
||||
const gid = CanvasRenderingContext2D.prototype.getImageData;
|
||||
CanvasRenderingContext2D.prototype.getImageData = function () { const d = gid.apply(this, arguments);
|
||||
for (let i = 0; i < Math.min(8, d.data.length / 4); i++) { const p = Math.floor(rnd() * d.data.length / 4) * 4; d.data[p] ^= 1; } return d; };
|
||||
for (const G of [window.WebGLRenderingContext, window.WebGL2RenderingContext]) { if (!G) continue;
|
||||
const gp = G.prototype.getParameter;
|
||||
G.prototype.getParameter = function (p) { if (p === 37445) return 'Intel Inc.'; if (p === 37446) return 'Intel Iris OpenGL Engine';
|
||||
return gp.apply(this, arguments); }; }
|
||||
try { const gc = AudioBuffer.prototype.getChannelData;
|
||||
AudioBuffer.prototype.getChannelData = function () { const d = gc.apply(this, arguments);
|
||||
for (let i = 0; i < d.length; i += 100) d[i] += (rnd() - 0.5) * 1e-7; return d; }; } catch (e) {}
|
||||
/// What `navigator` reports about the system in Firefox with this user agent. Servo answers "Linux" and "4.0",
|
||||
/// which no Firefox does, so privacy mode makes them agree with the user agent.
|
||||
#[derive(Debug, PartialEq, Serialize)]
|
||||
pub struct FirefoxNavigator {
|
||||
pub platform: String,
|
||||
pub oscpu: String,
|
||||
#[serde(rename = "appVersion")]
|
||||
pub app_version: String,
|
||||
}
|
||||
|
||||
/// `None` for a user agent that isn't Firefox on Windows, macOS or Linux (then Servo's own values stay).
|
||||
pub fn firefox_navigator(ua: &str) -> Option<FirefoxNavigator> {
|
||||
if !ua.contains("Firefox/") {
|
||||
return None;
|
||||
}
|
||||
// "Mozilla/5.0 (X11; Linux x86_64; rv:153.0) ..." -> "X11; Linux x86_64"
|
||||
let inside = ua.split_once('(')?.1.split_once(')')?.0;
|
||||
let os = inside.split("; ").filter(|part| !part.starts_with("rv:")).collect::<Vec<_>>().join("; ");
|
||||
let (platform, oscpu, app) = if os.starts_with("Windows") {
|
||||
("Win32".to_owned(), os.clone(), "Windows")
|
||||
} else if let Some(mac) = os.strip_prefix("Macintosh; ") {
|
||||
("MacIntel".to_owned(), mac.to_owned(), "Macintosh")
|
||||
} else if let Some(linux) = os.strip_prefix("X11; ").filter(|rest| rest.starts_with("Linux") || rest.starts_with("Ubuntu")) {
|
||||
let linux = linux.rsplit("; ").next().unwrap_or(linux).to_owned();
|
||||
(linux.clone(), linux, "X11")
|
||||
} else {
|
||||
return None;
|
||||
};
|
||||
Some(FirefoxNavigator { platform, oscpu, app_version: format!("5.0 ({app})") })
|
||||
}
|
||||
|
||||
/// Privacy mode's page script for this run's seed, user agent, language list and paused sites.
|
||||
pub fn privacy_script(seed: &str, user_agent: &str, languages: &[String], paused: &[String]) -> String {
|
||||
let nav = firefox_navigator(user_agent).map(|n| serde_json::to_string(&n).unwrap_or_default()).unwrap_or_else(|| "null".to_owned());
|
||||
PRIVACY_JS
|
||||
.replace("__SEED__", &util::js_string(seed))
|
||||
.replace("__NAV__", &nav)
|
||||
.replace("__LANGS__", &serde_json::to_string(languages).unwrap_or_else(|_| "[]".to_owned()))
|
||||
.replace("__PAUSED__", &serde_json::to_string(paused).unwrap_or_else(|_| "[]".to_owned()))
|
||||
}
|
||||
|
||||
/// Privacy mode: hide the browser's fingerprint (what coveryourtracks.eff.org measures), after the original
|
||||
/// Nacre's privacy.py. Brave-style noise plus common values:
|
||||
/// - canvas, WebGL pixels, audio and canvas text widths get tiny noise seeded per top-level site and per run,
|
||||
/// so values differ on every site and after every restart but stay stable inside one site;
|
||||
/// - text-width noise makes every font in a probe list measure as "installed", the same for every user;
|
||||
/// - WebGL vendor/renderer say "Mozilla" (as Firefox does) instead of "Mozilla/Servo";
|
||||
/// - screen size is the smallest common size that holds the window, colour depth 24, position 0,0;
|
||||
/// - CPU cores read 8; platform, oscpu and appVersion match the user agent (`firefox_navigator`);
|
||||
/// - WEBGL_debug_renderer_info exists (answering "Mozilla"); no touch points and `createEvent('TouchEvent')`
|
||||
/// fails, as in desktop Firefox;
|
||||
/// - `navigator.languages` is Firefox's list for the locale, the same as Accept-Language (`net::nacre`).
|
||||
/// Not changed: time zone and locale (real, and consistent with each other: Servo reads both from the system),
|
||||
/// the user agent itself, DOM-measured fonts, web workers. Paused sites (and every frame on their pages) keep
|
||||
/// the engine's values except the language list. Same-origin frames made by script get the same treatment through
|
||||
/// `contentWindow`, as Servo only injects scripts into documents it parses.
|
||||
const PRIVACY_JS: &str = r#"(() => {
|
||||
if (location.protocol === 'nacre:' || window.__nacrePriv) return;
|
||||
const SEED = __SEED__, NAV = __NAV__, LANGS = __LANGS__, PAUSED = __PAUSED__;
|
||||
const matches = (h, d) => { h = h.replace(/^www\./, ''); d = d.replace(/^www\./, ''); return !!d && (h === d || h.endsWith('.' + d)); };
|
||||
// The top-level page's host: readable when same-origin, else from the referrer (the frame's parent page).
|
||||
let top = ''; try { top = window.top.location.hostname; } catch (e) { try { top = new URL(document.referrer).hostname; } catch (e2) {} }
|
||||
const host = top || location.hostname;
|
||||
// Paused sites keep the engine's values, except the language list: it has to match Accept-Language, which is
|
||||
// the same for every request.
|
||||
const paused = PAUSED.some(d => matches(host, d));
|
||||
const site = /^[\d.]+$|:/.test(host) ? host : host.split('.').slice(-2).join('.');
|
||||
let H = 2166136261;
|
||||
for (const c of SEED + '|' + site) { H ^= c.charCodeAt(0); H = Math.imul(H, 16777619); }
|
||||
const hash = i => { let x = (H ^ Math.imul(i + 1, 0x9E3779B1)) >>> 0;
|
||||
x ^= x >>> 16; x = Math.imul(x, 0x85EBCA6B); x ^= x >>> 13; x = Math.imul(x, 0xC2B2AE35); return (x ^ (x >>> 16)) >>> 0; };
|
||||
const hashText = t => { let x = H; for (let i = 0; i < t.length; i++) { x ^= t.charCodeAt(i); x = Math.imul(x, 16777619); } return hash(x >>> 0); };
|
||||
const natives = new WeakMap();
|
||||
function install(W) {
|
||||
if (!W || W.__nacrePriv) return; try { Object.defineProperty(W, '__nacrePriv', { value: true }); } catch (e) { return; }
|
||||
if (LANGS.length) try { const list = Object.freeze(LANGS.slice());
|
||||
Object.defineProperty(W.Navigator.prototype, 'languages', { get: () => list, configurable: true, enumerable: true }); } catch (e) {}
|
||||
if (paused) return;
|
||||
// Replaced functions still print as native code.
|
||||
const fnToString = W.Function.prototype.toString;
|
||||
const toStr = function toString() { return natives.has(this) ? natives.get(this) : fnToString.call(this); };
|
||||
natives.set(toStr, 'function toString() {\n [native code]\n}');
|
||||
W.Function.prototype.toString = toStr;
|
||||
const native = (f, name) => { natives.set(f, `function ${name}() {\n [native code]\n}`); return f; };
|
||||
const wrap = (obj, name, make) => { const d = obj && Object.getOwnPropertyDescriptor(obj, name);
|
||||
if (!d || typeof d.value !== 'function') return; const orig = d.value, f = make(orig);
|
||||
Object.defineProperty(f, 'name', { value: name }); Object.defineProperty(f, 'length', { value: orig.length });
|
||||
d.value = native(f, name); Object.defineProperty(obj, name, d); };
|
||||
// A getter that replaces the native one, or a new one where the engine has none (Firefox has oscpu).
|
||||
const getter = (obj, name, fn) => { if (!obj) return; const d = Object.getOwnPropertyDescriptor(obj, name) || { configurable: true, enumerable: true };
|
||||
if (d.value !== undefined || d.configurable === false) return; const orig = d.get;
|
||||
d.get = native({ [`get ${name}`]() { return fn.call(this, orig); } }[`get ${name}`], `get ${name}`);
|
||||
Object.defineProperty(obj, name, d); };
|
||||
// Pixels: flip the low bits of ~1 in 40 colour values, chosen by the site hash (same picture -> same output).
|
||||
const noisePixels = data => { for (let i = 0; i < data.length; i++) {
|
||||
if ((i & 3) !== 3) { const r = hash(i); if (r % 40 === 0) data[i] ^= 1 + ((r >>> 8) & 1); } } };
|
||||
const CR = W.CanvasRenderingContext2D && W.CanvasRenderingContext2D.prototype;
|
||||
const getImageData = CR && CR.getImageData;
|
||||
wrap(CR, 'getImageData', orig => function () { const d = orig.apply(this, arguments); noisePixels(d.data); return d; });
|
||||
// Text widths: a few millionths of a pixel per font and text, so font probes find every font "installed".
|
||||
wrap(CR, 'measureText', orig => function (text) { const m = orig.apply(this, arguments);
|
||||
try { const w = m.width + ((hashText(this.font + '|' + text) % 2001) - 1000) * 1e-6;
|
||||
Object.defineProperty(m, 'width', { value: w, enumerable: true }); } catch (e) {} return m; });
|
||||
const noisyCopy = canvas => { const w = canvas.width, h = canvas.height; if (!w || !h) return null;
|
||||
const c = W.document.createElement('canvas'); c.width = w; c.height = h;
|
||||
const x = c.getContext('2d'); x.drawImage(canvas, 0, 0); const d = getImageData.call(x, 0, 0, w, h);
|
||||
noisePixels(d.data); x.putImageData(d, 0, 0); return c; };
|
||||
const CP = W.HTMLCanvasElement && W.HTMLCanvasElement.prototype;
|
||||
for (const m of ['toDataURL', 'toBlob']) wrap(CP, m, orig => function () {
|
||||
let c = null; try { c = noisyCopy(this); } catch (e) {} return orig.apply(c || this, arguments); });
|
||||
for (const P of [W.WebGLRenderingContext, W.WebGL2RenderingContext]) { if (!P) continue;
|
||||
wrap(P.prototype, 'getParameter', orig => function (p) {
|
||||
if (p === 0x1F00 || p === 0x1F01 || p === 0x9245 || p === 0x9246) return 'Mozilla'; return orig.apply(this, arguments); });
|
||||
wrap(P.prototype, 'readPixels', orig => function () { const r = orig.apply(this, arguments);
|
||||
const a = arguments[6]; if (a && a.length) noisePixels(a); return r; });
|
||||
// Servo has no WEBGL_debug_renderer_info; Firefox has it and answers "Mozilla" (getParameter above).
|
||||
const DEBUG = 'WEBGL_debug_renderer_info', info = Object.freeze({ UNMASKED_VENDOR_WEBGL: 0x9245, UNMASKED_RENDERER_WEBGL: 0x9246 });
|
||||
wrap(P.prototype, 'getExtension', orig => function (name) { const r = orig.apply(this, arguments); return r || name !== DEBUG ? r : info; });
|
||||
wrap(P.prototype, 'getSupportedExtensions', orig => function () { const r = orig.apply(this, arguments);
|
||||
return r && !r.includes(DEBUG) ? r.concat([DEBUG]) : r; }); }
|
||||
// Audio: tiny deterministic noise once per buffer.
|
||||
const seen = new WeakSet();
|
||||
wrap(W.AudioBuffer && W.AudioBuffer.prototype, 'getChannelData', orig => function () { const d = orig.apply(this, arguments);
|
||||
if (!seen.has(d)) { seen.add(d); for (let i = 0; i < d.length; i += 97) d[i] += ((hash(i) % 1000) - 500) * 1e-9; }
|
||||
return d; });
|
||||
wrap(W.AnalyserNode && W.AnalyserNode.prototype, 'getFloatFrequencyData', orig => function (a) { orig.apply(this, arguments);
|
||||
for (let i = 0; i < a.length; i++) a[i] += ((hash(i) % 100) - 50) * 1e-5; });
|
||||
// Screen: the smallest common size that holds the browser window (the top window's, in frames too).
|
||||
const SIZES = [[1366, 768], [1536, 864], [1920, 1080], [2560, 1440], [3840, 2160]];
|
||||
const size = () => { const w = W.outerWidth || W.innerWidth || 1366, h = W.outerHeight || W.innerHeight || 768;
|
||||
return SIZES.find(s => s[0] >= w && s[1] >= h) || SIZES[SIZES.length - 1]; };
|
||||
const SP = W.Screen && W.Screen.prototype;
|
||||
getter(SP, 'width', () => size()[0]); getter(SP, 'height', () => size()[1]);
|
||||
getter(SP, 'availWidth', () => size()[0]); getter(SP, 'availHeight', () => size()[1]);
|
||||
getter(SP, 'availLeft', () => 0); getter(SP, 'availTop', () => 0);
|
||||
getter(SP, 'colorDepth', () => 24); getter(SP, 'pixelDepth', () => 24);
|
||||
// Window position: Servo keeps Window's attributes on the window itself or its prototype.
|
||||
for (const k of ['screenX', 'screenY', 'screenLeft', 'screenTop'])
|
||||
getter(Object.getOwnPropertyDescriptor(W, k) ? W : W.Window && W.Window.prototype, k, () => 0);
|
||||
const NP = W.Navigator && W.Navigator.prototype;
|
||||
getter(NP, 'hardwareConcurrency', () => 8);
|
||||
// Desktop Firefox: no touch points, and touch events can't be created (Servo has touch events but no
|
||||
// maxTouchPoints, a rare combination). The TouchEvent globals stay: removing them breaks pages (Wikipedia's
|
||||
// search field, media documents).
|
||||
getter(NP, 'maxTouchPoints', () => 0);
|
||||
wrap(W.Document && W.Document.prototype, 'createEvent', orig => function (type) {
|
||||
if (/^touchevents?$/i.test(String(type))) throw new W.DOMException('Unsupported event type', 'NotSupportedError');
|
||||
return orig.apply(this, arguments); });
|
||||
if (NAV) { getter(NP, 'platform', () => NAV.platform); getter(NP, 'oscpu', () => NAV.oscpu); getter(NP, 'appVersion', () => NAV.appVersion); }
|
||||
// Same-origin frames made by script never get injected scripts: cover them when the page reaches in.
|
||||
for (const [P, prop] of [[W.HTMLIFrameElement, 'contentWindow'], [W.HTMLIFrameElement, 'contentDocument'], [W.HTMLFrameElement, 'contentWindow']])
|
||||
getter(P && P.prototype, prop, function (orig) { const r = orig.call(this);
|
||||
try { install(prop === 'contentDocument' ? r && r.defaultView : r); } catch (e) {} return r; });
|
||||
}
|
||||
install(window);
|
||||
})();"#;
|
||||
|
||||
/// Servo 0.7's `document.fonts` has no `check()`, and scripts that call it stop there (Cover Your Tracks never
|
||||
/// sends its fingerprint). Per the spec: false only when a face of a named family is in the set and not loaded yet.
|
||||
const FONTS_CHECK_JS: &str = r#"(() => { const P = window.FontFaceSet && FontFaceSet.prototype; if (!P || P.check) return;
|
||||
Object.defineProperty(P, 'check', { configurable: true, writable: true, value: function check(font) {
|
||||
const m = /(?:^|\s)[\d.]+(?:px|pt|em|rem|%)(?:\s*\/\s*\S+)?\s+(.+)$/.exec(String(font));
|
||||
if (!m) throw new DOMException('Invalid font', 'SyntaxError');
|
||||
const names = m[1].split(',').map(f => f.trim().replace(/^["']|["']$/g, '').toLowerCase());
|
||||
let ok = true;
|
||||
try { this.forEach(face => { if (names.includes(face.family.replace(/^["']|["']$/g, '').toLowerCase()) && face.status !== 'loaded') ok = false; }); } catch (e) {}
|
||||
return ok; } });
|
||||
})();"#;
|
||||
|
||||
/// Servo 0.7 has no DynamicsCompressorNode; audio fingerprint scripts (Fingerprint2, Cover Your Tracks) and some
|
||||
/// players throw at `createDynamicsCompressor`. This stand-in passes the sound through unchanged: a GainNode with
|
||||
/// the compressor's parameters (real AudioParams, so automation calls work) and `reduction` 0.
|
||||
const COMPRESSOR_JS: &str = r#"(() => { const B = window.BaseAudioContext || window.AudioContext; const P = B && B.prototype;
|
||||
if (!P || P.createDynamicsCompressor || !P.createGain) return;
|
||||
const PARAMS = { threshold: -24, knee: 30, ratio: 12, attack: 0.003, release: 0.25 };
|
||||
Object.defineProperty(P, 'createDynamicsCompressor', { configurable: true, writable: true, value: function createDynamicsCompressor() {
|
||||
const node = this.createGain();
|
||||
for (const [k, v] of Object.entries(PARAMS)) { const param = this.createGain().gain; param.value = v; Object.defineProperty(node, k, { value: param, enumerable: true }); }
|
||||
Object.defineProperty(node, 'reduction', { value: 0, enumerable: true });
|
||||
return node; } });
|
||||
})();"#;
|
||||
|
||||
/// Third-party cookie blocking for scripts: servo-net blocks the cookies of cross-site requests (S023), but a
|
||||
/// cross-site frame's `document.cookie` goes through the script thread, which doesn't say which page it is on.
|
||||
/// A frame whose top page is another site gets an empty, write-only-to-nowhere `document.cookie`. The top page
|
||||
/// is known when same-origin, else from the referrer; with neither, the frame counts as cross-site.
|
||||
const FRAME_COOKIE_JS: &str = r#"(() => { if (window.top === window || !location.hostname) return;
|
||||
let top = null; try { top = window.top.location.hostname; } catch (e) {}
|
||||
if (top === null) { try { top = new URL(document.referrer).hostname; } catch (e) { top = ''; } }
|
||||
const site = h => /^[\d.]+$|:/.test(h) ? h : h.split('.').slice(-2).join('.');
|
||||
if (top && site(top) === site(location.hostname)) return;
|
||||
const d = Object.getOwnPropertyDescriptor(Document.prototype, 'cookie'); if (!d || !d.configurable) return;
|
||||
Object.defineProperty(Document.prototype, 'cookie', { get() { return ''; }, set(v) {}, configurable: true, enumerable: d.enumerable });
|
||||
try { if ('cookieStore' in window) Object.defineProperty(window, 'cookieStore', { value: undefined }); } catch (e) {}
|
||||
})();"#;
|
||||
|
||||
/// Dark pages for sites that have no dark style of their own.
|
||||
|
|
@ -581,6 +754,40 @@ mod tests {
|
|||
assert_eq!(mainstream_ua(&ua), ua);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn navigator_values_match_the_user_agent() {
|
||||
let linux = firefox_navigator("Mozilla/5.0 (X11; Linux x86_64; rv:153.0) Gecko/20100101 Firefox/153.0").unwrap();
|
||||
assert_eq!(linux, FirefoxNavigator { platform: "Linux x86_64".into(), oscpu: "Linux x86_64".into(), app_version: "5.0 (X11)".into() });
|
||||
let ubuntu = firefox_navigator("Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:140.0) Gecko/20100101 Firefox/140.0").unwrap();
|
||||
assert_eq!(ubuntu.platform, "Linux x86_64");
|
||||
let windows = firefox_navigator("Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:153.0) Gecko/20100101 Firefox/153.0").unwrap();
|
||||
assert_eq!(windows, FirefoxNavigator { platform: "Win32".into(), oscpu: "Windows NT 10.0; Win64; x64".into(), app_version: "5.0 (Windows)".into() });
|
||||
let mac = firefox_navigator("Mozilla/5.0 (Macintosh; Intel Mac OS X 10.15; rv:153.0) Gecko/20100101 Firefox/153.0").unwrap();
|
||||
assert_eq!(mac, FirefoxNavigator { platform: "MacIntel".into(), oscpu: "Intel Mac OS X 10.15".into(), app_version: "5.0 (Macintosh)".into() });
|
||||
// Not Firefox, or an OS Firefox's form isn't known for: Servo's values stay.
|
||||
assert!(firefox_navigator("Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/140.0 Safari/537.36").is_none());
|
||||
assert!(firefox_navigator("Mozilla/5.0 (Android 14; Mobile; rv:140.0) Gecko/140.0 Firefox/140.0").is_none());
|
||||
// The script gets the default user agent's values (consistency with what Nacre sends).
|
||||
let ua = mainstream_ua("Mozilla/5.0 (X11; Linux x86_64; rv:153.0) Servo/0.7.0 Firefox/153.0");
|
||||
assert_eq!(firefox_navigator(&ua).unwrap().app_version, "5.0 (X11)");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn privacy_script_fills_every_value() {
|
||||
let paused = vec!["example.com".to_owned(), "a\"b".to_owned()];
|
||||
let langs = vec!["en-US".to_owned(), "en".to_owned()];
|
||||
let js = privacy_script("se\"ed", "Mozilla/5.0 (X11; Linux x86_64; rv:153.0) Gecko/20100101 Firefox/153.0", &langs, &paused);
|
||||
assert!(!js.contains("__SEED__") && !js.contains("__NAV__") && !js.contains("__LANGS__") && !js.contains("__PAUSED__"));
|
||||
assert!(js.contains(r#"const SEED = "se\"ed", NAV = {"platform":"Linux x86_64","oscpu":"Linux x86_64","appVersion":"5.0 (X11)"}, LANGS = ["en-US","en"], PAUSED = ["example.com","a\"b"];"#));
|
||||
assert!(privacy_script("s", "Custom agent", &[], &[]).contains("NAV = null, LANGS = [], PAUSED = [];"));
|
||||
// Off by default; cookie-blocking module only with blocking on.
|
||||
let mut o = Options { token: "t", privacy_mode: false, seed: "s", user_agent: "", privacy_paused: &[], languages: &[], block_third_party: false, dnt: false, force_dark: false, smooth_scroll: false, preload: false, save_data: false, cosmetic: false, animate_removal: false, youtube_ads: false, autofill: false, spell: false, google_signin: false };
|
||||
assert!(!page_scripts(&o)[0].contains("__nacrePriv") && !page_scripts(&o)[0].contains("'cookie'"));
|
||||
o.privacy_mode = true;
|
||||
o.block_third_party = true;
|
||||
assert!(page_scripts(&o)[0].contains("__nacrePriv") && page_scripts(&o)[0].contains("'cookie'"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn messages() {
|
||||
let m = parse_message("abc", r#"abc{"t":"media","d":{"title":"x"}}"#).unwrap();
|
||||
|
|
|
|||
|
|
@ -28,6 +28,7 @@
|
|||
//! install_script <url> (a .user.js / .user.css), open_app [id] (default: the first installed app),
|
||||
//! navigate <typed text>, mute, pin
|
||||
//! js <script> run JavaScript in the current tab; the result goes to the log
|
||||
//! save <name> <js> run JavaScript in the current tab and write its string result to <name>.json
|
||||
//! assert <js expression> the expression must give true, else `ASSERT FAILED` in the log fails the smoke run
|
||||
//! expect <pointer> <json> a value of the `status` JSON must equal json (e.g. `expect /tabs/1/pinned true`;
|
||||
//! `/active/...` is the active tab, `/tab_count` the number of tabs; `> n` a number above n)
|
||||
|
|
@ -438,6 +439,27 @@ impl App {
|
|||
}
|
||||
});
|
||||
},
|
||||
"save" => {
|
||||
let (name, script) = rest.split_once(' ').unwrap_or((rest, "null"));
|
||||
let Some(web) = self.windows.get(&window).and_then(|w| w.active_webview()).cloned() else {
|
||||
self.selftest_log(&format!("ASSERT FAILED (no page): save {name}"));
|
||||
return;
|
||||
};
|
||||
let (log_path, out) = (dir.join("selftest.log"), dir.join(format!("{name}.json")));
|
||||
web.evaluate_javascript(script.to_owned(), move |result| {
|
||||
use std::io::Write as _;
|
||||
let line = match result {
|
||||
Ok(servo::JSValue::String(text)) => match std::fs::write(&out, text) {
|
||||
Ok(()) => format!("saved {}", out.display()),
|
||||
Err(error) => format!("ASSERT FAILED (save): {error}"),
|
||||
},
|
||||
other => format!("ASSERT FAILED (save gave {other:?})"),
|
||||
};
|
||||
if let Ok(mut f) = std::fs::OpenOptions::new().create(true).append(true).open(&log_path) {
|
||||
let _ = writeln!(f, "{line}");
|
||||
}
|
||||
});
|
||||
},
|
||||
"pagescroll" => {
|
||||
// Turn the wheel over the page at x,y (page pixels, as `click`) by dy pixels, through `window_input`.
|
||||
let mut parts = rest.split_whitespace().filter_map(|p| p.parse::<f64>().ok());
|
||||
|
|
|
|||
|
|
@ -231,6 +231,8 @@ pub struct Privacy {
|
|||
/// Privacy mode: fingerprint noise and tracking cuts.
|
||||
pub mode: bool,
|
||||
pub mode_incognito: bool,
|
||||
/// Sites where privacy mode's fingerprint protection is paused (it breaks something there).
|
||||
pub mode_off: Vec<String>,
|
||||
pub block_third_party: bool,
|
||||
pub strip_params: bool,
|
||||
pub https_only: bool,
|
||||
|
|
@ -253,6 +255,7 @@ impl Default for Privacy {
|
|||
dnt: true,
|
||||
mode: false,
|
||||
mode_incognito: true,
|
||||
mode_off: Vec::new(),
|
||||
block_third_party: true,
|
||||
strip_params: true,
|
||||
https_only: false,
|
||||
|
|
@ -607,6 +610,10 @@ impl Settings {
|
|||
self.adblock.allow.iter().any(|h| util::host_matches(host, h))
|
||||
}
|
||||
|
||||
pub fn privacy_paused_on(&self, host: &str) -> bool {
|
||||
self.privacy.mode_off.iter().any(|h| util::host_matches(host, h))
|
||||
}
|
||||
|
||||
pub fn keeps_active(&self, host: &str) -> bool {
|
||||
self.perf.keep_active.iter().any(|h| util::host_matches(host, h))
|
||||
}
|
||||
|
|
|
|||
|
|
@ -853,7 +853,27 @@ fn shield_body(ui: &mut Ui, f: &mut Frame) {
|
|||
});
|
||||
let on = if incognito { &mut settings.privacy.mode_incognito } else { &mut settings.privacy.mode };
|
||||
line(ui, "Hide this browser's fingerprint", |ui| switch(ui, on));
|
||||
text(ui, if incognito { "Incognito windows: canvas, WebGL, screen and hardware details, from the next page load" } else { "Canvas, WebGL, screen and hardware details, from the next page load" }, true);
|
||||
let on = *on;
|
||||
if on && !host.is_empty() {
|
||||
let mut on_here = !settings.privacy_paused_on(&host);
|
||||
line(ui, &format!("On {}", util::ellipsize(&host, 30)), |ui| {
|
||||
if switch(ui, &mut on_here) {
|
||||
if on_here {
|
||||
settings.privacy.mode_off.retain(|h| !util::host_matches(&host, h));
|
||||
} else {
|
||||
settings.privacy.mode_off.push(host.clone());
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
let what = if on {
|
||||
"Canvas, WebGL, audio and fonts get noise; screen, CPU and system read common values; third-party cookies are blocked. Time zone and language stay real. From the next page load"
|
||||
} else if incognito {
|
||||
"Incognito windows: noise on canvas, WebGL, audio and fonts, common screen and hardware values, no third-party cookies"
|
||||
} else {
|
||||
"Noise on canvas, WebGL, audio and fonts, common screen and hardware values, no third-party cookies"
|
||||
};
|
||||
text(ui, what, true);
|
||||
ui.add_space(theme::GAP_S);
|
||||
divider(ui);
|
||||
|
||||
|
|
|
|||
|
|
@ -41,6 +41,7 @@ const SUBPAGES: &[(&str, &str, &str)] = &[
|
|||
("keys", "Keyboard shortcuts", "general"),
|
||||
("import", "Import from another browser", "general"),
|
||||
("newtab", "New tab page", "general"),
|
||||
("privacy_mode", "Privacy mode", "privacy"),
|
||||
("permissions", "Site permissions", "privacy"),
|
||||
("lists", "Filter lists", "adblock"),
|
||||
("managers", "Download managers", "downloads"),
|
||||
|
|
@ -261,6 +262,7 @@ fn section_keywords(key: &str) -> &'static str {
|
|||
"about" => "version update",
|
||||
"newtab" => "new tab page clock greeting weather background shortcuts customize",
|
||||
"keys" => "hotkeys keybindings",
|
||||
"privacy_mode" => "fingerprint canvas webgl audio fonts screen incognito cover your tracks",
|
||||
_ => "",
|
||||
}
|
||||
}
|
||||
|
|
@ -345,6 +347,7 @@ fn draw_section(ui: &mut Ui, f: &mut Frame, s: &mut Settings, key: &str) {
|
|||
"keys" => keys(ui, f, s),
|
||||
"import" => import(ui, f, s),
|
||||
"newtab" => newtab(ui, f, s),
|
||||
"privacy_mode" => privacy_mode(ui, f, s),
|
||||
"permissions" => permissions(ui, f, s),
|
||||
"lists" => lists(ui, f, s),
|
||||
"managers" => managers(ui, f, s),
|
||||
|
|
@ -751,8 +754,14 @@ fn privacy(ui: &mut Ui, f: &mut Frame, s: &mut Settings) {
|
|||
});
|
||||
section(ui, "Tracking and fingerprinting");
|
||||
card(ui, |ui| {
|
||||
row(ui, "Privacy mode", "Hides your browser's fingerprint (canvas, WebGL, screen and hardware details)", |ui| switch(ui, &mut s.privacy.mode));
|
||||
switch_row(ui, "Privacy mode in incognito windows", "", &mut s.privacy.mode_incognito);
|
||||
let state = match (s.privacy.mode, s.privacy.mode_incognito) {
|
||||
(true, _) => "On: fingerprint hidden, third-party cookies blocked",
|
||||
(false, true) => "On in incognito windows only",
|
||||
(false, false) => "Off: sites can fingerprint this browser",
|
||||
};
|
||||
if icon_link_row(ui, icons::FINGERPRINT, "Privacy mode", state) {
|
||||
open(f, "privacy_mode");
|
||||
}
|
||||
switch_row(ui, "Send Do Not Track and Global Privacy Control", "Asks every site not to sell or share your data (DNT and Sec-GPC headers)", &mut s.privacy.dnt);
|
||||
switch_row(ui, "Remove tracking parameters", "Strips utm_, fbclid, gclid and similar from links before they load", &mut s.privacy.strip_params);
|
||||
switch_row(ui, "Block third-party cookies", "Sites inside a page (ads, trackers) can't send or store cookies; always on in privacy mode", &mut s.privacy.block_third_party);
|
||||
|
|
@ -778,6 +787,34 @@ fn privacy(ui: &mut Ui, f: &mut Frame, s: &mut Settings) {
|
|||
});
|
||||
}
|
||||
|
||||
fn privacy_mode(ui: &mut Ui, f: &mut Frame, s: &mut Settings) {
|
||||
intro(ui, "Hides what makes this browser stand out from others, so sites can't recognise you without cookies. Applies from each page's next load.");
|
||||
card(ui, |ui| {
|
||||
icon_row(ui, icons::FINGERPRINT, "Use privacy mode", "Some canvas-based tools can look slightly different; pause it on a site from the shield menu", |ui| switch(ui, &mut s.privacy.mode));
|
||||
icon_row(ui, icons::DOMINO_MASK, "Always on in incognito windows", "Incognito windows use privacy mode even when it's off here", |ui| switch(ui, &mut s.privacy.mode_incognito));
|
||||
});
|
||||
section(ui, "What it hides");
|
||||
card(ui, |ui| {
|
||||
icon_row(ui, icons::PALETTE, "Canvas, WebGL and audio fingerprints", "Tiny noise, different on every site and after every restart, stable within a site", |_| {});
|
||||
icon_row(ui, icons::MEMORY, "Graphics, screen size and CPU", "Sites see common values: a common screen size, 8 cores, \"Mozilla\" graphics", |_| {});
|
||||
icon_row(ui, icons::TEXTURE, "Installed fonts", "Font probes on canvas see every font as installed", |_| {});
|
||||
icon_row(ui, icons::DEVICES, "System details", "Platform and version match the user agent, as in Firefox", |_| {});
|
||||
icon_row(ui, icons::COOKIE, "Third-party cookies", "Ads and trackers inside pages can't set or read cookies", |_| {});
|
||||
});
|
||||
section(ui, "Not hidden");
|
||||
card(ui, |ui| {
|
||||
icon_row(ui, icons::SCHEDULE, "Time zone and language", "Changing them breaks clocks, calendars and sites in your language; they stay consistent with each other", |_| {});
|
||||
icon_row(ui, icons::INFO, "Limits of the engine", "Fonts measured in the page layout, scripts in web workers, plugins list and the engine's own features (no WebRTC, no battery)", |_| {});
|
||||
});
|
||||
section(ui, "Sites");
|
||||
card(ui, |ui| {
|
||||
wide_row(ui, "Sites where privacy mode is paused", "", |ui| host_chips(ui, &mut s.privacy.mode_off, "Use privacy mode here again", "None"));
|
||||
if icon_row(ui, icons::OPEN_IN_NEW, "Check your fingerprint", "EFF's Cover Your Tracks test", |ui| button(ui, ButtonKind::Tonal, None, "Test it").clicked()) {
|
||||
f.send(Command::Open { url: "https://coveryourtracks.eff.org/".into(), how: crate::actions::Disposition::NewForegroundTab, from: None });
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
fn adblock(ui: &mut Ui, f: &mut Frame, s: &mut Settings) {
|
||||
section(ui, "Blocking");
|
||||
card(ui, |ui| {
|
||||
|
|
|
|||
28
tests/smoke/coveryourtracks.txt
Normal file
28
tests/smoke/coveryourtracks.txt
Normal file
|
|
@ -0,0 +1,28 @@
|
|||
# EFF's Cover Your Tracks with privacy mode off, then on (S024). Needs internet; direct connection only (VPN off,
|
||||
# smoke.sh drops proxy variables). Saves the fingerprint verdict and table as cyt-off.json / cyt-on.json and shots.
|
||||
# SMOKE_TIMEOUT=600 tools/smoke.sh tests/smoke/coveryourtracks.txt
|
||||
wait 3
|
||||
set /vpn/enabled false
|
||||
set /privacy/mode false
|
||||
wait 1
|
||||
open https://coveryourtracks.eff.org/
|
||||
waitload 60
|
||||
wait 3
|
||||
shot cyt-start
|
||||
js [...document.querySelectorAll("a,button,input")].find(e => /test your browser/i.test(e.innerText || e.value || "")).click(); 1
|
||||
waitfor 240 location.pathname.includes("results") && (document.getElementById("fingerprintTable") || { innerText: "" }).innerText.length > 100
|
||||
wait 5
|
||||
save cyt-off JSON.stringify({ url: location.href, status: document.getElementById("fp_status").innerText, table: document.getElementById("fingerprintTable").innerText })
|
||||
shot cyt-off
|
||||
set /privacy/mode true
|
||||
wait 1
|
||||
open https://coveryourtracks.eff.org/
|
||||
waitload 60
|
||||
wait 3
|
||||
js [...document.querySelectorAll("a,button,input")].find(e => /test your browser/i.test(e.innerText || e.value || "")).click(); 1
|
||||
waitfor 240 location.pathname.includes("results") && (document.getElementById("fingerprintTable") || { innerText: "" }).innerText.length > 100
|
||||
wait 5
|
||||
save cyt-on JSON.stringify({ url: location.href, status: document.getElementById("fp_status").innerText, table: document.getElementById("fingerprintTable").innerText })
|
||||
shot cyt-on
|
||||
status done
|
||||
quit
|
||||
|
|
@ -18,6 +18,8 @@ certificate for *.nacre.test. Port 8767 speaks plain HTTP only (an HTTPS upgrade
|
|||
/setcookie?name=N[&domain=D] sets cookie N=1 (Path=/, Domain=D if given); /cookies shows the Cookie header in
|
||||
the title; /pixel is a 1x1 GIF; /tp?tag=T is a page with a cross-site iframe and picture
|
||||
(127.0.0.1:8767) and a same-site picture (img.nacre.test:8766), titled "TP T done" when loaded
|
||||
/jstp?tag=T page with a cross-site frame (/jscookie) that writes and reads document.cookie and reports what
|
||||
it read as /note?tag=T&seen=... (S024)
|
||||
/reset empties the "reqs" list of /log
|
||||
/log JSON: every request path, DNS name asked, Range header and download manager call; "reqs" has
|
||||
each GET's host, path, Cookie, DNT, Sec-GPC and Save-Data headers (S023)
|
||||
|
|
@ -110,6 +112,15 @@ const one = () => { if (--left === 0) document.title = "TP TAG done"; };
|
|||
for (const e of [frame, cross, same]) { e.onload = one; e.onerror = one; }
|
||||
</script>"""
|
||||
|
||||
# document.cookie in a cross-site frame (S024): the frame on 127.0.0.1:8767 writes a cookie from script, reads
|
||||
# document.cookie and reports what it saw as /note?tag=T&seen=... (recorded in the request log).
|
||||
JSTP_PAGE = """<!doctype html><meta charset=utf-8><title>JSTP TAG</title>
|
||||
<iframe id=frame src="http://127.0.0.1:8767/jscookie?tag=TAG"></iframe>
|
||||
<script>frame.onload = () => setTimeout(() => { document.title = "JSTP TAG done"; }, 500);</script>"""
|
||||
JSCOOKIE_PAGE = """<!doctype html><meta charset=utf-8><title>JS cookie</title>
|
||||
<script>document.cookie = "jsTAG=1; Path=/";
|
||||
new Image().src = "/note?tag=TAG&seen=" + encodeURIComponent(document.cookie);</script>"""
|
||||
|
||||
GIF = bytes.fromhex("47494638396101000100800000ffffff00000021f90401000000002c00000000010001000002024401003b")
|
||||
|
||||
|
||||
|
|
@ -123,7 +134,7 @@ class Handler(BaseHTTPRequestHandler):
|
|||
if path != "/log":
|
||||
record("reqs", {"host": self.headers.get("Host", ""), "path": self.path, "cookie": self.headers.get("Cookie"),
|
||||
"dnt": self.headers.get("DNT"), "gpc": self.headers.get("Sec-GPC"),
|
||||
"savedata": self.headers.get("Save-Data")})
|
||||
"savedata": self.headers.get("Save-Data"), "lang": self.headers.get("Accept-Language")})
|
||||
if path == "/dns-query":
|
||||
import base64
|
||||
wire = parse_qs(url.query).get("dns", [""])[0]
|
||||
|
|
@ -154,6 +165,11 @@ class Handler(BaseHTTPRequestHandler):
|
|||
if path == "/tp":
|
||||
tag = parse_qs(url.query).get("tag", ["x"])[0]
|
||||
return self.reply(TP_PAGE.replace("TAG", tag).encode(), "text/html")
|
||||
if path in ("/jstp", "/jscookie"):
|
||||
tag = parse_qs(url.query).get("tag", ["x"])[0]
|
||||
return self.reply((JSTP_PAGE if path == "/jstp" else JSCOOKIE_PAGE).replace("TAG", tag).encode(), "text/html")
|
||||
if path == "/note":
|
||||
return self.reply(GIF, "image/gif")
|
||||
if path == "/ads.html":
|
||||
return self.reply(ADS_PAGE, "text/html")
|
||||
if path == "/ads/banner.js":
|
||||
|
|
|
|||
136
tests/smoke/pages/fingerprint.html
Normal file
136
tests/smoke/pages/fingerprint.html
Normal file
|
|
@ -0,0 +1,136 @@
|
|||
<!DOCTYPE html>
|
||||
<meta charset="utf-8">
|
||||
<title>Fingerprint</title>
|
||||
<!-- The fingerprint surfaces a page can read (S024), printed as JSON in #out and kept in window.fp.
|
||||
The same values are read in a same-origin frame from markup (srcdoc; file:// frames are cross-origin) and in a frame made by script
|
||||
(about:blank), so tests can check privacy mode covers frames too. Title becomes "FP done" when finished. -->
|
||||
<style>
|
||||
body { font: 13px monospace; margin: 12px; background: #fff; color: #111; }
|
||||
pre { white-space: pre-wrap; margin: 0; }
|
||||
iframe { width: 10px; height: 10px; border: 0; }
|
||||
</style>
|
||||
<pre id="out">reading…</pre>
|
||||
<iframe id="static" srcdoc="<!DOCTYPE html><title>frame</title><p>frame"></iframe>
|
||||
<script>
|
||||
// FNV-1a over a string, as hex.
|
||||
function hash(s) { let h = 2166136261; for (let i = 0; i < s.length; i++) { h ^= s.charCodeAt(i); h = Math.imul(h, 16777619); } return (h >>> 0).toString(16); }
|
||||
|
||||
// Everything that is read synchronously, from a window `W` (this one or a frame's).
|
||||
function basics(W) {
|
||||
const N = W.navigator, S = W.screen, out = {};
|
||||
const get = (k, f) => { try { out[k] = f(); } catch (e) { out[k] = 'error: ' + e.message; } };
|
||||
get('userAgent', () => N.userAgent);
|
||||
get('appVersion', () => N.appVersion);
|
||||
get('platform', () => N.platform);
|
||||
get('vendor', () => N.vendor);
|
||||
get('language', () => N.language);
|
||||
get('languages', () => N.languages ? Array.from(N.languages) : null);
|
||||
get('timezone', () => W.Intl.DateTimeFormat().resolvedOptions().timeZone);
|
||||
get('timezoneOffset', () => new W.Date(2026, 0, 1).getTimezoneOffset());
|
||||
get('locale', () => W.Intl.DateTimeFormat().resolvedOptions().locale);
|
||||
get('hardwareConcurrency', () => N.hardwareConcurrency);
|
||||
get('deviceMemory', () => N.deviceMemory === undefined ? null : N.deviceMemory);
|
||||
get('maxTouchPoints', () => N.maxTouchPoints);
|
||||
get('doNotTrack', () => N.doNotTrack === undefined ? null : N.doNotTrack);
|
||||
get('globalPrivacyControl', () => N.globalPrivacyControl === undefined ? null : N.globalPrivacyControl);
|
||||
get('cookieEnabled', () => N.cookieEnabled);
|
||||
get('plugins', () => N.plugins ? N.plugins.length : null);
|
||||
get('mimeTypes', () => N.mimeTypes ? N.mimeTypes.length : null);
|
||||
get('pdfViewerEnabled', () => N.pdfViewerEnabled === undefined ? null : N.pdfViewerEnabled);
|
||||
get('webdriver', () => N.webdriver === undefined ? null : N.webdriver);
|
||||
get('screen', () => [S.width, S.height, S.availWidth, S.availHeight, S.colorDepth, S.pixelDepth].join(' '));
|
||||
get('availOrigin', () => [S.availLeft, S.availTop].join(' '));
|
||||
get('devicePixelRatio', () => W.devicePixelRatio);
|
||||
get('window', () => [W.outerWidth, W.outerHeight, W.innerWidth, W.innerHeight].join(' '));
|
||||
get('getBattery', () => typeof N.getBattery);
|
||||
get('mediaDevices', () => typeof N.mediaDevices);
|
||||
get('RTCPeerConnection', () => typeof W.RTCPeerConnection);
|
||||
get('userAgentData', () => typeof N.userAgentData);
|
||||
get('touchEvents', () => typeof W.TouchEvent + ' ' + (() => { try { W.document.createEvent('TouchEvent'); return 'createEvent'; } catch (e) { return e.name; } })());
|
||||
get('gamepads', () => typeof N.getGamepads);
|
||||
get('bluetooth', () => typeof N.bluetooth);
|
||||
get('canvas', () => canvas(W));
|
||||
get('canvasPixels', () => canvasPixels(W));
|
||||
get('webgl', () => webgl(W));
|
||||
get('fonts', () => fonts(W));
|
||||
get('nativeLooking', () => [W.HTMLCanvasElement.prototype.toDataURL, W.CanvasRenderingContext2D.prototype.getImageData,
|
||||
Object.getOwnPropertyDescriptor(W.Navigator.prototype, 'hardwareConcurrency').get]
|
||||
.every(f => /\[native code\]/.test(W.Function.prototype.toString.call(f))));
|
||||
return out;
|
||||
}
|
||||
|
||||
function draw(W) {
|
||||
const c = W.document.createElement('canvas'); c.width = 220; c.height = 40;
|
||||
const x = c.getContext('2d');
|
||||
x.textBaseline = 'top'; x.font = '16px Arial'; x.fillStyle = '#f60'; x.fillRect(100, 1, 62, 20);
|
||||
x.fillStyle = '#069'; x.fillText('Nacre fingerprint 😃', 2, 15);
|
||||
x.fillStyle = 'rgba(102, 204, 0, 0.7)'; x.fillText('Nacre fingerprint 😃', 4, 17);
|
||||
return c;
|
||||
}
|
||||
// toDataURL twice: the two reads must match (noise stable inside a site).
|
||||
function canvas(W) { const a = hash(draw(W).toDataURL()), b = hash(draw(W).toDataURL()); return a === b ? a : a + ' != ' + b; }
|
||||
function canvasPixels(W) { const c = draw(W); return hash(Array.from(c.getContext('2d').getImageData(0, 0, c.width, c.height).data).join(',')); }
|
||||
|
||||
function webgl(W) {
|
||||
const c = W.document.createElement('canvas'); c.width = 16; c.height = 16;
|
||||
const gl = c.getContext('webgl') || c.getContext('experimental-webgl');
|
||||
if (!gl) return null;
|
||||
const ext = gl.getExtension('WEBGL_debug_renderer_info');
|
||||
gl.clearColor(0.2, 0.4, 0.6, 1); gl.clear(gl.COLOR_BUFFER_BIT);
|
||||
const px = new Uint8Array(16 * 16 * 4); gl.readPixels(0, 0, 16, 16, gl.RGBA, gl.UNSIGNED_BYTE, px);
|
||||
return { vendor: gl.getParameter(gl.VENDOR), renderer: gl.getParameter(gl.RENDERER),
|
||||
unmaskedVendor: ext ? gl.getParameter(ext.UNMASKED_VENDOR_WEBGL) : null,
|
||||
unmaskedRenderer: ext ? gl.getParameter(ext.UNMASKED_RENDERER_WEBGL) : null,
|
||||
version: gl.getParameter(gl.VERSION), extensions: (gl.getSupportedExtensions() || []).length,
|
||||
maxTexture: gl.getParameter(gl.MAX_TEXTURE_SIZE), pixels: hash(Array.from(px).join(',')) };
|
||||
}
|
||||
|
||||
// Installed fonts, the way fingerprinters measure them: text width against the generic fallbacks.
|
||||
const FONTS = ['Arial', 'Helvetica', 'Times New Roman', 'Courier New', 'Verdana', 'Georgia', 'Comic Sans MS', 'Impact',
|
||||
'DejaVu Sans', 'DejaVu Serif', 'Liberation Sans', 'Noto Sans', 'Noto Serif', 'Ubuntu', 'Cantarell', 'Roboto',
|
||||
'Open Sans', 'Fira Sans', 'Inter', 'JetBrains Mono', 'Source Code Pro', 'Hack', 'Segoe UI', 'Calibri', 'Cambria',
|
||||
'Tahoma', 'Lucida Grande', 'Menlo', 'Monaco', 'Consolas', 'Material Symbols Rounded', 'Noto Color Emoji'];
|
||||
function fonts(W) {
|
||||
const c = W.document.createElement('canvas').getContext('2d'), text = 'mmmmmmmmmmlli1WQ@#';
|
||||
const width = f => { c.font = '48px ' + f; return c.measureText(text).width; };
|
||||
const base = ['monospace', 'sans-serif', 'serif'].map(width);
|
||||
const found = FONTS.filter(f => ['monospace', 'sans-serif', 'serif'].some((g, i) => width(`"${f}", ${g}`) !== base[i]));
|
||||
return { count: found.length, hash: hash(found.join(',')), found };
|
||||
}
|
||||
|
||||
// Audio: the classic OfflineAudioContext oscillator (+ compressor) sum.
|
||||
function audio(W) {
|
||||
return new Promise(done => {
|
||||
try {
|
||||
const Ctx = W.OfflineAudioContext || W.webkitOfflineAudioContext;
|
||||
if (!Ctx) return done(null);
|
||||
// Servo has no DynamicsCompressorNode: the oscillator alone where it's missing.
|
||||
const ctx = new Ctx(1, 5000, 44100), osc = ctx.createOscillator();
|
||||
osc.type = 'triangle'; osc.frequency.value = 10000;
|
||||
if (ctx.createDynamicsCompressor) { const comp = ctx.createDynamicsCompressor(); osc.connect(comp); comp.connect(ctx.destination); }
|
||||
else osc.connect(ctx.destination);
|
||||
osc.start(0);
|
||||
const t = setTimeout(() => done('timeout'), 4000);
|
||||
ctx.startRendering().then(buf => { clearTimeout(t); const d = buf.getChannelData(0); let s = 0;
|
||||
for (let i = 4500; i < 5000; i++) s += Math.abs(d[i]); done(s.toFixed(12)); }, e => done('error: ' + e.message));
|
||||
} catch (e) { done('error: ' + e.message); }
|
||||
});
|
||||
}
|
||||
|
||||
async function run() {
|
||||
const fp = basics(window);
|
||||
fp.audio = await audio(window);
|
||||
// A same-origin frame from markup, and an about:blank frame made by script (no injected scripts of its own).
|
||||
await new Promise(r => { const f = document.getElementById('static'); if (f.contentDocument && f.contentDocument.readyState === 'complete') r(); else f.onload = r; });
|
||||
const made = document.createElement('iframe'); document.body.appendChild(made);
|
||||
const frames = { static: basics(document.getElementById('static').contentWindow), scripted: basics(made.contentWindow) };
|
||||
// Which values differ from the top document's (should be none).
|
||||
const keys = ['userAgent', 'platform', 'language', 'languages', 'timezone', 'hardwareConcurrency', 'deviceMemory', 'screen', 'webgl', 'canvas'];
|
||||
fp.frameMismatch = {};
|
||||
for (const [name, v] of Object.entries(frames)) fp.frameMismatch[name] = keys.filter(k => JSON.stringify(v[k]) !== JSON.stringify(fp[k]));
|
||||
window.fp = fp;
|
||||
document.getElementById('out').textContent = JSON.stringify(fp, null, 1);
|
||||
document.title = 'FP done';
|
||||
}
|
||||
addEventListener('load', () => run().catch(e => { document.getElementById('out').textContent = 'error: ' + e.stack; document.title = 'FP error'; }));
|
||||
</script>
|
||||
17
tests/smoke/privacy-incognito.txt
Normal file
17
tests/smoke/privacy-incognito.txt
Normal file
|
|
@ -0,0 +1,17 @@
|
|||
# Incognito windows start with privacy mode on (S024): privacy.mode off, mode_incognito on (the default).
|
||||
# SMOKE_ARGS=--incognito tools/smoke.sh tests/smoke/privacy-incognito.txt
|
||||
wait 3
|
||||
set /vpn/enabled false
|
||||
set /privacy/mode false
|
||||
set /privacy/mode_incognito true
|
||||
wait 1
|
||||
open @PAGES@/fingerprint.html
|
||||
waitfor 30 document.title === "FP done"
|
||||
save fp-incognito JSON.stringify(window.fp, null, 1)
|
||||
shot fp-incognito
|
||||
assert window.fp.hardwareConcurrency === 8 && window.fp.platform === "Linux x86_64" && window.fp.webgl.vendor === "Mozilla"
|
||||
flyout shield
|
||||
wait 1
|
||||
shot shield-incognito
|
||||
status done
|
||||
quit
|
||||
Some files were not shown because too many files have changed in this diff Show more
Loading…
Reference in a new issue