parse-filter.ts 20 KB

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