parse-filter.ts 20 KB

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