parse-filter.ts 21 KB

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