parse-filter.ts 21 KB

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