parse-filter.ts 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570
  1. // @ts-check
  2. import { fetchRemoteTextAndReadByLine } from './fetch-text-by-line';
  3. import { NetworkFilter } from '@cliqz/adblocker';
  4. import { processLine } from './process-line';
  5. import { getGorhillPublicSuffixPromise } from './get-gorhill-publicsuffix';
  6. import type { PublicSuffixList } from '@gorhill/publicsuffixlist';
  7. import { traceAsync } from './trace-runner';
  8. import picocolors from 'picocolors';
  9. import { normalizeDomain } from './normalize-domain';
  10. import { fetchAssets } from './fetch-assets';
  11. const DEBUG_DOMAIN_TO_FIND: string | null = null; // example.com | null
  12. let foundDebugDomain = false;
  13. const warnOnceUrl = new Set<string>();
  14. const warnOnce = (url: string, isWhite: boolean, ...message: string[]) => {
  15. const key = `${url}${isWhite ? 'white' : 'black'}`;
  16. if (warnOnceUrl.has(key)) {
  17. return;
  18. }
  19. warnOnceUrl.add(key);
  20. console.warn(url, isWhite ? '(white)' : '(black)', ...message);
  21. };
  22. export function processDomainLists(domainListsUrl: string, includeAllSubDomain = false) {
  23. return traceAsync(`- processDomainLists: ${domainListsUrl}`, async () => {
  24. const domainSets = new Set<string>();
  25. for await (const line of await fetchRemoteTextAndReadByLine(domainListsUrl)) {
  26. const domainToAdd = processLine(line);
  27. if (!domainToAdd) continue;
  28. if (DEBUG_DOMAIN_TO_FIND && domainToAdd.includes(DEBUG_DOMAIN_TO_FIND)) {
  29. warnOnce(domainListsUrl, false, DEBUG_DOMAIN_TO_FIND);
  30. foundDebugDomain = true;
  31. }
  32. domainSets.add(includeAllSubDomain ? `.${domainToAdd}` : domainToAdd);
  33. }
  34. return domainSets;
  35. });
  36. }
  37. export function processHosts(hostsUrl: string, includeAllSubDomain = false, skipDomainCheck = false) {
  38. return traceAsync(`- processHosts: ${hostsUrl}`, async () => {
  39. const domainSets = new Set<string>();
  40. for await (const l of await fetchRemoteTextAndReadByLine(hostsUrl)) {
  41. const line = processLine(l);
  42. if (!line) {
  43. continue;
  44. }
  45. const domain = line.split(/\s/)[1];
  46. if (!domain) {
  47. continue;
  48. }
  49. const _domain = domain.trim();
  50. if (DEBUG_DOMAIN_TO_FIND && _domain.includes(DEBUG_DOMAIN_TO_FIND)) {
  51. warnOnce(hostsUrl, false, DEBUG_DOMAIN_TO_FIND);
  52. foundDebugDomain = true;
  53. }
  54. const domainToAdd = skipDomainCheck ? _domain : normalizeDomain(_domain);
  55. if (domainToAdd) {
  56. domainSets.add(includeAllSubDomain ? `.${domainToAdd}` : domainToAdd);
  57. }
  58. }
  59. console.log(picocolors.gray('[process hosts]'), picocolors.gray(hostsUrl), picocolors.gray(domainSets.size));
  60. return domainSets;
  61. });
  62. }
  63. // eslint-disable-next-line sukka-ts/no-const-enum -- bun bundler is smart, maybe?
  64. const enum ParseType {
  65. WhiteIncludeSubdomain = 0,
  66. WhiteAbsolute = -1,
  67. BlackAbsolute = 1,
  68. BlackIncludeSubdomain = 2,
  69. ErrorMessage = 10
  70. }
  71. export async function processFilterRules(
  72. filterRulesUrl: string,
  73. fallbackUrls?: readonly string[] | undefined
  74. ): Promise<{ white: Set<string>, black: Set<string>, foundDebugDomain: boolean }> {
  75. const whitelistDomainSets = new Set<string>();
  76. const blacklistDomainSets = new Set<string>();
  77. const warningMessages: string[] = [];
  78. await traceAsync(`- processFilterRules: ${filterRulesUrl}`, async () => {
  79. const gorhill = await getGorhillPublicSuffixPromise();
  80. /**
  81. * @param {string} line
  82. */
  83. const lineCb = (line: string) => {
  84. const result = parse(line, gorhill);
  85. if (!result) {
  86. return;
  87. }
  88. const flag = result[1];
  89. const hostname = result[0];
  90. if (DEBUG_DOMAIN_TO_FIND) {
  91. if (hostname.includes(DEBUG_DOMAIN_TO_FIND)) {
  92. warnOnce(filterRulesUrl, flag === ParseType.WhiteIncludeSubdomain || flag === ParseType.WhiteAbsolute, DEBUG_DOMAIN_TO_FIND);
  93. foundDebugDomain = true;
  94. }
  95. }
  96. switch (flag) {
  97. case ParseType.WhiteIncludeSubdomain:
  98. if (hostname[0] !== '.') {
  99. whitelistDomainSets.add(`.${hostname}`);
  100. } else {
  101. whitelistDomainSets.add(hostname);
  102. }
  103. break;
  104. case ParseType.WhiteAbsolute:
  105. whitelistDomainSets.add(hostname);
  106. break;
  107. case ParseType.BlackAbsolute:
  108. blacklistDomainSets.add(hostname);
  109. break;
  110. case ParseType.BlackIncludeSubdomain:
  111. if (hostname[0] !== '.') {
  112. blacklistDomainSets.add(`.${hostname}`);
  113. } else {
  114. blacklistDomainSets.add(hostname);
  115. }
  116. break;
  117. case ParseType.ErrorMessage:
  118. warningMessages.push(hostname);
  119. break;
  120. default:
  121. break;
  122. }
  123. };
  124. if (!fallbackUrls || fallbackUrls.length === 0) {
  125. for await (const line of await fetchRemoteTextAndReadByLine(filterRulesUrl)) {
  126. // don't trim here
  127. lineCb(line);
  128. }
  129. } else {
  130. const filterRules = (await traceAsync(
  131. picocolors.gray(`- download ${filterRulesUrl}`),
  132. () => fetchAssets(filterRulesUrl, fallbackUrls),
  133. picocolors.gray
  134. )).split('\n');
  135. for (let i = 0, len = filterRules.length; i < len; i++) {
  136. lineCb(filterRules[i]);
  137. }
  138. }
  139. });
  140. warningMessages.forEach(msg => {
  141. console.warn(
  142. picocolors.yellow(msg),
  143. picocolors.gray(picocolors.underline(filterRulesUrl))
  144. );
  145. });
  146. console.log(
  147. picocolors.gray('[process filter]'),
  148. picocolors.gray(filterRulesUrl),
  149. picocolors.gray(`white: ${whitelistDomainSets.size}`),
  150. picocolors.gray(`black: ${blacklistDomainSets.size}`)
  151. );
  152. return {
  153. white: whitelistDomainSets,
  154. black: blacklistDomainSets,
  155. foundDebugDomain
  156. };
  157. }
  158. const R_KNOWN_NOT_NETWORK_FILTER_PATTERN = /[#%&=~]/;
  159. const R_KNOWN_NOT_NETWORK_FILTER_PATTERN_2 = /(\$popup|\$removeparam|\$popunder|\$cname)/;
  160. // cname exceptional filter can not be parsed by NetworkFilter
  161. // Surge / Clash can't handle CNAME either, so we just ignore them
  162. function parse($line: string, gorhill: PublicSuffixList): null | [hostname: string, flag: ParseType] {
  163. if (
  164. // doesn't include
  165. !$line.includes('.') // rule with out dot can not be a domain
  166. // includes
  167. || $line.includes('!')
  168. || $line.includes('?')
  169. || $line.includes('*')
  170. || $line.includes('[')
  171. || $line.includes('(')
  172. || $line.includes(']')
  173. || $line.includes(')')
  174. || $line.includes(',')
  175. || R_KNOWN_NOT_NETWORK_FILTER_PATTERN.test($line)
  176. ) {
  177. return null;
  178. }
  179. const line = $line.trim();
  180. /** @example line.length */
  181. const len = line.length;
  182. if (len === 0) {
  183. return null;
  184. }
  185. const firstCharCode = line[0].charCodeAt(0);
  186. const lastCharCode = line[len - 1].charCodeAt(0);
  187. if (
  188. firstCharCode === 47 // 47 `/`
  189. // ends with
  190. || lastCharCode === 46 // 46 `.`, line.endsWith('.')
  191. || lastCharCode === 45 // 45 `-`, line.endsWith('-')
  192. || lastCharCode === 95 // 95 `_`, line.endsWith('_')
  193. // special modifier
  194. || R_KNOWN_NOT_NETWORK_FILTER_PATTERN_2.test(line)
  195. // || line.includes('$popup')
  196. // || line.includes('$removeparam')
  197. // || line.includes('$popunder')
  198. ) {
  199. return null;
  200. }
  201. if ((line.includes('/') || line.includes(':')) && !line.includes('://')) {
  202. return null;
  203. }
  204. const filter = NetworkFilter.parse(line);
  205. if (filter) {
  206. if (
  207. // filter.isCosmeticFilter() // always false
  208. // filter.isNetworkFilter() // always true
  209. filter.isElemHide()
  210. || filter.isGenericHide()
  211. || filter.isSpecificHide()
  212. || filter.isRedirect()
  213. || filter.isRedirectRule()
  214. || filter.hasDomains()
  215. || filter.isCSP() // must not be csp rule
  216. || (!filter.fromAny() && !filter.fromDocument())
  217. ) {
  218. // not supported type
  219. return null;
  220. }
  221. if (
  222. filter.hostname // filter.hasHostname() // must have
  223. && filter.isPlain() // isPlain() === !isRegex()
  224. && (!filter.isFullRegex())
  225. ) {
  226. const hostname = normalizeDomain(filter.hostname);
  227. if (!hostname) {
  228. return null;
  229. }
  230. // |: filter.isHostnameAnchor(),
  231. // |: filter.isLeftAnchor(),
  232. // |https://: !filter.isHostnameAnchor() && (filter.fromHttps() || filter.fromHttp())
  233. const isIncludeAllSubDomain = filter.isHostnameAnchor();
  234. if (filter.isException() || filter.isBadFilter()) {
  235. return [hostname, isIncludeAllSubDomain ? ParseType.WhiteIncludeSubdomain : ParseType.WhiteAbsolute];
  236. }
  237. const _1p = filter.firstParty();
  238. const _3p = filter.thirdParty();
  239. if (_1p) {
  240. if (_1p === _3p) {
  241. return [hostname, isIncludeAllSubDomain ? ParseType.BlackIncludeSubdomain : ParseType.BlackAbsolute];
  242. }
  243. return null;
  244. }
  245. if (_3p) {
  246. return null;
  247. }
  248. }
  249. }
  250. // After NetworkFilter.parse, it means the line can not be parsed by cliqz NetworkFilter
  251. // We now need to "salvage" the line as much as possible
  252. /*
  253. * From now on, we are mostly facing non-standard domain rules (some are regex like)
  254. * We first skip third-party and frame rules, as Surge / Clash can't handle them
  255. *
  256. * `.sharecounter.$third-party`
  257. * `.bbelements.com^$third-party`
  258. * `://o0e.ru^$third-party`
  259. * `.1.1.1.l80.js^$third-party`
  260. */
  261. if (line.includes('$third-party') || line.includes('$frame')) {
  262. return null;
  263. }
  264. /** @example line.endsWith('^') */
  265. const linedEndsWithCaret = lastCharCode === 94; // lastChar === '^';
  266. /** @example line.endsWith('^|') */
  267. const lineEndsWithCaretVerticalBar = (lastCharCode === 124 /** lastChar === '|' */) && line[len - 2] === '^';
  268. /** @example line.endsWith('^') || line.endsWith('^|') */
  269. const lineEndsWithCaretOrCaretVerticalBar = linedEndsWithCaret || lineEndsWithCaretVerticalBar;
  270. // whitelist (exception)
  271. if (
  272. firstCharCode === 64 // 64 `@`
  273. && line[1] === '@'
  274. ) {
  275. /**
  276. * Some "malformed" regex-based filters can not be parsed by NetworkFilter
  277. * "$genericblock`" is also not supported by NetworkFilter, see:
  278. * https://github.com/ghostery/adblocker/blob/62caf7786ba10ef03beffecd8cd4eec111bcd5ec/packages/adblocker/test/parsing.test.ts#L950
  279. *
  280. * `@@||cmechina.net^$genericblock`
  281. * `@@|ftp.bmp.ovh^|`
  282. * `@@|adsterra.com^|`
  283. * `@@.atlassian.net$document`
  284. * `@@||ad.alimama.com^$genericblock`
  285. */
  286. let sliceStart = 0;
  287. let sliceEnd: number | undefined;
  288. // line.startsWith('@@|') || line.startsWith('@@.')
  289. if (line[2] === '|' || line[2] === '.') {
  290. sliceStart = 3;
  291. // line.startsWith('@@||')
  292. if (line[3] === '|') {
  293. sliceStart = 4;
  294. }
  295. }
  296. /**
  297. * line.startsWith('@@://')
  298. *
  299. * `@@://googleadservices.com^|`
  300. * `@@://www.googleadservices.com^|`
  301. */
  302. if (line[2] === ':' && line[3] === '/' && line[4] === '/') {
  303. sliceStart = 5;
  304. }
  305. if (lineEndsWithCaretOrCaretVerticalBar) {
  306. sliceEnd = -2;
  307. } else if (line.endsWith('$genericblock')) {
  308. sliceEnd = -13;
  309. if (line[len - 14] === '^') { // line.endsWith('^$genericblock')
  310. sliceEnd = -14;
  311. }
  312. } else if (line.endsWith('$document')) {
  313. sliceEnd = -9;
  314. if (line[len - 10] === '^') { // line.endsWith('^$document')
  315. sliceEnd = -10;
  316. }
  317. }
  318. if (sliceStart !== 0 || sliceEnd !== undefined) {
  319. const sliced = line.slice(sliceStart, sliceEnd);
  320. const domain = normalizeDomain(sliced);
  321. if (domain) {
  322. return [domain, ParseType.WhiteIncludeSubdomain];
  323. }
  324. return [
  325. `[parse-filter E0001] (white) invalid domain: ${JSON.stringify({
  326. line, sliced, sliceStart, sliceEnd
  327. })}`,
  328. ParseType.ErrorMessage
  329. ];
  330. }
  331. return [
  332. `[parse-filter E0006] (white) failed to parse: ${JSON.stringify({
  333. line, sliceStart, sliceEnd
  334. })}`,
  335. ParseType.ErrorMessage
  336. ];
  337. }
  338. if (firstCharCode === 124) { // 124 `|`
  339. if (lineEndsWithCaretOrCaretVerticalBar) {
  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 = lastCharCode === 94 // lastChar === '^'
  351. ? -1
  352. : (lineEndsWithCaretVerticalBar
  353. ? -2
  354. : undefined);
  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 = firstCharCode === 46; // 46 `.`
  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 (
  441. firstCharCode !== 124 // 124 `|`
  442. && lastCharCode === 94 // 94 `^`
  443. ) {
  444. const _domain = line.slice(0, -1);
  445. const suffix = gorhill.getPublicSuffix(_domain);
  446. if (!suffix || !gorhill.suffixInPSL(suffix)) {
  447. // This exclude domain-like resource like `_social_tracking.js^`
  448. return null;
  449. }
  450. const domain = normalizeDomain(_domain);
  451. if (domain) {
  452. return [domain, ParseType.BlackAbsolute];
  453. }
  454. return [
  455. `[parse-filter E0005] (black) invalid domain: ${_domain}`,
  456. ParseType.ErrorMessage
  457. ];
  458. }
  459. if (lineStartsWithSingleDot) {
  460. /**
  461. * `.cookielaw.js`
  462. * `.content_tracking.js`
  463. * `.ads.css`
  464. */
  465. const _domain = line.slice(1);
  466. const suffix = gorhill.getPublicSuffix(_domain);
  467. if (!suffix || !gorhill.suffixInPSL(suffix)) {
  468. // This exclude domain-like resource like `.gatracking.js`, `.beacon.min.js` and `.cookielaw.js`
  469. return null;
  470. }
  471. const tryNormalizeDomain = normalizeDomain(_domain);
  472. if (tryNormalizeDomain === _domain) {
  473. // the entire rule is domain
  474. return [line, ParseType.BlackIncludeSubdomain];
  475. }
  476. } else {
  477. /**
  478. * `_prebid.js`
  479. * `t.yesware.com`
  480. * `ubmcmm.baidustatic.com`
  481. * `://www.smfg-card.$document`
  482. * `portal.librus.pl$$advertisement-module`
  483. * `@@-ds.metric.gstatic.com^|`
  484. * `://gom.ge/cookie.js`
  485. * `://accout-update-smba.jp.$document`
  486. * `_200x250.png`
  487. * `@@://www.liquidweb.com/kb/wp-content/themes/lw-kb-theme/images/ads/vps-sidebar.jpg`
  488. */
  489. const tryNormalizeDomain = normalizeDomain(line);
  490. if (tryNormalizeDomain === line) {
  491. // the entire rule is domain
  492. return [line, ParseType.BlackIncludeSubdomain];
  493. }
  494. }
  495. return [
  496. `[parse-filter E0010] can not parse: ${line}`,
  497. ParseType.ErrorMessage
  498. ];
  499. }