parse-filter.ts 22 KB

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