parse-filter.js 15 KB

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