parse-filter.js 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547
  1. // @ts-check
  2. const { fetchWithRetry } = require('./fetch-retry');
  3. const tldts = require('tldts');
  4. const { fetchRemoteTextAndCreateReadlineInterface } = require('./fetch-remote-text-by-line');
  5. const { NetworkFilter } = require('@cliqz/adblocker');
  6. const { processLine } = require('./process-line');
  7. const { performance } = require('perf_hooks');
  8. const { getGorhillPublicSuffixPromise } = require('./get-gorhill-publicsuffix');
  9. const DEBUG_DOMAIN_TO_FIND = null; // example.com | null
  10. let foundDebugDomain = false;
  11. const warnOnceUrl = new Set();
  12. const warnOnce = (url, isWhite, ...message) => {
  13. const key = `${url}${isWhite ? 'white' : 'black'}`;
  14. if (warnOnceUrl.has(key)) {
  15. return;
  16. }
  17. warnOnceUrl.add(key);
  18. console.warn(url, isWhite ? '(white)' : '(black)', ...message);
  19. };
  20. const normalizeDomain = (domain) => {
  21. if (!domain) return null;
  22. const parsed = tldts.parse(domain);
  23. if (parsed.isIp) return null;
  24. if (parsed.isIcann || parsed.isPrivate) {
  25. const h = parsed.hostname;
  26. return h?.[0] === '.' ? h.slice(1) : h;
  27. }
  28. return null;
  29. };
  30. /**
  31. * @param {string | URL} domainListsUrl
  32. */
  33. async function processDomainLists(domainListsUrl) {
  34. if (typeof domainListsUrl === 'string') {
  35. domainListsUrl = new URL(domainListsUrl);
  36. }
  37. /** @type Set<string> */
  38. const domainSets = new Set();
  39. for await (const line of await fetchRemoteTextAndCreateReadlineInterface(domainListsUrl)) {
  40. if (line[0] === '!') {
  41. continue;
  42. }
  43. const domainToAdd = processLine(line);
  44. if (!domainToAdd) {
  45. continue;
  46. }
  47. if (DEBUG_DOMAIN_TO_FIND && domainToAdd.includes(DEBUG_DOMAIN_TO_FIND)) {
  48. warnOnce(domainListsUrl.toString(), false, DEBUG_DOMAIN_TO_FIND);
  49. foundDebugDomain = true;
  50. }
  51. domainSets.add(domainToAdd);
  52. }
  53. return domainSets;
  54. }
  55. /**
  56. * @param {string | URL} hostsUrl
  57. */
  58. async function processHosts(hostsUrl, includeAllSubDomain = false) {
  59. console.time(` - processHosts: ${hostsUrl}`);
  60. if (typeof hostsUrl === 'string') {
  61. hostsUrl = new URL(hostsUrl);
  62. }
  63. /** @type Set<string> */
  64. const domainSets = new Set();
  65. for await (const l of await fetchRemoteTextAndCreateReadlineInterface(hostsUrl)) {
  66. const line = processLine(l);
  67. if (!line) {
  68. continue;
  69. }
  70. const [, ...domains] = line.split(' ');
  71. const _domain = domains.join(' ').trim();
  72. if (DEBUG_DOMAIN_TO_FIND && _domain.includes(DEBUG_DOMAIN_TO_FIND)) {
  73. warnOnce(hostsUrl.toString(), false, DEBUG_DOMAIN_TO_FIND);
  74. foundDebugDomain = true;
  75. }
  76. const domain = normalizeDomain(_domain);
  77. if (domain) {
  78. if (includeAllSubDomain) {
  79. domainSets.add(`.${domain}`);
  80. } else {
  81. domainSets.add(domain);
  82. }
  83. }
  84. }
  85. console.timeEnd(` - processHosts: ${hostsUrl}`);
  86. return domainSets;
  87. }
  88. /**
  89. * @param {string | URL} filterRulesUrl
  90. * @param {readonly (string | URL)[] | undefined} [fallbackUrls]
  91. * @returns {Promise<{ white: Set<string>, black: Set<string>, foundDebugDomain: boolean }>}
  92. */
  93. async function processFilterRules(filterRulesUrl, fallbackUrls, includeThirdParties = false) {
  94. const runStart = performance.now();
  95. /** @type Set<string> */
  96. const whitelistDomainSets = new Set();
  97. /** @type Set<string> */
  98. const blacklistDomainSets = new Set();
  99. /**
  100. * @param {string} domainToBeAddedToBlack
  101. * @param {boolean} isSubDomain
  102. */
  103. const addToBlackList = (domainToBeAddedToBlack, isSubDomain) => {
  104. if (isSubDomain && domainToBeAddedToBlack[0] !== '.') {
  105. blacklistDomainSets.add(`.${domainToBeAddedToBlack}`);
  106. } else {
  107. blacklistDomainSets.add(domainToBeAddedToBlack);
  108. }
  109. };
  110. /**
  111. * @param {string} domainToBeAddedToWhite
  112. * @param {boolean} [isSubDomain]
  113. */
  114. const addToWhiteList = (domainToBeAddedToWhite, isSubDomain = true) => {
  115. if (isSubDomain && domainToBeAddedToWhite[0] !== '.') {
  116. blacklistDomainSets.add(`.${domainToBeAddedToWhite}`);
  117. } else {
  118. blacklistDomainSets.add(domainToBeAddedToWhite);
  119. }
  120. };
  121. let downloadTime = 0;
  122. const gorhill = await getGorhillPublicSuffixPromise();
  123. const lineCb = (line) => {
  124. const result = parse(line, includeThirdParties, gorhill);
  125. if (result) {
  126. const flag = result[1];
  127. const hostname = result[0];
  128. if (DEBUG_DOMAIN_TO_FIND) {
  129. if (hostname.includes(DEBUG_DOMAIN_TO_FIND)) {
  130. warnOnce(filterRulesUrl.toString(), flag === 0 || flag === -1, DEBUG_DOMAIN_TO_FIND);
  131. foundDebugDomain = true;
  132. }
  133. }
  134. switch (flag) {
  135. case 0:
  136. addToWhiteList(hostname, true);
  137. break;
  138. case -1:
  139. addToWhiteList(hostname, false);
  140. break;
  141. case 1:
  142. addToBlackList(hostname, false);
  143. break;
  144. case 2:
  145. addToBlackList(hostname, true);
  146. break;
  147. default:
  148. throw new Error(`Unknown flag: ${flag}`);
  149. }
  150. }
  151. };
  152. if (!fallbackUrls || fallbackUrls.length === 0) {
  153. const downloadStart = performance.now();
  154. for await (const line of await fetchRemoteTextAndCreateReadlineInterface(filterRulesUrl)) {
  155. // don't trim here
  156. lineCb(line);
  157. }
  158. downloadTime = performance.now() - downloadStart;
  159. } else {
  160. let filterRules;
  161. const downloadStart = performance.now();
  162. try {
  163. const controller = new AbortController();
  164. /** @type string[] */
  165. filterRules = (
  166. await Promise.any(
  167. [filterRulesUrl, ...(fallbackUrls || [])].map(async url => {
  168. const text = await fetchWithRetry(url, { signal: controller.signal }).then(r => r.text());
  169. controller.abort();
  170. return text;
  171. })
  172. )
  173. ).split('\n');
  174. } catch (e) {
  175. console.log(`Download Rule for [${filterRulesUrl}] failed`);
  176. throw e;
  177. }
  178. downloadTime = performance.now() - downloadStart;
  179. for (let i = 0, len = filterRules.length; i < len; i++) {
  180. lineCb(filterRules[i]);
  181. }
  182. }
  183. console.log(` ┬ processFilterRules (${filterRulesUrl}): ${(performance.now() - runStart).toFixed(3)}ms`);
  184. console.log(` └── download time: ${downloadTime.toFixed(3)}ms`);
  185. return {
  186. white: whitelistDomainSets,
  187. black: blacklistDomainSets,
  188. foundDebugDomain
  189. };
  190. }
  191. const R_KNOWN_NOT_NETWORK_FILTER_PATTERN = /[#&%~=]/;
  192. const R_KNOWN_NOT_NETWORK_FILTER_PATTERN_2 = /(\$popup|\$removeparam|\$popunder)/;
  193. /**
  194. * @param {string} $line
  195. * @param {boolean} includeThirdParties
  196. * @param {import('gorhill-publicsuffixlist').default} gorhill
  197. * @returns {null | [string, 0 | 1 | 2 | -1]} - 0 white include subdomain, 1 black abosulte, 2 black include subdomain, -1 white
  198. */
  199. function parse($line, includeThirdParties, gorhill) {
  200. if (
  201. // doesn't include
  202. !$line.includes('.') // rule with out dot can not be a domain
  203. // includes
  204. || $line.includes('!')
  205. || $line.includes('?')
  206. || $line.includes('*')
  207. || $line.includes('[')
  208. || $line.includes('(')
  209. || $line.includes(']')
  210. || $line.includes(')')
  211. || $line.includes(',')
  212. || R_KNOWN_NOT_NETWORK_FILTER_PATTERN.test($line)
  213. ) {
  214. return null;
  215. }
  216. const line = $line.trim();
  217. const len = line.length;
  218. if (len === 0) {
  219. return null;
  220. }
  221. const firstChar = line[0];
  222. const lastChar = line[len - 1];
  223. if (
  224. len === 0
  225. || firstChar === '/'
  226. // ends with
  227. || lastChar === '.' // || line.endsWith('.')
  228. || lastChar === '-' // || line.endsWith('-')
  229. || lastChar === '_' // || line.endsWith('_')
  230. // special modifier
  231. || R_KNOWN_NOT_NETWORK_FILTER_PATTERN_2.test(line)
  232. || ((line.includes('/') || line.includes(':')) && !line.includes('://'))
  233. // || line.includes('$popup')
  234. // || line.includes('$removeparam')
  235. // || line.includes('$popunder')
  236. ) {
  237. return null;
  238. }
  239. const filter = NetworkFilter.parse(line);
  240. if (filter) {
  241. if (
  242. filter.isElemHide()
  243. || filter.isGenericHide()
  244. || filter.isSpecificHide()
  245. || filter.isRedirect()
  246. || filter.isRedirectRule()
  247. || filter.hasDomains()
  248. || filter.isCSP() // must not be csp rule
  249. || (!filter.fromAny() && !filter.fromDocument())
  250. ) {
  251. // not supported type
  252. return null;
  253. }
  254. if (
  255. filter.hostname // filter.hasHostname() // must have
  256. && filter.isPlain()
  257. && (!filter.isRegex())
  258. && (!filter.isFullRegex())
  259. ) {
  260. if (!gorhill.getDomain(filter.hostname)) {
  261. return null;
  262. }
  263. const hostname = normalizeDomain(filter.hostname);
  264. if (!hostname) {
  265. return null;
  266. }
  267. if (filter.isException() || filter.isBadFilter()) {
  268. return [hostname, 0];
  269. }
  270. const _1p = filter.firstParty();
  271. const _3p = filter.thirdParty();
  272. if (_1p === _3p) {
  273. return [hostname, 2];
  274. }
  275. if (_3p) {
  276. if (includeThirdParties) {
  277. return [hostname, 2];
  278. }
  279. return null;
  280. }
  281. if (_1p) {
  282. return null;
  283. }
  284. }
  285. }
  286. /**
  287. * abnormal filter that can not be parsed by NetworkFilter
  288. */
  289. if (line.includes('$third-party') || line.includes('$frame')) {
  290. /*
  291. * `.bbelements.com^$third-party`
  292. * `://o0e.ru^$third-party`
  293. */
  294. return null;
  295. }
  296. const lineEndsWithCaretOrCaretVerticalBar = (
  297. lastChar === '^'
  298. || (lastChar === '|' && line[len - 2] === '^')
  299. );
  300. // whitelist (exception)
  301. if (firstChar === '@' && line[1] === '@') {
  302. /**
  303. * cname exceptional filter can not be parsed by NetworkFilter
  304. *
  305. * `@@||m.faz.net^$cname`
  306. *
  307. * Surge / Clash can't handle CNAME either, so we just ignore them
  308. */
  309. if (line.endsWith('$cname')) {
  310. return null;
  311. }
  312. /**
  313. * Some "malformed" regex-based filters can not be parsed by NetworkFilter
  314. * "$genericblock`" is also not supported by NetworkFilter
  315. *
  316. * `@@||cmechina.net^$genericblock`
  317. * `@@|ftp.bmp.ovh^|`
  318. * `@@|adsterra.com^|`
  319. */
  320. if (
  321. // (line.startsWith('@@|') || line.startsWith('@@.'))
  322. (line[2] === '|' || line[2] === '.')
  323. && (
  324. lineEndsWithCaretOrCaretVerticalBar
  325. || line.endsWith('$genericblock')
  326. || line.endsWith('$document')
  327. )
  328. ) {
  329. const _domain = line
  330. .replace('@@||', '')
  331. .replace('@@|', '')
  332. .replace('@@.', '')
  333. .replace('^|', '')
  334. .replace('^$genericblock', '')
  335. .replace('$genericblock', '')
  336. .replace('^$document', '')
  337. .replace('$document', '')
  338. .replaceAll('^', '')
  339. .trim();
  340. const domain = normalizeDomain(_domain);
  341. if (domain) {
  342. return [domain, 0];
  343. }
  344. console.warn(' * [parse-filter E0001] (black) invalid domain:', _domain);
  345. return null;
  346. }
  347. }
  348. if (
  349. firstChar === '|' && line[1] === '|'
  350. && (
  351. lineEndsWithCaretOrCaretVerticalBar
  352. || line.endsWith('$cname')
  353. )
  354. ) {
  355. /**
  356. * Some malformed filters can not be parsed by NetworkFilter:
  357. *
  358. * `||smetrics.teambeachbody.com^.com^`
  359. * `||solutions.|pages.indigovision.com^`
  360. * `||vystar..0rg@client.iebetanialaargentina.edu.co^`
  361. */
  362. const _domain = line
  363. // .replace('||', '')
  364. .slice(2) // we already make sure line startsWith ||
  365. .replace('^|', '')
  366. .replace('$cname', '')
  367. .replaceAll('^', '')
  368. .trim();
  369. const domain = normalizeDomain(_domain);
  370. if (domain) {
  371. return [domain, 2];
  372. }
  373. console.warn(' * [parse-filter E0002] (black) invalid domain:', _domain);
  374. return null;
  375. }
  376. const lineStartsWithSingleDot = firstChar === '.';
  377. if (
  378. lineStartsWithSingleDot
  379. && lineEndsWithCaretOrCaretVerticalBar
  380. ) {
  381. /**
  382. * `.ay.delivery^`
  383. * `.m.bookben.com^`
  384. * `.wap.x4399.com^`
  385. */
  386. const _domain = line
  387. .slice(1) // remove prefix dot
  388. .replace('^|', '')
  389. .replaceAll('^', '')
  390. .trim();
  391. const suffix = gorhill.getPublicSuffix(_domain);
  392. if (!gorhill.suffixInPSL(suffix)) {
  393. // This exclude domain-like resource like `1.1.4.514.js`
  394. return null;
  395. }
  396. const domain = normalizeDomain(_domain);
  397. if (domain) {
  398. return [domain, 2];
  399. }
  400. console.warn(' * [parse-filter E0003] (black) invalid domain:', _domain);
  401. return null;
  402. }
  403. /**
  404. * `|http://x.o2.pl^`
  405. * `://mine.torrent.pw^`
  406. * `://say.ac^`
  407. */
  408. if (
  409. (
  410. line.startsWith('://')
  411. || line.startsWith('http://')
  412. || line.startsWith('https://')
  413. || line.startsWith('|http://')
  414. || line.startsWith('|https://')
  415. )
  416. && lineEndsWithCaretOrCaretVerticalBar
  417. ) {
  418. const _domain = line
  419. .replace('|https://', '')
  420. .replace('https://', '')
  421. .replace('|http://', '')
  422. .replace('http://', '')
  423. .replace('://', '')
  424. .replace('^|', '')
  425. .replaceAll('^', '')
  426. .trim();
  427. const domain = normalizeDomain(_domain);
  428. if (domain) {
  429. return [domain, 1];
  430. }
  431. console.warn(' * [parse-filter E0004] (black) invalid domain:', _domain);
  432. return null;
  433. }
  434. /**
  435. * `_vmind.qqvideo.tc.qq.com^`
  436. * `arketing.indianadunes.com^`
  437. * `charlestownwyllie.oaklawnnonantum.com^`
  438. * `-telemetry.officeapps.live.com^`
  439. * `-tracker.biliapi.net`
  440. * `_social_tracking.js^`
  441. */
  442. if (firstChar !== '|' && lastChar === '^') {
  443. const _domain = line.slice(0, -1);
  444. const domain = normalizeDomain(_domain);
  445. if (domain) {
  446. return [domain, 1];
  447. }
  448. console.warn(' * [parse-filter E0005] (black) invalid domain:', _domain);
  449. return null;
  450. }
  451. /**
  452. * `.3.n.2.2.l30.js`
  453. * `_prebid.js`
  454. * `t.yesware.com`
  455. * `ubmcmm.baidustatic.com`
  456. * `portal.librus.pl$$advertisement-module`
  457. * `@@-ds.metric.gstatic.com^|`
  458. * `://gom.ge/cookie.js`
  459. * `://accout-update-smba.jp.$document`
  460. * `@@://googleadservices.com^|`
  461. */
  462. const tryNormalizeDomain = normalizeDomain(line);
  463. if (tryNormalizeDomain) {
  464. if (tryNormalizeDomain === line) {
  465. // the entire rule is domain
  466. return [line, 2];
  467. }
  468. if (lineStartsWithSingleDot && tryNormalizeDomain === line.slice(1)) {
  469. // dot prefixed line has stripped
  470. return [line, 2];
  471. }
  472. }
  473. if (!line.endsWith('.js') && !line.endsWith('.css')) {
  474. console.warn(' * [parse-filter E0010] can not parse:', line);
  475. }
  476. return null;
  477. }
  478. module.exports.processDomainLists = processDomainLists;
  479. module.exports.processHosts = processHosts;
  480. module.exports.processFilterRules = processFilterRules;