parse-filter.ts 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682
  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. }
  112. export async function processFilterRules(
  113. parentSpan: Span,
  114. filterRulesUrl: string,
  115. fallbackUrls?: readonly string[] | undefined | null,
  116. ttl: number | null = null
  117. ): Promise<{ white: string[], black: string[], foundDebugDomain: boolean }> {
  118. const [white, black, warningMessages] = await parentSpan.traceChild(`process filter rules: ${filterRulesUrl}`).traceAsyncFn((span) => fsFetchCache.apply<Readonly<[
  119. white: string[],
  120. black: string[],
  121. warningMessages: string[]
  122. ]>>(
  123. filterRulesUrl,
  124. async () => {
  125. const whitelistDomainSets = new Set<string>();
  126. const blacklistDomainSets = new Set<string>();
  127. const warningMessages: string[] = [];
  128. const gorhillPromise = getGorhillPublicSuffixPromise();
  129. const peekedGorhill = Bun.peek(gorhillPromise);
  130. const gorhill = peekedGorhill === gorhillPromise
  131. ? await span.traceChild('get gorhill').tracePromise(gorhillPromise)
  132. : (peekedGorhill as PublicSuffixList);
  133. /**
  134. * @param {string} line
  135. */
  136. const lineCb = (line: string) => {
  137. const result = parse(line, gorhill);
  138. if (!result) {
  139. return;
  140. }
  141. const flag = result[1];
  142. const hostname = result[0];
  143. if (DEBUG_DOMAIN_TO_FIND) {
  144. if (hostname.includes(DEBUG_DOMAIN_TO_FIND)) {
  145. console.warn(
  146. picocolors.red(filterRulesUrl),
  147. flag === ParseType.WhiteIncludeSubdomain || flag === ParseType.WhiteAbsolute
  148. ? '(white)'
  149. : '(black)',
  150. hostname.replaceAll(DEBUG_DOMAIN_TO_FIND, picocolors.bold(DEBUG_DOMAIN_TO_FIND))
  151. );
  152. foundDebugDomain = true;
  153. }
  154. }
  155. switch (flag) {
  156. case ParseType.WhiteIncludeSubdomain:
  157. if (hostname[0] !== '.') {
  158. whitelistDomainSets.add(`.${hostname}`);
  159. } else {
  160. whitelistDomainSets.add(hostname);
  161. }
  162. break;
  163. case ParseType.WhiteAbsolute:
  164. whitelistDomainSets.add(hostname);
  165. break;
  166. case ParseType.BlackAbsolute:
  167. blacklistDomainSets.add(hostname);
  168. break;
  169. case ParseType.BlackIncludeSubdomain:
  170. if (hostname[0] !== '.') {
  171. blacklistDomainSets.add(`.${hostname}`);
  172. } else {
  173. blacklistDomainSets.add(hostname);
  174. }
  175. break;
  176. case ParseType.ErrorMessage:
  177. warningMessages.push(hostname);
  178. break;
  179. default:
  180. break;
  181. }
  182. };
  183. if (!fallbackUrls || fallbackUrls.length === 0) {
  184. for await (const line of await fetchRemoteTextByLine(filterRulesUrl)) {
  185. // don't trim here
  186. lineCb(line);
  187. }
  188. } else {
  189. const filterRules = await span.traceChild('download adguard filter').traceAsyncFn(() => {
  190. return fetchAssets(filterRulesUrl, fallbackUrls).then(text => text.split('\n'));
  191. });
  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. }
  198. return [
  199. Array.from(whitelistDomainSets),
  200. Array.from(blacklistDomainSets),
  201. warningMessages
  202. ] as const;
  203. },
  204. {
  205. ttl,
  206. temporaryBypass,
  207. serializer: JSON.stringify,
  208. deserializer: JSON.parse
  209. }
  210. ));
  211. for (let i = 0, len = warningMessages.length; i < len; i++) {
  212. console.warn(
  213. picocolors.yellow(warningMessages[i]),
  214. picocolors.gray(picocolors.underline(filterRulesUrl))
  215. );
  216. }
  217. console.log(
  218. picocolors.gray('[process filter]'),
  219. picocolors.gray(filterRulesUrl),
  220. picocolors.gray(`white: ${white.length}`),
  221. picocolors.gray(`black: ${black.length}`)
  222. );
  223. return {
  224. white,
  225. black,
  226. foundDebugDomain
  227. };
  228. }
  229. // const R_KNOWN_NOT_NETWORK_FILTER_PATTERN_2 = /(\$popup|\$removeparam|\$popunder|\$cname)/;
  230. // cname exceptional filter can not be parsed by NetworkFilter
  231. // Surge / Clash can't handle CNAME either, so we just ignore them
  232. const kwfilter = createKeywordFilter([
  233. '!',
  234. '?',
  235. '*',
  236. '[',
  237. '(',
  238. ']',
  239. ')',
  240. ',',
  241. '#',
  242. '%',
  243. '&',
  244. '=',
  245. '~',
  246. // special modifier
  247. '$popup',
  248. '$removeparam',
  249. '$popunder',
  250. '$cname'
  251. ]);
  252. function parse($line: string, gorhill: PublicSuffixList): null | [hostname: string, flag: ParseType] {
  253. if (
  254. // doesn't include
  255. !$line.includes('.') // rule with out dot can not be a domain
  256. // includes
  257. || kwfilter($line)
  258. ) {
  259. return null;
  260. }
  261. const line = $line.trim();
  262. /** @example line.length */
  263. const len = line.length;
  264. if (len === 0) {
  265. return null;
  266. }
  267. const firstCharCode = line[0].charCodeAt(0);
  268. const lastCharCode = line[len - 1].charCodeAt(0);
  269. if (
  270. firstCharCode === 47 // 47 `/`
  271. // ends with
  272. || lastCharCode === 46 // 46 `.`, line.endsWith('.')
  273. || lastCharCode === 45 // 45 `-`, line.endsWith('-')
  274. || lastCharCode === 95 // 95 `_`, line.endsWith('_')
  275. // || line.includes('$popup')
  276. // || line.includes('$removeparam')
  277. // || line.includes('$popunder')
  278. ) {
  279. return null;
  280. }
  281. if ((line.includes('/') || line.includes(':')) && !line.includes('://')) {
  282. return null;
  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.fromAny() && !filter.fromDocument())
  297. ) {
  298. // not supported type
  299. return null;
  300. }
  301. if (
  302. filter.hostname // filter.hasHostname() // must have
  303. && filter.isPlain() // isPlain() === !isRegex()
  304. && (!filter.isFullRegex())
  305. ) {
  306. const hostname = normalizeDomain(filter.hostname);
  307. if (!hostname) {
  308. return null;
  309. }
  310. // |: filter.isHostnameAnchor(),
  311. // |: filter.isLeftAnchor(),
  312. // |https://: !filter.isHostnameAnchor() && (filter.fromHttps() || filter.fromHttp())
  313. const isIncludeAllSubDomain = filter.isHostnameAnchor();
  314. if (filter.isException() || filter.isBadFilter()) {
  315. return [hostname, isIncludeAllSubDomain ? ParseType.WhiteIncludeSubdomain : ParseType.WhiteAbsolute];
  316. }
  317. const _1p = filter.firstParty();
  318. const _3p = filter.thirdParty();
  319. if (_1p) {
  320. if (_1p === _3p) {
  321. return [hostname, isIncludeAllSubDomain ? ParseType.BlackIncludeSubdomain : ParseType.BlackAbsolute];
  322. }
  323. return null;
  324. }
  325. if (_3p) {
  326. return null;
  327. }
  328. }
  329. }
  330. // After NetworkFilter.parse, it means the line can not be parsed by cliqz NetworkFilter
  331. // We now need to "salvage" the line as much as possible
  332. /*
  333. * From now on, we are mostly facing non-standard domain rules (some are regex like)
  334. * We first skip third-party and frame rules, as Surge / Clash can't handle them
  335. *
  336. * `.sharecounter.$third-party`
  337. * `.bbelements.com^$third-party`
  338. * `://o0e.ru^$third-party`
  339. * `.1.1.1.l80.js^$third-party`
  340. */
  341. if (line.includes('$third-party') || line.includes('$frame')) {
  342. return null;
  343. }
  344. /** @example line.endsWith('^') */
  345. const lineEndsWithCaret = lastCharCode === 94; // lastChar === '^';
  346. /** @example line.endsWith('^|') */
  347. const lineEndsWithCaretVerticalBar = (lastCharCode === 124 /** lastChar === '|' */) && line[len - 2] === '^';
  348. /** @example line.endsWith('^') || line.endsWith('^|') */
  349. const lineEndsWithCaretOrCaretVerticalBar = lineEndsWithCaret || lineEndsWithCaretVerticalBar;
  350. // whitelist (exception)
  351. if (
  352. firstCharCode === 64 // 64 `@`
  353. && line[1] === '@'
  354. ) {
  355. let whiteIncludeAllSubDomain = true;
  356. /**
  357. * Some "malformed" regex-based filters can not be parsed by NetworkFilter
  358. * "$genericblock`" is also not supported by NetworkFilter, see:
  359. * https://github.com/ghostery/adblocker/blob/62caf7786ba10ef03beffecd8cd4eec111bcd5ec/packages/adblocker/test/parsing.test.ts#L950
  360. *
  361. * `@@||cmechina.net^$genericblock`
  362. * `@@|ftp.bmp.ovh^|`
  363. * `@@|adsterra.com^|`
  364. * `@@.atlassian.net$document`
  365. * `@@||ad.alimama.com^$genericblock`
  366. */
  367. let sliceStart = 0;
  368. let sliceEnd: number | undefined;
  369. if (line[2] === '|') { // line.startsWith('@@|')
  370. sliceStart = 3;
  371. whiteIncludeAllSubDomain = false;
  372. if (line[3] === '|') { // line.startsWith('@@||')
  373. sliceStart = 4;
  374. whiteIncludeAllSubDomain = true;
  375. }
  376. } else if (line[2] === '.') { // line.startsWith('@@.')
  377. sliceStart = 3;
  378. whiteIncludeAllSubDomain = true;
  379. } else if (
  380. /**
  381. * line.startsWith('@@://')
  382. *
  383. * `@@://googleadservices.com^|`
  384. * `@@://www.googleadservices.com^|`
  385. */
  386. line[2] === ':' && line[3] === '/' && line[4] === '/'
  387. ) {
  388. whiteIncludeAllSubDomain = false;
  389. sliceStart = 5;
  390. }
  391. if (lineEndsWithCaretOrCaretVerticalBar) {
  392. sliceEnd = -2;
  393. } else if (line.endsWith('$genericblock')) {
  394. sliceEnd = -13;
  395. if (line[len - 14] === '^') { // line.endsWith('^$genericblock')
  396. sliceEnd = -14;
  397. }
  398. } else if (line.endsWith('$document')) {
  399. sliceEnd = -9;
  400. if (line[len - 10] === '^') { // line.endsWith('^$document')
  401. sliceEnd = -10;
  402. }
  403. }
  404. if (sliceStart !== 0 || sliceEnd !== undefined) {
  405. const sliced = line.slice(sliceStart, sliceEnd);
  406. const domain = normalizeDomain(sliced);
  407. if (domain) {
  408. return [domain, whiteIncludeAllSubDomain ? ParseType.WhiteIncludeSubdomain : ParseType.WhiteAbsolute];
  409. }
  410. return [
  411. `[parse-filter E0001] (white) invalid domain: ${JSON.stringify({
  412. line, sliced, sliceStart, sliceEnd
  413. })}`,
  414. ParseType.ErrorMessage
  415. ];
  416. }
  417. return [
  418. `[parse-filter E0006] (white) failed to parse: ${JSON.stringify({
  419. line, sliceStart, sliceEnd
  420. })}`,
  421. ParseType.ErrorMessage
  422. ];
  423. }
  424. if (
  425. // 124 `|`
  426. // line.startsWith('|')
  427. firstCharCode === 124
  428. && lineEndsWithCaretOrCaretVerticalBar
  429. ) {
  430. /**
  431. * Some malformed filters can not be parsed by NetworkFilter:
  432. *
  433. * `||smetrics.teambeachbody.com^.com^`
  434. * `||solutions.|pages.indigovision.com^`
  435. * `||vystar..0rg@client.iebetanialaargentina.edu.co^`
  436. * `app-uat.latrobehealth.com.au^predirect.snapdeal.com`
  437. */
  438. const includeAllSubDomain = line[1] === '|';
  439. const sliceStart = includeAllSubDomain ? 2 : 1;
  440. const sliceEnd = lineEndsWithCaret
  441. ? -1
  442. : (lineEndsWithCaretVerticalBar ? -2 : undefined);
  443. const sliced = line.slice(sliceStart, sliceEnd); // we already make sure line startsWith "|"
  444. const domain = normalizeDomain(sliced);
  445. if (domain) {
  446. return [domain, includeAllSubDomain ? ParseType.BlackIncludeSubdomain : ParseType.BlackAbsolute];
  447. }
  448. return [
  449. `[parse-filter E0002] (black) invalid domain: ${sliced}`,
  450. ParseType.ErrorMessage
  451. ];
  452. }
  453. const lineStartsWithSingleDot = firstCharCode === 46; // 46 `.`
  454. if (
  455. lineStartsWithSingleDot
  456. && lineEndsWithCaretOrCaretVerticalBar
  457. ) {
  458. /**
  459. * `.ay.delivery^`
  460. * `.m.bookben.com^`
  461. * `.wap.x4399.com^`
  462. */
  463. const sliced = line.slice(
  464. 1, // remove prefix dot
  465. lineEndsWithCaret // replaceAll('^', '')
  466. ? -1
  467. : (lineEndsWithCaretVerticalBar ? -2 : undefined) // replace('^|', '')
  468. );
  469. const suffix = gorhill.getPublicSuffix(sliced);
  470. if (!gorhill.suffixInPSL(suffix)) {
  471. // This exclude domain-like resource like `1.1.4.514.js`
  472. return null;
  473. }
  474. const domain = normalizeDomain(sliced);
  475. if (domain) {
  476. return [domain, ParseType.BlackIncludeSubdomain];
  477. }
  478. return [
  479. `[paparse-filter E0003] (black) invalid domain: ${sliced}`,
  480. ParseType.ErrorMessage
  481. ];
  482. }
  483. /**
  484. * `|http://x.o2.pl^`
  485. * `://mine.torrent.pw^`
  486. * `://say.ac^`
  487. */
  488. if (lineEndsWithCaretOrCaretVerticalBar) {
  489. let sliceStart = 0;
  490. let sliceEnd;
  491. if (lineEndsWithCaret) { // line.endsWith('^')
  492. sliceEnd = -1;
  493. } else if (lineEndsWithCaretVerticalBar) { // line.endsWith('^|')
  494. sliceEnd = -2;
  495. }
  496. if (line.startsWith('://')) {
  497. sliceStart = 3;
  498. } else if (line.startsWith('http://')) {
  499. sliceStart = 7;
  500. } else if (line.startsWith('https://')) {
  501. sliceStart = 8;
  502. } else if (line.startsWith('|http://')) {
  503. sliceStart = 8;
  504. } else if (line.startsWith('|https://')) {
  505. sliceStart = 9;
  506. }
  507. if (sliceStart !== 0 || sliceEnd !== undefined) {
  508. const sliced = line.slice(sliceStart, sliceEnd);
  509. const domain = normalizeDomain(sliced);
  510. if (domain) {
  511. return [domain, ParseType.BlackIncludeSubdomain];
  512. }
  513. return [
  514. `[parse-filter E0004] (black) invalid domain: ${JSON.stringify({
  515. line, sliced, sliceStart, sliceEnd
  516. })}`,
  517. ParseType.ErrorMessage
  518. ];
  519. }
  520. }
  521. /**
  522. * `_vmind.qqvideo.tc.qq.com^`
  523. * `arketing.indianadunes.com^`
  524. * `charlestownwyllie.oaklawnnonantum.com^`
  525. * `-telemetry.officeapps.live.com^`
  526. * `-tracker.biliapi.net`
  527. * `-logging.nextmedia.com`
  528. * `_social_tracking.js^`
  529. */
  530. if (
  531. firstCharCode !== 124 // 124 `|`
  532. && lastCharCode === 94 // 94 `^`
  533. ) {
  534. const _domain = line.slice(0, -1);
  535. const suffix = gorhill.getPublicSuffix(_domain);
  536. if (!suffix || !gorhill.suffixInPSL(suffix)) {
  537. // This exclude domain-like resource like `_social_tracking.js^`
  538. return null;
  539. }
  540. const domain = normalizeDomain(_domain);
  541. if (domain) {
  542. return [domain, ParseType.BlackAbsolute];
  543. }
  544. return [
  545. `[parse-filter E0005] (black) invalid domain: ${_domain}`,
  546. ParseType.ErrorMessage
  547. ];
  548. }
  549. // Possibly that entire rule is domain
  550. /**
  551. * lineStartsWithSingleDot:
  552. *
  553. * `.cookielaw.js`
  554. * `.content_tracking.js`
  555. * `.ads.css`
  556. *
  557. * else:
  558. *
  559. * `_prebid.js`
  560. * `t.yesware.com`
  561. * `ubmcmm.baidustatic.com`
  562. * `://www.smfg-card.$document`
  563. * `portal.librus.pl$$advertisement-module`
  564. * `@@-ds.metric.gstatic.com^|`
  565. * `://gom.ge/cookie.js`
  566. * `://accout-update-smba.jp.$document`
  567. * `_200x250.png`
  568. * `@@://www.liquidweb.com/kb/wp-content/themes/lw-kb-theme/images/ads/vps-sidebar.jpg`
  569. */
  570. let sliceStart = 0;
  571. let sliceEnd: number | undefined;
  572. if (lineStartsWithSingleDot) {
  573. sliceStart = 1;
  574. }
  575. if (line.endsWith('^$all')) { // This salvage line `thepiratebay3.com^$all`
  576. sliceEnd = -5;
  577. } else if (
  578. // Try to salvage line like `://account.smba.$document`
  579. // For this specific line, it will fail anyway though.
  580. line.endsWith('$document')
  581. ) {
  582. sliceEnd = -9;
  583. }
  584. const sliced = (sliceStart !== 0 || sliceEnd !== undefined) ? line.slice(sliceStart, sliceEnd) : line;
  585. const suffix = gorhill.getPublicSuffix(sliced);
  586. /**
  587. * Fast exclude definitely not domain-like resource
  588. *
  589. * `.gatracking.js`, suffix is `js`,
  590. * `.ads.css`, suffix is `css`,
  591. * `-cpm-ads.$badfilter`, suffix is `$badfilter`,
  592. * `portal.librus.pl$$advertisement-module`, suffix is `pl$$advertisement-module`
  593. */
  594. if (!suffix || !gorhill.suffixInPSL(suffix)) {
  595. // This exclude domain-like resource like `.gatracking.js`, `.beacon.min.js` and `.cookielaw.js`
  596. return null;
  597. }
  598. const tryNormalizeDomain = normalizeDomain(sliced);
  599. if (tryNormalizeDomain === sliced) {
  600. // the entire rule is domain
  601. return [sliced, ParseType.BlackIncludeSubdomain];
  602. }
  603. return [
  604. `[parse-filter E0010] can not parse: ${line}`,
  605. ParseType.ErrorMessage
  606. ];
  607. }