Modern-Apps.git
Publicgit clone https://git.maproj.org/Modern-Apps.gitModern-Apps.git / scripts / generate_shields_lists.py
generate_shields_lists.py311 lines · 11.0 KiBRaw
| 1 | #!/usr/bin/env python3 |
| 2 | """Offline generator: Brave Shields filter lists -> web/src/main/assets/shields/ |
| 3 | |
| 4 | Developer-run, not part of the Gradle build. Fetches Brave's own default filter |
| 5 | lists and the resource bodies used by `$redirect` rules, then writes three assets |
| 6 | that `ShieldsEngine.kt` loads at runtime: |
| 7 | |
| 8 | filters.txt.br Every default-enabled list from Brave's list_catalog.json, |
| 9 | comments stripped and concatenated. Brotli-compressed. |
| 10 | resources.json.br A `Vec<Resource>` (adblock-rust's own serde format) holding |
| 11 | the bodies served for `$redirect` / `$redirect-rule` rules. |
| 12 | Brotli-compressed. |
| 13 | version.txt SHA-256 of the two payloads above. `ShieldsEngine` compares |
| 14 | it against the tag stored beside its serialized engine cache |
| 15 | and reparses the lists when they differ. |
| 16 | |
| 17 | The list set is read from Brave's catalog rather than hardcoded, so re-running |
| 18 | this script picks up upstream changes to what Brave enables by default. The |
| 19 | iOS-specific component is the only default-enabled entry that is skipped. |
| 20 | |
| 21 | Scriptlet coverage: the `$redirect` bodies come from uBlock Origin's |
| 22 | `web_accessible_resources/`, indexed by its `redirect-resources.js` map — the |
| 23 | same two inputs adblock-rust's own `resource-assembler` reads. uBO's `##+js(...)` |
| 24 | scriptlets are ES modules since 1.53, so they are enumerated the way Brave does |
| 25 | it: node imports `resources/scriptlets.js` and dumps the `builtinScriptlets` |
| 26 | registry. Scriptlets marked `requiresTrust` are given a non-default permission |
| 27 | mask, which makes adblock-rust refuse to inject them — none of the bundled lists |
| 28 | are trusted sources. |
| 29 | |
| 30 | Usage: python3 scripts/generate_shields_lists.py |
| 31 | Requires: `brotli` and `node` on PATH. |
| 32 | """ |
| 33 | |
| 34 | import base64 |
| 35 | import hashlib |
| 36 | import json |
| 37 | import os |
| 38 | import re |
| 39 | import shutil |
| 40 | import subprocess |
| 41 | import sys |
| 42 | import tempfile |
| 43 | import urllib.request |
| 44 | from pathlib import Path |
| 45 | |
| 46 | REPO_ROOT = Path(__file__).resolve().parent.parent |
| 47 | ASSET_DIR = REPO_ROOT / "web" / "src" / "main" / "assets" / "shields" |
| 48 | |
| 49 | BRAVE_RESOURCES = "https://raw.githubusercontent.com/brave/adblock-resources/master" |
| 50 | LIST_CATALOG = f"{BRAVE_RESOURCES}/filter_lists/list_catalog.json" |
| 51 | BRAVE_SCRIPTLETS = f"{BRAVE_RESOURCES}/dist/resources.json" |
| 52 | |
| 53 | UBO = "https://raw.githubusercontent.com/gorhill/uBlock/master/src" |
| 54 | UBO_REDIRECT_MAP = f"{UBO}/js/redirect-resources.js" |
| 55 | UBO_WEB_ACCESSIBLE = f"{UBO}/web_accessible_resources" |
| 56 | UBO_WEB_ACCESSIBLE_API = ( |
| 57 | "https://api.github.com/repos/gorhill/uBlock/contents/src/web_accessible_resources" |
| 58 | ) |
| 59 | UBO_SCRIPTLET_DIR = f"{UBO}/js/resources" |
| 60 | UBO_SCRIPTLET_API = ( |
| 61 | "https://api.github.com/repos/gorhill/uBlock/contents/src/js/resources" |
| 62 | ) |
| 63 | # Imported by files under js/resources/ but living one directory up. |
| 64 | UBO_SCRIPTLET_SIBLINGS = ("urlskip.js", "arglist-parser.js", "jsonpath.js") |
| 65 | |
| 66 | # adblock-rust refuses to inject a resource whose permission mask is not a subset of the |
| 67 | # filter's. Filters from untrusted lists carry mask 0, so any non-zero value here means |
| 68 | # "never injected" — which is what we want for uBO's trusted-* scriptlets. |
| 69 | TRUSTED_PERMISSION = 1 |
| 70 | |
| 71 | # Brave enables this for iOS only; every other default-enabled component applies. |
| 72 | SKIP_LIST_TITLES = {"Brave IOS-Specific Filters"} |
| 73 | |
| 74 | # adblock-rust's MimeType::from_extension. |
| 75 | MIME_BY_EXTENSION = { |
| 76 | ".css": "text/css", |
| 77 | ".gif": "image/gif", |
| 78 | ".html": "text/html", |
| 79 | ".js": "application/javascript", |
| 80 | ".json": "application/json", |
| 81 | ".mp3": "audio/mp3", |
| 82 | ".mp4": "video/mp4", |
| 83 | ".png": "image/png", |
| 84 | ".txt": "text/plain", |
| 85 | ".xml": "text/xml", |
| 86 | } |
| 87 | |
| 88 | |
| 89 | def fetch(url: str) -> bytes: |
| 90 | request = urllib.request.Request(url, headers={"User-Agent": "modern-apps-shields"}) |
| 91 | with urllib.request.urlopen(request, timeout=120) as response: |
| 92 | return response.read() |
| 93 | |
| 94 | |
| 95 | def fetch_text(url: str) -> str: |
| 96 | return fetch(url).decode("utf-8", errors="replace") |
| 97 | |
| 98 | |
| 99 | # --------------------------------------------------------------------------- |
| 100 | # filters.txt |
| 101 | # --------------------------------------------------------------------------- |
| 102 | def default_list_urls() -> list[str]: |
| 103 | catalog = json.loads(fetch_text(LIST_CATALOG)) |
| 104 | urls = [] |
| 105 | for component in catalog: |
| 106 | if not component.get("default_enabled"): |
| 107 | continue |
| 108 | if component.get("title") in SKIP_LIST_TITLES: |
| 109 | continue |
| 110 | for source in component.get("sources", []): |
| 111 | url = source.get("url") |
| 112 | if url and url not in urls: |
| 113 | urls.append(url) |
| 114 | return urls |
| 115 | |
| 116 | |
| 117 | def strip_comments(list_text: str) -> str: |
| 118 | """Drops comment and metadata lines. `#` alone never starts a filter comment — |
| 119 | `##selector` is a cosmetic rule — so only `!` and `[Adblock...]` are removed.""" |
| 120 | kept = [] |
| 121 | for line in list_text.splitlines(): |
| 122 | line = line.strip() |
| 123 | if not line or line.startswith("!"): |
| 124 | continue |
| 125 | if line.startswith("[") and line.lower().startswith("[adblock"): |
| 126 | continue |
| 127 | kept.append(line) |
| 128 | return "\n".join(kept) |
| 129 | |
| 130 | |
| 131 | def build_filters() -> bytes: |
| 132 | chunks = [] |
| 133 | for url in default_list_urls(): |
| 134 | print(f" {url}") |
| 135 | chunks.append(strip_comments(fetch_text(url))) |
| 136 | return ("\n".join(chunks) + "\n").encode("utf-8") |
| 137 | |
| 138 | |
| 139 | # --------------------------------------------------------------------------- |
| 140 | # resources.json |
| 141 | # --------------------------------------------------------------------------- |
| 142 | MAP_DECLARATION = "export default new Map([" |
| 143 | |
| 144 | |
| 145 | def parse_redirect_map(mapfile: str) -> list[dict]: |
| 146 | """Ports adblock-rust's `read_redirectable_resource_mapping`: coerce the JS |
| 147 | `Map` literal in redirect-resources.js into JSON and parse it strictly.""" |
| 148 | lines = mapfile.splitlines() |
| 149 | start = lines.index(MAP_DECLARATION) |
| 150 | body = [] |
| 151 | for line in lines[start:]: |
| 152 | if re.match(r"^\s*\]\s*\)", line): |
| 153 | break |
| 154 | line = line.split("//")[0] |
| 155 | line = re.sub(r"\s*/\*[^'\"]*\*/\s*$", "", line) |
| 156 | body.append(line) |
| 157 | |
| 158 | text = "".join(body) |
| 159 | text += "]" |
| 160 | text = text[len(MAP_DECLARATION) - 1 :].replace("'", '"') |
| 161 | text = "".join(text.split()) |
| 162 | text = re.sub(r",([\],\}])", r"\1", text) |
| 163 | text = re.sub(r"([\{,])([a-zA-Z][a-zA-Z0-9_]*):", r'\1"\2":', text) |
| 164 | |
| 165 | entries = [] |
| 166 | for name, props in json.loads(text): |
| 167 | # adblock-rust ignores parameterised resources; they need a JS engine. |
| 168 | if props.get("params") is not None: |
| 169 | continue |
| 170 | alias = props.get("alias") |
| 171 | if alias is None: |
| 172 | aliases = [] |
| 173 | elif isinstance(alias, str): |
| 174 | aliases = [alias] |
| 175 | else: |
| 176 | aliases = list(alias) |
| 177 | entries.append({"name": name, "aliases": aliases}) |
| 178 | return entries |
| 179 | |
| 180 | |
| 181 | DUMP_SCRIPTLETS_MJS = """\ |
| 182 | import { builtinScriptlets } from './resources/scriptlets.js'; |
| 183 | const out = []; |
| 184 | for (const entry of builtinScriptlets) { |
| 185 | if (typeof entry.fn !== 'function') continue; |
| 186 | const resource = { |
| 187 | name: entry.name, |
| 188 | aliases: entry.aliases ?? [], |
| 189 | kind: { mime: entry.name.endsWith('.fn') ? 'fn/javascript' : 'application/javascript' }, |
| 190 | content: Buffer.from(entry.fn.toString(), 'utf8').toString('base64'), |
| 191 | dependencies: entry.dependencies ?? [], |
| 192 | }; |
| 193 | if (entry.requiresTrust === true) resource.permission = %d; |
| 194 | out.push(resource); |
| 195 | } |
| 196 | process.stdout.write(JSON.stringify(out)); |
| 197 | """ % TRUSTED_PERMISSION |
| 198 | |
| 199 | |
| 200 | def build_scriptlets() -> list[dict]: |
| 201 | """Enumerates uBO's `##+js(...)` scriptlets by importing their ES modules in node. |
| 202 | |
| 203 | Each entry becomes a `Resource` whose content is the raw `function name(...) {...}` |
| 204 | source; adblock-rust detects the name and calls it with the filter's arguments, |
| 205 | emitting any `.fn` dependencies alongside it.""" |
| 206 | names = [ |
| 207 | item["name"] |
| 208 | for item in json.loads(fetch_text(UBO_SCRIPTLET_API)) |
| 209 | if item["type"] == "file" |
| 210 | ] |
| 211 | |
| 212 | with tempfile.TemporaryDirectory() as tmp: |
| 213 | root = Path(tmp) |
| 214 | (root / "resources").mkdir() |
| 215 | (root / "package.json").write_text('{"type":"module"}') |
| 216 | (root / "dump.mjs").write_text(DUMP_SCRIPTLETS_MJS) |
| 217 | for name in names: |
| 218 | (root / "resources" / name).write_bytes(fetch(f"{UBO_SCRIPTLET_DIR}/{name}")) |
| 219 | for name in UBO_SCRIPTLET_SIBLINGS: |
| 220 | (root / name).write_bytes(fetch(f"{UBO}/js/{name}")) |
| 221 | |
| 222 | dumped = subprocess.run( |
| 223 | ["node", "dump.mjs"], |
| 224 | cwd=root, |
| 225 | check=True, |
| 226 | capture_output=True, |
| 227 | env={**os.environ, "NODE_OPTIONS": "--no-warnings"}, |
| 228 | ).stdout |
| 229 | |
| 230 | return json.loads(dumped) |
| 231 | |
| 232 | |
| 233 | def build_resources() -> bytes: |
| 234 | print(" redirect-resources.js") |
| 235 | entries = parse_redirect_map(fetch_text(UBO_REDIRECT_MAP)) |
| 236 | |
| 237 | available = { |
| 238 | item["name"] |
| 239 | for item in json.loads(fetch_text(UBO_WEB_ACCESSIBLE_API)) |
| 240 | if item["type"] == "file" |
| 241 | } |
| 242 | |
| 243 | resources = [] |
| 244 | for entry in entries: |
| 245 | name = entry["name"] |
| 246 | if name not in available: |
| 247 | print(f" ! {name} listed in the map but missing upstream, skipping") |
| 248 | continue |
| 249 | raw = fetch(f"{UBO_WEB_ACCESSIBLE}/{name}") |
| 250 | mime = MIME_BY_EXTENSION.get(Path(name).suffix, "application/octet-stream") |
| 251 | if mime in ("application/javascript", "text/html", "text/plain"): |
| 252 | raw = raw.decode("utf-8").replace("\r", "").encode("utf-8") |
| 253 | resources.append( |
| 254 | { |
| 255 | "name": name, |
| 256 | "aliases": entry["aliases"], |
| 257 | "kind": {"mime": mime}, |
| 258 | "content": base64.b64encode(raw).decode("ascii"), |
| 259 | } |
| 260 | ) |
| 261 | print(f" {len(resources)} redirect resources") |
| 262 | |
| 263 | scriptlets = build_scriptlets() |
| 264 | print(f" {len(scriptlets)} uBO scriptlets") |
| 265 | resources.extend(scriptlets) |
| 266 | |
| 267 | brave = json.loads(fetch_text(BRAVE_SCRIPTLETS)) |
| 268 | print(f" {len(brave)} Brave scriptlets") |
| 269 | resources.extend(brave) |
| 270 | |
| 271 | return json.dumps(resources, separators=(",", ":")).encode("utf-8") |
| 272 | |
| 273 | |
| 274 | # --------------------------------------------------------------------------- |
| 275 | def brotli_compress(data: bytes, destination: Path) -> None: |
| 276 | destination.write_bytes(data) |
| 277 | subprocess.run( |
| 278 | ["brotli", "--force", "--quality=11", str(destination)], |
| 279 | check=True, |
| 280 | ) |
| 281 | destination.unlink() |
| 282 | |
| 283 | |
| 284 | def main() -> int: |
| 285 | for tool in ("brotli", "node"): |
| 286 | if shutil.which(tool) is None: |
| 287 | print(f"{tool} not found on PATH", file=sys.stderr) |
| 288 | return 1 |
| 289 | |
| 290 | ASSET_DIR.mkdir(parents=True, exist_ok=True) |
| 291 | |
| 292 | print("filters:") |
| 293 | filters = build_filters() |
| 294 | print("resources:") |
| 295 | resources = build_resources() |
| 296 | |
| 297 | brotli_compress(filters, ASSET_DIR / "filters.txt") |
| 298 | brotli_compress(resources, ASSET_DIR / "resources.json") |
| 299 | |
| 300 | digest = hashlib.sha256(filters + resources).hexdigest() |
| 301 | (ASSET_DIR / "version.txt").write_text(digest + "\n") |
| 302 | |
| 303 | for name in ("filters.txt.br", "resources.json.br", "version.txt"): |
| 304 | path = ASSET_DIR / name |
| 305 | print(f"{path.relative_to(REPO_ROOT)} {path.stat().st_size:,} bytes") |
| 306 | print(f"raw: filters {len(filters):,} resources {len(resources):,}") |
| 307 | return 0 |
| 308 | |
| 309 | |
| 310 | if __name__ == "__main__": |
| 311 | sys.exit(main()) |