is-domain-alive.ts 9.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342
  1. import tldts from 'tldts-experimental';
  2. import { looseTldtsOpt } from '../constants/loose-tldts-opt';
  3. import picocolors from 'picocolors';
  4. import DNS2 from 'dns2';
  5. import asyncRetry from 'async-retry';
  6. import * as whoiser from 'whoiser';
  7. import { createRetrieKeywordFilter as createKeywordFilter } from 'foxts/retrie';
  8. import process from 'node:process';
  9. const mutex = new Map<string, Promise<unknown>>();
  10. export function keyedAsyncMutexWithQueue<T>(key: string, fn: () => Promise<T>) {
  11. if (mutex.has(key)) {
  12. return mutex.get(key) as Promise<T>;
  13. }
  14. const promise = fn();
  15. mutex.set(key, promise);
  16. return promise;
  17. }
  18. class DnsError extends Error {
  19. name = 'DnsError';
  20. constructor(readonly message: string, public readonly server: string) {
  21. super(message);
  22. }
  23. }
  24. interface DnsResponse extends DNS2.$DnsResponse {
  25. dns: string
  26. }
  27. const dohServers: Array<[string, DNS2.DnsResolver]> = ([
  28. '8.8.8.8',
  29. '8.8.4.4',
  30. '1.0.0.1',
  31. '1.1.1.1',
  32. '162.159.36.1',
  33. '162.159.46.1',
  34. '101.101.101.101', // TWNIC
  35. '185.222.222.222', // DNS.SB
  36. '45.11.45.11', // DNS.SB
  37. 'dns10.quad9.net', // Quad9 unfiltered
  38. 'doh.sandbox.opendns.com', // OpenDNS sandbox (unfiltered)
  39. 'unfiltered.adguard-dns.com',
  40. // '0ms.dev', // Proxy Cloudflare
  41. // '76.76.2.0', // ControlD unfiltered, path not /dns-query
  42. // '76.76.10.0', // ControlD unfiltered, path not /dns-query
  43. // 'dns.bebasid.com', // BebasID, path not /dns-query but /unfiltered
  44. // '193.110.81.0', // dns0.eu
  45. // '185.253.5.0', // dns0.eu
  46. // 'zero.dns0.eu',
  47. 'dns.nextdns.io',
  48. 'anycast.dns.nextdns.io',
  49. 'wikimedia-dns.org',
  50. // 'ordns.he.net',
  51. // 'dns.mullvad.net',
  52. 'basic.rethinkdns.com',
  53. '198.54.117.10' // NameCheap DNS, supports DoT, DoH, UDP53
  54. // 'ada.openbld.net',
  55. // 'dns.rabbitdns.org'
  56. ] as const).map(dns => [
  57. dns,
  58. DNS2.DOHClient({
  59. dns,
  60. http: false
  61. })
  62. ] as const);
  63. const domesticDohServers: Array<[string, DNS2.DnsResolver]> = ([
  64. '223.5.5.5',
  65. '223.6.6.6',
  66. '120.53.53.53',
  67. '1.12.12.12'
  68. ] as const).map(dns => [
  69. dns,
  70. DNS2.DOHClient({
  71. dns,
  72. http: false
  73. })
  74. ] as const);
  75. function createResolve(server: Array<[string, DNS2.DnsResolver]>): DNS2.DnsResolver<DnsResponse> {
  76. return async (...args) => {
  77. try {
  78. return await asyncRetry(async () => {
  79. const [dohServer, dohClient] = server[Math.floor(Math.random() * server.length)];
  80. try {
  81. return {
  82. ...await dohClient(...args),
  83. dns: dohServer
  84. } satisfies DnsResponse;
  85. } catch (e) {
  86. // console.error(e);
  87. throw new DnsError((e as Error).message, dohServer);
  88. }
  89. }, { retries: 5 });
  90. } catch (e) {
  91. console.log('[doh error]', ...args, e);
  92. throw e;
  93. }
  94. };
  95. }
  96. const resolve = createResolve(dohServers);
  97. const domesticResolve = createResolve(domesticDohServers);
  98. async function getWhois(domain: string) {
  99. return asyncRetry(() => whoiser.domain(domain, { raw: true }), { retries: 5 });
  100. }
  101. const domainAliveMap = new Map<string, boolean>();
  102. function onDomainAlive(domain: string): [string, boolean] {
  103. domainAliveMap.set(domain, true);
  104. return [domain, true];
  105. }
  106. function onDomainDead(domain: string): [string, boolean] {
  107. domainAliveMap.set(domain, false);
  108. return [domain, false];
  109. }
  110. export async function isDomainAlive(domain: string, isSuffix: boolean): Promise<[string, boolean]> {
  111. if (domainAliveMap.has(domain)) {
  112. return [domain, domainAliveMap.get(domain)!];
  113. }
  114. const apexDomain = tldts.getDomain(domain, looseTldtsOpt);
  115. if (!apexDomain) {
  116. console.log(picocolors.gray('[domain invalid]'), picocolors.gray('no apex domain'), { domain });
  117. return onDomainAlive(domain);
  118. }
  119. const apexDomainAlive = await keyedAsyncMutexWithQueue(apexDomain, () => isApexDomainAlive(apexDomain));
  120. if (isSuffix) {
  121. return apexDomainAlive;
  122. }
  123. if (!apexDomainAlive[1]) {
  124. return apexDomainAlive;
  125. }
  126. const $domain = domain[0] === '.' ? domain.slice(1) : domain;
  127. const aDns: string[] = [];
  128. const aaaaDns: string[] = [];
  129. // test 2 times before make sure record is empty
  130. for (let i = 0; i < 2; i++) {
  131. // eslint-disable-next-line no-await-in-loop -- sequential
  132. const aRecords = (await resolve($domain, 'A'));
  133. if (aRecords.answers.length > 0) {
  134. return onDomainAlive(domain);
  135. }
  136. aDns.push(aRecords.dns);
  137. }
  138. for (let i = 0; i < 2; i++) {
  139. // eslint-disable-next-line no-await-in-loop -- sequential
  140. const aaaaRecords = (await resolve($domain, 'AAAA'));
  141. if (aaaaRecords.answers.length > 0) {
  142. return onDomainAlive(domain);
  143. }
  144. aaaaDns.push(aaaaRecords.dns);
  145. }
  146. // only then, let's test once with domesticDohServers
  147. const aRecords = (await domesticResolve($domain, 'A'));
  148. if (aRecords.answers.length > 0) {
  149. return onDomainAlive(domain);
  150. }
  151. aDns.push(aRecords.dns);
  152. const aaaaRecords = (await domesticResolve($domain, 'AAAA'));
  153. if (aaaaRecords.answers.length > 0) {
  154. return onDomainAlive(domain);
  155. }
  156. aaaaDns.push(aaaaRecords.dns);
  157. console.log(picocolors.red('[domain dead]'), 'no A/AAAA records', { domain, a: aDns, aaaa: aaaaDns });
  158. return onDomainDead($domain);
  159. }
  160. const apexDomainNsResolvePromiseMap = new Map<string, Promise<DnsResponse>>();
  161. async function isApexDomainAlive(apexDomain: string): Promise<[string, boolean]> {
  162. if (domainAliveMap.has(apexDomain)) {
  163. return [apexDomain, domainAliveMap.get(apexDomain)!];
  164. }
  165. let resp: DnsResponse;
  166. if (apexDomainNsResolvePromiseMap.has(apexDomain)) {
  167. resp = await apexDomainNsResolvePromiseMap.get(apexDomain)!;
  168. } else {
  169. const promise = resolve(apexDomain, 'NS');
  170. apexDomainNsResolvePromiseMap.set(apexDomain, promise);
  171. resp = await promise;
  172. }
  173. if (resp.answers.length > 0) {
  174. return onDomainAlive(apexDomain);
  175. }
  176. let whois;
  177. try {
  178. whois = await getWhois(apexDomain);
  179. } catch (e) {
  180. console.log(picocolors.red('[whois error]'), { domain: apexDomain }, e);
  181. return onDomainAlive(apexDomain);
  182. }
  183. if (process.env.DEBUG) {
  184. console.log(JSON.stringify(whois, null, 2));
  185. }
  186. const whoisError = noWhois(whois);
  187. if (!whoisError) {
  188. console.log(picocolors.gray('[domain alive]'), picocolors.gray('whois found'), { domain: apexDomain });
  189. return onDomainAlive(apexDomain);
  190. }
  191. console.log(picocolors.red('[domain dead]'), 'whois not found', { domain: apexDomain, err: whoisError });
  192. return onDomainDead(apexDomain);
  193. }
  194. // TODO: this is a workaround for https://github.com/LayeredStudio/whoiser/issues/117
  195. const whoisNotFoundKeywordTest = createKeywordFilter([
  196. 'no match for',
  197. 'does not exist',
  198. 'not found',
  199. 'no found',
  200. 'no entries',
  201. 'no data found',
  202. 'is available for registration',
  203. 'currently available for application',
  204. 'no matching record',
  205. 'no information available about domain name',
  206. 'not been registered',
  207. 'no match!!',
  208. 'status: available',
  209. ' is free',
  210. 'no object found',
  211. 'nothing found',
  212. 'status: free',
  213. 'pendingdelete',
  214. ' has been blocked by '
  215. ]);
  216. // whois server can redirect, so whoiser might/will get info from multiple whois servers
  217. // some servers (like TLD whois servers) might have cached/outdated results
  218. // we can only make sure a domain is alive once all response from all whois servers demonstrate so
  219. export function noWhois(whois: whoiser.WhoisSearchResult): null | string {
  220. let empty = true;
  221. for (const key in whois) {
  222. if (Object.hasOwn(whois, key)) {
  223. empty = false;
  224. // if (key === 'error') {
  225. // // if (
  226. // // (typeof whois.error === 'string' && whois.error)
  227. // // || (Array.isArray(whois.error) && whois.error.length > 0)
  228. // // ) {
  229. // // console.error(whois);
  230. // // return true;
  231. // // }
  232. // continue;
  233. // }
  234. // if (key === 'text') {
  235. // if (Array.isArray(whois.text)) {
  236. // for (const value of whois.text) {
  237. // if (whoisNotFoundKeywordTest(value.toLowerCase())) {
  238. // return value;
  239. // }
  240. // }
  241. // }
  242. // continue;
  243. // }
  244. // if (key === 'Name Server') {
  245. // // if (Array.isArray(whois[key]) && whois[key].length === 0) {
  246. // // return false;
  247. // // }
  248. // continue;
  249. // }
  250. // if (key === 'Domain Status') {
  251. // if (Array.isArray(whois[key])) {
  252. // for (const status of whois[key]) {
  253. // if (status === 'free' || status === 'AVAILABLE') {
  254. // return key + ': ' + status;
  255. // }
  256. // if (whoisNotFoundKeywordTest(status.toLowerCase())) {
  257. // return key + ': ' + status;
  258. // }
  259. // }
  260. // }
  261. // continue;
  262. // }
  263. // if (typeof whois[key] === 'string' && whois[key]) {
  264. // if (whoisNotFoundKeywordTest(whois[key].toLowerCase())) {
  265. // return key + ': ' + whois[key];
  266. // }
  267. // continue;
  268. // }
  269. if (key === '__raw' && typeof whois.__raw === 'string') {
  270. const lines = whois.__raw.trim().toLowerCase().replaceAll(/[\t ]+/g, ' ').split(/\r?\n/);
  271. if (process.env.DEBUG) {
  272. console.log({ lines });
  273. }
  274. for (const line of lines) {
  275. if (whoisNotFoundKeywordTest(line)) {
  276. return line;
  277. }
  278. }
  279. continue;
  280. }
  281. if (typeof whois[key] === 'object' && !Array.isArray(whois[key])) {
  282. const tmp = noWhois(whois[key]);
  283. if (tmp) {
  284. return tmp;
  285. }
  286. continue;
  287. }
  288. }
  289. }
  290. if (empty) {
  291. return 'whois is empty';
  292. }
  293. return null;
  294. }