parse-filter.ts 16 KB

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