parse-filter.ts 21 KB

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