parse-filter.ts 21 KB

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