parse-filter.ts 21 KB

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