validate-domain-alive.ts 8.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296
  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-experimental';
  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 { createRetrieKeywordFilter as createKeywordFilter } from 'foxts/retrie';
  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. 'dns10.quad9.net', // Quad9 unfiltered
  25. 'doh.sandbox.opendns.com', // OpenDNS sandbox (unfiltered)
  26. 'unfiltered.adguard-dns.com',
  27. // '0ms.dev', // Proxy Cloudflare
  28. // '76.76.2.0', // ControlD unfiltered, path not /dns-query
  29. // '76.76.10.0', // ControlD unfiltered, path not /dns-query
  30. // 'dns.bebasid.com', // BebasID, path not /dns-query but /unfiltered
  31. // '193.110.81.0', // dns0.eu
  32. // '185.253.5.0', // dns0.eu
  33. // 'zero.dns0.eu',
  34. 'dns.nextdns.io',
  35. 'anycast.dns.nextdns.io',
  36. 'wikimedia-dns.org',
  37. // 'ordns.he.net',
  38. // 'dns.mullvad.net',
  39. 'basic.rethinkdns.com'
  40. // 'ada.openbld.net',
  41. // 'dns.rabbitdns.org'
  42. ] as const).map(dns => [
  43. dns,
  44. DNS2.DOHClient({
  45. dns,
  46. http: false
  47. // get: (url: string) => undici.request(url).then(r => r.body)
  48. })
  49. ] as const);
  50. const domesticDohServers: Array<[string, DNS2.DnsResolver]> = ([
  51. '223.5.5.5',
  52. '223.6.6.6',
  53. '120.53.53.53',
  54. '1.12.12.12'
  55. ] as const).map(dns => [
  56. dns,
  57. DNS2.DOHClient({
  58. dns,
  59. http: false
  60. // get: (url: string) => undici.request(url).then(r => r.body)
  61. })
  62. ] as const);
  63. const queue = newQueue(32);
  64. const mutex = new Map<string, Promise<unknown>>();
  65. function keyedAsyncMutexWithQueue<T>(key: string, fn: () => Promise<T>) {
  66. if (mutex.has(key)) {
  67. return mutex.get(key) as Promise<T>;
  68. }
  69. const promise = queue.add(() => fn());
  70. mutex.set(key, promise);
  71. return promise;
  72. }
  73. class DnsError extends Error {
  74. name = 'DnsError';
  75. constructor(readonly message: string, public readonly server: string) {
  76. super(message);
  77. }
  78. }
  79. interface DnsResponse extends DNS2.$DnsResponse {
  80. dns: string
  81. }
  82. function createResolve(server: Array<[string, DNS2.DnsResolver]>): DNS2.DnsResolver<DnsResponse> {
  83. return async (...args) => {
  84. try {
  85. return await asyncRetry(async () => {
  86. const [dohServer, dohClient] = server[Math.floor(Math.random() * server.length)];
  87. try {
  88. return {
  89. ...await dohClient(...args),
  90. dns: dohServer
  91. } satisfies DnsResponse;
  92. } catch (e) {
  93. // console.error(e);
  94. throw new DnsError((e as Error).message, dohServer);
  95. }
  96. }, { retries: 5 });
  97. } catch (e) {
  98. console.log('[doh error]', ...args, e);
  99. throw e;
  100. }
  101. };
  102. }
  103. const resolve = createResolve(dohServers);
  104. const domesticResolve = createResolve(domesticDohServers);
  105. async function getWhois(domain: string) {
  106. return asyncRetry(() => whoiser.domain(domain), { retries: 5 });
  107. }
  108. (async () => {
  109. const domainSets = await new Fdir()
  110. .withFullPaths()
  111. .crawl(SOURCE_DIR + path.sep + 'domainset')
  112. .withPromise();
  113. const domainRules = await new Fdir()
  114. .withFullPaths()
  115. .crawl(SOURCE_DIR + path.sep + 'non_ip')
  116. .withPromise();
  117. await Promise.all([
  118. ...domainSets.map(runAgainstDomainset),
  119. ...domainRules.map(runAgainstRuleset)
  120. ]);
  121. console.log('done');
  122. })();
  123. const whoisNotFoundKeywordTest = createKeywordFilter([
  124. 'no match for',
  125. 'does not exist',
  126. 'not found'
  127. ]);
  128. const domainAliveMap = new Map<string, boolean>();
  129. async function isApexDomainAlive(apexDomain: string): Promise<[string, boolean]> {
  130. if (domainAliveMap.has(apexDomain)) {
  131. return [apexDomain, domainAliveMap.get(apexDomain)!];
  132. }
  133. const resp = await resolve(apexDomain, 'NS');
  134. if (resp.answers.length > 0) {
  135. return [apexDomain, true];
  136. }
  137. let whois;
  138. try {
  139. whois = await getWhois(apexDomain);
  140. } catch (e) {
  141. console.log('[whois fail]', 'whois error', { domain: apexDomain }, e);
  142. return [apexDomain, true];
  143. }
  144. if (Object.keys(whois).length > 0) {
  145. // TODO: this is a workaround for https://github.com/LayeredStudio/whoiser/issues/117
  146. if ('text' in whois && Array.isArray(whois.text) && whois.text.some(value => whoisNotFoundKeywordTest(value.toLowerCase()))) {
  147. console.log(picocolors.red('[domain dead]'), 'whois not found', { domain: apexDomain });
  148. domainAliveMap.set(apexDomain, false);
  149. return [apexDomain, false];
  150. }
  151. return [apexDomain, true];
  152. }
  153. if (!('dns' in whois)) {
  154. console.log({ whois });
  155. }
  156. console.log(picocolors.red('[domain dead]'), 'whois not found', { domain: apexDomain });
  157. domainAliveMap.set(apexDomain, false);
  158. return [apexDomain, false];
  159. }
  160. export async function isDomainAlive(domain: string, isSuffix: boolean): Promise<[string, boolean]> {
  161. if (domainAliveMap.has(domain)) {
  162. return [domain, domainAliveMap.get(domain)!];
  163. }
  164. const apexDomain = tldts.getDomain(domain, looseTldtsOpt);
  165. if (!apexDomain) {
  166. console.log('[domain invalid]', 'no apex domain', { domain });
  167. domainAliveMap.set(domain, true);
  168. return [domain, true] as const;
  169. }
  170. const apexDomainAlive = await isApexDomainAlive(apexDomain);
  171. if (!apexDomainAlive[1]) {
  172. domainAliveMap.set(domain, false);
  173. return [domain, false] as const;
  174. }
  175. const $domain = domain[0] === '.' ? domain.slice(1) : domain;
  176. if (!isSuffix) {
  177. const aDns: string[] = [];
  178. const aaaaDns: string[] = [];
  179. // test 2 times before make sure record is empty
  180. for (let i = 0; i < 2; i++) {
  181. // eslint-disable-next-line no-await-in-loop -- sequential
  182. const aRecords = (await resolve($domain, 'A'));
  183. if (aRecords.answers.length !== 0) {
  184. domainAliveMap.set(domain, true);
  185. return [domain, true] as const;
  186. }
  187. aDns.push(aRecords.dns);
  188. }
  189. for (let i = 0; i < 2; i++) {
  190. // eslint-disable-next-line no-await-in-loop -- sequential
  191. const aaaaRecords = (await resolve($domain, 'AAAA'));
  192. if (aaaaRecords.answers.length !== 0) {
  193. domainAliveMap.set(domain, true);
  194. return [domain, true] as const;
  195. }
  196. aaaaDns.push(aaaaRecords.dns);
  197. }
  198. // only then, let's test once with domesticDohServers
  199. const aRecords = (await domesticResolve($domain, 'A'));
  200. if (aRecords.answers.length !== 0) {
  201. domainAliveMap.set(domain, true);
  202. return [domain, true] as const;
  203. }
  204. aDns.push(aRecords.dns);
  205. const aaaaRecords = (await domesticResolve($domain, 'AAAA'));
  206. if (aaaaRecords.answers.length !== 0) {
  207. domainAliveMap.set(domain, true);
  208. return [domain, true] as const;
  209. }
  210. aaaaDns.push(aaaaRecords.dns);
  211. console.log(picocolors.red('[domain dead]'), 'no A/AAAA records', { domain, a: aDns, aaaa: aaaaDns });
  212. }
  213. domainAliveMap.set($domain, false);
  214. return [domain, false] as const;
  215. }
  216. export async function runAgainstRuleset(filepath: string) {
  217. const extname = path.extname(filepath);
  218. if (extname !== '.conf') {
  219. console.log('[skip]', filepath);
  220. return;
  221. }
  222. const promises: Array<Promise<[string, boolean]>> = [];
  223. for await (const l of readFileByLine(filepath)) {
  224. const line = processLine(l);
  225. if (!line) continue;
  226. const [type, domain] = line.split(',');
  227. switch (type) {
  228. case 'DOMAIN-SUFFIX':
  229. case 'DOMAIN': {
  230. promises.push(keyedAsyncMutexWithQueue(domain, () => isDomainAlive(domain, type === 'DOMAIN-SUFFIX')));
  231. break;
  232. }
  233. // no default
  234. }
  235. }
  236. await Promise.all(promises);
  237. console.log('[done]', filepath);
  238. }
  239. export async function runAgainstDomainset(filepath: string) {
  240. const extname = path.extname(filepath);
  241. if (extname !== '.conf') {
  242. console.log('[skip]', filepath);
  243. return;
  244. }
  245. const promises: Array<Promise<[string, boolean]>> = [];
  246. for await (const l of readFileByLine(filepath)) {
  247. const line = processLine(l);
  248. if (!line) continue;
  249. promises.push(keyedAsyncMutexWithQueue(line, () => isDomainAlive(line, line[0] === '.')));
  250. }
  251. await Promise.all(promises);
  252. console.log('[done]', filepath);
  253. }