parse-filter.ts 21 KB

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