is-domain-alive.ts 9.9 KB

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