validate-domain-alive.ts 6.5 KB

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