| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176 |
- // @ts-check
- import path from 'path';
- import { processHosts, processFilterRules, processDomainLists } from './lib/parse-filter';
- import { createTrie } from './lib/trie';
- import { HOSTS, ADGUARD_FILTERS, PREDEFINED_WHITELIST, DOMAIN_LISTS } from './lib/reject-data-source';
- import { createRuleset, compareAndWriteFile } from './lib/create-file';
- import { domainDeduper } from './lib/domain-deduper';
- import createKeywordFilter from './lib/aho-corasick';
- import { readFileByLine, readFileIntoProcessedArray } from './lib/fetch-text-by-line';
- import { sortDomains } from './lib/stable-sort-domain';
- import { task } from './trace';
- // tldts-experimental is way faster than tldts, but very little bit inaccurate
- // (since it is hashes based). But the result is still deterministic, which is
- // enough when creating a simple stat of reject hosts.
- import * as tldts from 'tldts-experimental';
- import { SHARED_DESCRIPTION } from './lib/constants';
- import { getPhishingDomains } from './lib/get-phishing-domains';
- import { add as SetAdd, subtract as SetSubstract } from 'mnemonist/set';
- import { setAddFromArray, setAddFromArrayCurried } from './lib/set-add-from-array';
- import { sort } from './lib/timsort';
- export const buildRejectDomainSet = task(import.meta.path, async (span) => {
- /** Whitelists */
- const filterRuleWhitelistDomainSets = new Set(PREDEFINED_WHITELIST);
- const domainSets = new Set<string>();
- // Parse from AdGuard Filters
- const shouldStop = await span
- .traceChild('download and process hosts / adblock filter rules')
- .traceAsyncFn(async (childSpan) => {
- // eslint-disable-next-line sukka/no-single-return -- not single return
- let shouldStop = false;
- await Promise.all([
- // Parse from remote hosts & domain lists
- ...HOSTS.map(entry => processHosts(childSpan, ...entry).then(setAddFromArrayCurried(domainSets))),
- ...DOMAIN_LISTS.map(entry => processDomainLists(childSpan, ...entry).then(setAddFromArrayCurried(domainSets))),
- ...ADGUARD_FILTERS.map(input => (
- typeof input === 'string'
- ? processFilterRules(childSpan, input)
- : processFilterRules(childSpan, ...input)
- ).then(({ white, black, foundDebugDomain }) => {
- if (foundDebugDomain) {
- // eslint-disable-next-line sukka/no-single-return -- not single return
- shouldStop = true;
- // we should not break here, as we want to see full matches from all data source
- }
- setAddFromArray(filterRuleWhitelistDomainSets, white);
- setAddFromArray(domainSets, black);
- })),
- ...([
- 'https://raw.githubusercontent.com/AdguardTeam/AdGuardSDNSFilter/master/Filters/exceptions.txt',
- 'https://raw.githubusercontent.com/AdguardTeam/AdGuardSDNSFilter/master/Filters/exclusions.txt'
- ].map(input => processFilterRules(childSpan, input).then(({ white, black }) => {
- setAddFromArray(filterRuleWhitelistDomainSets, white);
- setAddFromArray(filterRuleWhitelistDomainSets, black);
- }))),
- getPhishingDomains(childSpan).then(setAddFromArrayCurried(domainSets)),
- childSpan.traceChildAsync('process reject_sukka.conf', () => readFileIntoProcessedArray(path.resolve(import.meta.dir, '../Source/domainset/reject_sukka.conf'))
- .then(setAddFromArrayCurried(domainSets)))
- ]);
- // eslint-disable-next-line sukka/no-single-return -- not single return
- return shouldStop;
- });
- if (shouldStop) {
- process.exit(1);
- }
- console.log(`Import ${domainSets.size} rules from Hosts / AdBlock Filter Rules & reject_sukka.conf!`);
- // Dedupe domainSets
- await span.traceChildAsync('dedupe from black keywords/suffixes', async (childSpan) => {
- /** Collect DOMAIN-KEYWORD from non_ip/reject.conf for deduplication */
- const domainKeywordsSet = new Set<string>();
- await childSpan.traceChildAsync('collect keywords/suffixes', async () => {
- for await (const line of readFileByLine(path.resolve(import.meta.dir, '../Source/non_ip/reject.conf'))) {
- const [type, value] = line.split(',');
- if (type === 'DOMAIN-KEYWORD') {
- domainKeywordsSet.add(value.trim());
- } else if (type === 'DOMAIN-SUFFIX') {
- domainSets.add(`.${value.trim()}`); // Add to domainSets for later deduplication
- }
- }
- });
- // Remove as many domains as possible from domainSets before creating trie
- SetSubstract(domainSets, filterRuleWhitelistDomainSets);
- // Perform kwfilter to remove as many domains as possible from domainSets before creating trie
- childSpan.traceChildSync('dedupe from black keywords', () => {
- const kwfilter = createKeywordFilter(domainKeywordsSet);
- for (const domain of domainSets) {
- // Remove keyword
- if (kwfilter(domain)) {
- domainSets.delete(domain);
- }
- }
- });
- });
- const trie = createTrie(domainSets, true, true);
- span.traceChildSync('dedupe from white suffixes', () => {
- filterRuleWhitelistDomainSets.forEach(suffix => {
- trie.whitelist(suffix);
- });
- });
- // Dedupe domainSets
- const dudupedDominArray = span.traceChildSync('dedupe from covered subdomain', () => domainDeduper(trie));
- console.log(`Final size ${dudupedDominArray.length}`);
- // Create reject stats
- const rejectDomainsStats: Array<[string, number]> = span
- .traceChild('create reject stats')
- .traceSyncFn(() => {
- const tldtsOpt = { allowPrivateDomains: false, detectIp: false, validateHostname: false };
- const statMap = dudupedDominArray.reduce<Map<string, number>>((acc, cur) => {
- const suffix = tldts.getDomain(cur, tldtsOpt);
- if (!suffix) return acc;
- if (acc.has(suffix)) {
- acc.set(suffix, acc.get(suffix)! + 1);
- } else {
- acc.set(suffix, 1);
- }
- return acc;
- }, new Map());
- return sort(Array.from(statMap.entries()).filter(a => a[1] > 9), (a, b) => (b[1] - a[1]) || a[0].localeCompare(b[0]));
- });
- const description = [
- ...SHARED_DESCRIPTION,
- '',
- 'The domainset supports AD blocking, tracking protection, privacy protection, anti-phishing, anti-mining',
- '',
- 'Build from:',
- ...HOSTS.map(host => ` - ${host[0]}`),
- ...DOMAIN_LISTS.map(domainList => ` - ${domainList[0]}`),
- ...ADGUARD_FILTERS.map(filter => ` - ${Array.isArray(filter) ? filter[0] : filter}`),
- ' - https://curbengh.github.io/phishing-filter/phishing-filter-hosts.txt',
- ' - https://phishing.army/download/phishing_army_blocklist.txt'
- ];
- return Promise.all([
- createRuleset(
- span,
- 'Sukka\'s Ruleset - Reject Base',
- description,
- new Date(),
- span.traceChildSync('sort reject domainset', () => sortDomains(dudupedDominArray)),
- 'domainset',
- path.resolve(import.meta.dir, '../List/domainset/reject.conf'),
- path.resolve(import.meta.dir, '../Clash/domainset/reject.txt')
- ),
- compareAndWriteFile(
- span,
- rejectDomainsStats.map(([domain, count]) => `${domain}${' '.repeat(100 - domain.length)}${count}`),
- path.resolve(import.meta.dir, '../Internal/reject-stats.txt')
- )
- ]);
- });
- if (import.meta.main) {
- buildRejectDomainSet();
- }
|