build-reject-domainset.ts 9.7 KB

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