Skip to content

Commit a559f5f

Browse files
committed
Add experimental mv3 version
This create a separate Chromium extension, named "uBO Minus (MV3)". This experimental mv3 version supports only the blocking of network requests through the declarativeNetRequest API, so as to abide by the stated MV3 philosophy of not requiring broad "read/modify data" permission. Accordingly, the extension should not trigger the warning at installation time: Read and change all your data on all websites The consequences of being permission-less are the following: - No cosmetic filtering (##) - No scriptlet injection (##+js) - No redirect= filters - No csp= filters - No removeparam= filters At this point there is no popup panel or options pages. The default filterset correspond to the default filterset of uBO proper: Listset for 'default': https://ublockorigin.github.io/uAssets/filters/badware.txt https://ublockorigin.github.io/uAssets/filters/filters.txt https://ublockorigin.github.io/uAssets/filters/filters-2020.txt https://ublockorigin.github.io/uAssets/filters/filters-2021.txt https://ublockorigin.github.io/uAssets/filters/filters-2022.txt https://ublockorigin.github.io/uAssets/filters/privacy.txt https://ublockorigin.github.io/uAssets/filters/quick-fixes.txt https://ublockorigin.github.io/uAssets/filters/resource-abuse.txt https://ublockorigin.github.io/uAssets/filters/unbreak.txt https://easylist.to/easylist/easylist.txt https://easylist.to/easylist/easyprivacy.txt https://malware-filter.gitlab.io/malware-filter/urlhaus-filter-online.txt https://pgl.yoyo.org/adservers/serverlist.php?hostformat=hosts&showintro=1&mimetype=plaintext The result of the conversion of the filters in all these filter lists is as follow: Ruleset size for 'default': 22245 Good: 21408 Maybe good (regexes): 127 redirect-rule= (discarded): 458 csp= (discarded): 85 removeparams= (discarded): 22 Unsupported: 145 The fact that the number of DNR rules are far lower than the number of network filters reported in uBO comes from the fact that lists-to-rulesets converter does its best to coallesce filters into minimal set of rules. Notably, the DNR's requestDomains condition property allows to create a single DNR rule out of all pure hostname-based filters. Regex-based rules are dynamically added at launch time since they must be validated as valid DNR regexes through isRegexSupported() API call. At this point I consider being permission-less the limiting factor: if broad "read/modify data" permission is to be used, than there is not much point for an MV3 version over MV2, just use the MV2 version if you want to benefit all the features which can't be implemented without broad "read/modify data" permission. To locally build the MV3 extension: make mv3 Then load the resulting extension directory in the browser using the "Load unpacked" button. From now on there will be a uBlock0.mv3.zip package available in each release.
1 parent 1def4e7 commit a559f5f

28 files changed

+1651
-368
lines changed

.github/workflows/main.yml

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -45,6 +45,7 @@ jobs:
4545
tools/make-firefox.sh ${{ steps.release_info.outputs.VERSION }}
4646
tools/make-thunderbird.sh ${{ steps.release_info.outputs.VERSION }}
4747
tools/make-npm.sh ${{ steps.release_info.outputs.VERSION }}
48+
tools/make-mv3.sh all
4849
- name: Upload Chromium package
4950
uses: actions/upload-release-asset@v1
5051
env:
@@ -81,3 +82,12 @@ jobs:
8182
asset_path: dist/build/uBlock0_${{ steps.release_info.outputs.VERSION }}.npm.tgz
8283
asset_name: uBlock0_${{ steps.release_info.outputs.VERSION }}.npm.tgz
8384
asset_content_type: application/octet-stream
85+
- name: Upload Chromium MV3 package
86+
uses: actions/upload-release-asset@v1
87+
env:
88+
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
89+
with:
90+
upload_url: ${{ steps.create_release.outputs.upload_url }}
91+
asset_path: dist/build/uBlock0.mv3.zip
92+
asset_name: uBlock0.mv3.zip
93+
asset_content_type: application/octet-stream

Makefile

Lines changed: 6 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,7 @@
11
# https://stackoverflow.com/a/6273809
22
run_options := $(filter-out $@,$(MAKECMDGOALS))
33

4-
.PHONY: all clean test lint chromium firefox npm dig \
4+
.PHONY: all clean test lint chromium firefox npm dig mv3 \
55
compare maxcost medcost mincost modifiers record wasm
66

77
sources := $(wildcard assets/resources/* src/* src/*/* src/*/*/* src/*/*/*/*)
@@ -52,6 +52,11 @@ dig: dist/build/uBlock0.dig
5252
dig-snfe: dig
5353
cd dist/build/uBlock0.dig && npm run snfe $(run_options)
5454

55+
dist/build/uBlock0.mv3: tools/make-mv3.sh $(sources) $(platform)
56+
tools/make-mv3.sh all
57+
58+
mv3: dist/build/uBlock0.mv3
59+
5560
# Update submodules.
5661
update-submodules:
5762
tools/update-submodules.sh

platform/common/vapi-common.js

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -37,7 +37,10 @@ vAPI.setTimeout = vAPI.setTimeout || self.setTimeout.bind(self);
3737

3838
vAPI.webextFlavor = {
3939
major: 0,
40-
soup: new Set()
40+
soup: new Set(),
41+
get env() {
42+
return Array.from(this.soup);
43+
}
4144
};
4245

4346
(( ) => {

platform/mv3/extension/background.js

Lines changed: 65 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,65 @@
1+
'use strict';
2+
3+
import regexRulesets from '/rulesets/regexes.js';
4+
5+
const dnr = chrome.declarativeNetRequest;
6+
7+
dnr.setExtensionActionOptions({ displayActionCountAsBadgeText: true });
8+
9+
(async ( ) => {
10+
const allRules = [];
11+
const toCheck = [];
12+
for ( const regexRuleset of regexRulesets ) {
13+
if ( regexRuleset.enabled !== true ) { continue; }
14+
for ( const rule of regexRuleset.rules ) {
15+
const regex = rule.condition.regexFilter;
16+
const isCaseSensitive = rule.condition.isUrlFilterCaseSensitive === true;
17+
allRules.push(rule);
18+
toCheck.push(dnr.isRegexSupported({ regex, isCaseSensitive }));
19+
}
20+
}
21+
const results = await Promise.all(toCheck);
22+
const newRules = [];
23+
for ( let i = 0; i < allRules.length; i++ ) {
24+
const rule = allRules[i];
25+
const result = results[i];
26+
if ( result instanceof Object && result.isSupported ) {
27+
newRules.push(rule);
28+
} else {
29+
console.info(`${result.reason}: ${rule.condition.regexFilter}`);
30+
}
31+
}
32+
const oldRules = await dnr.getDynamicRules();
33+
const oldRuleMap = new Map(oldRules.map(rule => [ rule.id, rule ]));
34+
const newRuleMap = new Map(newRules.map(rule => [ rule.id, rule ]));
35+
const addRules = [];
36+
const removeRuleIds = [];
37+
for ( const oldRule of oldRules ) {
38+
const newRule = newRuleMap.get(oldRule.id);
39+
if ( newRule === undefined ) {
40+
removeRuleIds.push(oldRule.id);
41+
} else if ( JSON.stringify(oldRule) !== JSON.stringify(newRule) ) {
42+
removeRuleIds.push(oldRule.id);
43+
addRules.push(newRule);
44+
}
45+
}
46+
for ( const newRule of newRuleMap.values() ) {
47+
if ( oldRuleMap.has(newRule.id) ) { continue; }
48+
addRules.push(newRule);
49+
}
50+
if ( addRules.length !== 0 || removeRuleIds.length !== 0 ) {
51+
await dnr.updateDynamicRules({ addRules, removeRuleIds });
52+
}
53+
54+
const dynamicRules = await dnr.getDynamicRules();
55+
console.log(`Dynamic rule count: ${dynamicRules.length}`);
56+
57+
const enabledRulesets = await dnr.getEnabledRulesets();
58+
console.log(`Enabled rulesets: ${enabledRulesets}`);
59+
60+
console.log(`Available dynamic rule count: ${dnr.MAX_NUMBER_OF_DYNAMIC_AND_SESSION_RULES - dynamicRules.length}`);
61+
62+
dnr.getAvailableStaticRuleCount().then(count => {
63+
console.log(`Available static rule count: ${count}`);
64+
});
65+
})();
3.92 KB
Loading
534 Bytes
Loading
971 Bytes
Loading
1.88 KB
Loading

platform/mv3/extension/manifest.json

Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,25 @@
1+
{
2+
"author": "Raymond Hill",
3+
"background": {
4+
"service_worker": "background.js",
5+
"type": "module"
6+
},
7+
"declarative_net_request": {
8+
"rule_resources": [
9+
]
10+
},
11+
"description": "uBO Minus is permission-less experimental MV3-based network request blocker",
12+
"icons": {
13+
"16": "img/icon_16.png",
14+
"32": "img/icon_32.png",
15+
"64": "img/icon_64.png",
16+
"128": "img/icon_128.png"
17+
},
18+
"manifest_version": 3,
19+
"minimum_chrome_version": "101.0",
20+
"name": "uBO Minus (MV3)",
21+
"permissions": [
22+
"declarativeNetRequest"
23+
],
24+
"version": "0.1.0"
25+
}

platform/mv3/make-rulesets.js

Lines changed: 235 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,235 @@
1+
/*******************************************************************************
2+
3+
uBlock Origin - a browser extension to block requests.
4+
Copyright (C) 2022-present Raymond Hill
5+
6+
This program is free software: you can redistribute it and/or modify
7+
it under the terms of the GNU General Public License as published by
8+
the Free Software Foundation, either version 3 of the License, or
9+
(at your option) any later version.
10+
11+
This program is distributed in the hope that it will be useful,
12+
but WITHOUT ANY WARRANTY; without even the implied warranty of
13+
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14+
GNU General Public License for more details.
15+
16+
You should have received a copy of the GNU General Public License
17+
along with this program. If not, see {http://www.gnu.org/licenses/}.
18+
19+
Home: https://github.com/gorhill/uBlock
20+
*/
21+
22+
'use strict';
23+
24+
/******************************************************************************/
25+
26+
import fs from 'fs/promises';
27+
import process from 'process';
28+
29+
import rulesetConfigs from './ruleset-config.js';
30+
import { dnrRulesetFromRawLists } from './js/static-dnr-filtering.js';
31+
32+
/******************************************************************************/
33+
34+
const commandLineArgs = (( ) => {
35+
const args = new Map();
36+
let name, value;
37+
for ( const arg of process.argv.slice(2) ) {
38+
const pos = arg.indexOf('=');
39+
if ( pos === -1 ) {
40+
name = arg;
41+
value = '';
42+
} else {
43+
name = arg.slice(0, pos);
44+
value = arg.slice(pos+1);
45+
}
46+
args.set(name, value);
47+
}
48+
return args;
49+
})();
50+
51+
/******************************************************************************/
52+
53+
async function main() {
54+
55+
const writeOps = [];
56+
const ruleResources = [];
57+
const regexRuleResources = [];
58+
const outputDir = commandLineArgs.get('output') || '.';
59+
60+
let goodTotalCount = 0;
61+
let maybeGoodTotalCount = 0;
62+
63+
const output = [];
64+
const log = (text, silent = false) => {
65+
output.push(text);
66+
if ( silent === false ) {
67+
console.log(text);
68+
}
69+
};
70+
71+
const replacer = (k, v) => {
72+
if ( k.startsWith('__') ) { return; }
73+
if ( Array.isArray(v) ) {
74+
return v.sort();
75+
}
76+
if ( v instanceof Object ) {
77+
const sorted = {};
78+
for ( const kk of Object.keys(v).sort() ) {
79+
sorted[kk] = v[kk];
80+
}
81+
return sorted;
82+
}
83+
return v;
84+
};
85+
86+
const isUnsupported = rule =>
87+
rule._error !== undefined;
88+
const isRegex = rule =>
89+
rule.condition !== undefined &&
90+
rule.condition.regexFilter !== undefined;
91+
const isRedirect = rule =>
92+
rule.action !== undefined &&
93+
rule.action.type === 'redirect' &&
94+
rule.action.redirect.extensionPath !== undefined;
95+
const isCsp = rule =>
96+
rule.action !== undefined &&
97+
rule.action.type === 'modifyHeaders';
98+
const isRemoveparam = rule =>
99+
rule.action !== undefined &&
100+
rule.action.type === 'redirect' &&
101+
rule.action.redirect.transform !== undefined;
102+
const isGood = rule =>
103+
isUnsupported(rule) === false &&
104+
isRedirect(rule) === false &&
105+
isCsp(rule) === false &&
106+
isRemoveparam(rule) === false
107+
;
108+
109+
const rulesetDir = `${outputDir}/rulesets`;
110+
const rulesetDirPromise = fs.mkdir(`${rulesetDir}`, { recursive: true });
111+
112+
const fetchList = url => {
113+
return fetch(url)
114+
.then(response => response.text())
115+
.then(text => ({ name: url, text }));
116+
};
117+
118+
const readList = path =>
119+
fs.readFile(path, { encoding: 'utf8' })
120+
.then(text => ({ name: path, text }));
121+
122+
const writeFile = (path, data) =>
123+
rulesetDirPromise.then(( ) =>
124+
fs.writeFile(path, data));
125+
126+
for ( const ruleset of rulesetConfigs ) {
127+
const lists = [];
128+
129+
log(`Listset for '${ruleset.id}':`);
130+
131+
if ( Array.isArray(ruleset.paths) ) {
132+
for ( const path of ruleset.paths ) {
133+
log(`\t${path}`);
134+
lists.push(readList(`assets/${path}`));
135+
}
136+
}
137+
if ( Array.isArray(ruleset.urls) ) {
138+
for ( const url of ruleset.urls ) {
139+
log(`\t${url}`);
140+
lists.push(fetchList(url));
141+
}
142+
}
143+
144+
const rules = await dnrRulesetFromRawLists(lists, {
145+
env: [ 'chromium' ],
146+
});
147+
148+
log(`Ruleset size for '${ruleset.id}': ${rules.length}`);
149+
150+
const good = rules.filter(rule => isGood(rule) && isRegex(rule) === false);
151+
log(`\tGood: ${good.length}`);
152+
153+
const regexes = rules.filter(rule => isGood(rule) && isRegex(rule));
154+
log(`\tMaybe good (regexes): ${regexes.length}`);
155+
156+
const redirects = rules.filter(rule =>
157+
isUnsupported(rule) === false &&
158+
isRedirect(rule)
159+
);
160+
log(`\tredirect-rule= (discarded): ${redirects.length}`);
161+
162+
const headers = rules.filter(rule =>
163+
isUnsupported(rule) === false &&
164+
isCsp(rule)
165+
);
166+
log(`\tcsp= (discarded): ${headers.length}`);
167+
168+
const removeparams = rules.filter(rule =>
169+
isUnsupported(rule) === false &&
170+
isRemoveparam(rule)
171+
);
172+
log(`\tremoveparams= (discarded): ${removeparams.length}`);
173+
174+
const bad = rules.filter(rule =>
175+
isUnsupported(rule)
176+
);
177+
log(`\tUnsupported: ${bad.length}`);
178+
log(
179+
bad.map(rule => rule._error.map(v => `\t\t${v}`)).join('\n'),
180+
true
181+
);
182+
183+
writeOps.push(
184+
writeFile(
185+
`${rulesetDir}/${ruleset.id}.json`,
186+
`${JSON.stringify(good, replacer, 2)}\n`
187+
)
188+
);
189+
190+
regexRuleResources.push({
191+
id: ruleset.id,
192+
enabled: ruleset.enabled,
193+
rules: regexes
194+
});
195+
196+
ruleResources.push({
197+
id: ruleset.id,
198+
enabled: ruleset.enabled,
199+
path: `/rulesets/${ruleset.id}.json`
200+
});
201+
202+
goodTotalCount += good.length;
203+
maybeGoodTotalCount += regexes.length;
204+
}
205+
206+
writeOps.push(
207+
writeFile(
208+
`${rulesetDir}/regexes.js`,
209+
`export default ${JSON.stringify(regexRuleResources, replacer, 2)};\n`
210+
)
211+
);
212+
213+
await Promise.all(writeOps);
214+
215+
log(`Total good rules count: ${goodTotalCount}`);
216+
log(`Total regex rules count: ${maybeGoodTotalCount}`);
217+
218+
// Patch manifest
219+
const manifest = await fs.readFile(`${outputDir}/manifest.json`, { encoding: 'utf8' })
220+
.then(text => JSON.parse(text));
221+
manifest.declarative_net_request = { rule_resources: ruleResources };
222+
const now = new Date();
223+
manifest.version = `0.1.${now.getUTCFullYear() - 2000}.${now.getUTCMonth() * 100 + now.getUTCDate()}`;
224+
await fs.writeFile(
225+
`${outputDir}/manifest.json`,
226+
JSON.stringify(manifest, null, 2) + '\n'
227+
);
228+
229+
// Log results
230+
await fs.writeFile(`${outputDir}/log.txt`, output.join('\n') + '\n');
231+
}
232+
233+
main();
234+
235+
/******************************************************************************/

0 commit comments

Comments
 (0)