parse-filter.ts 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708
  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. return result;
  334. }
  335. result[1] = ParseType.Null;
  336. return result;
  337. }
  338. if (_3p) {
  339. result[1] = ParseType.Null;
  340. return result;
  341. }
  342. }
  343. }
  344. // After NetworkFilter.parse, it means the line can not be parsed by cliqz NetworkFilter
  345. // We now need to "salvage" the line as much as possible
  346. /*
  347. * From now on, we are mostly facing non-standard domain rules (some are regex like)
  348. * We first skip third-party and frame rules, as Surge / Clash can't handle them
  349. *
  350. * `.sharecounter.$third-party`
  351. * `.bbelements.com^$third-party`
  352. * `://o0e.ru^$third-party`
  353. * `.1.1.1.l80.js^$third-party`
  354. */
  355. if (line.includes('$third-party') || line.includes('$frame')) {
  356. result[1] = ParseType.Null;
  357. return result;
  358. }
  359. /** @example line.endsWith('^') */
  360. const lineEndsWithCaret = lastCharCode === 94; // lastChar === '^';
  361. /** @example line.endsWith('^|') */
  362. const lineEndsWithCaretVerticalBar = (lastCharCode === 124 /** lastChar === '|' */) && line[len - 2] === '^';
  363. /** @example line.endsWith('^') || line.endsWith('^|') */
  364. const lineEndsWithCaretOrCaretVerticalBar = lineEndsWithCaret || lineEndsWithCaretVerticalBar;
  365. // whitelist (exception)
  366. if (
  367. firstCharCode === 64 // 64 `@`
  368. && line[1] === '@'
  369. ) {
  370. let whiteIncludeAllSubDomain = true;
  371. /**
  372. * Some "malformed" regex-based filters can not be parsed by NetworkFilter
  373. * "$genericblock`" is also not supported by NetworkFilter, see:
  374. * https://github.com/ghostery/adblocker/blob/62caf7786ba10ef03beffecd8cd4eec111bcd5ec/packages/adblocker/test/parsing.test.ts#L950
  375. *
  376. * `@@||cmechina.net^$genericblock`
  377. * `@@|ftp.bmp.ovh^|`
  378. * `@@|adsterra.com^|`
  379. * `@@.atlassian.net$document`
  380. * `@@||ad.alimama.com^$genericblock`
  381. */
  382. let sliceStart = 0;
  383. let sliceEnd: number | undefined;
  384. if (line[2] === '|') { // line.startsWith('@@|')
  385. sliceStart = 3;
  386. whiteIncludeAllSubDomain = false;
  387. if (line[3] === '|') { // line.startsWith('@@||')
  388. sliceStart = 4;
  389. whiteIncludeAllSubDomain = true;
  390. }
  391. } else if (line[2] === '.') { // line.startsWith('@@.')
  392. sliceStart = 3;
  393. whiteIncludeAllSubDomain = true;
  394. } else if (
  395. /**
  396. * line.startsWith('@@://')
  397. *
  398. * `@@://googleadservices.com^|`
  399. * `@@://www.googleadservices.com^|`
  400. */
  401. line[2] === ':' && line[3] === '/' && line[4] === '/'
  402. ) {
  403. whiteIncludeAllSubDomain = false;
  404. sliceStart = 5;
  405. }
  406. if (lineEndsWithCaretOrCaretVerticalBar) {
  407. sliceEnd = -2;
  408. } else if (line.endsWith('$genericblock')) {
  409. sliceEnd = -13;
  410. if (line[len - 14] === '^') { // line.endsWith('^$genericblock')
  411. sliceEnd = -14;
  412. }
  413. } else if (line.endsWith('$document')) {
  414. sliceEnd = -9;
  415. if (line[len - 10] === '^') { // line.endsWith('^$document')
  416. sliceEnd = -10;
  417. }
  418. }
  419. if (sliceStart !== 0 || sliceEnd !== undefined) {
  420. const sliced = line.slice(sliceStart, sliceEnd);
  421. const domain = normalizeDomain(sliced);
  422. if (domain) {
  423. result[0] = domain;
  424. result[1] = whiteIncludeAllSubDomain ? ParseType.WhiteIncludeSubdomain : ParseType.WhiteAbsolute;
  425. return result;
  426. }
  427. result[0] = `[parse-filter E0001] (white) invalid domain: ${JSON.stringify({
  428. line, sliced, sliceStart, sliceEnd, domain
  429. })}`;
  430. result[1] = ParseType.ErrorMessage;
  431. return result;
  432. }
  433. result[0] = `[parse-filter E0006] (white) failed to parse: ${JSON.stringify({
  434. line, sliceStart, sliceEnd
  435. })}`;
  436. result[1] = ParseType.ErrorMessage;
  437. return result;
  438. }
  439. if (
  440. // 124 `|`
  441. // line.startsWith('|')
  442. firstCharCode === 124
  443. && lineEndsWithCaretOrCaretVerticalBar
  444. ) {
  445. /**
  446. * Some malformed filters can not be parsed by NetworkFilter:
  447. *
  448. * `||smetrics.teambeachbody.com^.com^`
  449. * `||solutions.|pages.indigovision.com^`
  450. * `||vystar..0rg@client.iebetanialaargentina.edu.co^`
  451. * `app-uat.latrobehealth.com.au^predirect.snapdeal.com`
  452. */
  453. const includeAllSubDomain = line[1] === '|';
  454. const sliceStart = includeAllSubDomain ? 2 : 1;
  455. const sliceEnd = lineEndsWithCaret
  456. ? -1
  457. : (lineEndsWithCaretVerticalBar ? -2 : undefined);
  458. const sliced = line.slice(sliceStart, sliceEnd); // we already make sure line startsWith "|"
  459. const domain = normalizeDomain(sliced);
  460. if (domain) {
  461. result[0] = domain;
  462. result[1] = includeAllSubDomain ? ParseType.BlackIncludeSubdomain : ParseType.BlackAbsolute;
  463. return result;
  464. }
  465. result[0] = `[parse-filter E0002] (black) invalid domain: ${sliced}`;
  466. result[1] = ParseType.ErrorMessage;
  467. return result;
  468. }
  469. const lineStartsWithSingleDot = firstCharCode === 46; // 46 `.`
  470. if (
  471. lineStartsWithSingleDot
  472. && lineEndsWithCaretOrCaretVerticalBar
  473. ) {
  474. /**
  475. * `.ay.delivery^`
  476. * `.m.bookben.com^`
  477. * `.wap.x4399.com^`
  478. */
  479. const sliced = line.slice(
  480. 1, // remove prefix dot
  481. lineEndsWithCaret // replaceAll('^', '')
  482. ? -1
  483. : (lineEndsWithCaretVerticalBar ? -2 : undefined) // replace('^|', '')
  484. );
  485. const suffix = gorhill.getPublicSuffix(sliced);
  486. if (!gorhill.suffixInPSL(suffix)) {
  487. // This exclude domain-like resource like `1.1.4.514.js`
  488. result[1] = ParseType.Null;
  489. return result;
  490. }
  491. const domain = normalizeDomain(sliced);
  492. if (domain) {
  493. result[0] = domain;
  494. result[1] = ParseType.BlackIncludeSubdomain;
  495. return result;
  496. }
  497. result[0] = `[parse-filter E0003] (black) invalid domain: ${JSON.stringify({ sliced, domain })}`;
  498. result[1] = ParseType.ErrorMessage;
  499. return result;
  500. }
  501. /**
  502. * `|http://x.o2.pl^`
  503. * `://mine.torrent.pw^`
  504. * `://say.ac^`
  505. */
  506. if (lineEndsWithCaretOrCaretVerticalBar) {
  507. let sliceStart = 0;
  508. let sliceEnd;
  509. if (lineEndsWithCaret) { // line.endsWith('^')
  510. sliceEnd = -1;
  511. } else if (lineEndsWithCaretVerticalBar) { // line.endsWith('^|')
  512. sliceEnd = -2;
  513. }
  514. if (line.startsWith('://')) {
  515. sliceStart = 3;
  516. } else if (line.startsWith('http://')) {
  517. sliceStart = 7;
  518. } else if (line.startsWith('https://')) {
  519. sliceStart = 8;
  520. } else if (line.startsWith('|http://')) {
  521. sliceStart = 8;
  522. } else if (line.startsWith('|https://')) {
  523. sliceStart = 9;
  524. }
  525. if (sliceStart !== 0 || sliceEnd !== undefined) {
  526. const sliced = line.slice(sliceStart, sliceEnd);
  527. const domain = normalizeDomain(sliced);
  528. if (domain) {
  529. result[0] = domain;
  530. result[1] = ParseType.BlackIncludeSubdomain;
  531. return result;
  532. }
  533. result[0] = `[parse-filter E0004] (black) invalid domain: ${JSON.stringify({
  534. line, sliced, sliceStart, sliceEnd
  535. })}`;
  536. result[1] = ParseType.ErrorMessage;
  537. return result;
  538. }
  539. }
  540. /**
  541. * `_vmind.qqvideo.tc.qq.com^`
  542. * `arketing.indianadunes.com^`
  543. * `charlestownwyllie.oaklawnnonantum.com^`
  544. * `-telemetry.officeapps.live.com^`
  545. * `-tracker.biliapi.net`
  546. * `-logging.nextmedia.com`
  547. * `_social_tracking.js^`
  548. */
  549. if (
  550. firstCharCode !== 124 // 124 `|`
  551. && lastCharCode === 94 // 94 `^`
  552. ) {
  553. const _domain = line.slice(0, -1);
  554. const suffix = gorhill.getPublicSuffix(_domain);
  555. if (!suffix || !gorhill.suffixInPSL(suffix)) {
  556. // This exclude domain-like resource like `_social_tracking.js^`
  557. result[1] = ParseType.Null;
  558. return result;
  559. }
  560. const domain = normalizeDomain(_domain);
  561. if (domain) {
  562. result[0] = domain;
  563. result[1] = ParseType.BlackAbsolute;
  564. return result;
  565. }
  566. result[0] = `[parse-filter E0005] (black) invalid domain: ${_domain}`;
  567. result[1] = ParseType.ErrorMessage;
  568. return result;
  569. }
  570. // Possibly that entire rule is domain
  571. /**
  572. * lineStartsWithSingleDot:
  573. *
  574. * `.cookielaw.js`
  575. * `.content_tracking.js`
  576. * `.ads.css`
  577. *
  578. * else:
  579. *
  580. * `_prebid.js`
  581. * `t.yesware.com`
  582. * `ubmcmm.baidustatic.com`
  583. * `://www.smfg-card.$document`
  584. * `portal.librus.pl$$advertisement-module`
  585. * `@@-ds.metric.gstatic.com^|`
  586. * `://gom.ge/cookie.js`
  587. * `://accout-update-smba.jp.$document`
  588. * `_200x250.png`
  589. * `@@://www.liquidweb.com/kb/wp-content/themes/lw-kb-theme/images/ads/vps-sidebar.jpg`
  590. */
  591. let sliceStart = 0;
  592. let sliceEnd: number | undefined;
  593. if (lineStartsWithSingleDot) {
  594. sliceStart = 1;
  595. }
  596. if (line.endsWith('^$all')) { // This salvage line `thepiratebay3.com^$all`
  597. sliceEnd = -5;
  598. } else if (
  599. // Try to salvage line like `://account.smba.$document`
  600. // For this specific line, it will fail anyway though.
  601. line.endsWith('$document')
  602. ) {
  603. sliceEnd = -9;
  604. }
  605. const sliced = (sliceStart !== 0 || sliceEnd !== undefined) ? line.slice(sliceStart, sliceEnd) : line;
  606. const suffix = gorhill.getPublicSuffix(sliced);
  607. /**
  608. * Fast exclude definitely not domain-like resource
  609. *
  610. * `.gatracking.js`, suffix is `js`,
  611. * `.ads.css`, suffix is `css`,
  612. * `-cpm-ads.$badfilter`, suffix is `$badfilter`,
  613. * `portal.librus.pl$$advertisement-module`, suffix is `pl$$advertisement-module`
  614. */
  615. if (!suffix || !gorhill.suffixInPSL(suffix)) {
  616. // This exclude domain-like resource like `.gatracking.js`, `.beacon.min.js` and `.cookielaw.js`
  617. result[1] = ParseType.Null;
  618. return result;
  619. }
  620. const tryNormalizeDomain = normalizeDomain(sliced);
  621. if (tryNormalizeDomain === sliced) {
  622. // the entire rule is domain
  623. result[0] = sliced;
  624. result[1] = ParseType.BlackIncludeSubdomain;
  625. return result;
  626. }
  627. result[0] = `[parse-filter E0010] can not parse: ${line}`;
  628. result[1] = ParseType.ErrorMessage;
  629. return result;
  630. }