parse-filter.ts 18 KB

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