diff --git a/.gitignore b/.gitignore index 0e6579a..3175a82 100644 --- a/.gitignore +++ b/.gitignore @@ -45,3 +45,6 @@ tools/text_corpus/cache/ # (RELEASE_NOTES_1.7.6.md and on) are committed. /RELEASE_NOTES_1.9.0.md /RESTYLE_REPORT_1.10.md + +# Chrome writes this when the repository root is loaded unpacked +_metadata/ diff --git a/CHANGELOG.md b/CHANGELOG.md index 7e6aa4e..718d609 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -33,6 +33,25 @@ All notable project changes should be documented here going forward. - A wrong answer says where it first went wrong (a character that didn't match, one left out or one extra, a letter in the wrong case) before the new code takes its place. Continue with nothing typed keeps the code. +- **NSFW subreddits opened unblocked when signed out of Reddit.** To tell + whether a subreddit is NSFW, the extension asked Reddit's + `/r//about.json`. Reddit now refuses that address to signed-out + visitors ("You've been blocked by network security", a 403), for every + subreddit, and the refusal was read as "not NSFW". So the page loaded. + - The answer is read from the page Reddit serves, which carries it + (``, `subreddit.isNsfw`). No request is needed for it. + - A refusal now counts as no answer, not as "not NSFW". It is never + remembered, and the extension stops asking about.json for ten minutes + after one, rather than send a refused request for every post in a feed. + Firefox receives the refusal as a failed request rather than a 403; that + pauses it the same way, and no longer prints an error on every Reddit + page. + - The page is checked again once it has parsed, since the first check runs + before Reddit's data is there. + - Posts on current Reddit (``) are recognised, and one Reddit + marks `nsfw` is hidden. The old selectors matched a Reddit layout that no + longer exists, so no post was ever hidden. + - Tests: `tests/reddit-nsfw.test.js`. ## [2.0.7] - 2026-11-09 diff --git a/PRIVACY_POLICY.md b/PRIVACY_POLICY.md index f555ae9..3586fb9 100644 --- a/PRIVACY_POLICY.md +++ b/PRIVACY_POLICY.md @@ -236,6 +236,8 @@ GitHub-hosted URL and caches them in your browser. When Reddit-related filtering features are used, BlockNSFW may query Reddit endpoints to determine whether a subreddit is marked as NSFW. +On a subreddit's own page, BlockNSFW first reads the NSFW flag Reddit includes in that page. That reading happens on your device and sends nothing. Reddit is asked only when the page doesn't answer, and not at all for ten minutes after Reddit refuses a request. + - Service used: `www.reddit.com` - Purpose: help identify NSFW Reddit content - Data involved: subreddit name or Reddit URL needed for the check, plus standard request metadata. Because this request is made from the page you are on, it carries your Reddit cookies when you are browsing Reddit itself diff --git a/README.md b/README.md index 56bd048..25a4105 100644 --- a/README.md +++ b/README.md @@ -71,7 +71,9 @@ Main files: - `data/UNSAFE_SEARCH.json` - search engines SafeSearch can't reach, blocked while "Block other search engines" is on, added since the last release (the ones that ship are in `shared/unsafe-search.js`) - `data/SOURCE_NOTES.txt` - data-file provenance, curation policy, missed-site flow - `blocklist.json` - bundled fallback blocklist (regenerated from `data/HOSTS.txt`) -- `build-chrome.ps1` / `build-firefox.ps1` - release bundle scripts +- `build-chrome.ps1` / `build-firefox.ps1` - release bundle scripts (Windows) +- `build-chrome.sh` / `build-firefox.sh` - the same builds on macOS and Linux (`scripts/build-extension.sh`) +- `build-safari.sh` - Safari Web Extension and its Xcode project (macOS) Tech stack: @@ -150,10 +152,24 @@ powershell -ExecutionPolicy Bypass -File .\build-firefox.ps1 powershell -ExecutionPolicy Bypass -File .\build-firefox.ps1 -Zip ``` +macOS and Linux (bash, node and zip): the same steps, checks and file lists, +read from the `.ps1` scripts so the two can't drift. + +```bash +./build-chrome.sh # or --zip, --open-source, --zip --sandbox +./build-firefox.sh +``` + +Safari (macOS with Xcode): the Firefox build, wrapped in a Mac app. + +```bash +./build-safari.sh --build # add --open-source without extras-private/ +``` + A build from this repository alone is the open-source build: every protection, without the Supporter extras (see "Open source, and the Supporter -extras" below). `-Zip` makes a store package and needs the extras; add -`-OpenSource` to package without them. A store package also refuses to +extras" below). `-Zip` (`--zip`) makes a store package and needs the extras; add +`-OpenSource` (`--open-source`) to package without them. A store package also refuses to build while Supporter is still in Polar's sandbox (`RELEASE_CHECKLIST.md`, section 0); `-Zip -Sandbox` makes a test package, never for a store. Every zip is read back by `scripts/check-package.js` before the build calls @@ -164,6 +180,7 @@ Build output: - `dist\chrome\` - `dist\firefox\` +- `dist/safari/` (`extension/`, `xcode/`, and with `--build` the app in `build/`) ## Manual Smoke Test diff --git a/background.js b/background.js index 1bcf63e..979bbe9 100644 --- a/background.js +++ b/background.js @@ -988,6 +988,26 @@ async function storeBlocklistInCache(domains) { return meta; } +// The chunk cache only makes the next wake cheaper, so nothing waits on it. +// Writes run detached and one at a time: Safari can leave a storage.local.set +// unsettled forever, and a second multi-megabyte write queued behind it would +// only pile up. A write that never settles therefore also blocks later writes +// for this lifetime, which is the point; the in-memory list is already live. +let blocklistCacheWrite = null; +function cacheBlocklistInBackground(domains, onStored) { + if (blocklistCacheWrite) return; + blocklistCacheWrite = (async () => { + try { + const meta = await storeBlocklistInCache(domains); + if (meta && onStored) await onStored(meta); + } catch (error) { + console.warn('BlockNSFW: blocklist cache write failed', error); + } finally { + blocklistCacheWrite = null; + } + })(); +} + async function loadBlocklistFromCache() { const meta = blocklistMeta || (await loadBlocklistMeta()); if (!meta || !meta.chunkCount) { @@ -1041,17 +1061,14 @@ async function ensureRemoteBlocklistUpToDate(options = {}) { const remoteDomains = await fetchRemoteBlocklist(); if (remoteDomains.length > 0) { - const newMeta = await storeBlocklistInCache(remoteDomains); - const refreshedDomains = await loadBlocklistFromCache(); - if (Array.isArray(refreshedDomains) && refreshedDomains.length > 0) { - defaultBlocklist = refreshedDomains; - } else { - defaultBlocklist = remoteDomains.map(normalizeDomainForCache).filter(isLikelyDomain); - } + // Applied in memory first and not read back from the cache: the write + // below may never settle, and verdicts must not wait on it. + defaultBlocklist = Array.from(new Set(remoteDomains.map(normalizeDomainForCache).filter(isLikelyDomain))); defaultBlocklistSet = new Set(defaultBlocklist); await applyPublicSuffixGuard(); await rebuildCompiledPatterns(); - return { meta: newMeta, domains: defaultBlocklist }; + cacheBlocklistInBackground(remoteDomains); + return { meta: blocklistMeta, domains: defaultBlocklist }; } return { meta, domains: defaultBlocklist }; @@ -2506,22 +2523,22 @@ async function loadDefaultBlocklist() { // 204k domains, while ensureRemoteBlocklistUpToDate() returned early // because the metadata was not stale. The chunk cache, whose entire // purpose is to make a wake cheap, was never populated at all. - const meta = await storeBlocklistInCache(defaultBlocklist); - if (meta) { + // Not awaited: initialisation must not wait on this write (Safari can + // leave it unsettled). The in-memory meta below keeps the bundled + // timestamp for this lifetime; the stored one lands when the write does. + blocklistMeta = { + updatedAt: BUNDLED_BLOCKLIST_BUILT_AT || Date.now(), + chunkCount: 0, + version: 1, + source: 'bundled', + domainCount: defaultBlocklist.length + }; + cacheBlocklistInBackground(defaultBlocklist, async meta => { meta.source = 'bundled'; meta.updatedAt = BUNDLED_BLOCKLIST_BUILT_AT || Date.now(); blocklistMeta = meta; await browserAPI.storage.local.set({ [BLOCKLIST_CACHE_META_KEY]: meta }); - } else { - blocklistMeta = { - updatedAt: BUNDLED_BLOCKLIST_BUILT_AT || Date.now(), - chunkCount: 0, - version: 1, - source: 'bundled', - domainCount: defaultBlocklist.length - }; - await browserAPI.storage.local.set({ [BLOCKLIST_CACHE_META_KEY]: blocklistMeta }); - } + }); } else { // Preserve the original bundled timestamp across restarts so its normal // TTL can expire and trigger a remote refresh. @@ -3868,7 +3885,25 @@ async function getActiveWhitelistDomains() { } } -async function updateDnrRules() { +// One update at a time, and calls that arrive while one is waiting to start +// share it: it reads the settings when it starts, so it already covers them. +// Two at once each clear the rules and re-add them, and Safari refuses the +// second copy of an id that's already there, which counted good rules as +// refused (seen 2026-11-19: startup and the settings-defaults write overlapped). +let dnrUpdateChain = Promise.resolve(); +let dnrUpdateWaiting = null; +function updateDnrRules() { + if (dnrUpdateWaiting) return dnrUpdateWaiting; + const run = dnrUpdateChain.then(() => { + dnrUpdateWaiting = null; + return syncDynamicRules(); + }); + dnrUpdateWaiting = run; + dnrUpdateChain = run.catch(() => {}); + return run; +} + +async function syncDynamicRules() { try { if (!browserAPI.declarativeNetRequest || typeof browserAPI.declarativeNetRequest.updateDynamicRules !== 'function') { console.warn('BlockNSFW: declarativeNetRequest API not available; skipping dynamic rules'); @@ -3893,17 +3928,113 @@ async function updateDnrRules() { addRules.push(...buildCustomImageBlockRules(imageBlockDomains)); } - await browserAPI.declarativeNetRequest.updateDynamicRules({ - removeRuleIds: ALL_DNR_RULE_IDS, - addRules - }); - - console.log(`BlockNSFW: Dynamic rules updated (${addRules.length} active)`); + const applied = await applyDynamicRules(addRules); + console.log(`BlockNSFW: Dynamic rules updated (${applied} of ${addRules.length} active)`); } catch (error) { console.error('BlockNSFW: failed to update dynamic rules', error); } } +// updateDynamicRules is all-or-nothing: one rule the browser can't take +// rejects the whole call. Safari compiles DNR rules into WebKit content-blocker +// rules, whose regex has no alternation (`a|b`) and no `\d`, so it refused the +// Bing rule and with it every SafeSearch, whitelist-allow and custom-image +// rule (Safari 17, 2026-11-19: dynamic rules 0). +// +// The batch is still tried first, so a browser that takes it keeps one atomic +// swap with no moment where the allow rules are missing. Only when it's +// refused are the old rules cleared and each new one added on its own, so the +// rules the browser can't take are the only ones missing. +// +// That fallback is ~23 calls, and Safari recompiles every rule list, static +// ruleset included, on each one it accepts. So a browser that refused rules +// gets them remembered (DNR_STATE_KEY): later updates leave them out and go in +// one call, and an update that would change nothing makes no call at all. +// A browser that never refused anything stores nothing and takes the batch +// every time, as before. Returns how many rules are in force. +async function applyDynamicRules(addRules) { + const dnr = browserAPI.declarativeNetRequest; + const state = await readDnrState(); + const refusedIds = new Set(state ? state.refused : []); + const wanted = addRules.filter(rule => !refusedIds.has(rule.id)); + const signature = JSON.stringify(wanted); + + if (state && state.signature === signature && await dnrRulesInForce(dnr, wanted)) { + return wanted.length; + } + + try { + await dnr.updateDynamicRules({ removeRuleIds: ALL_DNR_RULE_IDS, addRules: wanted }); + if (state) await writeDnrState({ ...state, signature }); + return wanted.length; + } catch (batchError) { + console.warn('BlockNSFW: dynamic rules refused as a batch, adding them one at a time', batchError); + } + + await dnr.updateDynamicRules({ removeRuleIds: ALL_DNR_RULE_IDS }); + const accepted = []; + const refused = []; + for (const rule of wanted) { + try { + await dnr.updateDynamicRules({ addRules: [rule] }); + accepted.push(rule); + } catch (error) { + refusedIds.add(rule.id); + refused.push(`${rule.id}: ${error && error.message ? error.message : error}`); + } + } + if (refused.length) { + console.warn(`BlockNSFW: ${refused.length} dynamic rule(s) this browser can't take:\n ${refused.join('\n ')}`); + } + await writeDnrState({ ...dnrStateScope(), refused: [...refusedIds], signature: JSON.stringify(accepted) }); + return accepted.length; +} + +// Refusals hold for one extension version in one browser build: a release can +// rewrite a refused rule, and a browser update can start taking it. +const DNR_STATE_KEY = 'pblocker_dnr_state'; + +function dnrStateScope() { + return { + version: browserAPI.runtime.getManifest().version, + ua: typeof navigator !== 'undefined' && navigator.userAgent ? navigator.userAgent : '' + }; +} + +async function readDnrState() { + try { + const { [DNR_STATE_KEY]: state } = await browserAPI.storage.local.get(DNR_STATE_KEY); + const scope = dnrStateScope(); + if (state && state.version === scope.version && state.ua === scope.ua && + Array.isArray(state.refused) && typeof state.signature === 'string') { + return state; + } + } catch (_) {} + return null; +} + +async function writeDnrState(state) { + try { + await browserAPI.storage.local.set({ [DNR_STATE_KEY]: state }); + } catch (error) { + console.warn('BlockNSFW: could not remember the refused dynamic rules', error); + } +} + +// The browser can drop dynamic rules (Safari clears them with the extension's +// data), so "nothing changed" also needs the ids it holds to be the ids wanted. +async function dnrRulesInForce(dnr, wanted) { + if (typeof dnr.getDynamicRules !== 'function') return false; + try { + const managed = new Set(ALL_DNR_RULE_IDS); + const held = (await dnr.getDynamicRules()).map(rule => rule.id).filter(id => managed.has(id)); + const want = wanted.map(rule => rule.id); + return held.length === want.length && want.every(id => held.includes(id)); + } catch (_) { + return false; + } +} + // storage.session is memory-only and never written to disk, which is what // makes it the right home for the blocked page's detail (see stashBlockedDetail // in content.js) and for the AI image verdict cache. Both live in content @@ -3947,7 +4078,10 @@ function initializeBackground() { .catch(e => console.warn('BlockNSFW: subscribed lists could not be loaded', e)); await rebuildCompiledPatterns(); await initializeExtensionStateTracking(); - await updateDnrRules(); + // Not awaited: verdicts never read the dynamic rules, and in Safari each + // accepted call recompiles every rule list, static ruleset included. Awaited, + // it held ready (and onboarding) back 16-28 s on every wake (2026-11-19). + updateDnrRules().catch(e => console.warn('BlockNSFW: dynamic rules update failed', e)); ensureRemoteWhitelistUpToDate().catch(e => console.warn('BlockNSFW: initial whitelist sync failed', e)); ensureUnsafeSearchUpToDate().catch(e => console.warn('BlockNSFW: search engine list sync failed', e)); // Not forced: each subscription re-downloads only once its own day is up. diff --git a/build-chrome.sh b/build-chrome.sh new file mode 100755 index 0000000..b41a2de --- /dev/null +++ b/build-chrome.sh @@ -0,0 +1,11 @@ +#!/usr/bin/env bash +# build-chrome.sh +# The macOS/Linux counterpart of build-chrome.ps1: builds dist/chrome/ from this folder. +# Usage: +# ./build-chrome.sh +# ./build-chrome.sh --zip +# ./build-chrome.sh --open-source +# ./build-chrome.sh --zip --sandbox +# Same steps and checks as build-chrome.ps1, whose file lists it reads +# (scripts/build-extension.sh does the work). +exec "$(dirname "${BASH_SOURCE[0]}")/scripts/build-extension.sh" chrome "$@" diff --git a/build-firefox.sh b/build-firefox.sh new file mode 100755 index 0000000..cef8824 --- /dev/null +++ b/build-firefox.sh @@ -0,0 +1,11 @@ +#!/usr/bin/env bash +# build-firefox.sh +# The macOS/Linux counterpart of build-firefox.ps1: builds dist/firefox/ from this folder. +# Usage: +# ./build-firefox.sh +# ./build-firefox.sh --zip +# ./build-firefox.sh --open-source +# ./build-firefox.sh --zip --sandbox +# Same steps and checks as build-firefox.ps1, whose file lists it reads +# (scripts/build-extension.sh does the work). +exec "$(dirname "${BASH_SOURCE[0]}")/scripts/build-extension.sh" firefox "$@" diff --git a/build-safari.sh b/build-safari.sh new file mode 100755 index 0000000..5f4d2c4 --- /dev/null +++ b/build-safari.sh @@ -0,0 +1,123 @@ +#!/usr/bin/env bash +# build-safari.sh +# Builds a Safari Web Extension (macOS) from this folder into dist/safari/. +# Usage: +# ./build-safari.sh # stage the extension and generate the Xcode project +# ./build-safari.sh --build # ...and compile it, signed to run locally +# ./build-safari.sh --open-source # leave the Supporter extras as empty stand-ins +# ./build-safari.sh --bundle-id com.example.blocknsfw +# +# macOS only: Apple's safari-web-extension-converter ships with Xcode, and a +# Safari extension has to live inside a Mac app, which Xcode builds. +# +# Safari gets the Firefox build, not the Chrome one. Safari has no +# chrome.offscreen, and the Firefox build already runs everything Chrome puts +# in the offscreen document (the AI image classifier) on the background page. +# So the extension is staged by the Firefox build itself +# (scripts/build-extension.sh firefox): one list per build, and Safari can't +# drift from the build it's based on. +# +# Output: +# dist/safari/extension/ the staged web extension (what the converter reads) +# dist/safari/xcode/ the generated Xcode project +# dist/safari/build/ with --build: BlockNSFW.app, signed to run locally +# +# This is a development build. It does not package for the App Store: that +# needs an Apple Developer team, its signing identity and a real bundle ID. + +set -euo pipefail + +BUILD=0 +OPEN_SOURCE=0 +BUNDLE_ID="local.blocknsfw.safari" + +while [[ $# -gt 0 ]]; do + case "$1" in + --build) BUILD=1 ;; + --open-source) OPEN_SOURCE=1 ;; + --bundle-id) + [[ $# -ge 2 ]] || { echo "--bundle-id needs a value" >&2; exit 2; } + BUNDLE_ID="$2"; shift ;; + -h|--help) sed -n '2,25p' "$0"; exit 0 ;; + *) echo "Unknown option: $1 (see --help)" >&2; exit 2 ;; + esac + shift +done + +step() { printf '\033[36m==> %s\033[0m\n' "$*"; } +warn() { printf '\033[33m==> %s\033[0m\n' "$*"; } +fail() { printf '\033[31mbuild-safari: %s\033[0m\n' "$*" >&2; exit 1; } + +[[ "$(uname -s)" == "Darwin" ]] || fail "Safari extensions build on macOS only." +xcrun --find safari-web-extension-converter >/dev/null 2>&1 \ + || fail "safari-web-extension-converter not found. Install Xcode and run: sudo xcode-select -s /Applications/Xcode.app" + +ROOT="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)" +OUT="$ROOT/dist/safari" +EXT="$OUT/extension" +cd "$ROOT" + +step "Cleaning $OUT" +rm -rf "$OUT" + +# Staged exactly as the Firefox build: the same lists, extras, data files, +# build timestamp and asset checks (scripts/build-extension.sh), only into +# dist/safari/extension/ instead of dist/firefox/. +STAGE_ARGS=(firefox --out "$EXT") +[[ $OPEN_SOURCE -eq 1 ]] && STAGE_ARGS+=(--open-source) +"$ROOT/scripts/build-extension.sh" "${STAGE_ARGS[@]}" +WITH_EXTRAS=0 +[[ -d "$ROOT/extras-private/extras" && $OPEN_SOURCE -eq 0 ]] && WITH_EXTRAS=1 + +step "Generating the Xcode project" +xcrun safari-web-extension-converter "$EXT" \ + --project-location "$OUT/xcode" \ + --app-name BlockNSFW \ + --bundle-identifier "$BUNDLE_ID" \ + --macos-only \ + --swift \ + --copy-resources \ + --no-open \ + --no-prompt \ + --force + +PROJECT_DIR="$OUT/xcode/BlockNSFW" +APP="$OUT/build/Build/Products/Debug/BlockNSFW.app" + +if [[ $BUILD -eq 1 ]]; then + # "-" is an ad-hoc signature. Without any signature macOS never registers + # the extension, and it doesn't appear in Safari's settings at all; with + # one, Safari runs it once Develop > Allow Unsigned Extensions is on. + step "Compiling, signed to run locally" + xcodebuild \ + -project "$PROJECT_DIR/BlockNSFW.xcodeproj" \ + -scheme BlockNSFW \ + -configuration Debug \ + -derivedDataPath "$OUT/build" \ + CODE_SIGN_IDENTITY="-" \ + CODE_SIGN_STYLE=Manual \ + DEVELOPMENT_TEAM="" \ + PROVISIONING_PROFILE_SPECIFIER="" \ + -quiet \ + build + [[ -d "$APP" ]] || fail "xcodebuild finished but $APP is missing" +fi + +printf '\033[32m==> Safari build complete: %s\033[0m\n' "$OUT" +if [[ $WITH_EXTRAS -eq 1 ]]; then + printf '\033[32m==> Supporter extras: included\033[0m\n' +else + warn "Supporter extras: not included (open-source build)" +fi +if [[ $BUILD -eq 1 ]]; then + cat < App: $APP + To try it: + 1. Safari > Settings > Advanced: show features for web developers + 2. Develop > Allow Unsigned Extensions (Safari turns this off on every quit) + 3. open "$APP" (launching the app is what registers the extension) + 4. Safari > Settings > Extensions: enable BlockNSFW, allow it on every website +EOF +else + echo "==> Xcode project: $PROJECT_DIR/BlockNSFW.xcodeproj (run again with --build to compile)" +fi diff --git a/changelog.html b/changelog.html index b2adefa..004b6f5 100644 --- a/changelog.html +++ b/changelog.html @@ -163,6 +163,12 @@

