parse-filter.ts 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715
  1. // @ts-check
  2. import { fetchRemoteTextByLine } from './fetch-text-by-line';
  3. import { NetworkFilter } from '@cliqz/adblocker';
  4. import { processLine } from './process-line';
  5. import tldts from 'tldts-experimental';
  6. import picocolors from 'picocolors';
  7. import { normalizeDomain } from './normalize-domain';
  8. import { fetchAssets } from './fetch-assets';
  9. import { deserializeArray, fsFetchCache, serializeArray } from './cache-filesystem';
  10. import type { Span } from '../trace';
  11. import createKeywordFilter from './aho-corasick';
  12. import { looseTldtsOpt } from '../constants/loose-tldts-opt';
  13. const DEBUG_DOMAIN_TO_FIND: string | null = null; // example.com | null
  14. let foundDebugDomain = false;
  15. const temporaryBypass = true;
  16. const domainListLineCb = (l: string, set: string[], includeAllSubDomain: boolean, meta: string) => {
  17. let line = processLine(l);
  18. if (!line) return;
  19. line = normalizeDomain(line);
  20. if (!line) return;
  21. if (DEBUG_DOMAIN_TO_FIND && line.includes(DEBUG_DOMAIN_TO_FIND)) {
  22. console.warn(picocolors.red(meta), '(black)', line.replaceAll(DEBUG_DOMAIN_TO_FIND, picocolors.bold(DEBUG_DOMAIN_TO_FIND)));
  23. foundDebugDomain = true;
  24. }
  25. set.push(includeAllSubDomain ? `.${line}` : line);
  26. };
  27. export function processDomainLists(span: Span, domainListsUrl: string, mirrors: string[] | null, includeAllSubDomain = false, ttl: number | null = null) {
  28. return span.traceChild(`process domainlist: ${domainListsUrl}`).traceAsyncFn((childSpan) => fsFetchCache.apply(
  29. domainListsUrl,
  30. async () => {
  31. const domainSets: string[] = [];
  32. if (mirrors == null || mirrors.length === 0) {
  33. for await (const l of await fetchRemoteTextByLine(domainListsUrl)) {
  34. domainListLineCb(l, domainSets, includeAllSubDomain, domainListsUrl);
  35. }
  36. } else {
  37. const filterRules = await childSpan
  38. .traceChild('download domain list')
  39. .traceAsyncFn(() => fetchAssets(domainListsUrl, mirrors).then(text => text.split('\n')));
  40. childSpan.traceChild('parse domain list').traceSyncFn(() => {
  41. for (let i = 0, len = filterRules.length; i < len; i++) {
  42. domainListLineCb(filterRules[i], domainSets, includeAllSubDomain, domainListsUrl);
  43. }
  44. });
  45. }
  46. return domainSets;
  47. },
  48. {
  49. ttl,
  50. temporaryBypass,
  51. serializer: serializeArray,
  52. deserializer: deserializeArray
  53. }
  54. ));
  55. }
  56. const hostsLineCb = (l: string, set: string[], includeAllSubDomain: boolean, meta: string) => {
  57. const line = processLine(l);
  58. if (!line) {
  59. return;
  60. }
  61. const _domain = line.split(/\s/)[1]?.trim();
  62. if (!_domain) {
  63. return;
  64. }
  65. const domain = normalizeDomain(_domain);
  66. if (!domain) {
  67. return;
  68. }
  69. if (DEBUG_DOMAIN_TO_FIND && domain.includes(DEBUG_DOMAIN_TO_FIND)) {
  70. console.warn(picocolors.red(meta), '(black)', domain.replaceAll(DEBUG_DOMAIN_TO_FIND, picocolors.bold(DEBUG_DOMAIN_TO_FIND)));
  71. foundDebugDomain = true;
  72. }
  73. set.push(includeAllSubDomain ? `.${domain}` : domain);
  74. };
  75. export function processHosts(span: Span, hostsUrl: string, mirrors: string[] | null, includeAllSubDomain = false, ttl: number | null = null) {
  76. return span.traceChild(`processhosts: ${hostsUrl}`).traceAsyncFn((childSpan) => fsFetchCache.apply(
  77. hostsUrl,
  78. async () => {
  79. const domainSets: string[] = [];
  80. if (mirrors == null || mirrors.length === 0) {
  81. for await (const l of await fetchRemoteTextByLine(hostsUrl)) {
  82. hostsLineCb(l, domainSets, includeAllSubDomain, hostsUrl);
  83. }
  84. } else {
  85. const filterRules = await childSpan
  86. .traceChild('download hosts')
  87. .traceAsyncFn(() => fetchAssets(hostsUrl, mirrors).then(text => text.split('\n')));
  88. childSpan.traceChild('parse hosts').traceSyncFn(() => {
  89. for (let i = 0, len = filterRules.length; i < len; i++) {
  90. hostsLineCb(filterRules[i], domainSets, includeAllSubDomain, hostsUrl);
  91. }
  92. });
  93. }
  94. return domainSets;
  95. },
  96. {
  97. ttl,
  98. temporaryBypass,
  99. serializer: serializeArray,
  100. deserializer: deserializeArray
  101. }
  102. ));
  103. }
  104. // eslint-disable-next-line sukka-ts/no-const-enum -- bun bundler is smart, maybe?
  105. const enum ParseType {
  106. WhiteIncludeSubdomain = 0,
  107. WhiteAbsolute = -1,
  108. BlackAbsolute = 1,
  109. BlackIncludeSubdomain = 2,
  110. ErrorMessage = 10,
  111. Null = 1000
  112. }
  113. export async function processFilterRules(
  114. parentSpan: Span,
  115. filterRulesUrl: string,
  116. fallbackUrls?: readonly string[] | undefined | null,
  117. ttl: number | null = null
  118. ): Promise<{ white: string[], black: string[], foundDebugDomain: boolean }> {
  119. const [white, black, warningMessages] = await parentSpan.traceChild(`process filter rules: ${filterRulesUrl}`).traceAsyncFn((span) => fsFetchCache.apply<Readonly<[
  120. white: string[],
  121. black: string[],
  122. warningMessages: string[]
  123. ]>>(
  124. filterRulesUrl,
  125. async () => {
  126. const whitelistDomainSets = new Set<string>();
  127. const blacklistDomainSets = new Set<string>();
  128. const warningMessages: string[] = [];
  129. const MUTABLE_PARSE_LINE_RESULT: [string, ParseType] = ['', 1000];
  130. /**
  131. * @param {string} line
  132. */
  133. const lineCb = (line: string) => {
  134. const result = parse(line, MUTABLE_PARSE_LINE_RESULT);
  135. const flag = result[1];
  136. if (flag === ParseType.Null) {
  137. return;
  138. }
  139. const hostname = result[0];
  140. if (DEBUG_DOMAIN_TO_FIND) {
  141. if (hostname.includes(DEBUG_DOMAIN_TO_FIND)) {
  142. console.warn(
  143. picocolors.red(filterRulesUrl),
  144. flag === ParseType.WhiteIncludeSubdomain || flag === ParseType.WhiteAbsolute
  145. ? '(white)'
  146. : '(black)',
  147. hostname.replaceAll(DEBUG_DOMAIN_TO_FIND, picocolors.bold(DEBUG_DOMAIN_TO_FIND))
  148. );
  149. foundDebugDomain = true;
  150. }
  151. }
  152. switch (flag) {
  153. case ParseType.WhiteIncludeSubdomain:
  154. if (hostname[0] !== '.') {
  155. whitelistDomainSets.add(`.${hostname}`);
  156. } else {
  157. whitelistDomainSets.add(hostname);
  158. }
  159. break;
  160. case ParseType.WhiteAbsolute:
  161. whitelistDomainSets.add(hostname);
  162. break;
  163. case ParseType.BlackAbsolute:
  164. blacklistDomainSets.add(hostname);
  165. break;
  166. case ParseType.BlackIncludeSubdomain:
  167. if (hostname[0] !== '.') {
  168. blacklistDomainSets.add(`.${hostname}`);
  169. } else {
  170. blacklistDomainSets.add(hostname);
  171. }
  172. break;
  173. case ParseType.ErrorMessage:
  174. warningMessages.push(hostname);
  175. break;
  176. default:
  177. break;
  178. }
  179. };
  180. if (!fallbackUrls || fallbackUrls.length === 0) {
  181. for await (const line of await fetchRemoteTextByLine(filterRulesUrl)) {
  182. // don't trim here
  183. lineCb(line);
  184. }
  185. } else {
  186. const filterRules = await span.traceChild('download adguard filter').traceAsyncFn(() => {
  187. return fetchAssets(filterRulesUrl, fallbackUrls).then(text => text.split('\n'));
  188. });
  189. span.traceChild('parse adguard filter').traceSyncFn(() => {
  190. for (let i = 0, len = filterRules.length; i < len; i++) {
  191. lineCb(filterRules[i]);
  192. }
  193. });
  194. }
  195. return [
  196. Array.from(whitelistDomainSets),
  197. Array.from(blacklistDomainSets),
  198. warningMessages
  199. ] as const;
  200. },
  201. {
  202. ttl,
  203. temporaryBypass,
  204. serializer: JSON.stringify,
  205. deserializer: JSON.parse
  206. }
  207. ));
  208. for (let i = 0, len = warningMessages.length; i < len; i++) {
  209. console.warn(
  210. picocolors.yellow(warningMessages[i]),
  211. picocolors.gray(picocolors.underline(filterRulesUrl))
  212. );
  213. }
  214. console.log(
  215. picocolors.gray('[process filter]'),
  216. picocolors.gray(filterRulesUrl),
  217. picocolors.gray(`white: ${white.length}`),
  218. picocolors.gray(`black: ${black.length}`)
  219. );
  220. return {
  221. white,
  222. black,
  223. foundDebugDomain
  224. };
  225. }
  226. // const R_KNOWN_NOT_NETWORK_FILTER_PATTERN_2 = /(\$popup|\$removeparam|\$popunder|\$cname)/;
  227. // cname exceptional filter can not be parsed by NetworkFilter
  228. // Surge / Clash can't handle CNAME either, so we just ignore them
  229. const kwfilter = createKeywordFilter([
  230. '!',
  231. '?',
  232. '*',
  233. '[',
  234. '(',
  235. ']',
  236. ')',
  237. ',',
  238. '#',
  239. '%',
  240. '&',
  241. '=',
  242. '~',
  243. // special modifier
  244. '$popup',
  245. '$removeparam',
  246. '$popunder',
  247. '$cname'
  248. ]);
  249. function parse($line: string, result: [string, ParseType]): [hostname: string, flag: ParseType] {
  250. if (
  251. // doesn't include
  252. !$line.includes('.') // rule with out dot can not be a domain
  253. // includes
  254. || kwfilter($line)
  255. ) {
  256. result[1] = ParseType.Null;
  257. return result;
  258. }
  259. const line = $line.trim();
  260. /** @example line.length */
  261. const len = line.length;
  262. if (len === 0) {
  263. result[1] = ParseType.Null;
  264. return result;
  265. }
  266. const firstCharCode = line[0].charCodeAt(0);
  267. const lastCharCode = line[len - 1].charCodeAt(0);
  268. if (
  269. firstCharCode === 47 // 47 `/`
  270. // ends with
  271. || lastCharCode === 46 // 46 `.`, line.endsWith('.')
  272. || lastCharCode === 45 // 45 `-`, line.endsWith('-')
  273. || lastCharCode === 95 // 95 `_`, line.endsWith('_')
  274. // || line.includes('$popup')
  275. // || line.includes('$removeparam')
  276. // || line.includes('$popunder')
  277. ) {
  278. result[1] = ParseType.Null;
  279. return result;
  280. }
  281. if ((line.includes('/') || line.includes(':')) && !line.includes('://')) {
  282. result[1] = ParseType.Null;
  283. return result;
  284. }
  285. const filter = NetworkFilter.parse(line);
  286. if (filter) {
  287. if (
  288. // filter.isCosmeticFilter() // always false
  289. // filter.isNetworkFilter() // always true
  290. filter.isElemHide()
  291. || filter.isGenericHide()
  292. || filter.isSpecificHide()
  293. || filter.isRedirect()
  294. || filter.isRedirectRule()
  295. || filter.hasDomains()
  296. || filter.isCSP() // must not be csp rule
  297. || (!filter.fromAny() && !filter.fromDocument())
  298. ) {
  299. // not supported type
  300. result[1] = ParseType.Null;
  301. return result;
  302. }
  303. if (
  304. filter.hostname // filter.hasHostname() // must have
  305. && filter.isPlain() // isPlain() === !isRegex()
  306. && (!filter.isFullRegex())
  307. ) {
  308. const hostname = normalizeDomain(filter.hostname);
  309. if (!hostname) {
  310. result[1] = ParseType.Null;
  311. return result;
  312. }
  313. // |: filter.isHostnameAnchor(),
  314. // |: filter.isLeftAnchor(),
  315. // |https://: !filter.isHostnameAnchor() && (filter.fromHttps() || filter.fromHttp())
  316. const isIncludeAllSubDomain = filter.isHostnameAnchor();
  317. if (filter.isException() || filter.isBadFilter()) {
  318. result[0] = hostname;
  319. result[1] = isIncludeAllSubDomain ? ParseType.WhiteIncludeSubdomain : ParseType.WhiteAbsolute;
  320. return result;
  321. }
  322. const _1p = filter.firstParty();
  323. const _3p = filter.thirdParty();
  324. if (_1p) {
  325. if (_1p === _3p) {
  326. result[0] = hostname;
  327. result[1] = isIncludeAllSubDomain ? ParseType.BlackIncludeSubdomain : ParseType.BlackAbsolute;
  328. return result;
  329. }
  330. result[1] = ParseType.Null;
  331. return result;
  332. }
  333. if (_3p) {
  334. result[1] = ParseType.Null;
  335. return result;
  336. }
  337. }
  338. }
  339. // After NetworkFilter.parse, it means the line can not be parsed by cliqz NetworkFilter
  340. // We now need to "salvage" the line as much as possible
  341. /*
  342. * From now on, we are mostly facing non-standard domain rules (some are regex like)
  343. * We first skip third-party and frame rules, as Surge / Clash can't handle them
  344. *
  345. * `.sharecounter.$third-party`
  346. * `.bbelements.com^$third-party`
  347. * `://o0e.ru^$third-party`
  348. * `.1.1.1.l80.js^$third-party`
  349. */
  350. if (line.includes('$third-party') || line.includes('$frame')) {
  351. result[1] = ParseType.Null;
  352. return result;
  353. }
  354. /** @example line.endsWith('^') */
  355. const lineEndsWithCaret = lastCharCode === 94; // lastChar === '^';
  356. /** @example line.endsWith('^|') */
  357. const lineEndsWithCaretVerticalBar = (lastCharCode === 124 /** lastChar === '|' */) && line[len - 2] === '^';
  358. /** @example line.endsWith('^') || line.endsWith('^|') */
  359. const lineEndsWithCaretOrCaretVerticalBar = lineEndsWithCaret || lineEndsWithCaretVerticalBar;
  360. // whitelist (exception)
  361. if (
  362. firstCharCode === 64 // 64 `@`
  363. && line[1] === '@'
  364. ) {
  365. let whiteIncludeAllSubDomain = true;
  366. /**
  367. * Some "malformed" regex-based filters can not be parsed by NetworkFilter
  368. * "$genericblock`" is also not supported by NetworkFilter, see:
  369. * https://github.com/ghostery/adblocker/blob/62caf7786ba10ef03beffecd8cd4eec111bcd5ec/packages/adblocker/test/parsing.test.ts#L950
  370. *
  371. * `@@||cmechina.net^$genericblock`
  372. * `@@|ftp.bmp.ovh^|`
  373. * `@@|adsterra.com^|`
  374. * `@@.atlassian.net$document`
  375. * `@@||ad.alimama.com^$genericblock`
  376. */
  377. let sliceStart = 0;
  378. let sliceEnd: number | undefined;
  379. switch (line[2]) {
  380. case '|':
  381. // line.startsWith('@@|')
  382. sliceStart = 3;
  383. whiteIncludeAllSubDomain = false;
  384. if (line[3] === '|') { // line.startsWith('@@||')
  385. sliceStart = 4;
  386. whiteIncludeAllSubDomain = true;
  387. }
  388. break;
  389. case '.': { // line.startsWith('@@.')
  390. sliceStart = 3;
  391. whiteIncludeAllSubDomain = true;
  392. break;
  393. }
  394. case ':': {
  395. /**
  396. * line.startsWith('@@://')
  397. *
  398. * `@@://googleadservices.com^|`
  399. * `@@://www.googleadservices.com^|`
  400. */
  401. if (line[3] === '/' && line[4] === '/') {
  402. whiteIncludeAllSubDomain = false;
  403. sliceStart = 5;
  404. }
  405. break;
  406. }
  407. default:
  408. break;
  409. }
  410. if (lineEndsWithCaretOrCaretVerticalBar) {
  411. sliceEnd = -2;
  412. } else if (line.endsWith('$genericblock')) {
  413. sliceEnd = -13;
  414. if (line[len - 14] === '^') { // line.endsWith('^$genericblock')
  415. sliceEnd = -14;
  416. }
  417. } else if (line.endsWith('$document')) {
  418. sliceEnd = -9;
  419. if (line[len - 10] === '^') { // line.endsWith('^$document')
  420. sliceEnd = -10;
  421. }
  422. }
  423. if (sliceStart !== 0 || sliceEnd !== undefined) {
  424. const sliced = line.slice(sliceStart, sliceEnd);
  425. const domain = normalizeDomain(sliced);
  426. if (domain) {
  427. result[0] = domain;
  428. result[1] = whiteIncludeAllSubDomain ? ParseType.WhiteIncludeSubdomain : ParseType.WhiteAbsolute;
  429. return result;
  430. }
  431. result[0] = `[parse-filter E0001] (white) invalid domain: ${JSON.stringify({
  432. line, sliced, sliceStart, sliceEnd, domain
  433. })}`;
  434. result[1] = ParseType.ErrorMessage;
  435. return result;
  436. }
  437. result[0] = `[parse-filter E0006] (white) failed to parse: ${JSON.stringify({
  438. line, sliceStart, sliceEnd
  439. })}`;
  440. result[1] = ParseType.ErrorMessage;
  441. return result;
  442. }
  443. if (
  444. // 124 `|`
  445. // line.startsWith('|')
  446. firstCharCode === 124
  447. && lineEndsWithCaretOrCaretVerticalBar
  448. ) {
  449. /**
  450. * Some malformed filters can not be parsed by NetworkFilter:
  451. *
  452. * `||smetrics.teambeachbody.com^.com^`
  453. * `||solutions.|pages.indigovision.com^`
  454. * `||vystar..0rg@client.iebetanialaargentina.edu.co^`
  455. * `app-uat.latrobehealth.com.au^predirect.snapdeal.com`
  456. */
  457. const includeAllSubDomain = line[1] === '|';
  458. const sliceStart = includeAllSubDomain ? 2 : 1;
  459. const sliceEnd = lineEndsWithCaret
  460. ? -1
  461. : (lineEndsWithCaretVerticalBar ? -2 : undefined);
  462. const sliced = line.slice(sliceStart, sliceEnd); // we already make sure line startsWith "|"
  463. const domain = normalizeDomain(sliced);
  464. if (domain) {
  465. result[0] = domain;
  466. result[1] = includeAllSubDomain ? ParseType.BlackIncludeSubdomain : ParseType.BlackAbsolute;
  467. return result;
  468. }
  469. result[0] = `[parse-filter E0002] (black) invalid domain: ${sliced}`;
  470. result[1] = ParseType.ErrorMessage;
  471. return result;
  472. }
  473. const lineStartsWithSingleDot = firstCharCode === 46; // 46 `.`
  474. if (
  475. lineStartsWithSingleDot
  476. && lineEndsWithCaretOrCaretVerticalBar
  477. ) {
  478. /**
  479. * `.ay.delivery^`
  480. * `.m.bookben.com^`
  481. * `.wap.x4399.com^`
  482. */
  483. const sliced = line.slice(
  484. 1, // remove prefix dot
  485. lineEndsWithCaret // replaceAll('^', '')
  486. ? -1
  487. : (lineEndsWithCaretVerticalBar ? -2 : undefined) // replace('^|', '')
  488. );
  489. const suffix = tldts.getPublicSuffix(sliced, looseTldtsOpt);
  490. if (!suffix) {
  491. // This exclude domain-like resource like `1.1.4.514.js`
  492. result[1] = ParseType.Null;
  493. return result;
  494. }
  495. const domain = normalizeDomain(sliced);
  496. if (domain) {
  497. result[0] = domain;
  498. result[1] = ParseType.BlackIncludeSubdomain;
  499. return result;
  500. }
  501. result[0] = `[parse-filter E0003] (black) invalid domain: ${JSON.stringify({ sliced, domain })}`;
  502. result[1] = ParseType.ErrorMessage;
  503. return result;
  504. }
  505. /**
  506. * `|http://x.o2.pl^`
  507. * `://mine.torrent.pw^`
  508. * `://say.ac^`
  509. */
  510. if (lineEndsWithCaretOrCaretVerticalBar) {
  511. let sliceStart = 0;
  512. let sliceEnd;
  513. if (lineEndsWithCaret) { // line.endsWith('^')
  514. sliceEnd = -1;
  515. } else if (lineEndsWithCaretVerticalBar) { // line.endsWith('^|')
  516. sliceEnd = -2;
  517. }
  518. if (line.startsWith('://')) {
  519. sliceStart = 3;
  520. } else if (line.startsWith('http://')) {
  521. sliceStart = 7;
  522. } else if (line.startsWith('https://')) {
  523. sliceStart = 8;
  524. } else if (line.startsWith('|http://')) {
  525. sliceStart = 8;
  526. } else if (line.startsWith('|https://')) {
  527. sliceStart = 9;
  528. }
  529. if (sliceStart !== 0 || sliceEnd !== undefined) {
  530. const sliced = line.slice(sliceStart, sliceEnd);
  531. const domain = normalizeDomain(sliced);
  532. if (domain) {
  533. result[0] = domain;
  534. result[1] = ParseType.BlackIncludeSubdomain;
  535. return result;
  536. }
  537. result[0] = `[parse-filter E0004] (black) invalid domain: ${JSON.stringify({
  538. line, sliced, sliceStart, sliceEnd, domain
  539. })}`;
  540. result[1] = ParseType.ErrorMessage;
  541. return result;
  542. }
  543. }
  544. /**
  545. * `_vmind.qqvideo.tc.qq.com^`
  546. * `arketing.indianadunes.com^`
  547. * `charlestownwyllie.oaklawnnonantum.com^`
  548. * `-telemetry.officeapps.live.com^`
  549. * `-tracker.biliapi.net`
  550. * `-logging.nextmedia.com`
  551. * `_social_tracking.js^`
  552. */
  553. if (
  554. firstCharCode !== 124 // 124 `|`
  555. && lastCharCode === 94 // 94 `^`
  556. ) {
  557. const _domain = line.slice(0, -1);
  558. const suffix = tldts.getPublicSuffix(_domain, looseTldtsOpt);
  559. if (!suffix) {
  560. // This exclude domain-like resource like `_social_tracking.js^`
  561. result[1] = ParseType.Null;
  562. return result;
  563. }
  564. const domain = normalizeDomain(_domain);
  565. if (domain) {
  566. result[0] = domain;
  567. result[1] = ParseType.BlackAbsolute;
  568. return result;
  569. }
  570. result[0] = `[parse-filter E0005] (black) invalid domain: ${_domain}`;
  571. result[1] = ParseType.ErrorMessage;
  572. return result;
  573. }
  574. // Possibly that entire rule is domain
  575. /**
  576. * lineStartsWithSingleDot:
  577. *
  578. * `.cookielaw.js`
  579. * `.content_tracking.js`
  580. * `.ads.css`
  581. *
  582. * else:
  583. *
  584. * `_prebid.js`
  585. * `t.yesware.com`
  586. * `ubmcmm.baidustatic.com`
  587. * `://www.smfg-card.$document`
  588. * `portal.librus.pl$$advertisement-module`
  589. * `@@-ds.metric.gstatic.com^|`
  590. * `://gom.ge/cookie.js`
  591. * `://accout-update-smba.jp.$document`
  592. * `_200x250.png`
  593. * `@@://www.liquidweb.com/kb/wp-content/themes/lw-kb-theme/images/ads/vps-sidebar.jpg`
  594. */
  595. let sliceStart = 0;
  596. let sliceEnd: number | undefined;
  597. if (lineStartsWithSingleDot) {
  598. sliceStart = 1;
  599. }
  600. if (line.endsWith('^$all')) { // This salvage line `thepiratebay3.com^$all`
  601. sliceEnd = -5;
  602. } else if (
  603. // Try to salvage line like `://account.smba.$document`
  604. // For this specific line, it will fail anyway though.
  605. line.endsWith('$document')
  606. ) {
  607. sliceEnd = -9;
  608. }
  609. const sliced = (sliceStart !== 0 || sliceEnd !== undefined) ? line.slice(sliceStart, sliceEnd) : line;
  610. const suffix = tldts.getPublicSuffix(sliced, looseTldtsOpt);
  611. /**
  612. * Fast exclude definitely not domain-like resource
  613. *
  614. * `.gatracking.js`, suffix is `js`,
  615. * `.ads.css`, suffix is `css`,
  616. * `-cpm-ads.$badfilter`, suffix is `$badfilter`,
  617. * `portal.librus.pl$$advertisement-module`, suffix is `pl$$advertisement-module`
  618. */
  619. if (!suffix) {
  620. // This exclude domain-like resource like `.gatracking.js`, `.beacon.min.js` and `.cookielaw.js`
  621. result[1] = ParseType.Null;
  622. return result;
  623. }
  624. const tryNormalizeDomain = normalizeDomain(sliced);
  625. if (tryNormalizeDomain === sliced) {
  626. // the entire rule is domain
  627. result[0] = sliced;
  628. result[1] = ParseType.BlackIncludeSubdomain;
  629. return result;
  630. }
  631. result[0] = `[parse-filter ${tryNormalizeDomain === null ? 'E0010' : 'E0011'}] can not parse: ${JSON.stringify({ line, tryNormalizeDomain, sliced })}`;
  632. result[1] = ParseType.ErrorMessage;
  633. return result;
  634. }