build-reject-domainset.ts 9.3 KB

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