parse-filter.ts 21 KB

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