parse-filter.js 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575
  1. // @ts-check
  2. const { fetchWithRetry } = require('./fetch-retry');
  3. const tldts = require('./cached-tld-parse');
  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) {
  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, 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. downloadTime = 0;
  154. let last = performance.now();
  155. for await (const line of await fetchRemoteTextAndCreateReadlineInterface(filterRulesUrl)) {
  156. const now = performance.now();
  157. downloadTime += performance.now() - last;
  158. last = now;
  159. // don't trim here
  160. lineCb(line);
  161. }
  162. } else {
  163. let filterRules;
  164. const downloadStart = performance.now();
  165. try {
  166. const controller = new AbortController();
  167. /** @type string[] */
  168. filterRules = (
  169. await Promise.any(
  170. [filterRulesUrl, ...(fallbackUrls || [])].map(async url => {
  171. const text = await fetchWithRetry(url, { signal: controller.signal }).then(r => r.text());
  172. controller.abort();
  173. return text;
  174. })
  175. )
  176. ).split('\n');
  177. } catch (e) {
  178. console.log(`Download Rule for [${filterRulesUrl}] failed`);
  179. throw e;
  180. }
  181. downloadTime = performance.now() - downloadStart;
  182. for (let i = 0, len = filterRules.length; i < len; i++) {
  183. lineCb(filterRules[i]);
  184. }
  185. }
  186. console.log(` ┬ processFilterRules (${filterRulesUrl}): ${(performance.now() - runStart).toFixed(3)}ms`);
  187. console.log(` └── download time: ${downloadTime.toFixed(3)}ms`);
  188. return {
  189. white: whitelistDomainSets,
  190. black: blacklistDomainSets,
  191. foundDebugDomain
  192. };
  193. }
  194. const R_KNOWN_NOT_NETWORK_FILTER_PATTERN = /[#&%~=]/;
  195. const R_KNOWN_NOT_NETWORK_FILTER_PATTERN_2 = /(\$popup|\$removeparam|\$popunder)/;
  196. /**
  197. * @param {string} $line
  198. * @param {import('gorhill-publicsuffixlist').default} gorhill
  199. * @returns {null | [hostname: string, flag: 0 | 1 | 2 | -1]} - 0 white include subdomain, 1 black abosulte, 2 black include subdomain, -1 white
  200. */
  201. function parse($line, gorhill) {
  202. if (
  203. // doesn't include
  204. !$line.includes('.') // rule with out dot can not be a domain
  205. // includes
  206. || $line.includes('!')
  207. || $line.includes('?')
  208. || $line.includes('*')
  209. || $line.includes('[')
  210. || $line.includes('(')
  211. || $line.includes(']')
  212. || $line.includes(')')
  213. || $line.includes(',')
  214. || R_KNOWN_NOT_NETWORK_FILTER_PATTERN.test($line)
  215. ) {
  216. return null;
  217. }
  218. const line = $line.trim();
  219. const len = line.length;
  220. if (len === 0) {
  221. return null;
  222. }
  223. const firstChar = line[0];
  224. const lastChar = line[len - 1];
  225. if (
  226. len === 0
  227. || firstChar === '/'
  228. // ends with
  229. || lastChar === '.' // || line.endsWith('.')
  230. || lastChar === '-' // || line.endsWith('-')
  231. || lastChar === '_' // || line.endsWith('_')
  232. // special modifier
  233. || R_KNOWN_NOT_NETWORK_FILTER_PATTERN_2.test(line)
  234. || ((line.includes('/') || line.includes(':')) && !line.includes('://'))
  235. // || line.includes('$popup')
  236. // || line.includes('$removeparam')
  237. // || line.includes('$popunder')
  238. ) {
  239. return null;
  240. }
  241. const filter = NetworkFilter.parse(line);
  242. if (filter) {
  243. if (
  244. filter.isElemHide()
  245. || filter.isGenericHide()
  246. || filter.isSpecificHide()
  247. || filter.isRedirect()
  248. || filter.isRedirectRule()
  249. || filter.hasDomains()
  250. || filter.isCSP() // must not be csp rule
  251. || (!filter.fromAny() && !filter.fromDocument())
  252. ) {
  253. // not supported type
  254. return null;
  255. }
  256. if (
  257. filter.hostname // filter.hasHostname() // must have
  258. && filter.isPlain()
  259. // && (!filter.isRegex()) // isPlain() === !isRegex()
  260. && (!filter.isFullRegex())
  261. ) {
  262. if (!gorhill.getDomain(filter.hostname)) {
  263. return null;
  264. }
  265. const hostname = normalizeDomain(filter.hostname);
  266. if (!hostname) {
  267. return null;
  268. }
  269. // console.log({
  270. // '||': filter.isHostnameAnchor(),
  271. // '|': filter.isLeftAnchor(),
  272. // '|https://': !filter.isHostnameAnchor() && (filter.fromHttps() || filter.fromHttp())
  273. // });
  274. const isIncludeAllSubDomain = filter.isHostnameAnchor();
  275. if (filter.isException() || filter.isBadFilter()) {
  276. return [hostname, isIncludeAllSubDomain ? 0 : -1];
  277. }
  278. const _1p = filter.firstParty();
  279. const _3p = filter.thirdParty();
  280. if (_1p) {
  281. if (_1p === _3p) {
  282. return [hostname, isIncludeAllSubDomain ? 2 : 1];
  283. }
  284. return null;
  285. }
  286. if (_3p) {
  287. return null;
  288. }
  289. }
  290. }
  291. /**
  292. * abnormal filter that can not be parsed by NetworkFilter
  293. */
  294. if (line.includes('$third-party') || line.includes('$frame')) {
  295. /*
  296. * `.bbelements.com^$third-party`
  297. * `://o0e.ru^$third-party`
  298. */
  299. return null;
  300. }
  301. /* eslint-disable no-nested-ternary -- speed */
  302. const linedEndsWithCaret = lastChar === '^';
  303. const lineEndsWithCaretVerticalBar = lastChar === '|' && line[len - 2] === '^';
  304. const lineEndsWithCaretOrCaretVerticalBar = linedEndsWithCaret || lineEndsWithCaretVerticalBar;
  305. // whitelist (exception)
  306. if (firstChar === '@' && line[1] === '@') {
  307. /**
  308. * cname exceptional filter can not be parsed by NetworkFilter
  309. *
  310. * `@@||m.faz.net^$cname`
  311. *
  312. * Surge / Clash can't handle CNAME either, so we just ignore them
  313. */
  314. if (line.endsWith('$cname')) {
  315. return null;
  316. }
  317. /**
  318. * Some "malformed" regex-based filters can not be parsed by NetworkFilter
  319. * "$genericblock`" is also not supported by NetworkFilter
  320. *
  321. * `@@||cmechina.net^$genericblock`
  322. * `@@|ftp.bmp.ovh^|`
  323. * `@@|adsterra.com^|`
  324. */
  325. if (
  326. // (line.startsWith('@@|') || line.startsWith('@@.'))
  327. (line[2] === '|' || line[2] === '.')
  328. && (
  329. lineEndsWithCaretOrCaretVerticalBar
  330. || line.endsWith('$genericblock')
  331. || line.endsWith('$document')
  332. )
  333. ) {
  334. const _domain = line
  335. .replace('@@||', '')
  336. .replace('@@|', '')
  337. .replace('@@.', '')
  338. .replace('^|', '')
  339. .replace('^$genericblock', '')
  340. .replace('$genericblock', '')
  341. .replace('^$document', '')
  342. .replace('$document', '')
  343. .replaceAll('^', '')
  344. .trim();
  345. const domain = normalizeDomain(_domain);
  346. if (domain) {
  347. return [domain, 0];
  348. }
  349. console.warn(' * [parse-filter E0001] (black) invalid domain:', _domain);
  350. return null;
  351. }
  352. }
  353. if (firstChar === '|' && (lineEndsWithCaretOrCaretVerticalBar || line.endsWith('$cname'))) {
  354. /**
  355. * Some malformed filters can not be parsed by NetworkFilter:
  356. *
  357. * `||smetrics.teambeachbody.com^.com^`
  358. * `||solutions.|pages.indigovision.com^`
  359. * `||vystar..0rg@client.iebetanialaargentina.edu.co^`
  360. */
  361. const includeAllSubDomain = line[1] === '|';
  362. const sliceStart = includeAllSubDomain ? 2 : 1;
  363. const sliceEnd = lastChar === '^'
  364. ? -1
  365. : lineEndsWithCaretOrCaretVerticalBar
  366. ? -2
  367. : line.endsWith('$cname')
  368. ? -6
  369. : 0;
  370. const _domain = line
  371. // .replace('||', '')
  372. .slice(sliceStart, sliceEnd) // we already make sure line startsWith ||
  373. .trim();
  374. const domain = normalizeDomain(_domain);
  375. if (domain) {
  376. return [domain, includeAllSubDomain ? 2 : 1];
  377. }
  378. console.warn(' * [parse-filter E0002] (black) invalid domain:', _domain);
  379. return null;
  380. }
  381. const lineStartsWithSingleDot = firstChar === '.';
  382. if (
  383. lineStartsWithSingleDot
  384. && lineEndsWithCaretOrCaretVerticalBar
  385. ) {
  386. /**
  387. * `.ay.delivery^`
  388. * `.m.bookben.com^`
  389. * `.wap.x4399.com^`
  390. */
  391. const _domain = line
  392. .slice(
  393. 1,
  394. linedEndsWithCaret
  395. ? -1
  396. : lineEndsWithCaretVerticalBar
  397. ? -2
  398. : 0
  399. ) // remove prefix dot
  400. .replace('^|', '')
  401. .replaceAll('^', '')
  402. .trim();
  403. const suffix = gorhill.getPublicSuffix(_domain);
  404. if (!gorhill.suffixInPSL(suffix)) {
  405. // This exclude domain-like resource like `1.1.4.514.js`
  406. return null;
  407. }
  408. const domain = normalizeDomain(_domain);
  409. if (domain) {
  410. return [domain, 2];
  411. }
  412. console.warn(' * [parse-filter E0003] (black) invalid domain:', _domain);
  413. return null;
  414. }
  415. /**
  416. * `|http://x.o2.pl^`
  417. * `://mine.torrent.pw^`
  418. * `://say.ac^`
  419. */
  420. if (
  421. (
  422. line.startsWith('://')
  423. || line.startsWith('http://')
  424. || line.startsWith('https://')
  425. || line.startsWith('|http://')
  426. || line.startsWith('|https://')
  427. )
  428. && lineEndsWithCaretOrCaretVerticalBar
  429. ) {
  430. const _domain = line
  431. .replace('|https://', '')
  432. .replace('https://', '')
  433. .replace('|http://', '')
  434. .replace('http://', '')
  435. .replace('://', '')
  436. .replace('^|', '')
  437. .replaceAll('^', '')
  438. .trim();
  439. const domain = normalizeDomain(_domain);
  440. if (domain) {
  441. return [domain, 1];
  442. }
  443. console.warn(' * [parse-filter E0004] (black) invalid domain:', _domain);
  444. return null;
  445. }
  446. /**
  447. * `_vmind.qqvideo.tc.qq.com^`
  448. * `arketing.indianadunes.com^`
  449. * `charlestownwyllie.oaklawnnonantum.com^`
  450. * `-telemetry.officeapps.live.com^`
  451. * `-tracker.biliapi.net`
  452. * `_social_tracking.js^`
  453. */
  454. if (firstChar !== '|' && lastChar === '^') {
  455. const _domain = line.slice(0, -1);
  456. const suffix = gorhill.getPublicSuffix(_domain);
  457. if (!suffix || !gorhill.suffixInPSL(suffix)) {
  458. // This exclude domain-like resource like `_social_tracking.js^`
  459. return null;
  460. }
  461. const domain = normalizeDomain(_domain);
  462. if (domain) {
  463. return [domain, 1];
  464. }
  465. console.warn(' * [parse-filter E0005] (black) invalid domain:', _domain);
  466. return null;
  467. }
  468. /**
  469. * `.3.n.2.2.l30.js`
  470. * `_prebid.js`
  471. * `t.yesware.com`
  472. * `ubmcmm.baidustatic.com`
  473. * `portal.librus.pl$$advertisement-module`
  474. * `@@-ds.metric.gstatic.com^|`
  475. * `://gom.ge/cookie.js`
  476. * `://accout-update-smba.jp.$document`
  477. * `@@://googleadservices.com^|`
  478. */
  479. const tryNormalizeDomain = normalizeDomain(line);
  480. if (tryNormalizeDomain) {
  481. if (tryNormalizeDomain === line) {
  482. // the entire rule is domain
  483. return [line, 2];
  484. }
  485. if (lineStartsWithSingleDot && tryNormalizeDomain === line.slice(1)) {
  486. // dot prefixed line has stripped
  487. return [line, 2];
  488. }
  489. }
  490. if (!line.endsWith('.js') && !line.endsWith('.css')) {
  491. console.warn(' * [parse-filter E0010] can not parse:', line);
  492. }
  493. return null;
  494. /* eslint-enable no-nested-ternary */
  495. }
  496. module.exports.processDomainLists = processDomainLists;
  497. module.exports.processHosts = processHosts;
  498. module.exports.processFilterRules = processFilterRules;