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