parse-filter.ts 21 KB

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