Fixed

    +
  • +

    NSFW subreddits opened when signed out of Reddit

    +

    + To tell whether a subreddit is NSFW, BlockNSFW asked Reddit, and Reddit now refuses that question to anyone not signed in. The refusal was taken as “not NSFW”, so the subreddit opened. BlockNSFW now reads the answer from the page Reddit sends, which always carries it, and a refusal no longer counts as an answer. Posts Reddit marks NSFW are hidden on today’s Reddit too. +

    +
  • Community stories when they can’t load

    diff --git a/content.js b/content.js index b0687f7..59dd91f 100644 --- a/content.js +++ b/content.js @@ -511,6 +511,11 @@ const INSTAGRAM_REELS_STYLE_ID = 'pblocker-instagram-reels-style'; // Reddit NSFW checking let redditNSFWCache = new Map(); // Cache for Reddit subreddit NSFW status const REDDIT_CACHE_DURATION = 30 * 60 * 1000; // 30 minutes +// Reddit refuses about.json to a whole client at once (signed out, or not +// trusted by its bot check), not to one subreddit. After a refusal, stop asking +// for a while rather than send one refused request per post in a feed. +let redditApiRefusedUntil = 0; +const REDDIT_API_BACKOFF_MS = 10 * 60 * 1000; // 10 minutes // Performance optimization: Debouncing and caching const DEBOUNCE_DELAY = 100; @@ -1774,8 +1779,10 @@ const SEARCH_SELECTORS = { // Social site specific selectors - target post containers (not whole feeds) const SOCIAL_SELECTORS = { reddit: { - // New Reddit uses data-testid post containers; include classic .Post as fallback - containers: 'div[data-testid="post-container"], article[data-testid="post-container"], .Post' + // Current Reddit renders each post as (marked `nsfw` when + // Reddit counts it as NSFW). The data-testid containers are the previous + // redesign, and .Post the one before; both kept for old.reddit-style pages. + containers: 'shreddit-post, div[data-testid="post-container"], article[data-testid="post-container"], .Post' }, twitter: { // Twitter/X tweet articles @@ -3393,13 +3400,56 @@ function extractSubredditFromURL(url) { } } +// Reddit's own answer, from the page it served. +// +// Reddit refuses /r//about.json to signed-out visitors with an HTML 403 +// ("You've been blocked by network security"): its HTML pages are served once +// the browser passes a JavaScript challenge, its JSON endpoints are refused +// outright. Every subreddit page it renders still carries the flag: +// +// Reading it needs no request, so there is nothing for Reddit to refuse. +// +// true/false only when the data is about `subredditName`. null when the element +// has not parsed yet, is malformed, has no flag, or names another subreddit (an +// in-app navigation can leave the previous page's data behind). The name may +// sit on instead; it is taken from there only when +// both elements carry the same subreddit id, i.e. describe the same render. +function readRedditPageNsfw(subredditName, doc) { + if (!subredditName || !doc || typeof doc.querySelector !== 'function') return null; + const subredditData = (selector) => { + try { + const el = doc.querySelector(selector); + const raw = el && el.getAttribute('data'); + const sub = raw ? JSON.parse(raw).subreddit : null; + return sub && typeof sub === 'object' ? sub : null; + } catch (_) { + return null; + } + }; + const page = subredditData('reddit-page-data[data]'); + if (!page || typeof page.isNsfw !== 'boolean') return null; + // Reddit serves the name as `prefixedName` ("r/pics"); `name` is accepted too. + let name = typeof page.name === 'string' ? page.name + : typeof page.prefixedName === 'string' ? page.prefixedName : ''; + if (!name) { + const view = subredditData('shreddit-screenview-data[data]'); + if (view && typeof view.name === 'string' && page.id && view.id === page.id) name = view.name; + } + name = name.replace(/^\/?r\//i, '').toLowerCase(); + if (!name || name !== String(subredditName).toLowerCase()) return null; + return page.isNsfw; +} + +// true or false when Reddit has answered, null when it has not (refused, +// failed, or no answer yet). A refusal is not "not NSFW": it is never cached, +// so the page data can still answer once it has parsed. async function checkRedditSubredditNSFW(subredditName) { if (!useSmartBlocking) return false; if (!subredditName) return false; - + const cacheKey = subredditName.toLowerCase(); const now = Date.now(); - + // Check cache first if (redditNSFWCache.has(cacheKey)) { const cached = redditNSFWCache.get(cacheKey); @@ -3410,12 +3460,28 @@ async function checkRedditSubredditNSFW(subredditName) { return cached.isNSFW; } } - + + // 1) The page Reddit served, when it is the subreddit asked about. + if ((extractSubredditFromURL(window.location.href) || '').toLowerCase() === cacheKey) { + const fromPage = readRedditPageNsfw(subredditName, document); + if (fromPage !== null) { + redditNSFWCache.set(cacheKey, { isNSFW: fromPage, timestamp: now }); + if (debugMode) log(`Reddit page data: r/${subredditName} NSFW status: ${fromPage}`); + return fromPage; + } + } + + // 2) about.json, unless Reddit refused it recently. + if (now < redditApiRefusedUntil) { + if (debugMode) log(`Reddit API refused recently; r/${subredditName} unknown`); + return null; + } + try { if (debugMode) { log(`Checking Reddit API for r/${subredditName}...`); } - + // Fetch subreddit info from Reddit API const apiUrl = `https://www.reddit.com/r/${subredditName}/about.json`; const response = await fetch(apiUrl, { @@ -3423,52 +3489,78 @@ async function checkRedditSubredditNSFW(subredditName) { 'User-Agent': 'BlockNSFW Extension' } }); - + if (!response.ok) { + // 403 "blocked by network security" or 429: Reddit refused to answer. + if (response.status === 403 || response.status === 429) { + redditApiRefusedUntil = now + REDDIT_API_BACKOFF_MS; + } if (debugMode) { log(`Reddit API error for r/${subredditName}: ${response.status}`); } - return false; + return null; } - + const data = await response.json(); - const isNSFW = data?.data?.over18 || false; - + const over18 = data && data.data ? data.data.over18 : undefined; + if (typeof over18 !== 'boolean') return null; + // Cache the result redditNSFWCache.set(cacheKey, { - isNSFW: isNSFW, + isNSFW: over18, timestamp: now }); - + if (debugMode) { - log(`Reddit r/${subredditName} NSFW status: ${isNSFW}`); + log(`Reddit r/${subredditName} NSFW status: ${over18}`); } - - return isNSFW; - + + return over18; + } catch (error) { - log('Error checking Reddit subreddit NSFW status:', error); - return false; + // Firefox's content script receives Reddit's refusal as a NetworkError, + // not a 403. Same pause, and no console error: it happens on every Reddit + // page there and says nothing the user can act on. + redditApiRefusedUntil = now + REDDIT_API_BACKOFF_MS; + if (debugMode) log('Reddit API request failed for r/' + subredditName + ':', error); + return null; } } async function shouldBlockRedditPage(url) { if (!useSmartBlocking) return false; if (!isRedditURL(url)) return false; - + const subreddit = extractSubredditFromURL(url); if (!subreddit) return false; - - // Check if subreddit is NSFW - const isNSFW = await checkRedditSubredditNSFW(subreddit); - + + // Check if subreddit is NSFW. Unknown (null) does not block. + const isNSFW = (await checkRedditSubredditNSFW(subreddit)) === true; + if (isNSFW && debugMode) { log(`Blocking Reddit page - r/${subreddit} is marked as NSFW`); } - + return isNSFW; } +// processContent() first runs at document_start, before has +// parsed, so its Reddit check can only reach about.json, which Reddit refuses +// to signed-out visitors. It may also still be busy (and so skip) when the +// page finishes parsing. This asks again on its own: once the page has parsed, +// and whenever Reddit renders new page data. +async function recheckRedditPage() { + if (!IS_TOP_FRAME || blockedTriggered || !isEnabled || !useSmartBlocking) return false; + const href = window.location.href; + if (!isRedditURL(href) || !extractSubredditFromURL(href)) return false; + if (await isCurrentPageWhitelisted()) return false; + if (!(await shouldBlockRedditPage(href))) return false; + if (blockedTriggered || window.location.href !== href) return false; + log('Reddit page blocked - subreddit is NSFW (page data)'); + redirectToBlockedPage('reddit_nsfw'); + return true; +} + // Social post-level blocking (synchronous): detect NSFW labels or adult-domain links function shouldBlockSocialPost(element, site) { try { @@ -3477,6 +3569,8 @@ function shouldBlockSocialPost(element, site) { // 1) NSFW/Sensitive labels if (site === 'reddit') { + // Current Reddit marks the post itself: . + if (useSmartBlocking && typeof element.hasAttribute === 'function' && element.hasAttribute('nsfw')) return true; // Reddit posts commonly show an "NSFW" badge if (useSmartBlocking && text.includes('nsfw')) return true; // Badge/aria-based hints @@ -6174,6 +6268,7 @@ function setupMutationObserver() { let scheduleSocialProcess = false; let schedulePageTextScan = false; let scheduleMedia = false; + let scheduleRedditRecheck = false; const engine = getSearchEngine(); const containerSelector = engine ? searchContainerSelector(SEARCH_SELECTORS[engine]) : null; const socialSite = getSocialSite(); @@ -6196,6 +6291,9 @@ function setupMutationObserver() { if (el.tagName === 'IMG') observeImage(el); else if (el.tagName === 'VIDEO') observeMedia(el); else if (el.tagName === 'IFRAME') processIframe(el); + // Reddit's answer to "is this subreddit NSFW" arriving in the page + // (see readRedditPageNsfw). A tag-name compare, so free elsewhere. + else if (el.tagName === 'REDDIT-PAGE-DATA') scheduleRedditRecheck = true; // A full-page text scan is only worth scheduling when a text feature // is actually enabled. We no longer read el.textContent per node just // to decide this — the debounced scan re-reads the page once anyway, @@ -6305,6 +6403,9 @@ function setupMutationObserver() { if (scheduleMedia) { scheduleMediaDiscovery(); } + if (scheduleRedditRecheck) { + recheckRedditPage(); + } if (scheduleResultsProcess) { debouncedProcessResults(); } @@ -6459,6 +6560,9 @@ function setupEventListeners() { if (document.readyState === 'loading') { document.addEventListener('DOMContentLoaded', () => { setTimeout(processContent, 100); + // Not left to processContent: it skips while an earlier pass is still + // running, and on Reddit that pass started before the page data parsed. + recheckRedditPage(); }, { once: true }); } @@ -6671,7 +6775,7 @@ if (typeof window !== 'undefined') { log(`Testing Reddit NSFW status for r/${subredditName}...`); try { const isNSFW = await checkRedditSubredditNSFW(subredditName); - log(`Result: r/${subredditName} is ${isNSFW ? 'NSFW' : 'SFW'}`); + log(`Result: r/${subredditName} is ${isNSFW === null ? 'unknown (Reddit did not answer)' : isNSFW ? 'NSFW' : 'SFW'}`); return isNSFW; } catch (error) { log('Error testing Reddit NSFW:', error); diff --git a/scripts/build-extension.sh b/scripts/build-extension.sh new file mode 100755 index 0000000..6e6adc9 --- /dev/null +++ b/scripts/build-extension.sh @@ -0,0 +1,192 @@ +#!/usr/bin/env bash +# scripts/build-extension.sh +# The macOS/Linux build. Stages a Chrome or Firefox bundle step for step as +# build-chrome.ps1 / build-firefox.ps1 do, and with --zip packs it and reads +# it back. build-chrome.sh, build-firefox.sh and build-safari.sh call it. +# Usage: +# scripts/build-extension.sh [--zip] [--open-source] [--sandbox] [--out DIR] +# +# The file lists are read from build-.ps1, parsed the way the tests +# parse them (tests/page-scripts-ship.test.js), so each build keeps one list +# and the two platforms can't drift apart. +# +# --zip makes a store package: it needs the Supporter extras (extras-private/), +# Polar's live store, and everything that ships committed, as on Windows. +# --open-source packages without the extras; --sandbox makes a test package. +# --out stages somewhere other than dist// (build-safari.sh uses it). + +set -euo pipefail + +step() { printf '\033[36m==> %s\033[0m\n' "$*"; } +warn() { printf '\033[33m==> %s\033[0m\n' "$*"; } +ok() { printf '\033[32m==> %s\033[0m\n' "$*"; } +fail() { printf '\033[31mbuild-extension: %s\033[0m\n' "$*" >&2; exit 1; } + +TARGET="${1:-}" +case "$TARGET" in + chrome|firefox) shift ;; + -h|--help) sed -n '2,17p' "$0"; exit 0 ;; + *) echo "First argument must be chrome or firefox (see --help)" >&2; exit 2 ;; +esac + +ZIP=0 +OPEN_SOURCE=0 +SANDBOX=0 +OUT="" +while [[ $# -gt 0 ]]; do + case "$1" in + --zip) ZIP=1 ;; + --open-source) OPEN_SOURCE=1 ;; + --sandbox) SANDBOX=1 ;; + --out) + [[ $# -ge 2 ]] || { echo "--out needs a directory" >&2; exit 2; } + OUT="$2"; shift ;; + -h|--help) sed -n '2,17p' "$0"; exit 0 ;; + *) echo "Unknown option: $1 (see --help)" >&2; exit 2 ;; + esac + shift +done + +command -v node >/dev/null || fail "node is required." + +ROOT="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)" +cd "$ROOT" + +case "$TARGET" in + chrome) LABEL="Chrome"; MANIFEST="manifest.json" ;; + firefox) LABEL="Firefox"; MANIFEST="manifest.firefox.json" ;; +esac +PS1="$ROOT/build-$TARGET.ps1" +OUT="${OUT:-$ROOT/dist/$TARGET}" +ZIP_PATH="$ROOT/dist/blocknsfw-$TARGET.zip" + +# Checked before anything is cleaned, so a refused package leaves dist/ as it was. +if [[ $ZIP -eq 1 && $OPEN_SOURCE -eq 0 && $SANDBOX -eq 0 ]]; then + step "Checking that Supporter sells through the live store" + node scripts/check-store-mode.js \ + || fail "Not packaging for a store while Supporter is in Polar's sandbox (RELEASE_CHECKLIST.md, section 0). Pass --sandbox for a test package." + step "Checking that everything that ships is committed" + node scripts/check-package.js tree \ + || fail "Not packaging for a store from code that isn't committed: the build note couldn't say what the release carries." +fi +if [[ $ZIP -eq 1 ]]; then + command -v zip >/dev/null || fail "zip is required for --zip (macOS ships it; on Linux install the zip package)." +fi + +read_list() { + node -e ' + const src = require("fs").readFileSync(process.argv[1], "utf8"); + const block = src.match(new RegExp("\\$" + process.argv[2] + "\\s*=\\s*@\\(([\\s\\S]*?)\\)")); + if (!block) { console.error("no $" + process.argv[2] + " list in " + process.argv[1]); process.exit(1); } + for (const m of block[1].matchAll(/"([^"]+)"/g)) console.log(m[1]); + ' "$PS1" "$1" +} +FOLDERS=(); while IFS= read -r line; do FOLDERS+=("$line"); done < <(read_list RuntimeFolders) +FILES=(); while IFS= read -r line; do FILES+=("$line"); done < <(read_list RuntimeFiles) +[[ ${#FOLDERS[@]} -gt 0 && ${#FILES[@]} -gt 0 ]] || fail "Could not read the file lists from $(basename "$PS1")" + +step "Building static declarativeNetRequest ruleset" +# Generated from data/HOSTS.txt. Committed, but rebuilt here so a stale +# ruleset can never ship. +node scripts/build-dnr-ruleset.mjs || fail "Failed to build the static DNR ruleset" + +step "Cleaning $OUT" +rm -rf "$OUT" +mkdir -p "$OUT" + +step "Copying manifest ($MANIFEST)" +cp "$MANIFEST" "$OUT/manifest.json" + +step "Copying runtime folders" +for folder in "${FOLDERS[@]}"; do + [[ -e "$folder" ]] && cp -R "$folder" "$OUT/" +done + +if [[ "$TARGET" == "firefox" ]]; then + step "Packing the static ruleset into one rule for Firefox" + # Same domains, one rule (see FIREFOX GETS ONE RULE in the generator). + node scripts/build-dnr-ruleset.mjs --firefox "$OUT/rules/blocklist-rules.json" \ + || fail "Failed to pack the static DNR ruleset for Firefox" +fi + +step "Copying runtime files" +for file in "${FILES[@]}"; do + [[ -e "$file" ]] && cp "$file" "$OUT/$file" +done + +# Supporter extras: each empty stand-in in extras/ is replaced by its file +# from the private repository. Only those names, so nothing else in that +# repository (its tests, its tools) can reach a package. +EXTRAS_SRC="$ROOT/extras-private/extras" +rm -f "$OUT"/extras/*.md +WITH_EXTRAS=0 +if [[ -d "$EXTRAS_SRC" && $OPEN_SOURCE -eq 0 ]]; then + step "Copying the Supporter extras from extras-private" + for stub in "$OUT"/extras/*; do + [[ -f "$stub" ]] || continue + name="$(basename "$stub")" + real="$EXTRAS_SRC/$name" + [[ -f "$real" ]] || fail "extras-private/extras is missing $name" + [[ -s "$real" ]] || fail "extras-private/extras/$name is empty" + cmp -s "$real" "$stub" && fail "extras-private/extras/$name is only the stand-in" + cp "$real" "$stub" + done + WITH_EXTRAS=1 +elif [[ $ZIP -eq 1 && $OPEN_SOURCE -eq 0 ]]; then + fail "A store package needs the Supporter extras. Check out the private repository at extras-private/, or pass --open-source to package without them." +else + warn "Open-source build: the Supporter extras stay empty stand-ins" +fi + +step "Copying data files" +# Only the public suffix list ships; data/HOSTS.txt and data/WHITELIST.txt are +# fetched at runtime, not package content. +mkdir -p "$OUT/data" +cp data/public-suffixes.txt "$OUT/data/public-suffixes.txt" + +node -e ' + const fs = require("fs"); + const [file, label] = process.argv.slice(1); + const token = "__BLOCKNSFW_BUILD_TIMESTAMP_MS__"; + const src = fs.readFileSync(file, "utf8"); + if (!src.includes(token)) { console.error("Missing bundled blocklist build timestamp token in " + label + " background.js"); process.exit(1); } + fs.writeFileSync(file, src.split(token).join(String(Date.now()))); +' "$OUT/background.js" "$LABEL" + +step "Verifying AI runtime assets" +for asset in \ + data/public-suffixes.txt \ + rules/blocklist-rules.json \ + vendor/tfjs/tf.es2017.js \ + vendor/nsfwjs/nsfwjs.runtime.js \ + nsfwjs/model.json \ + nsfwjs/group1-shard1of1.bin \ + text-model.json; do + [[ -e "$OUT/$asset" ]] || fail "Missing required asset in $LABEL build: $asset" +done + +if [[ $ZIP -eq 1 ]]; then + step "Creating $ZIP_PATH" + rm -f "$ZIP_PATH" + # Files only (-D), forward-slash paths, no macOS extra attributes (-X), and + # no dotfiles: the .ps1 builds skip hidden files too, and .DS_Store must + # never reach a store. + (cd "$OUT" && zip -q -r -X -D -9 "$ZIP_PATH" . -x '.*' '*/.*') + + # Read the package back: the extras right for its kind, nothing that + # mustn't ship, and a build note of the commits it came from. + if [[ $OPEN_SOURCE -eq 1 ]]; then KIND="open-source"; elif [[ $SANDBOX -eq 1 ]]; then KIND="test"; else KIND="store"; fi + step "Checking the package ($KIND)" + if ! node scripts/check-package.js zip "$ZIP_PATH" "$TARGET" "$KIND"; then + rm -f "$ZIP_PATH" + fail "The package failed its check and was removed. See the list above." + fi +fi + +ok "$LABEL build complete: $OUT" +if [[ $WITH_EXTRAS -eq 1 ]]; then ok "Supporter extras: included"; else warn "Supporter extras: not included (open-source build)"; fi +if [[ $ZIP -eq 1 && $SANDBOX -eq 1 ]]; then warn "TEST PACKAGE: Supporter uses Polar's sandbox. Never upload it to a store."; fi +if [[ $ZIP -eq 1 ]]; then + ok "Zip: $ZIP_PATH" + ok "Build note: ${ZIP_PATH%.zip}.build.txt (keep it with the release)" +fi diff --git a/scripts/check-package.js b/scripts/check-package.js index fe8e6ea..aa70389 100644 --- a/scripts/check-package.js +++ b/scripts/check-package.js @@ -1,6 +1,6 @@ // scripts/check-package.js // Checks a finished package, and keeps a note of what went into it. -// build-chrome.ps1 and build-firefox.ps1 run it after -Zip; RELEASE_CHECKLIST.md +// build-chrome/firefox .ps1 (-Zip) and .sh (--zip) run it after zipping; RELEASE_CHECKLIST.md // says what to do with the note. // // node scripts/check-package.js tree diff --git a/shared/site-access.js b/shared/site-access.js index 353cb4f..3566a6a 100644 --- a/shared/site-access.js +++ b/shared/site-access.js @@ -26,7 +26,13 @@ (function (root) { 'use strict'; + // What a request asks for (both manifests declare , which covers it). var ORIGINS = ['']; + // What the code needs: content scripts and DNR host access cover http and + // https pages, which is *://*/*. Safari 17 stores an "Always allow on every + // website" grant as *://*/* and answers false for (measured + // 2026-11), so either pattern counts as access. + var NEEDED_ORIGINS = ['*://*/*']; // A held page's address travels in session storage under this prefix, never // in the URL, where it would reach history (see BLOCK_DETAIL_PREFIX in // content.js for why that matters here). @@ -43,7 +49,7 @@ } // 'off' (access is there, or protection is off: nothing to do), 'hold' or - // 'net'. `granted` is permissions.contains for ORIGINS. + // 'net'. `granted` is contains() for the permissions above. function mode(input) { var o = input || {}; if (o.granted !== false || o.enabled === false) return 'off'; @@ -51,16 +57,23 @@ } // Resolves true when the API can't say: a browser without it has no switch. - function contains(permissions) { + // Access is there if either pattern is granted; an grant still + // answers true in Chrome and Firefox, as before. + function containsOne(permissions, origins) { try { - if (!permissions || typeof permissions.contains !== 'function') return Promise.resolve(true); - return Promise.resolve(permissions.contains({ origins: ORIGINS })) + return Promise.resolve(permissions.contains({ origins: origins })) .then(function (ok) { return ok !== false; }, function () { return true; }); } catch (_) { return Promise.resolve(true); } } + function contains(permissions) { + if (!permissions || typeof permissions.contains !== 'function') return Promise.resolve(true); + return Promise.all([containsOne(permissions, ORIGINS), containsOne(permissions, NEEDED_ORIGINS)]) + .then(function (answers) { return answers[0] || answers[1]; }); + } + function newHoldKey() { var c = (root && root.crypto) || (typeof globalThis !== 'undefined' ? globalThis.crypto : null); if (c && typeof c.randomUUID === 'function') return HOLD_PREFIX + c.randomUUID(); diff --git a/tests/block-event-batching.test.js b/tests/block-event-batching.test.js index 076114c..0e24099 100644 --- a/tests/block-event-batching.test.js +++ b/tests/block-event-batching.test.js @@ -20,6 +20,9 @@ const KEYS = { async function harness() { const context = loadBackgroundContext(); await vm.runInContext('backgroundInitializationPromise', context); + // Startup leaves the dynamic-rules update running past ready; its reads are + // startup's, not the flush's, so let it finish before counting. + await vm.runInContext('dnrUpdateChain', context); const disk = {}; const writes = []; diff --git a/tests/bundled-blocklist-freshness.test.js b/tests/bundled-blocklist-freshness.test.js index 10e43a2..134be95 100644 --- a/tests/bundled-blocklist-freshness.test.js +++ b/tests/bundled-blocklist-freshness.test.js @@ -36,7 +36,10 @@ test('packaged blocklist is fresh until its normal refresh TTL expires', async ( throw new Error(`unexpected remote fetch: ${url}`); }; await context.loadDefaultBlocklist(); - await new Promise(resolve => setImmediate(resolve)); + // The cache write is detached from init, so wait for it to land. + for (let i = 0; i < 50 && !writes.some(value => value[META_KEY]); i++) { + await new Promise(resolve => setTimeout(resolve, 5)); + } const metaWrite = writes.find(value => value[META_KEY]); assert.equal(metaWrite[META_KEY].source, 'bundled'); diff --git a/tests/dnr-rule-by-rule.test.js b/tests/dnr-rule-by-rule.test.js new file mode 100644 index 0000000..3f1210c --- /dev/null +++ b/tests/dnr-rule-by-rule.test.js @@ -0,0 +1,242 @@ +const test = require('node:test'); +const assert = require('node:assert/strict'); +const vm = require('node:vm'); +const { loadBackgroundContext } = require('./setup.js'); + +// updateDynamicRules is all-or-nothing: one rule the browser can't take rejects +// the whole call. Safari turns DNR rules into WebKit content-blocker rules, +// whose regex has no alternation (`a|b`) and no `\d`, so it rejected rule 10002 +// (Bing) and with it every SafeSearch, whitelist-allow and custom-image rule. +// Measured 2026-11-19 in Safari 17: dynamic rules 0. These tests pin the +// fallback: when the batch is refused, each rule is added on its own, so only +// the rules the browser can't take are missing. + +// A browser that refuses any call carrying a rule it can't compile, the way +// Safari does, and keeps the rules of every call it accepts. +function safariLikeDnr() { + const applied = new Map(); + const calls = []; + const unsupported = (rule) => { + const re = rule.condition && rule.condition.regexFilter; + return typeof re === 'string' && (re.includes('|') || re.includes('\\d')); + }; + return { + applied, + calls, + updateDynamicRules: async ({ removeRuleIds = [], addRules = [] } = {}) => { + calls.push({ removeRuleIds, addRules }); + const bad = addRules.findIndex(unsupported); + if (bad !== -1) { + throw new Error(`Error with rule at index ${bad}: Rule with id ${addRules[bad].id} is invalid. \`regexFilter\` is not a supported regular expression.`); + } + for (const id of removeRuleIds) applied.delete(id); + for (const rule of addRules) applied.set(rule.id, rule); + }, + getDynamicRules: async () => [...applied.values()] + }; +} + +// The update startup kicks off is drained on the default stub before `dnr` +// goes in, so every call a test counts is one it made itself. +async function harness(dnr, { storage } = {}) { + const context = loadBackgroundContext(); + await vm.runInContext('backgroundInitializationPromise', context); + context.console = { ...console, log() {}, warn() {}, error() {} }; + await context.updateDnrRules(); + if (storage) { + context.chrome.storage.local.get = async (keys) => { + const list = keys == null ? [...storage.keys()] : [].concat(keys); + const out = {}; + for (const key of list) if (storage.has(key)) out[key] = JSON.parse(JSON.stringify(storage.get(key))); + return out; + }; + context.chrome.storage.local.set = async (items) => { + for (const [key, value] of Object.entries(items)) storage.set(key, JSON.parse(JSON.stringify(value))); + }; + } + context.chrome.declarativeNetRequest = dnr; + return context; +} + +// What Safari takes from the current SafeSearch set, by id. Spread into this +// realm's Array: deepStrictEqual tells the vm sandbox's arrays apart. +function acceptedIds(context) { + return [...vm.runInContext('buildSafeSearchRules()', context)] + .filter(r => !/\||\\d/.test(r.condition.regexFilter || '')) + .map(r => r.id) + .sort((a, b) => a - b); +} + +function appliedIds(dnr) { + return [...dnr.applied.keys()].sort((a, b) => a - b); +} + +test('a rule the browser rejects no longer takes every other dynamic rule with it', async () => { + const dnr = safariLikeDnr(); + const context = await harness(dnr); + const built = vm.runInContext('buildSafeSearchRules()', context); + const accepted = built.filter(r => !/\||\\d/.test(r.condition.regexFilter || '')); + assert.ok(accepted.length > 0 && accepted.length < built.length, + 'the SafeSearch set should mix rules Safari takes and rules it refuses'); + + await context.updateDnrRules(); + + assert.ok(dnr.applied.has(10001), 'Google SafeSearch (no alternation) should apply'); + assert.ok(!dnr.applied.has(10002), 'Bing (alternation) is refused on its own'); + for (const rule of accepted) { + assert.ok(dnr.applied.has(rule.id), `rule ${rule.id} should survive a refused neighbour`); + } +}); + +test('the fallback clears the old rules, so a removed rule does not linger', async () => { + const dnr = safariLikeDnr(); + dnr.applied.set(10050, { id: 10050 }); // left over from an earlier update + const context = await harness(dnr); + + await context.updateDnrRules(); + + assert.ok(!dnr.applied.has(10050), 'every managed id is removed before the rules go back one by one'); +}); + +test('a browser that takes the whole batch gets one atomic call, as before', async () => { + const applied = new Map(); + const calls = []; + const dnr = { + updateDynamicRules: async ({ removeRuleIds = [], addRules = [] } = {}) => { + calls.push({ removeRuleIds, addRules }); + for (const id of removeRuleIds) applied.delete(id); + for (const rule of addRules) applied.set(rule.id, rule); + }, + getDynamicRules: async () => [...applied.values()] + }; + const context = await harness(dnr); + + await context.updateDnrRules(); + + assert.equal(calls.length, 1, 'Chrome and Firefox keep the single remove-and-add update'); + assert.ok(calls[0].removeRuleIds.length > 0 && calls[0].addRules.length > 0); +}); + +// ---- What the fallback costs, measured in Safari 17 (2026-11-19) ------------ +// +// Safari recompiles its whole content-blocker list, static ruleset included, +// on every updateDynamicRules call it accepts. The fallback made ~23 calls, and +// startup awaited them: ready at 16-28 s, so onboarding opened that late and +// every wake left that long a window where the full list didn't answer. + +function never() { + return new Promise(() => {}); +} + +function settlesWithin(promise, ms) { + return Promise.race([ + promise.then(() => 'settled'), + new Promise(resolve => setTimeout(() => resolve('pending'), ms)) + ]); +} + +test('readiness does not wait on dynamic rules', async () => { + const context = loadBackgroundContext(undefined, sandbox => { + sandbox.chrome.declarativeNetRequest.updateDynamicRules = never; + }); + context.console = { ...console, log() {}, warn() {}, error() {} }; + + assert.equal(await settlesWithin(vm.runInContext('initReady', context), 1000), 'settled', + 'verdicts never read the dynamic rules, so they must not wait for them'); + assert.equal(await settlesWithin(vm.runInContext('backgroundInitializationPromise', context), 1000), 'settled', + 'onInstalled awaits initialisation before it opens onboarding'); +}); + +// Real browsers refuse a rule id that's already there. Two fallbacks running +// at once each clear the rules and re-add them, so one's adds collide with the +// other's and good rules get counted as refused. +function strictSafariLikeDnr() { + const dnr = safariLikeDnr(); + const inner = dnr.updateDynamicRules; + dnr.inFlight = 0; + dnr.maxInFlight = 0; + dnr.updateDynamicRules = async (options = {}) => { + dnr.inFlight++; + dnr.maxInFlight = Math.max(dnr.maxInFlight, dnr.inFlight); + try { + await new Promise(resolve => setTimeout(resolve, 1)); + for (const rule of options.addRules || []) { + const removed = (options.removeRuleIds || []).includes(rule.id); + if (dnr.applied.has(rule.id) && !removed) { + dnr.calls.push(options); + throw new Error(`Rule with id ${rule.id} already exists.`); + } + } + return await inner(options); + } finally { + dnr.inFlight--; + } + }; + return dnr; +} + +test('updates that overlap run one after the other and leave the right rules', async () => { + const dnr = strictSafariLikeDnr(); + const context = await harness(dnr, { storage: new Map() }); + + await Promise.all([context.updateDnrRules(), context.updateDnrRules(), context.updateDnrRules()]); + + assert.equal(dnr.maxInFlight, 1, 'never two DNR calls at once'); + assert.deepEqual(appliedIds(dnr), acceptedIds(context)); +}); + +test('a wake with nothing to change makes no DNR call', async () => { + const dnr = safariLikeDnr(); + const storage = new Map(); + const context = await harness(dnr, { storage }); + + await context.updateDnrRules(); + const before = dnr.calls.length; + await context.updateDnrRules(); + + assert.equal(dnr.calls.length, before, 'each accepted call costs Safari a full recompile'); + assert.deepEqual(appliedIds(dnr), acceptedIds(context)); +}); + +test('a later change goes in one call, without the rules the browser refused', async () => { + const dnr = safariLikeDnr(); + const storage = new Map(); + const context = await harness(dnr, { storage }); + + await context.updateDnrRules(); + storage.set('pblocker_whitelist', [{ domain: 'example.com', type: 'permanent' }]); + const before = dnr.calls.length; + await context.updateDnrRules(); + + const made = dnr.calls.slice(before); + assert.equal(made.length, 1, 'one batch, not the fallback again'); + assert.ok(!made[0].addRules.some(r => r.id === 10002), 'a remembered refusal is left out'); + assert.ok(appliedIds(dnr).length > acceptedIds(context).length, 'the whitelist allow rule went in'); +}); + +test('rules the browser lost are put back', async () => { + const dnr = safariLikeDnr(); + const context = await harness(dnr, { storage: new Map() }); + + await context.updateDnrRules(); + dnr.applied.clear(); + await context.updateDnrRules(); + + assert.deepEqual(appliedIds(dnr), acceptedIds(context)); +}); + +test('a new extension version forgets the refusals and asks again', async () => { + const dnr = safariLikeDnr(); + const storage = new Map(); + const context = await harness(dnr, { storage }); + + await context.updateDnrRules(); + context.chrome.runtime.getManifest = () => ({ version: '9.9.9' }); + const before = dnr.calls.length; + await context.updateDnrRules(); + + const made = dnr.calls.slice(before); + assert.ok(made[0].addRules.some(r => r.id === 10002), + 'a release can fix a refused rule, so its first update offers every rule again'); + assert.deepEqual(appliedIds(dnr), acceptedIds(context)); +}); diff --git a/tests/init-ready-cache-write.test.js b/tests/init-ready-cache-write.test.js new file mode 100644 index 0000000..e379050 --- /dev/null +++ b/tests/init-ready-cache-write.test.js @@ -0,0 +1,56 @@ +const test = require('node:test'); +const assert = require('node:assert/strict'); +const fs = require('node:fs'); +const path = require('node:path'); +const vm = require('node:vm'); +const { loadBackgroundContext } = require('./setup.js'); + +// Readiness must not depend on the blocklist cache write. +// +// Safari 17 never settles the chunked storage.local.set that stores the 4 MB +// bundled list, so the old init path awaited it forever: initReady never +// resolved, shouldBlock() never answered, and content scripts (which fail open) +// let every navigation through. The cache is a speed-up for the next wake, so +// a hung or rejected write must not hold up anything that waits on init. + +const CHUNK_PREFIX = 'pblocker_blocklist_chunk_v2_'; +const BUNDLED_LIST = JSON.parse(fs.readFileSync(path.join(__dirname, '..', 'blocklist.json'), 'utf8')); +const PUBLIC_SUFFIX_TEXT = fs.readFileSync(path.join(__dirname, '..', 'data', 'public-suffixes.txt'), 'utf8'); + +function never() { + return new Promise(() => {}); +} + +function settlesWithin(promise, ms) { + return Promise.race([ + promise.then(() => 'settled'), + new Promise(resolve => setTimeout(() => resolve('pending'), ms)) + ]); +} + +test('a never-settling blocklist cache write does not hold up readiness or verdicts', async () => { + const context = loadBackgroundContext(undefined, sandbox => { + sandbox.fetch = async url => { + if (String(url).endsWith('public-suffixes.txt')) { + return { ok: true, text: async () => PUBLIC_SUFFIX_TEXT }; + } + if (url === 'blocklist.json') { + return { json: async () => BUNDLED_LIST }; + } + throw new Error(`unexpected fetch in test: ${url}`); + }; + sandbox.chrome.storage.local.set = items => ( + Object.keys(items).some(key => key.startsWith(CHUNK_PREFIX)) + ? never() + : Promise.resolve() + ); + }); + + const ready = vm.runInContext('initReady', context); + assert.equal(await settlesWithin(ready, 1000), 'settled', + 'initReady must resolve even though the chunk write never settles'); + + const domain = BUNDLED_LIST[0]; + assert.equal(await context.shouldBlock(`https://${domain}/`), true, + 'a domain from the bundled list must be blocked once ready'); +}); diff --git a/tests/reddit-nsfw.test.js b/tests/reddit-nsfw.test.js new file mode 100644 index 0000000..ae97879 --- /dev/null +++ b/tests/reddit-nsfw.test.js @@ -0,0 +1,275 @@ +const test = require('node:test'); +const assert = require('node:assert/strict'); +const fs = require('node:fs'); +const path = require('node:path'); +const vm = require('node:vm'); + +// Reddit refuses /r//about.json to signed-out visitors with an HTML 403 +// ("You've been blocked by network security"), for SFW and NSFW subreddits +// alike. The check read that refusal as "not NSFW", so r/ loaded +// unblocked. Reddit does give the answer in the page it serves: +// . + +const source = fs.readFileSync(path.join(__dirname, '..', 'content.js'), 'utf8'); + +function functionSource(name) { + const match = new RegExp(`(?:async )?function ${name}\\(`).exec(source); + assert.ok(match, `${name} should exist`); + const bodyStart = source.indexOf('{', match.index); + let depth = 0; + for (let index = bodyStart; index < source.length; index++) { + if (source[index] === '{') depth++; + if (source[index] === '}') depth--; + if (depth === 0) return source.slice(match.index, index + 1); + } + throw new Error(`could not parse ${name}`); +} + +// A document holding Reddit's page-data elements, as a subreddit page has them. +function redditDocument({ page, view } = {}) { + const elements = { + 'reddit-page-data[data]': page, + 'shreddit-screenview-data[data]': view + }; + return { + querySelector(selector) { + const data = elements[selector]; + if (data === undefined) return null; + return { getAttribute: (name) => (name === 'data' ? (typeof data === 'string' ? data : JSON.stringify(data)) : null) }; + } + }; +} + +const GONEWILD_PAGE = { + page: { subreddit: { id: 't5_2qq5c', isNsfw: true } }, + view: { subreddit: { id: 't5_2qq5c', name: 'gonewild' } } +}; + +function response(status, body) { + return { + ok: status >= 200 && status < 300, + status, + json: async () => (typeof body === 'string' ? JSON.parse(body) : body) + }; +} + +function loadRedditCheck({ href = 'https://www.reddit.com/r/gonewild/', doc = redditDocument(), replies = [] } = {}) { + const requests = []; + const redirects = []; + const sandbox = { + Map, URL, Date, JSON, Promise, console, + window: { location: { href } }, + document: doc, + requests, + redirects, + logged: [], + async fetch(url) { + requests.push(url); + const next = replies.length ? replies.shift() : response(403, 'blocked'); + if (next instanceof Error) throw next; + return next; + } + }; + vm.createContext(sandbox); + vm.runInContext(` + let useSmartBlocking = true; + let debugMode = false; + let isEnabled = true; + let blockedTriggered = false; + const IS_TOP_FRAME = true; + function log(...args) { logged.push(args.map(String).join(' ')); } + async function isCurrentPageWhitelisted() { return false; } + function redirectToBlockedPage(reason) { blockedTriggered = true; redirects.push(reason); } + let redditNSFWCache = new Map(); + const REDDIT_CACHE_DURATION = 30 * 60 * 1000; + let redditApiRefusedUntil = 0; + const REDDIT_API_BACKOFF_MS = 10 * 60 * 1000; + ${functionSource('isRedditURL')} + ${functionSource('extractSubredditFromURL')} + ${functionSource('readRedditPageNsfw')} + ${functionSource('checkRedditSubredditNSFW')} + ${functionSource('shouldBlockRedditPage')} + ${functionSource('recheckRedditPage')} + this.setSmartBlocking = (on) => { useSmartBlocking = on; }; + this.cacheSize = () => redditNSFWCache.size; + `, sandbox); + return sandbox; +} + +// ─── Reddit's answer in the page ───────────────────────────────────────────── + +test('the page data answers for the subreddit it names', () => { + const ctx = loadRedditCheck(); + assert.equal(ctx.readRedditPageNsfw('gonewild', redditDocument(GONEWILD_PAGE)), true); + assert.equal(ctx.readRedditPageNsfw('GoneWild', redditDocument(GONEWILD_PAGE)), true, 'names compare case-insensitively'); + assert.equal(ctx.readRedditPageNsfw('pics', redditDocument({ + page: { subreddit: { id: 't5_2qh0u', name: 'pics', isNsfw: false } } + })), false); +}); + +test('page data about another subreddit is no answer', () => { + // An in-app navigation can leave the previous page's data behind. + const ctx = loadRedditCheck(); + assert.equal(ctx.readRedditPageNsfw('pics', redditDocument(GONEWILD_PAGE)), null); + // A name from a different render (ids disagree) is not trusted either. + assert.equal(ctx.readRedditPageNsfw('gonewild', redditDocument({ + page: { subreddit: { id: 't5_aaaaa', isNsfw: true } }, + view: { subreddit: { id: 't5_2qq5c', name: 'gonewild' } } + })), null); +}); + +test('missing, malformed or nameless page data is no answer', () => { + const ctx = loadRedditCheck(); + assert.equal(ctx.readRedditPageNsfw('gonewild', redditDocument()), null, 'not parsed yet'); + assert.equal(ctx.readRedditPageNsfw('gonewild', redditDocument({ page: '{"subreddit":' })), null, 'bad JSON'); + assert.equal(ctx.readRedditPageNsfw('gonewild', redditDocument({ page: { subreddit: { id: 't5_2qq5c', isNsfw: true } } })), null, 'no name anywhere'); + assert.equal(ctx.readRedditPageNsfw('gonewild', redditDocument({ + page: { subreddit: { id: 't5_2qq5c', name: 'gonewild' } } + })), null, 'no isNsfw flag'); +}); + +// ─── The check ─────────────────────────────────────────────────────────────── + +test('an NSFW subreddit page is blocked from its own page data, with no request', async () => { + const ctx = loadRedditCheck({ doc: redditDocument(GONEWILD_PAGE) }); + assert.equal(await ctx.shouldBlockRedditPage('https://www.reddit.com/r/gonewild/'), true); + assert.deepEqual(ctx.requests, [], 'about.json is not asked when the page already says'); +}); + +test('a refused about.json is unknown: not "not NSFW", not cached, not asked again at once', async () => { + // The signed-out case: no page data yet (document_start), Reddit answers 403. + const ctx = loadRedditCheck({ replies: [response(403, 'blocked by network security')] }); + assert.equal(await ctx.checkRedditSubredditNSFW('gonewild'), null); + assert.equal(await ctx.shouldBlockRedditPage('https://www.reddit.com/r/gonewild/'), false); + assert.equal(ctx.cacheSize(), 0, 'a refusal is never remembered as an answer'); + // Reddit refuses the client, not one subreddit: a feed must not send one + // refused request per post. + await ctx.checkRedditSubredditNSFW('pics'); + await ctx.checkRedditSubredditNSFW('aww'); + assert.equal(ctx.requests.length, 1, 'no further about.json while Reddit is refusing'); +}); + +test('a refusal does not stop the page data from answering later', async () => { + const ctx = loadRedditCheck({ replies: [response(403, 'blocked')] }); + assert.equal(await ctx.shouldBlockRedditPage('https://www.reddit.com/r/gonewild/'), false); + ctx.document = redditDocument(GONEWILD_PAGE); // the page has now parsed + assert.equal(await ctx.shouldBlockRedditPage('https://www.reddit.com/r/gonewild/'), true); +}); + +test('about.json still answers when Reddit allows it, and the answer is cached', async () => { + const ctx = loadRedditCheck({ replies: [response(200, { data: { over18: true } })] }); + assert.equal(await ctx.shouldBlockRedditPage('https://www.reddit.com/r/gonewild/'), true); + assert.equal(await ctx.shouldBlockRedditPage('https://www.reddit.com/r/gonewild/'), true); + assert.equal(ctx.requests.length, 1, 'served from cache the second time'); +}); + +test('a network failure or an answer without over18 is unknown', async () => { + const failed = loadRedditCheck({ replies: [new TypeError('NetworkError')] }); + assert.equal(await failed.checkRedditSubredditNSFW('gonewild'), null); + const odd = loadRedditCheck({ replies: [response(200, { kind: 't5' })] }); + assert.equal(await odd.checkRedditSubredditNSFW('gonewild'), null); + assert.equal(odd.cacheSize(), 0); +}); + +test('a network failure pauses about.json too, and stays out of the console', async () => { + // Firefox's content script gets Reddit's refusal as a NetworkError, not a + // 403. Without a pause, every post linking a subreddit in a feed would send + // a failing request and print an error. + const ctx = loadRedditCheck({ replies: [new TypeError('NetworkError when attempting to fetch resource.')] }); + assert.equal(await ctx.checkRedditSubredditNSFW('gonewild'), null); + assert.equal(await ctx.checkRedditSubredditNSFW('pics'), null); + assert.equal(await ctx.checkRedditSubredditNSFW('aww'), null); + assert.equal(ctx.requests.length, 1, 'no further about.json after a network failure'); + assert.deepEqual(ctx.logged, [], 'nothing logged with debug mode off'); +}); + +test('the page data names the subreddit as prefixedName ("r/")', () => { + // As Reddit serves it: no `name`, and no needed. + const ctx = loadRedditCheck(); + const page = { subreddit: { id: 't5_2qq5c', isNsfw: true, prefixedName: 'r/gonewild' } }; + assert.equal(ctx.readRedditPageNsfw('gonewild', redditDocument({ page })), true); + assert.equal(ctx.readRedditPageNsfw('pics', redditDocument({ page })), null); +}); + +test('page data for another subreddit is not read for a link elsewhere', async () => { + // On r/gonewild, a post linking r/pics must not borrow r/gonewild's answer. + const ctx = loadRedditCheck({ doc: redditDocument(GONEWILD_PAGE), replies: [response(200, { data: { over18: false } })] }); + assert.equal(await ctx.shouldBlockRedditPage('https://www.reddit.com/r/pics/comments/abc/'), false); + assert.deepEqual(ctx.requests, ['https://www.reddit.com/r/pics/about.json']); +}); + +test('smart blocking off asks nothing and blocks nothing', async () => { + const ctx = loadRedditCheck({ doc: redditDocument(GONEWILD_PAGE) }); + ctx.setSmartBlocking(false); + assert.equal(await ctx.shouldBlockRedditPage('https://www.reddit.com/r/gonewild/'), false); + assert.deepEqual(ctx.requests, []); +}); + +// ─── Checking again once the page has parsed ───────────────────────────────── + +test('the recheck redirects once the page data says NSFW', async () => { + const ctx = loadRedditCheck({ doc: redditDocument(GONEWILD_PAGE) }); + assert.equal(await ctx.recheckRedditPage(), true); + assert.deepEqual(ctx.redirects, ['reddit_nsfw']); +}); + +test('the recheck leaves SFW, non-subreddit and non-Reddit pages alone', async () => { + const sfw = loadRedditCheck({ + href: 'https://www.reddit.com/r/pics/', + doc: redditDocument({ page: { subreddit: { id: 't5_2qh0u', name: 'pics', isNsfw: false } } }) + }); + assert.equal(await sfw.recheckRedditPage(), false); + const home = loadRedditCheck({ href: 'https://www.reddit.com/' }); + assert.equal(await home.recheckRedditPage(), false); + const other = loadRedditCheck({ href: 'https://example.com/r/gonewild/', doc: redditDocument(GONEWILD_PAGE) }); + assert.equal(await other.recheckRedditPage(), false); + for (const ctx of [sfw, home, other]) assert.deepEqual(ctx.redirects, []); + assert.deepEqual(home.requests, []); + assert.deepEqual(other.requests, []); +}); + +test('the recheck runs when the page has parsed and when Reddit renders new page data', () => { + const domReady = /document\.addEventListener\('DOMContentLoaded',\s*\(\)\s*=>\s*\{[^}]*recheckRedditPage\(\)/; + assert.match(source, domReady, 'DOMContentLoaded asks again'); + assert.match(source, /el\.tagName === 'REDDIT-PAGE-DATA'/, 'the observer notices a new '); +}); + +// ─── Posts ─────────────────────────────────────────────────────────────────── + +function loadSocialPostCheck() { + const sandbox = { URL, window: { location: { href: 'https://www.reddit.com/' } } }; + vm.createContext(sandbox); + vm.runInContext(` + let useSmartBlocking = true; + function isAdultURL() { return false; } + function isHostInDefaultBlocklist() { return false; } + function matchesAdultKeywordHost() { return false; } + function containsAdultKeywords() { return false; } + ${functionSource('shouldBlockSocialPost')} + this.setSmartBlocking = (on) => { useSmartBlocking = on; }; + `, sandbox); + return sandbox; +} + +function shredditPost(attributes) { + return { + tagName: 'SHREDDIT-POST', + textContent: 'A post title', + hasAttribute: (name) => Object.prototype.hasOwnProperty.call(attributes, name), + getAttribute: (name) => attributes[name] ?? null, + querySelector: () => null, + querySelectorAll: () => [] + }; +} + +test('current Reddit posts are matched and their nsfw mark is honoured', () => { + const selectors = /reddit:\s*\{[\s\S]*?containers:\s*'([^']*)'/.exec(source); + assert.ok(selectors, 'SOCIAL_SELECTORS.reddit should exist'); + assert.ok(selectors[1].split(',').map(s => s.trim()).includes('shreddit-post'), ' is a post container'); + + const ctx = loadSocialPostCheck(); + assert.equal(ctx.shouldBlockSocialPost(shredditPost({ nsfw: '' }), 'reddit'), true); + assert.equal(ctx.shouldBlockSocialPost(shredditPost({}), 'reddit'), false); + ctx.setSmartBlocking(false); + assert.equal(ctx.shouldBlockSocialPost(shredditPost({ nsfw: '' }), 'reddit'), false); +}); diff --git a/tests/site-access.test.js b/tests/site-access.test.js index 2566c40..7bb5ef3 100644 --- a/tests/site-access.test.js +++ b/tests/site-access.test.js @@ -40,9 +40,36 @@ test('locked means a PIN, a pact, the access code, or a boost, not the extension assert.equal(SA.locked(L.lockState({})), false); }); +// Safari 17 stores "Always allow on every website" as *://*/* and answers +// false for (measured 2026-11). Chrome and Firefox answer for the +// pattern the page needs; a withheld grant answers false for both. +function permissionsStub(granted) { + return { + contains: async (p) => { + assert.equal(p.origins.length, 1); + assert.ok(['', '*://*/*'].includes(p.origins[0]), p.origins[0]); + return granted.includes(p.origins[0]); + }, + }; +} + +test('Safari: all sites granted as *://*/* counts as access', async () => { + assert.equal(await SA.contains(permissionsStub(['*://*/*'])), true); + assert.equal(await SA.contains(permissionsStub(['*://*/*', 'https://*/*'])), true); +}); + +test('Chrome and Firefox: still counts as access', async () => { + assert.equal(await SA.contains(permissionsStub([''])), true); +}); + +test('withheld access, with neither pattern granted, is no access', async () => { + assert.equal(await SA.contains(permissionsStub([])), false); + assert.equal(await SA.contains(permissionsStub(['https://*/*'])), false, 'a single-scheme grant is not all of the web'); +}); + test('asks the browser for all sites, and trusts a browser that cannot say', async () => { assert.equal(await SA.contains(undefined), true); - assert.equal(await SA.contains({ contains: async (p) => { assert.deepEqual(p, { origins: [''] }); return false; } }), false); + assert.equal(await SA.contains({ contains: async (p) => { assert.ok(p.origins.length === 1); return false; } }), false); assert.equal(await SA.contains({ contains: async () => { throw new Error('x'); } }), true); assert.equal(await SA.request({ request: async () => true }), true); assert.equal(await SA.request({ request: () => { throw new Error('no gesture'); } }), false);