parse-filter.ts 18 KB

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