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