parse-filter.ts 21 KB

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