build-reject-domainset.ts 9.2 KB

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