parse-filter.ts 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746
  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 { createAhoCorasick as createKeywordFilter } from 'foxts/ahocorasick';
  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. /** @example line.length */
  266. const len = line.length;
  267. if (len === 0) {
  268. result[1] = ParseType.Null;
  269. return result;
  270. }
  271. const firstCharCode = line[0].charCodeAt(0);
  272. const lastCharCode = line[len - 1].charCodeAt(0);
  273. if (
  274. firstCharCode === 47 // 47 `/`
  275. // ends with
  276. || lastCharCode === 46 // 46 `.`, line.endsWith('.')
  277. || lastCharCode === 45 // 45 `-`, line.endsWith('-')
  278. || lastCharCode === 95 // 95 `_`, line.endsWith('_')
  279. // || line.includes('$popup')
  280. // || line.includes('$removeparam')
  281. // || line.includes('$popunder')
  282. ) {
  283. result[1] = ParseType.Null;
  284. return result;
  285. }
  286. if ((line.includes('/') || line.includes(':')) && !line.includes('://')) {
  287. result[1] = ParseType.Null;
  288. return result;
  289. }
  290. const filter = NetworkFilter.parse(line);
  291. if (filter) {
  292. if (
  293. // filter.isCosmeticFilter() // always false
  294. // filter.isNetworkFilter() // always true
  295. filter.isElemHide()
  296. || filter.isGenericHide()
  297. || filter.isSpecificHide()
  298. || filter.isRedirect()
  299. || filter.isRedirectRule()
  300. || filter.hasDomains()
  301. || filter.isCSP() // must not be csp rule
  302. || (!filter.fromHttp() && !filter.fromHttps())
  303. ) {
  304. // not supported type
  305. result[1] = ParseType.Null;
  306. return result;
  307. }
  308. if (
  309. !filter.fromAny()
  310. // $image, $websocket, $xhr this are all non-any
  311. && !filter.fromDocument() // $document, $doc
  312. // && !filter.fromSubdocument() // $subdocument, $subdoc
  313. ) {
  314. result[1] = ParseType.Null;
  315. return result;
  316. }
  317. if (
  318. filter.hostname // filter.hasHostname() // must have
  319. && filter.isPlain() // isPlain() === !isRegex()
  320. && (!filter.isFullRegex())
  321. ) {
  322. const hostname = normalizeDomain(filter.hostname);
  323. if (!hostname) {
  324. result[1] = ParseType.Null;
  325. return result;
  326. }
  327. // |: filter.isHostnameAnchor(),
  328. // |: filter.isLeftAnchor(),
  329. // |https://: !filter.isHostnameAnchor() && (filter.fromHttps() || filter.fromHttp())
  330. const isIncludeAllSubDomain = filter.isHostnameAnchor();
  331. if (filter.isException() || filter.isBadFilter()) {
  332. result[0] = hostname;
  333. result[1] = isIncludeAllSubDomain ? ParseType.WhiteIncludeSubdomain : ParseType.WhiteAbsolute;
  334. return result;
  335. }
  336. const _1p = filter.firstParty();
  337. const _3p = filter.thirdParty();
  338. if (_1p) { // first party is true
  339. if (_3p) { // third party is also true
  340. result[0] = hostname;
  341. result[1] = isIncludeAllSubDomain ? ParseType.BlackIncludeSubdomain : ParseType.BlackAbsolute;
  342. return result;
  343. }
  344. result[1] = ParseType.Null;
  345. return result;
  346. }
  347. if (_3p) {
  348. if (allowThirdParty) {
  349. result[0] = hostname;
  350. result[1] = isIncludeAllSubDomain ? ParseType.BlackIncludeSubdomain : ParseType.BlackAbsolute;
  351. return result;
  352. }
  353. result[1] = ParseType.Null;
  354. return result;
  355. }
  356. }
  357. }
  358. // After NetworkFilter.parse, it means the line can not be parsed by cliqz NetworkFilter
  359. // We now need to "salvage" the line as much as possible
  360. /*
  361. * From now on, we are mostly facing non-standard domain rules (some are regex like)
  362. * We first skip third-party and frame rules, as Surge / Clash can't handle them
  363. *
  364. * `.sharecounter.$third-party`
  365. * `.bbelements.com^$third-party`
  366. * `://o0e.ru^$third-party`
  367. * `.1.1.1.l80.js^$third-party`
  368. */
  369. if (line.includes('$third-party')) {
  370. if (!allowThirdParty) {
  371. result[1] = ParseType.Null;
  372. return result;
  373. }
  374. line = line
  375. .replace('$third-party,', '$')
  376. .replace('$third-party', '');
  377. }
  378. /** @example line.endsWith('^') */
  379. const lineEndsWithCaret = lastCharCode === 94; // lastChar === '^';
  380. /** @example line.endsWith('^|') */
  381. const lineEndsWithCaretVerticalBar = (lastCharCode === 124 /** lastChar === '|' */) && line[len - 2] === '^';
  382. /** @example line.endsWith('^') || line.endsWith('^|') */
  383. const lineEndsWithCaretOrCaretVerticalBar = lineEndsWithCaret || lineEndsWithCaretVerticalBar;
  384. // whitelist (exception)
  385. if (
  386. firstCharCode === 64 // 64 `@`
  387. && line[1] === '@'
  388. ) {
  389. let whiteIncludeAllSubDomain = true;
  390. /**
  391. * Some "malformed" regex-based filters can not be parsed by NetworkFilter
  392. * "$genericblock`" is also not supported by NetworkFilter, see:
  393. * https://github.com/ghostery/adblocker/blob/62caf7786ba10ef03beffecd8cd4eec111bcd5ec/packages/adblocker/test/parsing.test.ts#L950
  394. *
  395. * `@@||cmechina.net^$genericblock`
  396. * `@@|ftp.bmp.ovh^|`
  397. * `@@|adsterra.com^|`
  398. * `@@.atlassian.net$document`
  399. * `@@||ad.alimama.com^$genericblock`
  400. */
  401. let sliceStart = 0;
  402. let sliceEnd: number | undefined;
  403. switch (line[2]) {
  404. case '|':
  405. // line.startsWith('@@|')
  406. sliceStart = 3;
  407. whiteIncludeAllSubDomain = false;
  408. if (line[3] === '|') { // line.startsWith('@@||')
  409. sliceStart = 4;
  410. whiteIncludeAllSubDomain = true;
  411. }
  412. break;
  413. case '.': { // line.startsWith('@@.')
  414. sliceStart = 3;
  415. whiteIncludeAllSubDomain = true;
  416. break;
  417. }
  418. case ':': {
  419. /**
  420. * line.startsWith('@@://')
  421. *
  422. * `@@://googleadservices.com^|`
  423. * `@@://www.googleadservices.com^|`
  424. */
  425. if (line[3] === '/' && line[4] === '/') {
  426. whiteIncludeAllSubDomain = false;
  427. sliceStart = 5;
  428. }
  429. break;
  430. }
  431. default:
  432. break;
  433. }
  434. if (lineEndsWithCaretOrCaretVerticalBar) {
  435. sliceEnd = -2;
  436. } else if (line.endsWith('$genericblock')) {
  437. sliceEnd = -13;
  438. if (line[len - 14] === '^') { // line.endsWith('^$genericblock')
  439. sliceEnd = -14;
  440. }
  441. } else if (line.endsWith('$document')) {
  442. sliceEnd = -9;
  443. if (line[len - 10] === '^') { // line.endsWith('^$document')
  444. sliceEnd = -10;
  445. }
  446. }
  447. if (sliceStart !== 0 || sliceEnd !== undefined) {
  448. const sliced = line.slice(sliceStart, sliceEnd);
  449. const domain = normalizeDomain(sliced);
  450. if (domain) {
  451. result[0] = domain;
  452. result[1] = whiteIncludeAllSubDomain ? ParseType.WhiteIncludeSubdomain : ParseType.WhiteAbsolute;
  453. return result;
  454. }
  455. result[0] = `[parse-filter E0001] (white) invalid domain: ${JSON.stringify({
  456. line, sliced, sliceStart, sliceEnd, domain
  457. })}`;
  458. result[1] = ParseType.ErrorMessage;
  459. return result;
  460. }
  461. result[0] = `[parse-filter E0006] (white) failed to parse: ${JSON.stringify({
  462. line, sliceStart, sliceEnd
  463. })}`;
  464. result[1] = ParseType.ErrorMessage;
  465. return result;
  466. }
  467. if (
  468. // 124 `|`
  469. // line.startsWith('|')
  470. firstCharCode === 124
  471. && lineEndsWithCaretOrCaretVerticalBar
  472. ) {
  473. /**
  474. * Some malformed filters can not be parsed by NetworkFilter:
  475. *
  476. * `||smetrics.teambeachbody.com^.com^`
  477. * `||solutions.|pages.indigovision.com^`
  478. * `||vystar..0rg@client.iebetanialaargentina.edu.co^`
  479. * `app-uat.latrobehealth.com.au^predirect.snapdeal.com`
  480. */
  481. const includeAllSubDomain = line[1] === '|';
  482. const sliceStart = includeAllSubDomain ? 2 : 1;
  483. const sliceEnd = lineEndsWithCaret
  484. ? -1
  485. : (lineEndsWithCaretVerticalBar ? -2 : undefined);
  486. const sliced = line.slice(sliceStart, sliceEnd); // we already make sure line startsWith "|"
  487. const domain = normalizeDomain(sliced);
  488. if (domain) {
  489. result[0] = domain;
  490. result[1] = includeAllSubDomain ? ParseType.BlackIncludeSubdomain : ParseType.BlackAbsolute;
  491. return result;
  492. }
  493. result[0] = `[parse-filter E0002] (black) invalid domain: ${sliced}`;
  494. result[1] = ParseType.ErrorMessage;
  495. return result;
  496. }
  497. // if (line.endsWith('$image')) {
  498. // /**
  499. // * Some $image filters are not NetworkFilter:
  500. // *
  501. // * `app.site123.com$image`
  502. // * `t.signaux$image`
  503. // * `track.customer.io$image`
  504. // */
  505. // }
  506. const lineStartsWithSingleDot = firstCharCode === 46; // 46 `.`
  507. if (
  508. lineStartsWithSingleDot
  509. && lineEndsWithCaretOrCaretVerticalBar
  510. ) {
  511. /**
  512. * `.ay.delivery^`
  513. * `.m.bookben.com^`
  514. * `.wap.x4399.com^`
  515. */
  516. const sliced = line.slice(
  517. 1, // remove prefix dot
  518. lineEndsWithCaret // replaceAll('^', '')
  519. ? -1
  520. : (lineEndsWithCaretVerticalBar ? -2 : undefined) // replace('^|', '')
  521. );
  522. const suffix = tldts.getPublicSuffix(sliced, looseTldtsOpt);
  523. if (!suffix) {
  524. // This exclude domain-like resource like `1.1.4.514.js`
  525. result[1] = ParseType.Null;
  526. return result;
  527. }
  528. const domain = normalizeDomain(sliced);
  529. if (domain) {
  530. result[0] = domain;
  531. result[1] = ParseType.BlackIncludeSubdomain;
  532. return result;
  533. }
  534. result[0] = `[parse-filter E0003] (black) invalid domain: ${JSON.stringify({ sliced, domain })}`;
  535. result[1] = ParseType.ErrorMessage;
  536. return result;
  537. }
  538. /**
  539. * `|http://x.o2.pl^`
  540. * `://mine.torrent.pw^`
  541. * `://say.ac^`
  542. */
  543. if (lineEndsWithCaretOrCaretVerticalBar) {
  544. let sliceStart = 0;
  545. let sliceEnd;
  546. if (lineEndsWithCaret) { // line.endsWith('^')
  547. sliceEnd = -1;
  548. } else if (lineEndsWithCaretVerticalBar) { // line.endsWith('^|')
  549. sliceEnd = -2;
  550. }
  551. if (line.startsWith('://')) {
  552. sliceStart = 3;
  553. } else if (line.startsWith('http://')) {
  554. sliceStart = 7;
  555. } else if (line.startsWith('https://')) {
  556. sliceStart = 8;
  557. } else if (line.startsWith('|http://')) {
  558. sliceStart = 8;
  559. } else if (line.startsWith('|https://')) {
  560. sliceStart = 9;
  561. }
  562. if (sliceStart !== 0 || sliceEnd !== undefined) {
  563. const sliced = line.slice(sliceStart, sliceEnd);
  564. const domain = normalizeDomain(sliced);
  565. if (domain) {
  566. result[0] = domain;
  567. result[1] = ParseType.BlackIncludeSubdomain;
  568. return result;
  569. }
  570. result[0] = `[parse-filter E0004] (black) invalid domain: ${JSON.stringify({
  571. line, sliced, sliceStart, sliceEnd, domain
  572. })}`;
  573. result[1] = ParseType.ErrorMessage;
  574. return result;
  575. }
  576. }
  577. /**
  578. * `_vmind.qqvideo.tc.qq.com^`
  579. * `arketing.indianadunes.com^`
  580. * `charlestownwyllie.oaklawnnonantum.com^`
  581. * `-telemetry.officeapps.live.com^`
  582. * `-tracker.biliapi.net`
  583. * `-logging.nextmedia.com`
  584. * `_social_tracking.js^`
  585. */
  586. if (
  587. firstCharCode !== 124 // 124 `|`
  588. && lastCharCode === 94 // 94 `^`
  589. ) {
  590. const _domain = line.slice(0, -1);
  591. const suffix = tldts.getPublicSuffix(_domain, looseTldtsOpt);
  592. if (!suffix) {
  593. // This exclude domain-like resource like `_social_tracking.js^`
  594. result[1] = ParseType.Null;
  595. return result;
  596. }
  597. const domain = normalizeDomain(_domain);
  598. if (domain) {
  599. result[0] = domain;
  600. result[1] = ParseType.BlackAbsolute;
  601. return result;
  602. }
  603. result[0] = `[parse-filter E0005] (black) invalid domain: ${_domain}`;
  604. result[1] = ParseType.ErrorMessage;
  605. return result;
  606. }
  607. // Possibly that entire rule is domain
  608. /**
  609. * lineStartsWithSingleDot:
  610. *
  611. * `.cookielaw.js`
  612. * `.content_tracking.js`
  613. * `.ads.css`
  614. *
  615. * else:
  616. *
  617. * `_prebid.js`
  618. * `t.yesware.com`
  619. * `ubmcmm.baidustatic.com`
  620. * `://www.smfg-card.$document`
  621. * `portal.librus.pl$$advertisement-module`
  622. * `@@-ds.metric.gstatic.com^|`
  623. * `://gom.ge/cookie.js`
  624. * `://accout-update-smba.jp.$document`
  625. * `_200x250.png`
  626. * `@@://www.liquidweb.com/kb/wp-content/themes/lw-kb-theme/images/ads/vps-sidebar.jpg`
  627. */
  628. let sliceStart = 0;
  629. let sliceEnd: number | undefined;
  630. if (lineStartsWithSingleDot) {
  631. sliceStart = 1;
  632. }
  633. if (line.endsWith('^$all')) { // This salvage line `thepiratebay3.com^$all`
  634. sliceEnd = -5;
  635. } else if (
  636. // Try to salvage line like `://account.smba.$document`
  637. // For this specific line, it will fail anyway though.
  638. line.endsWith('$document')
  639. ) {
  640. sliceEnd = -9;
  641. } else if (line.endsWith('$badfilter')) {
  642. sliceEnd = -10;
  643. }
  644. const sliced = (sliceStart !== 0 || sliceEnd !== undefined) ? line.slice(sliceStart, sliceEnd) : line;
  645. const tryNormalizeDomain = normalizeDomain(sliced);
  646. if (tryNormalizeDomain === sliced) {
  647. // the entire rule is domain
  648. result[0] = sliced;
  649. result[1] = ParseType.BlackIncludeSubdomain;
  650. return result;
  651. }
  652. result[0] = `[parse-filter ${tryNormalizeDomain === null ? 'E0010' : 'E0011'}] can not parse: ${JSON.stringify({ line, tryNormalizeDomain, sliced })}`;
  653. result[1] = ParseType.ErrorMessage;
  654. return result;
  655. }