parse-filter.ts 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731
  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(() => fetchAssets(filterRulesUrl, fallbackUrls).then(text => text.split('\n')));
  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. '$frame',
  258. // some bad syntax
  259. '^popup'
  260. ]);
  261. export function parse($line: string, result: [string, ParseType], allowThirdParty: boolean): [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. let 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. if (allowThirdParty) {
  347. result[0] = hostname;
  348. result[1] = isIncludeAllSubDomain ? ParseType.BlackIncludeSubdomain : ParseType.BlackAbsolute;
  349. return result;
  350. }
  351. result[1] = ParseType.Null;
  352. return result;
  353. }
  354. }
  355. }
  356. // After NetworkFilter.parse, it means the line can not be parsed by cliqz NetworkFilter
  357. // We now need to "salvage" the line as much as possible
  358. /*
  359. * From now on, we are mostly facing non-standard domain rules (some are regex like)
  360. * We first skip third-party and frame rules, as Surge / Clash can't handle them
  361. *
  362. * `.sharecounter.$third-party`
  363. * `.bbelements.com^$third-party`
  364. * `://o0e.ru^$third-party`
  365. * `.1.1.1.l80.js^$third-party`
  366. */
  367. if (line.includes('$third-party')) {
  368. if (!allowThirdParty) {
  369. result[1] = ParseType.Null;
  370. return result;
  371. }
  372. line = line
  373. .replace('$third-party,', '$')
  374. .replace('$third-party', '');
  375. }
  376. /** @example line.endsWith('^') */
  377. const lineEndsWithCaret = lastCharCode === 94; // lastChar === '^';
  378. /** @example line.endsWith('^|') */
  379. const lineEndsWithCaretVerticalBar = (lastCharCode === 124 /** lastChar === '|' */) && line[len - 2] === '^';
  380. /** @example line.endsWith('^') || line.endsWith('^|') */
  381. const lineEndsWithCaretOrCaretVerticalBar = lineEndsWithCaret || lineEndsWithCaretVerticalBar;
  382. // whitelist (exception)
  383. if (
  384. firstCharCode === 64 // 64 `@`
  385. && line[1] === '@'
  386. ) {
  387. let whiteIncludeAllSubDomain = true;
  388. /**
  389. * Some "malformed" regex-based filters can not be parsed by NetworkFilter
  390. * "$genericblock`" is also not supported by NetworkFilter, see:
  391. * https://github.com/ghostery/adblocker/blob/62caf7786ba10ef03beffecd8cd4eec111bcd5ec/packages/adblocker/test/parsing.test.ts#L950
  392. *
  393. * `@@||cmechina.net^$genericblock`
  394. * `@@|ftp.bmp.ovh^|`
  395. * `@@|adsterra.com^|`
  396. * `@@.atlassian.net$document`
  397. * `@@||ad.alimama.com^$genericblock`
  398. */
  399. let sliceStart = 0;
  400. let sliceEnd: number | undefined;
  401. switch (line[2]) {
  402. case '|':
  403. // line.startsWith('@@|')
  404. sliceStart = 3;
  405. whiteIncludeAllSubDomain = false;
  406. if (line[3] === '|') { // line.startsWith('@@||')
  407. sliceStart = 4;
  408. whiteIncludeAllSubDomain = true;
  409. }
  410. break;
  411. case '.': { // line.startsWith('@@.')
  412. sliceStart = 3;
  413. whiteIncludeAllSubDomain = true;
  414. break;
  415. }
  416. case ':': {
  417. /**
  418. * line.startsWith('@@://')
  419. *
  420. * `@@://googleadservices.com^|`
  421. * `@@://www.googleadservices.com^|`
  422. */
  423. if (line[3] === '/' && line[4] === '/') {
  424. whiteIncludeAllSubDomain = false;
  425. sliceStart = 5;
  426. }
  427. break;
  428. }
  429. default:
  430. break;
  431. }
  432. if (lineEndsWithCaretOrCaretVerticalBar) {
  433. sliceEnd = -2;
  434. } else if (line.endsWith('$genericblock')) {
  435. sliceEnd = -13;
  436. if (line[len - 14] === '^') { // line.endsWith('^$genericblock')
  437. sliceEnd = -14;
  438. }
  439. } else if (line.endsWith('$document')) {
  440. sliceEnd = -9;
  441. if (line[len - 10] === '^') { // line.endsWith('^$document')
  442. sliceEnd = -10;
  443. }
  444. }
  445. if (sliceStart !== 0 || sliceEnd !== undefined) {
  446. const sliced = line.slice(sliceStart, sliceEnd);
  447. const domain = normalizeDomain(sliced);
  448. if (domain) {
  449. result[0] = domain;
  450. result[1] = whiteIncludeAllSubDomain ? ParseType.WhiteIncludeSubdomain : ParseType.WhiteAbsolute;
  451. return result;
  452. }
  453. result[0] = `[parse-filter E0001] (white) invalid domain: ${JSON.stringify({
  454. line, sliced, sliceStart, sliceEnd, domain
  455. })}`;
  456. result[1] = ParseType.ErrorMessage;
  457. return result;
  458. }
  459. result[0] = `[parse-filter E0006] (white) failed to parse: ${JSON.stringify({
  460. line, sliceStart, sliceEnd
  461. })}`;
  462. result[1] = ParseType.ErrorMessage;
  463. return result;
  464. }
  465. if (
  466. // 124 `|`
  467. // line.startsWith('|')
  468. firstCharCode === 124
  469. && lineEndsWithCaretOrCaretVerticalBar
  470. ) {
  471. /**
  472. * Some malformed filters can not be parsed by NetworkFilter:
  473. *
  474. * `||smetrics.teambeachbody.com^.com^`
  475. * `||solutions.|pages.indigovision.com^`
  476. * `||vystar..0rg@client.iebetanialaargentina.edu.co^`
  477. * `app-uat.latrobehealth.com.au^predirect.snapdeal.com`
  478. */
  479. const includeAllSubDomain = line[1] === '|';
  480. const sliceStart = includeAllSubDomain ? 2 : 1;
  481. const sliceEnd = lineEndsWithCaret
  482. ? -1
  483. : (lineEndsWithCaretVerticalBar ? -2 : undefined);
  484. const sliced = line.slice(sliceStart, sliceEnd); // we already make sure line startsWith "|"
  485. const domain = normalizeDomain(sliced);
  486. if (domain) {
  487. result[0] = domain;
  488. result[1] = includeAllSubDomain ? ParseType.BlackIncludeSubdomain : ParseType.BlackAbsolute;
  489. return result;
  490. }
  491. result[0] = `[parse-filter E0002] (black) invalid domain: ${sliced}`;
  492. result[1] = ParseType.ErrorMessage;
  493. return result;
  494. }
  495. const lineStartsWithSingleDot = firstCharCode === 46; // 46 `.`
  496. if (
  497. lineStartsWithSingleDot
  498. && lineEndsWithCaretOrCaretVerticalBar
  499. ) {
  500. /**
  501. * `.ay.delivery^`
  502. * `.m.bookben.com^`
  503. * `.wap.x4399.com^`
  504. */
  505. const sliced = line.slice(
  506. 1, // remove prefix dot
  507. lineEndsWithCaret // replaceAll('^', '')
  508. ? -1
  509. : (lineEndsWithCaretVerticalBar ? -2 : undefined) // replace('^|', '')
  510. );
  511. const suffix = tldts.getPublicSuffix(sliced, looseTldtsOpt);
  512. if (!suffix) {
  513. // This exclude domain-like resource like `1.1.4.514.js`
  514. result[1] = ParseType.Null;
  515. return result;
  516. }
  517. const domain = normalizeDomain(sliced);
  518. if (domain) {
  519. result[0] = domain;
  520. result[1] = ParseType.BlackIncludeSubdomain;
  521. return result;
  522. }
  523. result[0] = `[parse-filter E0003] (black) invalid domain: ${JSON.stringify({ sliced, domain })}`;
  524. result[1] = ParseType.ErrorMessage;
  525. return result;
  526. }
  527. /**
  528. * `|http://x.o2.pl^`
  529. * `://mine.torrent.pw^`
  530. * `://say.ac^`
  531. */
  532. if (lineEndsWithCaretOrCaretVerticalBar) {
  533. let sliceStart = 0;
  534. let sliceEnd;
  535. if (lineEndsWithCaret) { // line.endsWith('^')
  536. sliceEnd = -1;
  537. } else if (lineEndsWithCaretVerticalBar) { // line.endsWith('^|')
  538. sliceEnd = -2;
  539. }
  540. if (line.startsWith('://')) {
  541. sliceStart = 3;
  542. } else if (line.startsWith('http://')) {
  543. sliceStart = 7;
  544. } else if (line.startsWith('https://')) {
  545. sliceStart = 8;
  546. } else if (line.startsWith('|http://')) {
  547. sliceStart = 8;
  548. } else if (line.startsWith('|https://')) {
  549. sliceStart = 9;
  550. }
  551. if (sliceStart !== 0 || sliceEnd !== undefined) {
  552. const sliced = line.slice(sliceStart, sliceEnd);
  553. const domain = normalizeDomain(sliced);
  554. if (domain) {
  555. result[0] = domain;
  556. result[1] = ParseType.BlackIncludeSubdomain;
  557. return result;
  558. }
  559. result[0] = `[parse-filter E0004] (black) invalid domain: ${JSON.stringify({
  560. line, sliced, sliceStart, sliceEnd, domain
  561. })}`;
  562. result[1] = ParseType.ErrorMessage;
  563. return result;
  564. }
  565. }
  566. /**
  567. * `_vmind.qqvideo.tc.qq.com^`
  568. * `arketing.indianadunes.com^`
  569. * `charlestownwyllie.oaklawnnonantum.com^`
  570. * `-telemetry.officeapps.live.com^`
  571. * `-tracker.biliapi.net`
  572. * `-logging.nextmedia.com`
  573. * `_social_tracking.js^`
  574. */
  575. if (
  576. firstCharCode !== 124 // 124 `|`
  577. && lastCharCode === 94 // 94 `^`
  578. ) {
  579. const _domain = line.slice(0, -1);
  580. const suffix = tldts.getPublicSuffix(_domain, looseTldtsOpt);
  581. if (!suffix) {
  582. // This exclude domain-like resource like `_social_tracking.js^`
  583. result[1] = ParseType.Null;
  584. return result;
  585. }
  586. const domain = normalizeDomain(_domain);
  587. if (domain) {
  588. result[0] = domain;
  589. result[1] = ParseType.BlackAbsolute;
  590. return result;
  591. }
  592. result[0] = `[parse-filter E0005] (black) invalid domain: ${_domain}`;
  593. result[1] = ParseType.ErrorMessage;
  594. return result;
  595. }
  596. // Possibly that entire rule is domain
  597. /**
  598. * lineStartsWithSingleDot:
  599. *
  600. * `.cookielaw.js`
  601. * `.content_tracking.js`
  602. * `.ads.css`
  603. *
  604. * else:
  605. *
  606. * `_prebid.js`
  607. * `t.yesware.com`
  608. * `ubmcmm.baidustatic.com`
  609. * `://www.smfg-card.$document`
  610. * `portal.librus.pl$$advertisement-module`
  611. * `@@-ds.metric.gstatic.com^|`
  612. * `://gom.ge/cookie.js`
  613. * `://accout-update-smba.jp.$document`
  614. * `_200x250.png`
  615. * `@@://www.liquidweb.com/kb/wp-content/themes/lw-kb-theme/images/ads/vps-sidebar.jpg`
  616. */
  617. let sliceStart = 0;
  618. let sliceEnd: number | undefined;
  619. if (lineStartsWithSingleDot) {
  620. sliceStart = 1;
  621. }
  622. if (line.endsWith('^$all')) { // This salvage line `thepiratebay3.com^$all`
  623. sliceEnd = -5;
  624. } else if (
  625. // Try to salvage line like `://account.smba.$document`
  626. // For this specific line, it will fail anyway though.
  627. line.endsWith('$document')
  628. ) {
  629. sliceEnd = -9;
  630. } else if (line.endsWith('$badfilter')) {
  631. sliceEnd = -10;
  632. }
  633. const sliced = (sliceStart !== 0 || sliceEnd !== undefined) ? line.slice(sliceStart, sliceEnd) : line;
  634. const tryNormalizeDomain = normalizeDomain(sliced);
  635. if (tryNormalizeDomain === sliced) {
  636. // the entire rule is domain
  637. result[0] = sliced;
  638. result[1] = ParseType.BlackIncludeSubdomain;
  639. return result;
  640. }
  641. result[0] = `[parse-filter ${tryNormalizeDomain === null ? 'E0010' : 'E0011'}] can not parse: ${JSON.stringify({ line, tryNormalizeDomain, sliced })}`;
  642. result[1] = ParseType.ErrorMessage;
  643. return result;
  644. }