Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 3 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -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/
19 changes: 19 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -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/<name>/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
(`<reddit-page-data>`, `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 (`<shreddit-post>`) 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

Expand Down
2 changes: 2 additions & 0 deletions PRIVACY_POLICY.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
23 changes: 20 additions & 3 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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:

Expand Down Expand Up @@ -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
Expand All @@ -164,6 +180,7 @@ Build output:

- `dist\chrome\`
- `dist\firefox\`
- `dist/safari/` (`extension/`, `xcode/`, and with `--build` the app in `build/`)

## Manual Smoke Test

Expand Down
190 changes: 162 additions & 28 deletions background.js
Original file line number Diff line number Diff line change
Expand Up @@ -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) {
Expand Down Expand Up @@ -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 };
Expand Down Expand Up @@ -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.
Expand Down Expand Up @@ -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');
Expand All @@ -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
Expand Down Expand Up @@ -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.
Expand Down
11 changes: 11 additions & 0 deletions build-chrome.sh
Original file line number Diff line number Diff line change
@@ -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 "$@"
11 changes: 11 additions & 0 deletions build-firefox.sh
Original file line number Diff line number Diff line change
@@ -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 "$@"
Loading