parse-filter.js 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407
  1. // @ts-check
  2. const { fetchWithRetry } = require('./fetch-retry');
  3. const { NetworkFilter } = require('@cliqz/adblocker');
  4. const { normalizeDomain } = require('./is-domain-loose');
  5. const DEBUG_DOMAIN_TO_FIND = null; // example.com | null
  6. let foundDebugDomain = false;
  7. const warnOnceUrl = new Set();
  8. const warnOnce = (url, isWhite, ...message) => {
  9. const key = `${url}${isWhite ? 'white' : 'black'}`;
  10. if (warnOnceUrl.has(key)) {
  11. return;
  12. }
  13. warnOnceUrl.add(key);
  14. console.warn(url, isWhite ? '(white)' : '(black)', ...message);
  15. }
  16. /**
  17. * @param {string | URL} domainListsUrl
  18. */
  19. async function processDomainLists(domainListsUrl) {
  20. if (typeof domainListsUrl === 'string') {
  21. domainListsUrl = new URL(domainListsUrl);
  22. }
  23. /** @type Set<string> */
  24. const domainSets = new Set();
  25. /** @type string[] */
  26. const domains = (await (await fetchWithRetry(domainListsUrl)).text()).split('\n');
  27. domains.forEach(line => {
  28. if (
  29. line.startsWith('#')
  30. || line.startsWith('!')
  31. || line.startsWith(' ')
  32. || line === ''
  33. || line.startsWith('\r')
  34. || line.startsWith('\n')
  35. ) {
  36. return;
  37. }
  38. const domainToAdd = line.trim();
  39. if (DEBUG_DOMAIN_TO_FIND && domainToAdd.includes(DEBUG_DOMAIN_TO_FIND)) {
  40. warnOnce(domainListsUrl.toString(), false, DEBUG_DOMAIN_TO_FIND);
  41. foundDebugDomain = true;
  42. }
  43. domainSets.add(domainToAdd);
  44. });
  45. return [...domainSets];
  46. }
  47. /**
  48. * @param {string | URL} hostsUrl
  49. */
  50. async function processHosts(hostsUrl, includeAllSubDomain = false) {
  51. console.time(` - processHosts: ${hostsUrl}`);
  52. if (typeof hostsUrl === 'string') {
  53. hostsUrl = new URL(hostsUrl);
  54. }
  55. /** @type Set<string> */
  56. const domainSets = new Set();
  57. /** @type string[] */
  58. const hosts = (await (await fetchWithRetry(hostsUrl)).text()).split('\n');
  59. hosts.forEach(line => {
  60. if (line.includes('#')) {
  61. return;
  62. }
  63. if (line.startsWith(' ') || line.startsWith('\r') || line.startsWith('\n') || line.trim() === '') {
  64. return;
  65. }
  66. const [, ...domains] = line.split(' ');
  67. const _domain = domains.join(' ').trim();
  68. if (DEBUG_DOMAIN_TO_FIND && _domain.includes(DEBUG_DOMAIN_TO_FIND)) {
  69. warnOnce(hostsUrl.toString(), false, DEBUG_DOMAIN_TO_FIND);
  70. foundDebugDomain = true;
  71. }
  72. const domain = normalizeDomain(_domain);
  73. if (domain) {
  74. if (includeAllSubDomain) {
  75. domainSets.add(`.${domain}`);
  76. } else {
  77. domainSets.add(domain);
  78. }
  79. }
  80. });
  81. console.timeEnd(` - processHosts: ${hostsUrl}`);
  82. return [...domainSets];
  83. }
  84. /**
  85. * @param {string | URL} filterRulesUrl
  86. * @param {readonly (string | URL)[] | undefined} [fallbackUrls]
  87. * @returns {Promise<{ white: Set<string>, black: Set<string>, foundDebugDomain: boolean, parseFailed: boolean }>}
  88. */
  89. async function processFilterRules(filterRulesUrl, fallbackUrls, includeThirdParties = false) {
  90. console.time(` - processFilterRules: ${filterRulesUrl}`);
  91. /** @type Set<string> */
  92. const whitelistDomainSets = new Set();
  93. /** @type Set<string> */
  94. const blacklistDomainSets = new Set();
  95. const addToBlackList = (domainToBeAddedToBlack, isSubDomain) => {
  96. if (DEBUG_DOMAIN_TO_FIND && domainToBeAddedToBlack.includes(DEBUG_DOMAIN_TO_FIND)) {
  97. warnOnce(filterRulesUrl.toString(), false, DEBUG_DOMAIN_TO_FIND);
  98. foundDebugDomain = true;
  99. }
  100. if (isSubDomain && !domainToBeAddedToBlack.startsWith('.')) {
  101. blacklistDomainSets.add(`.${domainToBeAddedToBlack}`);
  102. } else {
  103. blacklistDomainSets.add(domainToBeAddedToBlack);
  104. }
  105. };
  106. const addToWhiteList = (domainToBeAddedToWhite) => {
  107. if (DEBUG_DOMAIN_TO_FIND && domainToBeAddedToWhite.includes(DEBUG_DOMAIN_TO_FIND)) {
  108. warnOnce(filterRulesUrl.toString(), true, DEBUG_DOMAIN_TO_FIND);
  109. foundDebugDomain = true;
  110. }
  111. whitelistDomainSets.add(domainToBeAddedToWhite);
  112. }
  113. let filterRules;
  114. try {
  115. /** @type string[] */
  116. filterRules = (
  117. await Promise.any(
  118. [filterRulesUrl, ...(fallbackUrls || [])].map(
  119. async url => (await fetchWithRetry(url)).text()
  120. )
  121. )
  122. ).split('\n').map(line => line.trim());
  123. } catch (e) {
  124. console.log('Download Rule for [' + filterRulesUrl + '] failed');
  125. throw e;
  126. }
  127. let hasParseFailed = false;
  128. for (let i = 0, len = filterRules.length; i < len; i++) {
  129. const line = filterRules[i].trim();
  130. if (
  131. line === ''
  132. // doesn't include
  133. || !line.includes('.') // rule with out dot can not be a domain
  134. // includes
  135. || line.includes('#')
  136. || line.includes('!')
  137. || line.includes('?')
  138. || line.includes('*')
  139. || line.includes('=')
  140. || line.includes('[')
  141. || line.includes('(')
  142. || line.includes(']')
  143. || line.includes(')')
  144. || line.includes(',')
  145. || line.includes('~')
  146. || line.includes('&')
  147. || line.includes('%')
  148. || ((line.includes('/') || line.includes(':')) && !line.includes('://'))
  149. // ends with
  150. || line.endsWith('.')
  151. || line.endsWith('-')
  152. || line.endsWith('_')
  153. // special modifier
  154. || line.includes('$popup')
  155. || line.includes('$removeparam')
  156. || line.includes('$popunder')
  157. ) {
  158. continue;
  159. }
  160. const filter = NetworkFilter.parse(line);
  161. if (filter) {
  162. if (
  163. filter.isElemHide()
  164. || filter.isGenericHide()
  165. || filter.isSpecificHide()
  166. || filter.isRedirect()
  167. || filter.isRedirectRule()
  168. || filter.hasDomains()
  169. || filter.isCSP() // must not be csp rule
  170. || (!filter.fromAny() && !filter.fromDocument())
  171. ) {
  172. // not supported type
  173. continue;
  174. }
  175. if (
  176. filter.hasHostname() // must have
  177. && filter.isPlain()
  178. && (!filter.isRegex())
  179. && (!filter.isFullRegex())
  180. ) {
  181. const hostname = normalizeDomain(filter.getHostname());
  182. if (hostname) {
  183. if (filter.isException() || filter.isBadFilter()) {
  184. addToWhiteList(hostname);
  185. continue;
  186. }
  187. if (filter.firstParty() === filter.thirdParty()) {
  188. addToBlackList(hostname, true);
  189. continue;
  190. }
  191. if (filter.thirdParty()) {
  192. if (includeThirdParties) {
  193. addToBlackList(hostname, true);
  194. }
  195. continue;
  196. }
  197. if (filter.firstParty()) {
  198. continue;
  199. }
  200. } else {
  201. continue;
  202. }
  203. }
  204. }
  205. if (line.includes('$third-party') || line.includes('$frame')) {
  206. continue;
  207. }
  208. const lineEndsWithCaret = line.endsWith('^');
  209. const lineEndsWithCaretVerticalBar = line.endsWith('^|');
  210. if (line.startsWith('@@')) {
  211. if (line.endsWith('$cname')) {
  212. continue;
  213. }
  214. if (
  215. (line.startsWith('@@|') || line.startsWith('@@.'))
  216. && (
  217. lineEndsWithCaret
  218. || lineEndsWithCaretVerticalBar
  219. || line.endsWith('$genericblock')
  220. || line.endsWith('$document')
  221. )
  222. ) {
  223. const _domain = line
  224. .replace('@@||', '')
  225. .replace('@@|', '')
  226. .replace('@@.', '')
  227. .replace('^|', '')
  228. .replace('^$genericblock', '')
  229. .replace('$genericblock', '')
  230. .replace('^$document', '')
  231. .replace('$document', '')
  232. .replaceAll('^', '')
  233. .trim();
  234. const domain = normalizeDomain(_domain);
  235. if (domain) {
  236. addToWhiteList(domain);
  237. } else {
  238. console.warn(' * [parse-filter E0001] (black) invalid domain:', _domain);
  239. }
  240. continue;
  241. }
  242. }
  243. if (
  244. line.startsWith('||')
  245. && (
  246. lineEndsWithCaret
  247. || lineEndsWithCaretVerticalBar
  248. || line.endsWith('$cname')
  249. )
  250. ) {
  251. const _domain = line
  252. .replace('||', '')
  253. .replace('^|', '')
  254. .replace('$cname', '')
  255. .replaceAll('^', '')
  256. .trim();
  257. const domain = normalizeDomain(_domain);
  258. if (domain) {
  259. addToBlackList(domain, true);
  260. } else {
  261. console.warn(' * [parse-filter E0002] (black) invalid domain:', _domain);
  262. }
  263. continue;
  264. }
  265. const lineStartsWithSingleDot = line.startsWith('.');
  266. if (
  267. lineStartsWithSingleDot
  268. && (
  269. lineEndsWithCaret
  270. || lineEndsWithCaretVerticalBar
  271. )
  272. ) {
  273. const _domain = line
  274. .replace('^|', '')
  275. .replaceAll('^', '')
  276. .slice(1)
  277. .trim();
  278. const domain = normalizeDomain(_domain);
  279. if (domain) {
  280. addToBlackList(domain, true);
  281. } else {
  282. console.warn(' * [parse-filter E0003] (black) invalid domain:', _domain);
  283. }
  284. continue;
  285. }
  286. if (
  287. (
  288. line.startsWith('://')
  289. || line.startsWith('http://')
  290. || line.startsWith('https://')
  291. || line.startsWith('|http://')
  292. || line.startsWith('|https://')
  293. )
  294. && (
  295. lineEndsWithCaret
  296. || lineEndsWithCaretVerticalBar
  297. )
  298. ) {
  299. const _domain = line
  300. .replace('|https://', '')
  301. .replace('https://', '')
  302. .replace('|http://', '')
  303. .replace('http://', '')
  304. .replace('://', '')
  305. .replace('^|', '')
  306. .replaceAll('^', '')
  307. .trim();
  308. const domain = normalizeDomain(_domain);
  309. if (domain) {
  310. addToBlackList(domain, false);
  311. } else {
  312. console.warn(' * [parse-filter E0004] (black) invalid domain:', _domain);
  313. }
  314. continue;
  315. }
  316. if (!line.startsWith('|') && lineEndsWithCaret) {
  317. const _domain = line.slice(0, -1);
  318. const domain = normalizeDomain(_domain);
  319. if (domain) {
  320. addToBlackList(domain, false);
  321. } else {
  322. console.warn(' * [parse-filter E0005] (black) invalid domain:', _domain);
  323. }
  324. continue;
  325. }
  326. const tryNormalizeDomain = normalizeDomain(lineStartsWithSingleDot ? line.slice(1) : line);
  327. if (
  328. tryNormalizeDomain
  329. && (
  330. lineStartsWithSingleDot
  331. ? tryNormalizeDomain.length === line.length - 1
  332. : tryNormalizeDomain === line
  333. )
  334. ) {
  335. addToBlackList(line, true);
  336. continue;
  337. }
  338. if (
  339. !line.endsWith('.js')
  340. ) {
  341. hasParseFailed = true;
  342. console.warn(' * [parse-filter E0010] can not parse:', line);
  343. }
  344. }
  345. console.timeEnd(` - processFilterRules: ${filterRulesUrl}`);
  346. return {
  347. white: whitelistDomainSets,
  348. black: blacklistDomainSets,
  349. foundDebugDomain,
  350. parseFailed: hasParseFailed
  351. };
  352. }
  353. /**
  354. * @param {string[]} data
  355. */
  356. function preprocessFullDomainSetBeforeUsedAsWorkerData(data) {
  357. return data
  358. .filter(domain => domain.charCodeAt(0) === 46)
  359. .sort((a, b) => a.length - b.length);
  360. }
  361. module.exports.processDomainLists = processDomainLists;
  362. module.exports.processHosts = processHosts;
  363. module.exports.processFilterRules = processFilterRules;
  364. module.exports.preprocessFullDomainSetBeforeUsedAsWorkerData = preprocessFullDomainSetBeforeUsedAsWorkerData;