parse-filter.ts 21 KB

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