parse-filter.ts 21 KB

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