@tokioapp/adblock 0.0.0-stage → 0.0.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +21 -0
- package/README.md +68 -2
- package/THIRD_PARTY_NOTICES.md +50 -0
- package/dist/content/cosmetics.d.ts +22 -0
- package/dist/content/cosmetics.js +173 -0
- package/dist/content/mainWorld.d.ts +8 -0
- package/dist/content/mainWorld.js +10 -0
- package/dist/content/preload.d.ts +1 -0
- package/dist/content/preload.js +34 -0
- package/dist/content/procedural.d.ts +19 -0
- package/dist/content/procedural.js +212 -0
- package/dist/cosmetic/engine.d.ts +95 -0
- package/dist/cosmetic/engine.js +268 -0
- package/dist/electron/blocker.d.ts +84 -0
- package/dist/electron/blocker.js +320 -0
- package/dist/electron/channels.d.ts +10 -0
- package/dist/electron/channels.js +6 -0
- package/dist/electron/scheme.d.ts +21 -0
- package/dist/electron/scheme.js +21 -0
- package/dist/engine.d.ts +86 -0
- package/dist/engine.js +163 -0
- package/dist/index.d.ts +13 -0
- package/dist/index.js +12 -0
- package/dist/lists/defaults.d.ts +6 -0
- package/dist/lists/defaults.js +59 -0
- package/dist/lists/manager.d.ts +86 -0
- package/dist/lists/manager.js +154 -0
- package/dist/lists/preprocessor.d.ts +21 -0
- package/dist/lists/preprocessor.js +152 -0
- package/dist/lists/storage.d.ts +37 -0
- package/dist/lists/storage.js +66 -0
- package/dist/network/engine.d.ts +105 -0
- package/dist/network/engine.js +431 -0
- package/dist/network/filterIndex.d.ts +40 -0
- package/dist/network/filterIndex.js +343 -0
- package/dist/network/modifiers.d.ts +23 -0
- package/dist/network/modifiers.js +192 -0
- package/dist/network/pattern.d.ts +7 -0
- package/dist/network/pattern.js +145 -0
- package/dist/network/request.d.ts +50 -0
- package/dist/network/request.js +136 -0
- package/dist/network/tokens.d.ts +5 -0
- package/dist/network/tokens.js +150 -0
- package/dist/parser/cosmetic.d.ts +21 -0
- package/dist/parser/cosmetic.js +171 -0
- package/dist/parser/hosts.d.ts +20 -0
- package/dist/parser/hosts.js +143 -0
- package/dist/parser/index.d.ts +40 -0
- package/dist/parser/index.js +158 -0
- package/dist/parser/network.d.ts +6 -0
- package/dist/parser/network.js +474 -0
- package/dist/parser/selector.d.ts +25 -0
- package/dist/parser/selector.js +522 -0
- package/dist/parser/types.d.ts +175 -0
- package/dist/parser/types.js +75 -0
- package/dist/preload.cjs +1988 -0
- package/dist/psl/psl.d.ts +32 -0
- package/dist/psl/psl.js +119 -0
- package/dist/resources/binary.d.ts +9 -0
- package/dist/resources/binary.js +54 -0
- package/dist/resources/defusers.d.ts +29 -0
- package/dist/resources/defusers.js +180 -0
- package/dist/resources/documents.d.ts +12 -0
- package/dist/resources/documents.js +56 -0
- package/dist/resources/ima.d.ts +6 -0
- package/dist/resources/ima.js +313 -0
- package/dist/resources/index.d.ts +14 -0
- package/dist/resources/index.js +85 -0
- package/dist/resources/surrogates.d.ts +30 -0
- package/dist/resources/surrogates.js +486 -0
- package/dist/scriptlets/abort.d.ts +5 -0
- package/dist/scriptlets/abort.js +97 -0
- package/dist/scriptlets/dom/attributes.d.ts +5 -0
- package/dist/scriptlets/dom/attributes.js +92 -0
- package/dist/scriptlets/dom/click.d.ts +2 -0
- package/dist/scriptlets/dom/click.js +107 -0
- package/dist/scriptlets/dom/cookies.d.ts +16 -0
- package/dist/scriptlets/dom/cookies.js +194 -0
- package/dist/scriptlets/dom/createHtml.d.ts +2 -0
- package/dist/scriptlets/dom/createHtml.js +27 -0
- package/dist/scriptlets/dom/dialogs.d.ts +3 -0
- package/dist/scriptlets/dom/dialogs.js +21 -0
- package/dist/scriptlets/dom/hrefSanitizer.d.ts +2 -0
- package/dist/scriptlets/dom/hrefSanitizer.js +91 -0
- package/dist/scriptlets/dom/index.d.ts +3 -0
- package/dist/scriptlets/dom/index.js +38 -0
- package/dist/scriptlets/dom/navigation.d.ts +5 -0
- package/dist/scriptlets/dom/navigation.js +60 -0
- package/dist/scriptlets/dom/nodeText.d.ts +3 -0
- package/dist/scriptlets/dom/nodeText.js +98 -0
- package/dist/scriptlets/dom/spoofCss.d.ts +2 -0
- package/dist/scriptlets/dom/spoofCss.js +58 -0
- package/dist/scriptlets/dom/storage.d.ts +5 -0
- package/dist/scriptlets/dom/storage.js +50 -0
- package/dist/scriptlets/dom/watch.d.ts +8 -0
- package/dist/scriptlets/dom/watch.js +41 -0
- package/dist/scriptlets/events.d.ts +2 -0
- package/dist/scriptlets/events.js +42 -0
- package/dist/scriptlets/helpers.d.ts +58 -0
- package/dist/scriptlets/helpers.js +206 -0
- package/dist/scriptlets/index.d.ts +6 -0
- package/dist/scriptlets/index.js +47 -0
- package/dist/scriptlets/network/edit.d.ts +9 -0
- package/dist/scriptlets/network/edit.js +104 -0
- package/dist/scriptlets/network/eval.d.ts +3 -0
- package/dist/scriptlets/network/eval.js +22 -0
- package/dist/scriptlets/network/fetch.d.ts +10 -0
- package/dist/scriptlets/network/fetch.js +145 -0
- package/dist/scriptlets/network/index.d.ts +3 -0
- package/dist/scriptlets/network/index.js +43 -0
- package/dist/scriptlets/network/jsonPath.d.ts +13 -0
- package/dist/scriptlets/network/jsonPath.js +482 -0
- package/dist/scriptlets/network/media.d.ts +3 -0
- package/dist/scriptlets/network/media.js +97 -0
- package/dist/scriptlets/network/methods.d.ts +5 -0
- package/dist/scriptlets/network/methods.js +139 -0
- package/dist/scriptlets/network/prune.d.ts +13 -0
- package/dist/scriptlets/network/prune.js +194 -0
- package/dist/scriptlets/network/rendering.d.ts +4 -0
- package/dist/scriptlets/network/rendering.js +46 -0
- package/dist/scriptlets/network/replace.d.ts +5 -0
- package/dist/scriptlets/network/replace.js +168 -0
- package/dist/scriptlets/network/request.d.ts +19 -0
- package/dist/scriptlets/network/request.js +124 -0
- package/dist/scriptlets/network/util.d.ts +19 -0
- package/dist/scriptlets/network/util.js +80 -0
- package/dist/scriptlets/network/webrtc.d.ts +3 -0
- package/dist/scriptlets/network/webrtc.js +62 -0
- package/dist/scriptlets/network/windowOpen.d.ts +2 -0
- package/dist/scriptlets/network/windowOpen.js +28 -0
- package/dist/scriptlets/network/xhr.d.ts +9 -0
- package/dist/scriptlets/network/xhr.js +177 -0
- package/dist/scriptlets/runner.d.ts +8 -0
- package/dist/scriptlets/runner.js +19 -0
- package/dist/scriptlets/setConstant.d.ts +5 -0
- package/dist/scriptlets/setConstant.js +117 -0
- package/dist/scriptlets/timers.d.ts +5 -0
- package/dist/scriptlets/timers.js +66 -0
- package/dist/scriptlets/types.d.ts +32 -0
- package/dist/scriptlets/types.js +1 -0
- package/dist/util.d.ts +5 -0
- package/dist/util.js +16 -0
- package/package.json +83 -4
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 Italo Alfaro and contributors
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
package/README.md
CHANGED
|
@@ -1,3 +1,69 @@
|
|
|
1
|
-
#
|
|
1
|
+
# Tokio Adblock
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
A content blocker for Electron that applies [uBlock Origin](https://github.com/gorhill/uBlock)'s filter lists inside an Electron session: network filters, cosmetic and procedural cosmetic filters, scriptlet injection and redirect resources. It is written from scratch, MIT-licensed, and has no runtime dependency. It is the blocker behind [Tokio](https://tokio.ialfaro.com)'s music player.
|
|
4
|
+
|
|
5
|
+
## Status
|
|
6
|
+
|
|
7
|
+
In development. It isn't on npm yet, and the API can still change.
|
|
8
|
+
|
|
9
|
+
## Use
|
|
10
|
+
|
|
11
|
+
Electron 35 or later, Node 24 or later. The package is ESM only and ships its TypeScript types.
|
|
12
|
+
|
|
13
|
+
```ts
|
|
14
|
+
import path from "node:path";
|
|
15
|
+
import { app, ipcMain, protocol, session } from "electron";
|
|
16
|
+
import { ElectronBlocker, FileStorage, adblockScheme } from "@tokioapp/adblock";
|
|
17
|
+
|
|
18
|
+
// Once, before the app is ready, in the same call as your own schemes:
|
|
19
|
+
// Electron takes one call for the whole app.
|
|
20
|
+
protocol.registerSchemesAsPrivileged([adblockScheme]);
|
|
21
|
+
|
|
22
|
+
app.whenReady().then(async () => {
|
|
23
|
+
const blocker = new ElectronBlocker({
|
|
24
|
+
ipcMain,
|
|
25
|
+
// Where the downloaded lists are kept between runs.
|
|
26
|
+
storage: new FileStorage(path.join(app.getPath("userData"), "adblock")),
|
|
27
|
+
onError: (error) => console.warn(error.message),
|
|
28
|
+
});
|
|
29
|
+
blocker.enable(session.fromPartition("persist:player"));
|
|
30
|
+
await blocker.ready; // The lists are in effect.
|
|
31
|
+
});
|
|
32
|
+
```
|
|
33
|
+
|
|
34
|
+
- `enable(session)` starts filtering a session and `disable(session)` stops it. Both can be called again without harm, and `dispose()` stops everything.
|
|
35
|
+
- `ready` resolves once the lists are in effect. The first run downloads them; later runs read them from the storage, and the blocker looks for new versions as each list expires. `update()` looks right away.
|
|
36
|
+
- Nothing the blocker does can fail a page load: what goes wrong is passed to `onError`.
|
|
37
|
+
- By default it applies the lists uBlock Origin enables by default (`DEFAULT_LISTS`). Pass `lists` to choose: `DEFAULT_LISTS.filter((list) => list.id !== "urlhaus-1")` leaves out the largest one, which holds a third of the memory.
|
|
38
|
+
- `blocker.counts` says how many requests were blocked, redirected and rewritten, and how many scriptlets were given to documents.
|
|
39
|
+
|
|
40
|
+
What you need to know as the host app:
|
|
41
|
+
|
|
42
|
+
- **The blocker owns `webRequest.onBeforeRequest` and `webRequest.onHeadersReceived`** in the sessions it is enabled in: Electron keeps one listener per event per session. If you need one of your own, set it after `enable()` and call `blocker.onBeforeRequest(details, callback)` or `blocker.onHeadersReceived(details, callback)` from it for the requests you don't decide yourself.
|
|
43
|
+
- **Register `adblockScheme`**, as above. Without it the redirect resources don't load.
|
|
44
|
+
- The preload script ships in the package and is registered for you. If you bundle the package into your own main process code, pass `preloadPath: require.resolve("@tokioapp/adblock/preload")`.
|
|
45
|
+
- Frames only get scriptlets and cosmetic filters when the window has `nodeIntegrationInSubFrames`. Their requests are filtered either way.
|
|
46
|
+
- To apply `popup` filters, ask in your `setWindowOpenHandler`: `blocker.engine.blocksPopup(url, openerUrl)`.
|
|
47
|
+
|
|
48
|
+
## What it applies
|
|
49
|
+
|
|
50
|
+
- **Lists:** downloads with mirrors, `! Expires:`, `ETag` and `Last-Modified`, the pre-parsing directives (`!#if`, `!#else`, `!#include`) and hosts files. Any list in uBlock Origin's syntax works.
|
|
51
|
+
- **Network filters:** every pattern form and option uBlock Origin documents: types, `1p` and `3p`, `strict1p` and `strict3p`, `domain`, `to`, `top`, `denyallow`, `method`, `header`, `important`, `badfilter`, `match-case`, exceptions, and the modifiers `redirect`, `redirect-rule`, `removeparam`, `csp`, `permissions`, `urlskip`, `uritransform`, `inline-script` and `inline-font`.
|
|
52
|
+
- **Redirect resources:** empty scripts, styles and documents, transparent images, silent sounds, and stand-ins for the IMA SDK, Google Publisher Tag, Google Analytics, Tag Manager, AdSense and others.
|
|
53
|
+
- **Cosmetic filters:** specific, entity and generic filters, exceptions, `generichide`, `specifichide` and `elemhide`, `:style()`, and the procedural operators (`:has-text()`, `:upward()`, `:matches-css()`, `:matches-path()`, `:xpath()`, `:remove()`, `:remove-attr()` and the rest).
|
|
54
|
+
- **Scriptlets:** 95, every one uBlock Origin's default lists use but six that it doesn't document. `trusted-` scriptlets only run from trusted lists, which by default are uBlock Origin's own.
|
|
55
|
+
|
|
56
|
+
With the nine default lists (307,000 lines) it is ready about a second and a half after it finds them in the storage, holds about 63 MB, and decides between 55,000 and 110,000 requests a second, depending on what else the machine is doing.
|
|
57
|
+
|
|
58
|
+
## What it doesn't
|
|
59
|
+
|
|
60
|
+
- HTML filters (`##^`) and `replace=`: Electron can't rewrite a response's body. `##^responseheader()` is applied.
|
|
61
|
+
- `cname` and, mostly, `ipaddress`: Chromium doesn't tell what a name resolved to.
|
|
62
|
+
- `popunder`, which needs a browser's tabs.
|
|
63
|
+
- The page uBlock Origin shows in place of a blocked site: a blocked page just doesn't load.
|
|
64
|
+
- Six scriptlets that are in uBlock Origin's lists but not in its documentation, and `overlay-buster`.
|
|
65
|
+
- `noop-1s.mp4` is an empty file for now: a filter that redirects a video to it makes the video fail instead of playing a silent second.
|
|
66
|
+
|
|
67
|
+
## License
|
|
68
|
+
|
|
69
|
+
MIT, see [`LICENSE`](LICENSE). The library is an independent implementation: it contains no code from uBlock Origin or any other content blocker. The filter lists it downloads at runtime belong to their authors and have their own licenses, see [`THIRD_PARTY_NOTICES.md`](THIRD_PARTY_NOTICES.md).
|
|
@@ -0,0 +1,50 @@
|
|
|
1
|
+
# Third-party notices
|
|
2
|
+
|
|
3
|
+
## Summary
|
|
4
|
+
|
|
5
|
+
`@tokioapp/adblock` is MIT ([`LICENSE`](LICENSE)). It is an independent implementation: no code from uBlock Origin or any other content blocker was copied into it, and it doesn't depend on them.
|
|
6
|
+
|
|
7
|
+
| What | License |
|
|
8
|
+
| ------------------------------------------------- | ------------------------------------------------- |
|
|
9
|
+
| This library's source code and its package | MIT ([`LICENSE`](LICENSE)) |
|
|
10
|
+
| Runtime dependencies | None |
|
|
11
|
+
| The documentation the library was written from | Credited below; no code is copied |
|
|
12
|
+
| The filter lists the library downloads at runtime | Their authors', listed below; not in this package |
|
|
13
|
+
|
|
14
|
+
## Documentation used as a reference
|
|
15
|
+
|
|
16
|
+
The filter syntax and the behavior of scriptlets and redirect resources come from public documentation. The library's code, including its parser, its matching engines, its scriptlets and its redirect resources, is written from scratch from that understanding. The source code of uBlock Origin, uBlock Origin Lite, Ghostery's adblocker, AdGuard's libraries and Brave's adblock-rust was not read.
|
|
17
|
+
|
|
18
|
+
- **uBlock Origin's wiki** (<https://github.com/gorhill/uBlock/wiki>), by Raymond Hill and contributors: "Static filter syntax", "Procedural cosmetic filters", "Resources Library", "uBO-flavored JSONPath", "Filter Performance", "Syntax quirks" and "Strict blocking".
|
|
19
|
+
- **Adblock Plus's filter documentation** (<https://help.adblockplus.org/hc/en-us/articles/360062733293-How-to-write-filters>).
|
|
20
|
+
- **AdGuard's filter documentation** (<https://adguard.com/kb/general/ad-filtering/create-own-filters/>), for the options uBlock Origin's wiki defers to it for.
|
|
21
|
+
- **MDN** and the **Electron** and **Chromium** documentation, for the web and Electron APIs.
|
|
22
|
+
- **The public developer documentation of the scripts the redirect resources stand in for**, for the names those scripts define: Google's IMA SDK for HTML5 reference (<https://developers.google.com/interactive-media-ads/docs/sdks/html5/client-side/reference/js/google.ima>), the Google Publisher Tag reference (<https://developers.google.com/publisher-tag/reference>), Google Analytics' `analytics.js` and `ga.js` references, AdSense's and Google Tag Manager's documentation, FingerprintJS's and FuckAdBlock's READMEs, the Sensors Data web API (<https://docs.sensorsdata.com>), and the file format specifications (GIF89a, PNG, MPEG audio, VAST, VMAP). Each stand-in is our own code that defines those names and does nothing; no code from those scripts is included.
|
|
23
|
+
|
|
24
|
+
The filter lists were also read as data, to measure which syntax, scriptlets and redirect resources real rules use. No line of a filter list is included in this repository or in the package.
|
|
25
|
+
|
|
26
|
+
## Development tools
|
|
27
|
+
|
|
28
|
+
Development tools (TypeScript, Vitest, jsdom, esbuild, Electron, oxlint, Prettier and the rest of `devDependencies`) aren't part of the published package. A scan of the 172 installed packages on 2026-11-14 found only permissive licenses: MIT, Apache-2.0, ISC, BSD-2-Clause, BSD-3-Clause, BlueOak-1.0.0 and Python-2.0. Electron is also the package's peer dependency: the host app's own copy, which the library uses only through what the app passes it.
|
|
29
|
+
|
|
30
|
+
## Services
|
|
31
|
+
|
|
32
|
+
The library downloads filter lists from these hosts when the host app asks it to. None of them is covered by this library's license. Each list belongs to its authors, is subject to its own license, and can change or stop being served at any time. The library downloads them on the user's machine and doesn't redistribute them.
|
|
33
|
+
|
|
34
|
+
It also downloads Mozilla's **Public Suffix List** (<https://publicsuffix.org>, MPL-2.0) from `publicsuffix.org`, to tell a site from its subdomains. The list is data read by this library's own code; it isn't included in the repository or in the package.
|
|
35
|
+
|
|
36
|
+
The default lists (`DEFAULT_LISTS`) are the ones uBlock Origin enables by default:
|
|
37
|
+
|
|
38
|
+
| List | Authors | License | Downloaded from |
|
|
39
|
+
| ---------------------------------------- | -------------------------------------------------------- | -------------------------------------------------- | ------------------------------------------------------------------------------------------ |
|
|
40
|
+
| uBlock filters – Ads | Raymond Hill and contributors | GPL-3.0 | `ublockorigin.github.io`, then its mirrors `ublockorigin.pages.dev` and `cdn.jsdelivr.net` |
|
|
41
|
+
| uBlock filters – Badware risks | Raymond Hill and contributors | GPL-3.0 | The same hosts |
|
|
42
|
+
| uBlock filters – Privacy | Raymond Hill and contributors | GPL-3.0 | The same hosts |
|
|
43
|
+
| uBlock filters – Unbreak | Raymond Hill and contributors | GPL-3.0 | The same hosts |
|
|
44
|
+
| uBlock filters – Quick fixes | Raymond Hill and contributors | GPL-3.0 | The same hosts |
|
|
45
|
+
| EasyList | The EasyList authors | GPL-3.0 or CC BY-SA 3.0, at the recipient's choice | The same hosts (uBlock Origin's copy) |
|
|
46
|
+
| EasyPrivacy | The EasyList authors | GPL-3.0 or CC BY-SA 3.0, at the recipient's choice | The same hosts (uBlock Origin's copy) |
|
|
47
|
+
| Online Malicious URL Blocklist | The malware-filter project, from URLhaus (abuse.ch) data | CC0-1.0 | `malware-filter.gitlab.io`, then `curbengh.github.io` |
|
|
48
|
+
| Peter Lowe's Ad and tracking server list | Peter Lowe | None stated | `pgl.yoyo.org` |
|
|
49
|
+
|
|
50
|
+
The list of defaults and their URLs come from uBlock Origin's published asset index (`assets/assets.json`), read as data. A host app can pass its own lists instead; their licenses are then its concern. Peter Lowe's list states no license. Its site (<https://pgl.yoyo.org/adservers/>, checked 2026-11-14) says: "Feel free to combine this list with yours or lists from other sites and put it up on the web".
|
|
@@ -0,0 +1,22 @@
|
|
|
1
|
+
import type { ProceduralPlan } from "../parser/types.js";
|
|
2
|
+
/** The cosmetic part of what main gives a document (`DocumentCosmetics`). */
|
|
3
|
+
export interface CosmeticsConfig {
|
|
4
|
+
css: string;
|
|
5
|
+
procedural: ProceduralPlan[];
|
|
6
|
+
generic: boolean;
|
|
7
|
+
}
|
|
8
|
+
/** What the page-side code needs from where it runs. */
|
|
9
|
+
export interface CosmeticsHost {
|
|
10
|
+
/** Adds a stylesheet the page can't read or remove. */
|
|
11
|
+
insertCSS(css: string): void;
|
|
12
|
+
/**
|
|
13
|
+
* Gives the stylesheet of the generic filters that need one of these
|
|
14
|
+
* classes or ids.
|
|
15
|
+
*/
|
|
16
|
+
generic(classes: string[], ids: string[]): Promise<string>;
|
|
17
|
+
}
|
|
18
|
+
/**
|
|
19
|
+
* Hides what a document's cosmetic filters select, and keeps doing it as
|
|
20
|
+
* the page changes. Returns a function that stops it.
|
|
21
|
+
*/
|
|
22
|
+
export declare function startCosmetics(config: CosmeticsConfig, host: CosmeticsHost): () => void;
|
|
@@ -0,0 +1,173 @@
|
|
|
1
|
+
import { compileFilter, nameMatcher, } from "./procedural.js";
|
|
2
|
+
// How long changes to the page gather before they are looked at, in ms.
|
|
3
|
+
const DELAY = 30;
|
|
4
|
+
/**
|
|
5
|
+
* Hides what a document's cosmetic filters select, and keeps doing it as
|
|
6
|
+
* the page changes. Returns a function that stops it.
|
|
7
|
+
*/
|
|
8
|
+
export function startCosmetics(config, host) {
|
|
9
|
+
if (config.css !== "")
|
|
10
|
+
host.insertCSS(config.css);
|
|
11
|
+
const filters = [];
|
|
12
|
+
for (const plan of config.procedural) {
|
|
13
|
+
try {
|
|
14
|
+
filters.push(compileFilter(plan));
|
|
15
|
+
}
|
|
16
|
+
catch {
|
|
17
|
+
// A filter this version can't run only loses itself.
|
|
18
|
+
}
|
|
19
|
+
}
|
|
20
|
+
if (filters.length === 0 && !config.generic)
|
|
21
|
+
return () => { };
|
|
22
|
+
// Elements are marked with an attribute no page uses, and a stylesheet
|
|
23
|
+
// rule hides or restyles what carries it.
|
|
24
|
+
const token = `x${Math.random().toString(36).slice(2, 10)}`;
|
|
25
|
+
const marks = new Map();
|
|
26
|
+
const mark = (style, elements) => {
|
|
27
|
+
let entry = marks.get(style);
|
|
28
|
+
if (entry === undefined) {
|
|
29
|
+
entry = { attribute: `${token}${marks.size}`, elements: new Set() };
|
|
30
|
+
marks.set(style, entry);
|
|
31
|
+
host.insertCSS(`[${entry.attribute}]{${style}}`);
|
|
32
|
+
}
|
|
33
|
+
for (const element of entry.elements) {
|
|
34
|
+
if (!elements.has(element))
|
|
35
|
+
element.removeAttribute(entry.attribute);
|
|
36
|
+
}
|
|
37
|
+
for (const element of elements) {
|
|
38
|
+
if (!entry.elements.has(element))
|
|
39
|
+
element.setAttribute(entry.attribute, "");
|
|
40
|
+
}
|
|
41
|
+
entry.elements = elements;
|
|
42
|
+
};
|
|
43
|
+
const runFilters = () => {
|
|
44
|
+
const selected = new Map();
|
|
45
|
+
for (const style of marks.keys())
|
|
46
|
+
selected.set(style, new Set());
|
|
47
|
+
for (const filter of filters) {
|
|
48
|
+
const elements = filter.select();
|
|
49
|
+
const [action, argument = ""] = filter.action ?? [];
|
|
50
|
+
if (action === "remove") {
|
|
51
|
+
for (const element of elements)
|
|
52
|
+
element.remove();
|
|
53
|
+
}
|
|
54
|
+
else if (action === "remove-attr" || action === "remove-class") {
|
|
55
|
+
const matches = nameMatcher(argument);
|
|
56
|
+
for (const element of elements) {
|
|
57
|
+
const names = action === "remove-attr"
|
|
58
|
+
? [...element.attributes].map((attribute) => attribute.name)
|
|
59
|
+
: [...element.classList];
|
|
60
|
+
for (const name of names) {
|
|
61
|
+
if (!matches(name))
|
|
62
|
+
continue;
|
|
63
|
+
if (action === "remove-attr")
|
|
64
|
+
element.removeAttribute(name);
|
|
65
|
+
else
|
|
66
|
+
element.classList.remove(name);
|
|
67
|
+
}
|
|
68
|
+
}
|
|
69
|
+
}
|
|
70
|
+
else {
|
|
71
|
+
const style = action === "style" ? argument : "display:none!important;";
|
|
72
|
+
let set = selected.get(style);
|
|
73
|
+
if (set === undefined)
|
|
74
|
+
selected.set(style, (set = new Set()));
|
|
75
|
+
for (const element of elements)
|
|
76
|
+
set.add(element);
|
|
77
|
+
}
|
|
78
|
+
}
|
|
79
|
+
// What a filter no longer selects loses its mark.
|
|
80
|
+
for (const [style, elements] of selected)
|
|
81
|
+
mark(style, elements);
|
|
82
|
+
};
|
|
83
|
+
// Generic filters are asked for by the classes and ids the page uses.
|
|
84
|
+
const seen = new Set();
|
|
85
|
+
let unsurveyed = [];
|
|
86
|
+
const survey = () => {
|
|
87
|
+
const classes = [];
|
|
88
|
+
const ids = [];
|
|
89
|
+
const note = (element) => {
|
|
90
|
+
if (element.id !== "" && !seen.has(`#${element.id}`)) {
|
|
91
|
+
seen.add(`#${element.id}`);
|
|
92
|
+
ids.push(element.id);
|
|
93
|
+
}
|
|
94
|
+
for (const name of element.classList) {
|
|
95
|
+
if (seen.has(`.${name}`))
|
|
96
|
+
continue;
|
|
97
|
+
seen.add(`.${name}`);
|
|
98
|
+
classes.push(name);
|
|
99
|
+
}
|
|
100
|
+
};
|
|
101
|
+
for (const root of unsurveyed) {
|
|
102
|
+
note(root);
|
|
103
|
+
for (const element of root.querySelectorAll("[class],[id]"))
|
|
104
|
+
note(element);
|
|
105
|
+
}
|
|
106
|
+
unsurveyed = [];
|
|
107
|
+
if (classes.length === 0 && ids.length === 0)
|
|
108
|
+
return;
|
|
109
|
+
host.generic(classes, ids).then((css) => {
|
|
110
|
+
if (css !== "")
|
|
111
|
+
host.insertCSS(css);
|
|
112
|
+
}, () => { });
|
|
113
|
+
};
|
|
114
|
+
let timer;
|
|
115
|
+
let stale = true;
|
|
116
|
+
const run = () => {
|
|
117
|
+
timer = undefined;
|
|
118
|
+
if (config.generic)
|
|
119
|
+
survey();
|
|
120
|
+
if (stale && filters.length > 0) {
|
|
121
|
+
stale = false;
|
|
122
|
+
runFilters();
|
|
123
|
+
// Marking elements is a change of the page too: don't answer it.
|
|
124
|
+
observer.takeRecords();
|
|
125
|
+
}
|
|
126
|
+
};
|
|
127
|
+
const schedule = () => {
|
|
128
|
+
timer ??= setTimeout(run, DELAY);
|
|
129
|
+
};
|
|
130
|
+
const watched = new Set(filters.flatMap((filter) => [...filter.watched]));
|
|
131
|
+
const observer = new MutationObserver((records) => {
|
|
132
|
+
for (const record of records) {
|
|
133
|
+
if (record.type === "attributes") {
|
|
134
|
+
const name = record.attributeName ?? "";
|
|
135
|
+
if (name.startsWith(token))
|
|
136
|
+
continue;
|
|
137
|
+
if (watched.has("*") || watched.has(name))
|
|
138
|
+
stale = true;
|
|
139
|
+
if (config.generic && record.target instanceof Element) {
|
|
140
|
+
unsurveyed.push(record.target);
|
|
141
|
+
}
|
|
142
|
+
}
|
|
143
|
+
else {
|
|
144
|
+
stale = true;
|
|
145
|
+
if (!config.generic)
|
|
146
|
+
continue;
|
|
147
|
+
for (const node of record.addedNodes) {
|
|
148
|
+
if (node instanceof Element)
|
|
149
|
+
unsurveyed.push(node);
|
|
150
|
+
}
|
|
151
|
+
}
|
|
152
|
+
}
|
|
153
|
+
schedule();
|
|
154
|
+
});
|
|
155
|
+
const attributes = [...watched, ...(config.generic ? ["class", "id"] : [])];
|
|
156
|
+
observer.observe(document, {
|
|
157
|
+
childList: true,
|
|
158
|
+
subtree: true,
|
|
159
|
+
attributes: attributes.length > 0,
|
|
160
|
+
// Without a filter every attribute is watched.
|
|
161
|
+
...(watched.has("*") || attributes.length === 0
|
|
162
|
+
? {}
|
|
163
|
+
: { attributeFilter: attributes }),
|
|
164
|
+
});
|
|
165
|
+
if (document.documentElement !== null) {
|
|
166
|
+
unsurveyed.push(document.documentElement);
|
|
167
|
+
}
|
|
168
|
+
run();
|
|
169
|
+
return () => {
|
|
170
|
+
observer.disconnect();
|
|
171
|
+
clearTimeout(timer);
|
|
172
|
+
};
|
|
173
|
+
}
|
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
import type { ScriptletCall } from "../scriptlets/types.js";
|
|
2
|
+
/**
|
|
3
|
+
* Runs a document's scriptlets. The preload hands this function to the
|
|
4
|
+
* page's own world, which only keeps a function's own text: the build
|
|
5
|
+
* (`scripts/build`) replaces this file with the scriptlets bundled into one
|
|
6
|
+
* self-contained function. From source, as in tests, it just calls them.
|
|
7
|
+
*/
|
|
8
|
+
export declare function runScriptlets(calls: ScriptletCall[]): void;
|
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
import { run } from "../scriptlets/runner.js";
|
|
2
|
+
/**
|
|
3
|
+
* Runs a document's scriptlets. The preload hands this function to the
|
|
4
|
+
* page's own world, which only keeps a function's own text: the build
|
|
5
|
+
* (`scripts/build`) replaces this file with the scriptlets bundled into one
|
|
6
|
+
* self-contained function. From source, as in tests, it just calls them.
|
|
7
|
+
*/
|
|
8
|
+
export function runScriptlets(calls) {
|
|
9
|
+
run(calls);
|
|
10
|
+
}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export {};
|
|
@@ -0,0 +1,34 @@
|
|
|
1
|
+
// The session preload: it runs in every document of a session the blocker is
|
|
2
|
+
// enabled in, before the document's scripts. The build bundles it into one
|
|
3
|
+
// CommonJS file, dist/preload.cjs: a sandboxed preload can only load
|
|
4
|
+
// `electron`.
|
|
5
|
+
import { contextBridge, ipcRenderer, webFrame } from "electron";
|
|
6
|
+
import { DOCUMENT_CHANNEL, GENERIC_CHANNEL, } from "../electron/channels.js";
|
|
7
|
+
import { startCosmetics } from "./cosmetics.js";
|
|
8
|
+
import { runScriptlets } from "./mainWorld.js";
|
|
9
|
+
try {
|
|
10
|
+
const url = location.href;
|
|
11
|
+
// Synchronous on purpose: the answer has to be there before the page's
|
|
12
|
+
// first script. Main answers from memory.
|
|
13
|
+
const config = ipcRenderer.sendSync(DOCUMENT_CHANNEL, url);
|
|
14
|
+
if (config !== null) {
|
|
15
|
+
if (config.scriptlets.length > 0) {
|
|
16
|
+
contextBridge.executeInMainWorld({
|
|
17
|
+
func: runScriptlets,
|
|
18
|
+
args: [config.scriptlets],
|
|
19
|
+
});
|
|
20
|
+
}
|
|
21
|
+
startCosmetics(config, {
|
|
22
|
+
// A user stylesheet: the page can't see it, remove it or outrank it.
|
|
23
|
+
insertCSS: (css) => void webFrame.insertCSS(css, { cssOrigin: "user" }),
|
|
24
|
+
generic: (classes, ids) => ipcRenderer.invoke(GENERIC_CHANNEL, {
|
|
25
|
+
url,
|
|
26
|
+
classes,
|
|
27
|
+
ids,
|
|
28
|
+
}),
|
|
29
|
+
});
|
|
30
|
+
}
|
|
31
|
+
}
|
|
32
|
+
catch {
|
|
33
|
+
// Whatever goes wrong here, the page loads as if there were no blocker.
|
|
34
|
+
}
|
|
@@ -0,0 +1,19 @@
|
|
|
1
|
+
import type { ProceduralPlan } from "../parser/types.js";
|
|
2
|
+
type Matcher = (text: string) => boolean;
|
|
3
|
+
/** A procedural filter ready to run. */
|
|
4
|
+
export interface CompiledFilter {
|
|
5
|
+
/** The elements the filter selects in the document now. */
|
|
6
|
+
select(): Element[];
|
|
7
|
+
/**
|
|
8
|
+
* The attributes whose changes should run it again (`:watch-attr()`),
|
|
9
|
+
* `*` for any.
|
|
10
|
+
*/
|
|
11
|
+
watched: ReadonlySet<string>;
|
|
12
|
+
/** What to do with the elements. Undefined: hide them. */
|
|
13
|
+
action: ProceduralPlan["action"];
|
|
14
|
+
}
|
|
15
|
+
/** Compiles the plan the parser made of a procedural filter. */
|
|
16
|
+
export declare function compileFilter(plan: ProceduralPlan): CompiledFilter;
|
|
17
|
+
/** `name` or `/regex/flags`, as the action operators take them. */
|
|
18
|
+
export declare function nameMatcher(text: string): Matcher;
|
|
19
|
+
export {};
|
|
@@ -0,0 +1,212 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* A matcher from what the parser compiled an operator's argument to: text,
|
|
3
|
+
* or the source and flags of a regular expression. Text has to be found in
|
|
4
|
+
* the value, or with `exact` to be the value.
|
|
5
|
+
*/
|
|
6
|
+
function textMatcher(spec, exact = false) {
|
|
7
|
+
if (Array.isArray(spec)) {
|
|
8
|
+
const regex = new RegExp(String(spec[0]), String(spec[1]));
|
|
9
|
+
return (text) => {
|
|
10
|
+
regex.lastIndex = 0;
|
|
11
|
+
return regex.test(text);
|
|
12
|
+
};
|
|
13
|
+
}
|
|
14
|
+
const literal = String(spec);
|
|
15
|
+
return exact ? (text) => text === literal : (text) => text.includes(literal);
|
|
16
|
+
}
|
|
17
|
+
function select(root, selector) {
|
|
18
|
+
try {
|
|
19
|
+
return [...root.querySelectorAll(selector)];
|
|
20
|
+
}
|
|
21
|
+
catch {
|
|
22
|
+
// Not a selector this browser knows: the filter selects nothing.
|
|
23
|
+
return [];
|
|
24
|
+
}
|
|
25
|
+
}
|
|
26
|
+
const unique = (nodes) => [...new Set(nodes)];
|
|
27
|
+
/**
|
|
28
|
+
* The CSS that follows an operator, from each node the operator kept:
|
|
29
|
+
* ` > a` and ` a` look below the node, `+ a` and `~ a` after it, and `.a`
|
|
30
|
+
* (no space) keeps the node if it matches.
|
|
31
|
+
*/
|
|
32
|
+
function continueFrom(node, css) {
|
|
33
|
+
const trimmed = css.trim();
|
|
34
|
+
if (!(node instanceof Element))
|
|
35
|
+
return select(node, trimmed);
|
|
36
|
+
if (css.includes(":scope"))
|
|
37
|
+
return select(node, css);
|
|
38
|
+
const sibling = /^[+~]/.test(trimmed);
|
|
39
|
+
if (!sibling && (/^\s/.test(css) || trimmed.startsWith(">"))) {
|
|
40
|
+
return select(node, `:scope ${trimmed}`);
|
|
41
|
+
}
|
|
42
|
+
// The node itself has to take part: name it from its parent.
|
|
43
|
+
const parent = node.parentElement;
|
|
44
|
+
if (parent === null)
|
|
45
|
+
return [];
|
|
46
|
+
const index = [...parent.children].indexOf(node) + 1;
|
|
47
|
+
return select(parent, `:scope > :nth-child(${index})${sibling ? trimmed : css}`);
|
|
48
|
+
}
|
|
49
|
+
/** Everything but the nodes, what is inside them and what they are inside. */
|
|
50
|
+
function others(nodes) {
|
|
51
|
+
const subjects = new Set(nodes);
|
|
52
|
+
const ancestors = new Set();
|
|
53
|
+
for (const node of nodes) {
|
|
54
|
+
for (let up = node.parentNode; up !== null; up = up.parentNode) {
|
|
55
|
+
ancestors.add(up);
|
|
56
|
+
}
|
|
57
|
+
}
|
|
58
|
+
const found = [];
|
|
59
|
+
const visit = (element) => {
|
|
60
|
+
if (subjects.has(element))
|
|
61
|
+
return;
|
|
62
|
+
if (!ancestors.has(element))
|
|
63
|
+
found.push(element);
|
|
64
|
+
else
|
|
65
|
+
for (const child of element.children)
|
|
66
|
+
visit(child);
|
|
67
|
+
};
|
|
68
|
+
visit(document.documentElement);
|
|
69
|
+
return found;
|
|
70
|
+
}
|
|
71
|
+
function compileTask([op, arg], watched) {
|
|
72
|
+
const keep = (test) => (nodes) => nodes.filter(test);
|
|
73
|
+
switch (op) {
|
|
74
|
+
case "spath": {
|
|
75
|
+
const css = String(arg);
|
|
76
|
+
return (nodes) => unique(nodes.flatMap((node) => continueFrom(node, css)));
|
|
77
|
+
}
|
|
78
|
+
case "has":
|
|
79
|
+
case "not": {
|
|
80
|
+
const inner = compileSteps(arg.tasks, watched);
|
|
81
|
+
const wanted = op === "has";
|
|
82
|
+
return keep((node) => run(inner, [node]).length > 0 === wanted);
|
|
83
|
+
}
|
|
84
|
+
case "has-text": {
|
|
85
|
+
const matches = textMatcher(arg);
|
|
86
|
+
return keep((node) => matches(node.textContent ?? ""));
|
|
87
|
+
}
|
|
88
|
+
case "matches-path": {
|
|
89
|
+
const matches = textMatcher(arg);
|
|
90
|
+
// All or nothing: the filter only applies on some pages of the site.
|
|
91
|
+
return (nodes) => matches(location.pathname + location.search) ? nodes : [];
|
|
92
|
+
}
|
|
93
|
+
case "matches-media": {
|
|
94
|
+
const query = String(arg);
|
|
95
|
+
return (nodes) => (matchMedia(query).matches ? nodes : []);
|
|
96
|
+
}
|
|
97
|
+
case "matches-attr": {
|
|
98
|
+
const { name, value } = arg;
|
|
99
|
+
const nameMatches = textMatcher(name, true);
|
|
100
|
+
const valueMatches = value === undefined ? () => true : textMatcher(value, true);
|
|
101
|
+
return keep((node) => node instanceof Element &&
|
|
102
|
+
[...node.attributes].some((attribute) => nameMatches(attribute.name) && valueMatches(attribute.value)));
|
|
103
|
+
}
|
|
104
|
+
case "matches-css": {
|
|
105
|
+
const { name, pseudo, value } = arg;
|
|
106
|
+
const matches = textMatcher(value, true);
|
|
107
|
+
return keep((node) => node instanceof Element &&
|
|
108
|
+
matches(getComputedStyle(node, pseudo === "" ? null : pseudo)
|
|
109
|
+
.getPropertyValue(name)
|
|
110
|
+
.trim()));
|
|
111
|
+
}
|
|
112
|
+
case "matches-prop": {
|
|
113
|
+
const { name, value } = arg;
|
|
114
|
+
const chain = String(name).split(".");
|
|
115
|
+
const matches = value === undefined ? undefined : textMatcher(value, true);
|
|
116
|
+
return keep((node) => {
|
|
117
|
+
let current = node;
|
|
118
|
+
for (const property of chain) {
|
|
119
|
+
if (typeof current !== "object" || current === null)
|
|
120
|
+
return false;
|
|
121
|
+
current = current[property];
|
|
122
|
+
}
|
|
123
|
+
if (current === undefined)
|
|
124
|
+
return false;
|
|
125
|
+
if (matches === undefined)
|
|
126
|
+
return true;
|
|
127
|
+
// An object has no text to compare with the filter's value.
|
|
128
|
+
return ((typeof current === "string" ||
|
|
129
|
+
typeof current === "number" ||
|
|
130
|
+
typeof current === "boolean") &&
|
|
131
|
+
matches(String(current)));
|
|
132
|
+
});
|
|
133
|
+
}
|
|
134
|
+
case "min-text-length": {
|
|
135
|
+
const length = Number(arg);
|
|
136
|
+
return keep((node) => (node.textContent ?? "").length >= length);
|
|
137
|
+
}
|
|
138
|
+
case "others":
|
|
139
|
+
return others;
|
|
140
|
+
case "upward": {
|
|
141
|
+
if (typeof arg !== "number") {
|
|
142
|
+
const selector = String(arg);
|
|
143
|
+
return (nodes) => unique(nodes.flatMap((node) => {
|
|
144
|
+
try {
|
|
145
|
+
return node.parentElement?.closest(selector) ?? [];
|
|
146
|
+
}
|
|
147
|
+
catch {
|
|
148
|
+
return [];
|
|
149
|
+
}
|
|
150
|
+
}));
|
|
151
|
+
}
|
|
152
|
+
return (nodes) => unique(nodes.flatMap((node) => {
|
|
153
|
+
let up = node;
|
|
154
|
+
for (let i = 0; i < arg && up !== null; i++)
|
|
155
|
+
up = up.parentElement;
|
|
156
|
+
return up ?? [];
|
|
157
|
+
}));
|
|
158
|
+
}
|
|
159
|
+
case "watch-attr": {
|
|
160
|
+
// Selects nothing new: it says which attribute changes to rerun for.
|
|
161
|
+
const names = arg;
|
|
162
|
+
for (const name of names.length === 0 ? ["*"] : names)
|
|
163
|
+
watched.add(name);
|
|
164
|
+
return (nodes) => nodes;
|
|
165
|
+
}
|
|
166
|
+
case "xpath": {
|
|
167
|
+
const expression = String(arg);
|
|
168
|
+
return (nodes) => unique(nodes.flatMap((node) => {
|
|
169
|
+
try {
|
|
170
|
+
const result = document.evaluate(expression, node, null, XPathResult.UNORDERED_NODE_SNAPSHOT_TYPE, null);
|
|
171
|
+
return Array.from({ length: result.snapshotLength }, (_, i) => result.snapshotItem(i)).filter((found) => found instanceof Element);
|
|
172
|
+
}
|
|
173
|
+
catch {
|
|
174
|
+
return [];
|
|
175
|
+
}
|
|
176
|
+
}));
|
|
177
|
+
}
|
|
178
|
+
default:
|
|
179
|
+
return undefined;
|
|
180
|
+
}
|
|
181
|
+
}
|
|
182
|
+
function compileSteps(tasks, watched) {
|
|
183
|
+
return tasks.map(
|
|
184
|
+
// An operator this version doesn't know selects nothing: hiding too
|
|
185
|
+
// little is the safe way to be wrong.
|
|
186
|
+
(task) => compileTask(task, watched) ?? (() => []));
|
|
187
|
+
}
|
|
188
|
+
function run(steps, nodes) {
|
|
189
|
+
for (const step of steps) {
|
|
190
|
+
if (nodes.length === 0)
|
|
191
|
+
break;
|
|
192
|
+
nodes = step(nodes);
|
|
193
|
+
}
|
|
194
|
+
return nodes;
|
|
195
|
+
}
|
|
196
|
+
/** Compiles the plan the parser made of a procedural filter. */
|
|
197
|
+
export function compileFilter(plan) {
|
|
198
|
+
const watched = new Set();
|
|
199
|
+
const steps = compileSteps(plan.tasks, watched);
|
|
200
|
+
return {
|
|
201
|
+
select: () => run(steps, plan.selector === "" ? [document] : select(document, plan.selector)).filter((node) => node instanceof Element),
|
|
202
|
+
watched,
|
|
203
|
+
action: plan.action,
|
|
204
|
+
};
|
|
205
|
+
}
|
|
206
|
+
/** `name` or `/regex/flags`, as the action operators take them. */
|
|
207
|
+
export function nameMatcher(text) {
|
|
208
|
+
const regex = /^\/(.+)\/([dgimsuvy]*)$/.exec(text);
|
|
209
|
+
return regex === null
|
|
210
|
+
? (name) => name === text
|
|
211
|
+
: textMatcher([regex[1], regex[2]]);
|
|
212
|
+
}
|