build-reject-domainset.ts 9.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239
  1. // @ts-check
  2. import path from 'node:path';
  3. import process from 'node:process';
  4. import { processHosts, processFilterRules, processDomainLists } from './lib/parse-filter';
  5. import { createTrie } from './lib/trie';
  6. import { HOSTS, ADGUARD_FILTERS, PREDEFINED_WHITELIST, DOMAIN_LISTS, HOSTS_EXTRA, DOMAIN_LISTS_EXTRA, ADGUARD_FILTERS_EXTRA, PHISHING_DOMAIN_LISTS_EXTRA } from './constants/reject-data-source';
  7. import { createRuleset, compareAndWriteFile } from './lib/create-file';
  8. import { domainDeduper } from './lib/domain-deduper';
  9. import createKeywordFilter from './lib/aho-corasick';
  10. import { readFileByLine, readFileIntoProcessedArray } from './lib/fetch-text-by-line';
  11. import { buildParseDomainMap, sortDomains } from './lib/stable-sort-domain';
  12. import { task } from './trace';
  13. // tldts-experimental is way faster than tldts, but very little bit inaccurate
  14. // (since it is hashes based). But the result is still deterministic, which is
  15. // enough when creating a simple stat of reject hosts.
  16. import { SHARED_DESCRIPTION } from './lib/constants';
  17. import { getPhishingDomains } from './lib/get-phishing-domains';
  18. import { setAddFromArray, setAddFromArrayCurried } from './lib/set-add-from-array';
  19. import { output } from './lib/misc';
  20. import { appendArrayInPlace } from './lib/append-array-in-place';
  21. const getRejectSukkaConfPromise = readFileIntoProcessedArray(path.resolve(__dirname, '../Source/domainset/reject_sukka.conf'));
  22. export const buildRejectDomainSet = task(require.main === module, __filename)(async (span) => {
  23. /** Whitelists */
  24. const filterRuleWhitelistDomainSets = new Set(PREDEFINED_WHITELIST);
  25. const domainSets = new Set<string>();
  26. const appendArrayToDomainSets = setAddFromArrayCurried(domainSets);
  27. const domainSetsExtra = new Set<string>();
  28. const appendArrayToDomainSetsExtra = setAddFromArrayCurried(domainSetsExtra);
  29. // Parse from AdGuard Filters
  30. const shouldStop = await span
  31. .traceChild('download and process hosts / adblock filter rules')
  32. .traceAsyncFn(async (childSpan) => {
  33. // eslint-disable-next-line sukka/no-single-return -- not single return
  34. let shouldStop = false;
  35. await Promise.all([
  36. // Parse from remote hosts & domain lists
  37. HOSTS.map(entry => processHosts(childSpan, ...entry).then(appendArrayToDomainSets)),
  38. HOSTS_EXTRA.map(entry => processHosts(childSpan, ...entry).then(appendArrayToDomainSetsExtra)),
  39. DOMAIN_LISTS.map(entry => processDomainLists(childSpan, ...entry).then(appendArrayToDomainSets)),
  40. DOMAIN_LISTS_EXTRA.map(entry => processDomainLists(childSpan, ...entry).then(appendArrayToDomainSetsExtra)),
  41. ADGUARD_FILTERS.map(
  42. entry => processFilterRules(childSpan, ...entry)
  43. .then(({ white, black, foundDebugDomain }) => {
  44. if (foundDebugDomain) {
  45. // eslint-disable-next-line sukka/no-single-return -- not single return
  46. shouldStop = true;
  47. // we should not break here, as we want to see full matches from all data source
  48. }
  49. setAddFromArray(filterRuleWhitelistDomainSets, white);
  50. setAddFromArray(domainSets, black);
  51. })
  52. ),
  53. ADGUARD_FILTERS_EXTRA.map(
  54. entry => processFilterRules(childSpan, ...entry)
  55. .then(({ white, black, foundDebugDomain }) => {
  56. if (foundDebugDomain) {
  57. // eslint-disable-next-line sukka/no-single-return -- not single return
  58. shouldStop = true;
  59. // we should not break here, as we want to see full matches from all data source
  60. }
  61. setAddFromArray(filterRuleWhitelistDomainSets, white);
  62. setAddFromArray(domainSetsExtra, black);
  63. })
  64. ),
  65. ([
  66. 'https://raw.githubusercontent.com/AdguardTeam/AdGuardSDNSFilter/master/Filters/exceptions.txt',
  67. 'https://raw.githubusercontent.com/AdguardTeam/AdGuardSDNSFilter/master/Filters/exclusions.txt'
  68. ].map(
  69. input => processFilterRules(childSpan, input).then(({ white, black }) => {
  70. setAddFromArray(filterRuleWhitelistDomainSets, white);
  71. setAddFromArray(filterRuleWhitelistDomainSets, black);
  72. })
  73. )),
  74. getPhishingDomains(childSpan).then(appendArrayToDomainSetsExtra),
  75. getRejectSukkaConfPromise.then(appendArrayToDomainSets)
  76. ].flat());
  77. // eslint-disable-next-line sukka/no-single-return -- not single return
  78. return shouldStop;
  79. });
  80. if (shouldStop) {
  81. process.exit(1);
  82. }
  83. console.log(`Import ${domainSets.size} + ${domainSetsExtra.size} rules from Hosts / AdBlock Filter Rules & reject_sukka.conf!`);
  84. // Dedupe domainSets
  85. const domainKeywordsSet = await span.traceChildAsync('collect black keywords/suffixes', async () => {
  86. /** Collect DOMAIN-KEYWORD from non_ip/reject.conf for deduplication */
  87. const domainKeywordsSet = new Set<string>();
  88. for await (const line of readFileByLine(path.resolve(__dirname, '../Source/non_ip/reject.conf'))) {
  89. const [type, value] = line.split(',');
  90. if (type === 'DOMAIN-KEYWORD') {
  91. domainKeywordsSet.add(value);
  92. } else if (type === 'DOMAIN-SUFFIX') {
  93. domainSets.add('.' + value); // Add to domainSets for later deduplication
  94. }
  95. }
  96. return domainKeywordsSet;
  97. });
  98. const [baseTrie, extraTrie] = span.traceChildSync('create smol trie while deduping black keywords', (childSpan) => {
  99. const baseTrie = createTrie(null, true, true);
  100. const extraTrie = createTrie(null, true, true);
  101. const kwfilter = createKeywordFilter(domainKeywordsSet);
  102. childSpan.traceChildSync('add items to trie (extra)', () => {
  103. for (const domain of domainSetsExtra) {
  104. // exclude keyword when creating trie
  105. if (!kwfilter(domain)) {
  106. extraTrie.add(domain);
  107. }
  108. }
  109. });
  110. childSpan.traceChildSync('add items to trie (base) + dedupe extra trie', () => {
  111. for (const domain of domainSets) {
  112. // exclude keyword when creating trie
  113. if (!kwfilter(domain)) {
  114. baseTrie.add(domain);
  115. extraTrie.whitelist(domain);
  116. }
  117. }
  118. });
  119. return [baseTrie, extraTrie] as const;
  120. });
  121. span.traceChildSync('dedupe from white suffixes (base)', () => filterRuleWhitelistDomainSets.forEach(baseTrie.whitelist));
  122. span.traceChildSync('dedupe from white suffixes and base (extra)', () => {
  123. filterRuleWhitelistDomainSets.forEach(extraTrie.whitelist);
  124. });
  125. // Dedupe domainSets
  126. const dudupedDominArray = span.traceChildSync('dedupe from covered subdomain (base)', () => domainDeduper(baseTrie));
  127. const dudupedDominArrayExtra = span.traceChildSync('dedupe from covered subdomain (extra)', () => domainDeduper(extraTrie));
  128. console.log(`Final size ${dudupedDominArray.length} + ${dudupedDominArrayExtra.length}`);
  129. const {
  130. domainMap: domainArrayMainDomainMap,
  131. subdomainMap: domainArraySubdomainMap
  132. } = span.traceChildSync(
  133. 'build map for stat and sort',
  134. () => buildParseDomainMap(dudupedDominArray.concat(dudupedDominArrayExtra))
  135. );
  136. // Create reject stats
  137. const rejectDomainsStats: string[] = span
  138. .traceChild('create reject stats')
  139. .traceSyncFn(() => {
  140. const results = [];
  141. results.push('=== base ===');
  142. appendArrayInPlace(results, getStatMap(dudupedDominArray, domainArrayMainDomainMap));
  143. results.push('=== extra ===');
  144. appendArrayInPlace(results, getStatMap(dudupedDominArrayExtra, domainArrayMainDomainMap));
  145. return results;
  146. });
  147. return Promise.all([
  148. createRuleset(
  149. span,
  150. 'Sukka\'s Ruleset - Reject Base',
  151. [
  152. ...SHARED_DESCRIPTION,
  153. '',
  154. 'The domainset supports AD blocking, tracking protection, privacy protection, anti-phishing, anti-mining',
  155. '',
  156. 'Build from:',
  157. ...HOSTS.map(host => ` - ${host[0]}`),
  158. ...DOMAIN_LISTS.map(domainList => ` - ${domainList[0]}`),
  159. ...ADGUARD_FILTERS.map(filter => ` - ${Array.isArray(filter) ? filter[0] : filter}`)
  160. ],
  161. new Date(),
  162. span.traceChildSync('sort reject domainset (base)', () => sortDomains(dudupedDominArray, domainArrayMainDomainMap, domainArraySubdomainMap)),
  163. 'domainset',
  164. output('reject', 'domainset')
  165. ),
  166. createRuleset(
  167. span,
  168. 'Sukka\'s Ruleset - Reject Extra',
  169. [
  170. ...SHARED_DESCRIPTION,
  171. '',
  172. 'The domainset supports AD blocking, tracking protection, privacy protection, anti-phishing, anti-mining',
  173. '',
  174. 'Build from:',
  175. ...HOSTS_EXTRA.map(host => ` - ${host[0]}`),
  176. ...DOMAIN_LISTS_EXTRA.map(domainList => ` - ${domainList[0]}`),
  177. ...ADGUARD_FILTERS_EXTRA.map(filter => ` - ${Array.isArray(filter) ? filter[0] : filter}`),
  178. ...PHISHING_DOMAIN_LISTS_EXTRA.map(domainList => ` - ${domainList[0]}`)
  179. ],
  180. new Date(),
  181. span.traceChildSync('sort reject domainset (extra)', () => sortDomains(dudupedDominArrayExtra, domainArrayMainDomainMap, domainArraySubdomainMap)),
  182. 'domainset',
  183. output('reject_extra', 'domainset')
  184. ),
  185. compareAndWriteFile(
  186. span,
  187. rejectDomainsStats,
  188. path.resolve(__dirname, '../Internal/reject-stats.txt')
  189. )
  190. ]);
  191. });
  192. function getStatMap(domains: string[], domainArrayMainDomainMap: Map<string, string>): string[] {
  193. return Array.from(
  194. (
  195. domains.reduce<Map<string, number>>((acc, cur) => {
  196. const suffix = domainArrayMainDomainMap.get(cur);
  197. if (suffix) {
  198. acc.set(suffix, (acc.get(suffix) ?? 0) + 1);
  199. }
  200. return acc;
  201. }, new Map())
  202. ).entries()
  203. )
  204. .filter(a => a[1] > 9)
  205. .sort(
  206. (a, b) => (b[1] - a[1]) || a[0].localeCompare(b[0])
  207. )
  208. .map(([domain, count]) => `${domain}${' '.repeat(100 - domain.length)}${count}`);
  209. };