validate-domain-alive.ts 6.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246
  1. import DNS2 from 'dns2';
  2. import { readFileByLine } from './lib/fetch-text-by-line';
  3. import { processLine } from './lib/process-line';
  4. import tldts from 'tldts';
  5. import { looseTldtsOpt } from './constants/loose-tldts-opt';
  6. import { fdir as Fdir } from 'fdir';
  7. import { SOURCE_DIR } from './constants/dir';
  8. import path from 'node:path';
  9. import { newQueue } from '@henrygd/queue';
  10. import asyncRetry from 'async-retry';
  11. import * as whoiser from 'whoiser';
  12. import picocolors from 'picocolors';
  13. import createKeywordFilter from './lib/aho-corasick';
  14. const dohServers: Array<[string, DNS2.DnsResolver]> = ([
  15. '8.8.8.8',
  16. '8.8.4.4',
  17. '1.0.0.1',
  18. '1.1.1.1',
  19. '162.159.36.1',
  20. '162.159.46.1',
  21. '101.101.101.101', // TWNIC
  22. '185.222.222.222', // DNS.SB
  23. '45.11.45.11', // DNS.SB
  24. 'dns10.quad9.net', // Quad9 unfiltered
  25. 'doh.sandbox.opendns.com', // OpenDNS sandbox (unfiltered)
  26. 'unfiltered.adguard-dns.com',
  27. // '0ms.dev', // Proxy Cloudflare
  28. // '76.76.2.0', // ControlD unfiltered, path not /dns-query
  29. // '76.76.10.0', // ControlD unfiltered, path not /dns-query
  30. // 'dns.bebasid.com', // BebasID, path not /dns-query but /unfiltered
  31. '193.110.81.0', // dns0.eu
  32. '185.253.5.0', // dns0.eu
  33. 'dns.nextdns.io',
  34. 'anycast.dns.nextdns.io',
  35. 'wikimedia-dns.org',
  36. // 'ordns.he.net',
  37. 'dns.mullvad.net',
  38. 'zero.dns0.eu',
  39. '193.110.81.0',
  40. 'basic.rethinkdns.com'
  41. // 'ada.openbld.net',
  42. // 'dns.rabbitdns.org'
  43. ] as const).map(server => [
  44. server,
  45. DNS2.DOHClient({
  46. dns: server,
  47. http: false
  48. })
  49. ] as const);
  50. const queue = newQueue(24);
  51. const mutex = new Map<string, Promise<unknown>>();
  52. function keyedAsyncMutexWithQueue<T>(key: string, fn: () => Promise<T>) {
  53. if (mutex.has(key)) {
  54. return mutex.get(key) as Promise<T>;
  55. }
  56. const promise = queue.add(() => fn()).finally(() => mutex.delete(key));
  57. mutex.set(key, promise);
  58. return promise;
  59. }
  60. class DnsError extends Error {
  61. name = 'DnsError';
  62. constructor(readonly message: string, public readonly server: string) {
  63. super(message);
  64. }
  65. }
  66. interface DnsResponse extends DNS2.$DnsResponse {
  67. dns: string
  68. }
  69. const resolve: DNS2.DnsResolver<DnsResponse> = async (...args) => {
  70. try {
  71. return await asyncRetry(async () => {
  72. const [dohServer, dohClient] = dohServers[Math.floor(Math.random() * dohServers.length)];
  73. try {
  74. const resp = await dohClient(...args);
  75. return {
  76. ...resp,
  77. dns: dohServer
  78. } satisfies DnsResponse;
  79. } catch (e) {
  80. throw new DnsError((e as Error).message, dohServer);
  81. }
  82. }, { retries: 5 });
  83. } catch (e) {
  84. console.log('[doh error]', ...args, e);
  85. throw e;
  86. }
  87. };
  88. (async () => {
  89. const domainSets = await new Fdir()
  90. .withFullPaths()
  91. .crawl(SOURCE_DIR + path.sep + 'domainset')
  92. .withPromise();
  93. const domainRules = await new Fdir()
  94. .withFullPaths()
  95. .crawl(SOURCE_DIR + path.sep + 'non_ip')
  96. .withPromise();
  97. await Promise.all([
  98. ...domainSets.map(runAgainstDomainset),
  99. ...domainRules.map(runAgainstRuleset)
  100. ]);
  101. console.log('done');
  102. })();
  103. const whoisNotFoundKeywordTest = createKeywordFilter([
  104. 'no match for',
  105. 'does not exist',
  106. 'not found'
  107. ]);
  108. const domainAliveMap = new Map<string, boolean>();
  109. async function isApexDomainAlive(apexDomain: string): Promise<[string, boolean]> {
  110. if (domainAliveMap.has(apexDomain)) {
  111. return [apexDomain, domainAliveMap.get(apexDomain)!];
  112. }
  113. const resp = await resolve(apexDomain, 'NS');
  114. if (resp.answers.length > 0) {
  115. return [apexDomain, true];
  116. }
  117. let whois;
  118. try {
  119. whois = await whoiser.domain(apexDomain);
  120. } catch (e) {
  121. console.log('[whois fail]', 'whois error', { domain: apexDomain }, e);
  122. return [apexDomain, true];
  123. }
  124. if (Object.keys(whois).length > 0) {
  125. // TODO: this is a workaround for https://github.com/LayeredStudio/whoiser/issues/117
  126. if ('text' in whois && Array.isArray(whois.text) && whois.text.some(value => whoisNotFoundKeywordTest(value.toLowerCase()))) {
  127. console.log(picocolors.red('[domain dead]'), 'whois not found', { domain: apexDomain });
  128. domainAliveMap.set(apexDomain, false);
  129. return [apexDomain, false];
  130. }
  131. return [apexDomain, true];
  132. }
  133. if (!('dns' in whois)) {
  134. console.log({ whois });
  135. }
  136. console.log(picocolors.red('[domain dead]'), 'whois not found', { domain: apexDomain });
  137. domainAliveMap.set(apexDomain, false);
  138. return [apexDomain, false];
  139. }
  140. export async function isDomainAlive(domain: string, isSuffix: boolean): Promise<[string, boolean]> {
  141. if (domainAliveMap.has(domain)) {
  142. return [domain, domainAliveMap.get(domain)!];
  143. }
  144. const apexDomain = tldts.getDomain(domain, looseTldtsOpt);
  145. if (!apexDomain) {
  146. console.log('[domain invalid]', 'no apex domain', { domain });
  147. domainAliveMap.set(domain, true);
  148. return [domain, true] as const;
  149. }
  150. const apexDomainAlive = await keyedAsyncMutexWithQueue(apexDomain, () => isApexDomainAlive(apexDomain));
  151. if (!apexDomainAlive[1]) {
  152. domainAliveMap.set(domain, false);
  153. return [domain, false] as const;
  154. }
  155. if (!isSuffix) {
  156. const $domain = domain[0] === '.' ? domain.slice(1) : domain;
  157. const aRecords = (await resolve($domain, 'A'));
  158. if (aRecords.answers.length === 0) {
  159. const aaaaRecords = (await resolve($domain, 'AAAA'));
  160. if (aaaaRecords.answers.length === 0) {
  161. console.log(picocolors.red('[domain dead]'), 'no A/AAAA records', { domain, a: aRecords.dns, aaaa: aaaaRecords.dns });
  162. domainAliveMap.set($domain, false);
  163. return [domain, false] as const;
  164. }
  165. }
  166. }
  167. domainAliveMap.set(domain, true);
  168. return [domain, true] as const;
  169. }
  170. export async function runAgainstRuleset(filepath: string) {
  171. const extname = path.extname(filepath);
  172. if (extname !== '.conf') {
  173. console.log('[skip]', filepath);
  174. return;
  175. }
  176. const promises: Array<Promise<[string, boolean]>> = [];
  177. for await (const l of readFileByLine(filepath)) {
  178. const line = processLine(l);
  179. if (!line) continue;
  180. const [type, domain] = line.split(',');
  181. switch (type) {
  182. case 'DOMAIN-SUFFIX':
  183. case 'DOMAIN': {
  184. promises.push(keyedAsyncMutexWithQueue(domain, () => isDomainAlive(domain, type === 'DOMAIN-SUFFIX')));
  185. break;
  186. }
  187. // no default
  188. // case 'DOMAIN-KEYWORD': {
  189. // break;
  190. // }
  191. // no default
  192. }
  193. }
  194. await Promise.all(promises);
  195. console.log('[done]', filepath);
  196. }
  197. export async function runAgainstDomainset(filepath: string) {
  198. const extname = path.extname(filepath);
  199. if (extname !== '.conf') {
  200. console.log('[skip]', filepath);
  201. return;
  202. }
  203. const promises: Array<Promise<[string, boolean]>> = [];
  204. for await (const l of readFileByLine(filepath)) {
  205. const line = processLine(l);
  206. if (!line) continue;
  207. promises.push(isDomainAlive(line, line[0] === '.'));
  208. }
  209. await Promise.all(promises);
  210. console.log('[done]', filepath);
  211. }