Full Toolkit for Next-Level Domain Analysis
Move further logic into lib folder 🏗️
Felix Wotschofsky2cafe9a8792f
diff --git a/app/api/lookup-ip/route.ts b/app/api/lookup-ip/route.tsindex 31db439..f4dc18e 100644--- a/app/api/lookup-ip/route.ts+++ b/app/api/lookup-ip/route.ts@@ -2,66 +2,15 @@ import { NextResponse } from 'next/server';import isIP from 'validator/lib/isIP';import { applyRateLimit } from '@/lib/api';-import { getIpDetails } from '@/lib/ips';+import { getIpDetails, lookupReverse } from '@/lib/ips';export const runtime = 'edge';-export type IpLookupResponse = {- city: string;- country: string;- isp: string;- lat: number;- lon: number;- org: string;- region: string;+export type IpLookupResponse = Pick<+ Awaited<ReturnType<typeof getIpDetails>>,+ 'city' | 'country' | 'isp' | 'lat' | 'lon' | 'org' | 'region' | 'timezone'+> & {reverse: string[];- timezone: string;-};--const ipv4ToDnsName = (ipv4: string) =>- ipv4.split('.').reverse().join('.') + '.in-addr.arpa';--const ipv6ToDnsName = (ipv6: string) => {- const segments = ipv6.split(':');- const missingSegments = 8 - segments.length + (ipv6.includes('::') ? 1 : 0);- const expandedSegments = segments.map((segment) => segment.padStart(4, '0'));- for (let i = 0; i < missingSegments; i++) {- expandedSegments.splice(segments.indexOf(''), 0, '0000');- }- const fullAddress = expandedSegments.join('');-- return (- fullAddress- .split('')- .reverse()- .join('.')- .replace(/:/g, '')- .split('.')- .filter((x) => x)- .join('.') + '.ip6.arpa'- );-};--const lookupReverse = async (ip: string): Promise<string[]> => {- const reverseDnsName = ip.includes(':')- ? ipv6ToDnsName(ip)- : ipv4ToDnsName(ip);-- const response = await fetch(- `https://cloudflare-dns.com/dns-query?name=${reverseDnsName}&type=PTR`,- {- headers: { Accept: 'application/dns-json' },- }- );-- if (!response.ok)- throw new Error(`Error fetching DNS records: ${response.statusText}`);-- const data = await response.json();-- return data.Answer- ? data.Answer.map((record: { data: string }) => record.data.slice(0, -1))- : [];};export async function GET(request: Request) {diff --git a/app/api/whois-summary/route.ts b/app/api/whois-summary/route.tsindex b48f12f..20d0086 100644--- a/app/api/whois-summary/route.ts+++ b/app/api/whois-summary/route.ts@@ -1,91 +1,9 @@-import { getDomain } from 'tldts';-import whoiser, { type WhoisSearchResult } from 'whoiser';-import { applyRateLimit } from '@/lib/api';-import { isValidDomain } from '@/lib/utils';--const UNREGISTERED_INDICATORS = [- 'no data found',- 'no match',- 'no object found',- 'not been registered',- 'not found',- 'status: free',-];--export type WhoisSummaryResponse =- | {- registered: false;- }- | {- registered: true;- registrar: string | null;- createdAt: string | null;- dnssec: string | null;- };+import { getWhoisSummary } from '@/lib/whois';+export type WhoisSummaryResponse = Awaited<ReturnType<typeof getWhoisSummary>>;export type WhoisSummaryErrorResponse = { error: true; message: string };-const getSummary = async (domain: string): Promise<WhoisSummaryResponse> => {- // TODO Allow resolving for TLDs- if (!isValidDomain(domain)) {- return {- registered: true,- registrar: null,- createdAt: null,- dnssec: null,- };- }-- const rawDomain = getDomain(domain) || domain;-- try {- const results = await whoiser(rawDomain, {- timeout: 5000,- raw: true,- });-- const resultsKey = Object.keys(results).find(- // @ts-expect-error- (key) => !('error' in results[key])- );- if (!resultsKey) {- throw new Error('No valid results found for domain ' + domain);- }- const firstResult = results[resultsKey] as WhoisSearchResult;-- if (- UNREGISTERED_INDICATORS.some((indicator) =>- firstResult['__raw'].toString().toLowerCase().includes(indicator)- )- ) {- return {- registered: false,- };- }-- return {- registered: true,- registrar: firstResult['Registrar']?.toString(),- createdAt:- firstResult && 'Created Date' in firstResult- ? new Date(firstResult['Created Date'].toString()).toLocaleDateString(- 'en-US'- )- : null,- dnssec: firstResult['DNSSEC']?.toString(),- };- } catch (error) {- console.error(error);- return {- registered: true,- registrar: null,- createdAt: null,- dnssec: null,- };- }-};-export async function GET(request: Request) {const { searchParams } = new URL(request.url);const domain = searchParams.get('domain');@@ -112,7 +30,7 @@ export async function GET(request: Request) {}try {- const summary = await getSummary(domain);+ const summary = await getWhoisSummary(domain);return Response.json(summary, {headers: {'Cache-Control': 'public, max-age=600, s-maxage=1800',diff --git a/app/lookup/[domain]/(dns)/_components/dns-table.tsx b/app/lookup/[domain]/(dns)/_components/dns-table.tsxindex 4063f40..1eaec01 100644--- a/app/lookup/[domain]/(dns)/_components/dns-table.tsx+++ b/app/lookup/[domain]/(dns)/_components/dns-table.tsx@@ -9,15 +9,15 @@ import {TableRow,} from '@/components/ui/table';+import type { RecordContextEntry } from '@/lib/record-context';import type { ResolvedRecords } from '@/lib/resolvers/base';import { RecordRow } from './record-row';-import type { SubvalueInfo } from './record-subvalues';import { StackedRecord } from './stacked-record';type DnsTableProps = {records: ResolvedRecords;- subvalues: Record<string, SubvalueInfo[]>;+ subvalues: Record<string, RecordContextEntry[]>;};export const DnsTable: FC<DnsTableProps> = ({ records, subvalues }) => (diff --git a/app/lookup/[domain]/(dns)/_components/record-row.tsx b/app/lookup/[domain]/(dns)/_components/record-row.tsxindex 4976ade..d2989a7 100644--- a/app/lookup/[domain]/(dns)/_components/record-row.tsx+++ b/app/lookup/[domain]/(dns)/_components/record-row.tsx@@ -3,11 +3,12 @@ import reactStringReplace from 'react-string-replace';import { TableCell, TableRow } from '@/components/ui/table';+import type { RecordContextEntry } from '@/lib/record-context';import { cn } from '@/lib/utils';import { DomainLink } from '../../_components/domain-link';import { IpLink } from '../../_components/ip-link';-import { RecordSubvalues, type SubvalueInfo } from './record-subvalues';+import { RecordSubvalues } from './record-subvalues';const DOMAIN_REGEX = /([a-zA-Z0-9-_]+\.)+[a-z]+\.?/gi;const IPV4_REGEX = /(\d{1,3}\.){3}\d{1,3}/g;@@ -18,7 +19,7 @@ type RecordRowProps = {name: string;TTL: number;value: string;- subvalues?: SubvalueInfo[];+ subvalues?: RecordContextEntry[];};export const RecordRow: FC<RecordRowProps> = ({diff --git a/app/lookup/[domain]/(dns)/_components/record-subvalues.tsx b/app/lookup/[domain]/(dns)/_components/record-subvalues.tsxindex ae1f73c..5c6df14 100644--- a/app/lookup/[domain]/(dns)/_components/record-subvalues.tsx+++ b/app/lookup/[domain]/(dns)/_components/record-subvalues.tsx@@ -1,12 +1,9 @@import type { FC } from 'react';-export type SubvalueInfo = {- description: string;- url?: string;-};+import type { RecordContextEntry } from '@/lib/record-context';type RecordSubvaluesProps = {- subvalues: SubvalueInfo[];+ subvalues: RecordContextEntry[];};export const RecordSubvalues: FC<RecordSubvaluesProps> = ({ subvalues }) => (diff --git a/app/lookup/[domain]/(dns)/_components/stacked-record.tsx b/app/lookup/[domain]/(dns)/_components/stacked-record.tsxindex 0826ca3..2b4bfd3 100644--- a/app/lookup/[domain]/(dns)/_components/stacked-record.tsx+++ b/app/lookup/[domain]/(dns)/_components/stacked-record.tsx@@ -1,9 +1,11 @@import type { FC, ReactNode } from 'react';import reactStringReplace from 'react-string-replace';+import type { RecordContextEntry } from '@/lib/record-context';+import { DomainLink } from '../../_components/domain-link';import { IpLink } from '../../_components/ip-link';-import { RecordSubvalues, type SubvalueInfo } from './record-subvalues';+import { RecordSubvalues } from './record-subvalues';const DOMAIN_REGEX = /([a-zA-Z0-9-_]+\.)+[a-z]+\.?/gi;const IPV4_REGEX = /(\d{1,3}\.){3}\d{1,3}/g;@@ -14,7 +16,7 @@ type StackedRecordProps = {name: string;TTL: number;value: string;- subvalues?: SubvalueInfo[];+ subvalues?: RecordContextEntry[];};export const StackedRecord: FC<StackedRecordProps> = ({diff --git a/app/lookup/[domain]/(dns)/page.tsx b/app/lookup/[domain]/(dns)/page.tsxindex a810430..bdefa30 100644--- a/app/lookup/[domain]/(dns)/page.tsx+++ b/app/lookup/[domain]/(dns)/page.tsx@@ -2,92 +2,13 @@ import type { Metadata } from 'next';import { redirect, RedirectType } from 'next/navigation';import type { FC } from 'react';-import { RECORD_INSIGHTS } from '@/lib/data';-import { hostLookupLoader } from '@/lib/ips';-import { AuthoritativeResolver } from '@/lib/resolvers/authoritative';-import type { ResolvedRecords } from '@/lib/resolvers/base';-import { CloudflareDoHResolver } from '@/lib/resolvers/cloudflare';-import { GoogleDoHResolver } from '@/lib/resolvers/google';-import { InternalDoHResolver } from '@/lib/resolvers/internal';+import { getRecordContextEntries } from '@/lib/record-context';+import { getResolverFromName } from '@/lib/resolvers/utils';import { DnsTable } from './_components/dns-table';import { LocationSelector } from './_components/location-selector';-import type { SubvalueInfo } from './_components/record-subvalues';import { ResolverSelector } from './_components/resolver-selector';-const getResolver = (- resolverName: string | undefined,- locationName: string | undefined-) => {- if (locationName) {- switch (resolverName) {- case 'cloudflare':- return new InternalDoHResolver(locationName, 'cloudflare');- case 'google':- return new InternalDoHResolver(locationName, 'google');- }-- throw new Error('Invalid resolver');- }-- switch (resolverName) {- case 'cloudflare':- return new CloudflareDoHResolver();- case 'google':- return new GoogleDoHResolver();- default:- return new AuthoritativeResolver();- }-};--const getIpsInfo = async (ips: string[]): Promise<Record<string, string[]>> => {- const hosts = await hostLookupLoader.loadMany(ips);- return Object.fromEntries(- ips- .map((ip, index) => [ip, hosts[index]])- .filter(([, hosts]) => Array.isArray(hosts))- );-};--const getSubvalues = async (records: ResolvedRecords) => {- const allSubvalues: Record<string, SubvalueInfo[]> = {};-- const ips = records.A.map((r) => r.data).concat(- records.AAAA.map((r) => r.data)- );- const ipsInfo = await getIpsInfo(ips);-- const flatRecords = Object.values(records).flat();- for (const record of flatRecords) {- const subvalues: SubvalueInfo[] = [];-- const normalizedRecord = record.data.endsWith('.')- ? record.data.slice(0, -1)- : record.data;-- const possibleInsights = RECORD_INSIGHTS[record.type];- for (const insight of possibleInsights) {- if (insight.test.test(normalizedRecord)) {- subvalues.push(insight);- }- }-- if (record.data in ipsInfo) {- subvalues.push(- ...ipsInfo[record.data].map((h) => ({- description: h,- }))- );- }-- if (subvalues.length > 0) {- allSubvalues[record.data] = subvalues;- }- }-- return allSubvalues;-};-type LookupDomainProps = {params: {domain: string;@@ -130,14 +51,12 @@ const LookupDomain: FC<LookupDomainProps> = async ({);}- const resolver = getResolver(resolverName, locationName);+ const resolver = getResolverFromName(resolverName, locationName);const records = await resolver.resolveAllRecords(domain);- const subvalues = await getSubvalues(records);+ const subvalues = await getRecordContextEntries(records);const hasResults =- Object.values(records)- .map((r) => r.length)- .reduce((prev, curr) => prev + curr, 0) > 0;+ Object.values(records).reduce((prev, curr) => prev + curr.length, 0) > 0;return (<>diff --git a/app/lookup/[domain]/certs/page.tsx b/app/lookup/[domain]/certs/page.tsxindex 7fb6272..956e000 100644--- a/app/lookup/[domain]/certs/page.tsx+++ b/app/lookup/[domain]/certs/page.tsx@@ -10,7 +10,7 @@ import {TableRow,} from '@/components/ui/table';-import { lookupCerts } from '@/lib/certs';+import { lookupRelatedCerts } from '@/lib/certs';import { isValidDomain } from '@/lib/utils';import { DomainLink } from '../_components/domain-link';@@ -19,28 +19,6 @@ export const runtime = 'edge';// crt.sh located in GB, always use LHR1 for lowest latencyexport const preferredRegion = 'lhr1';-const getRelatedCerts = async (domain: string) => {- const requests = [lookupCerts(domain)];-- const hasParentDomain = domain.split('.').filter(Boolean).length > 2;- if (hasParentDomain) {- const parentDomain = domain.split('.').slice(1).join('.');- requests.push(lookupCerts(`*.${parentDomain}`));- }-- const responses = await Promise.all(requests);-- const certs = responses- .flat()- .toSorted(- (a, b) =>- new Date(b.entry_timestamp).getTime() -- new Date(a.entry_timestamp).getTime()- );-- return certs;-};-type CertsResultsPageProps = {params: {domain: string;@@ -61,7 +39,7 @@ export const generateMetadata = ({const CertsResultsPage: FC<CertsResultsPageProps> = async ({params: { domain },}) => {- const certs = await getRelatedCerts(domain);+ const certs = await lookupRelatedCerts(domain);if (!certs.length) {return (diff --git a/app/lookup/[domain]/map/page.tsx b/app/lookup/[domain]/map/page.tsxindex 51ab49b..23961da 100644--- a/app/lookup/[domain]/map/page.tsx+++ b/app/lookup/[domain]/map/page.tsx@@ -4,54 +4,13 @@ import { headers } from 'next/headers';import type { FC } from 'react';import { isUserBot } from '@/lib/api';-import { REGIONS } from '@/lib/data';-import { InternalDoHResolver } from '@/lib/resolvers/internal';+import { getGlobalLookupResults, getHasDifferences } from '@/lib/map';import { BaseAlert } from './_components/base-alert';import { ResultsGlobe } from './_components/results-globe';export const runtime = 'edge';-const getMarkers = (domain: string) =>- Promise.all(- Object.entries(REGIONS).map(async ([code, data]) => {- const resolver = new InternalDoHResolver(code, 'cloudflare');- // TODO Optimize this to only required records- const results = await resolver.resolveAllRecords(domain);-- return {- ...data,- code,- results: {- A: results.A.map((r) => r.data),- AAAA: results.AAAA.map((r) => r.data),- CNAME: results.CNAME.map((r) => r.data),- },- };- })- );--const getHasDifferences = (- markers: { A: string[]; AAAA: string[]; CNAME: string[] }[]-) => {- let hasDifferentRecords = false;- for (let i = 1; i < markers.length; i++) {- const previous = markers[i - 1];- const current = markers[i];- if (- previous.A.toSorted().toString() !== current.A.toSorted().toString() ||- previous.AAAA.toSorted().toString() !==- current.AAAA.toSorted().toString() ||- previous.CNAME.toSorted().toString() !==- current.CNAME.toSorted().toString()- ) {- hasDifferentRecords = true;- break;- }- }- return hasDifferentRecords;-};-type MapResultsPageProps = {params: {domain: string;@@ -86,8 +45,8 @@ const MapResultsPage: FC<MapResultsPageProps> = async ({);}- const markers = await getMarkers(domain);- const hasDifferences = getHasDifferences(markers.map((m) => m.results));+ const lookupResults = await getGlobalLookupResults(domain);+ const hasDifferences = getHasDifferences(lookupResults.map((m) => m.results));return (<>@@ -105,7 +64,7 @@ const MapResultsPage: FC<MapResultsPageProps> = async ({</BaseAlert>)}- <ResultsGlobe domain={domain} markers={markers} />+ <ResultsGlobe domain={domain} markers={lookupResults} /></>);};diff --git a/app/lookup/[domain]/whois/page.tsx b/app/lookup/[domain]/whois/page.tsxindex 5258646..dffcb5c 100644--- a/app/lookup/[domain]/whois/page.tsx+++ b/app/lookup/[domain]/whois/page.tsx@@ -2,25 +2,8 @@ import type { Metadata } from 'next';import Link from 'next/link';import { type FC, Fragment } from 'react';import { getDomain } from 'tldts';-import whoiser, { type WhoisSearchResult } from 'whoiser';-const lookupWhois = async (domain: string) => {- const result = await whoiser(domain, {- raw: true,- timeout: 5000,- });-- const mappedResults: Record<string, string> = {};- for (const key in result) {- mappedResults[key] = (result[key] as WhoisSearchResult).__raw as string;- }-- const filteredResults = Object.entries(mappedResults).filter(- ([_key, value]) => Boolean(value)- );-- return filteredResults;-};+import { lookupWhois } from '@/lib/whois';type WhoisResultsPageProps = {params: {diff --git a/lib/certs.ts b/lib/certs.tsindex f2296f0..59de030 100644--- a/lib/certs.ts+++ b/lib/certs.ts@@ -25,3 +25,25 @@ export const lookupCerts = async (domain: string): Promise<CertsData> => {return await response.json();};++export const lookupRelatedCerts = async (domain: string) => {+ const requests = [lookupCerts(domain)];++ const hasParentDomain = domain.split('.').filter(Boolean).length > 2;+ if (hasParentDomain) {+ const parentDomain = domain.split('.').slice(1).join('.');+ requests.push(lookupCerts(`*.${parentDomain}`));+ }++ const responses = await Promise.all(requests);++ const certs = responses+ .flat()+ .toSorted(+ (a, b) =>+ new Date(b.entry_timestamp).getTime() -+ new Date(a.entry_timestamp).getTime()+ );++ return certs;+};diff --git a/lib/ips.ts b/lib/ips.tsindex 160fa88..f017a63 100644--- a/lib/ips.ts+++ b/lib/ips.ts@@ -28,6 +28,53 @@ export const getIpDetails = async (ip: string) => {return data as IpDetails;};+const ipv4ToDnsName = (ipv4: string) =>+ ipv4.split('.').reverse().join('.') + '.in-addr.arpa';++const ipv6ToDnsName = (ipv6: string) => {+ const segments = ipv6.split(':');+ const missingSegments = 8 - segments.length + (ipv6.includes('::') ? 1 : 0);+ const expandedSegments = segments.map((segment) => segment.padStart(4, '0'));+ for (let i = 0; i < missingSegments; i++) {+ expandedSegments.splice(segments.indexOf(''), 0, '0000');+ }+ const fullAddress = expandedSegments.join('');++ return (+ fullAddress+ .split('')+ .reverse()+ .join('.')+ .replace(/:/g, '')+ .split('.')+ .filter((x) => x)+ .join('.') + '.ip6.arpa'+ );+};++const ipToDnsName = (ip: string) =>+ ip.includes(':') ? ipv6ToDnsName(ip) : ipv4ToDnsName(ip);++export const lookupReverse = async (ip: string): Promise<string[]> => {+ const reverseDnsName = ipToDnsName(ip);++ const response = await fetch(+ `https://cloudflare-dns.com/dns-query?name=${reverseDnsName}&type=PTR`,+ {+ headers: { Accept: 'application/dns-json' },+ }+ );++ if (!response.ok)+ throw new Error(`Error fetching DNS records: ${response.statusText}`);++ const data = await response.json();++ return data.Answer+ ? data.Answer.map((record: { data: string }) => record.data.slice(0, -1))+ : [];+};+// Standardize last segment of IP address to reduce the number of requests and avoid rate limiting// 1st Regex is for IPv4// 2nd Regex is for IPv6diff --git a/lib/map.ts b/lib/map.tsnew file mode 100644index 0000000..9062248--- /dev/null+++ b/lib/map.ts@@ -0,0 +1,42 @@+import { REGIONS } from '@/lib/data';+import { InternalDoHResolver } from '@/lib/resolvers/internal';++export const getGlobalLookupResults = (domain: string) =>+ Promise.all(+ Object.entries(REGIONS).map(async ([code, data]) => {+ const resolver = new InternalDoHResolver(code, 'cloudflare');+ // TODO Optimize this to only required records+ const results = await resolver.resolveAllRecords(domain);++ return {+ ...data,+ code,+ results: {+ A: results.A.map((r) => r.data),+ AAAA: results.AAAA.map((r) => r.data),+ CNAME: results.CNAME.map((r) => r.data),+ },+ };+ })+ );++export const getHasDifferences = (+ markers: { A: string[]; AAAA: string[]; CNAME: string[] }[]+) => {+ let hasDifferentRecords = false;+ for (let i = 1; i < markers.length; i++) {+ const previous = markers[i - 1];+ const current = markers[i];+ if (+ previous.A.toSorted().toString() !== current.A.toSorted().toString() ||+ previous.AAAA.toSorted().toString() !==+ current.AAAA.toSorted().toString() ||+ previous.CNAME.toSorted().toString() !==+ current.CNAME.toSorted().toString()+ ) {+ hasDifferentRecords = true;+ break;+ }+ }+ return hasDifferentRecords;+};diff --git a/lib/record-context.ts b/lib/record-context.tsnew file mode 100644index 0000000..bc2bb74--- /dev/null+++ b/lib/record-context.ts@@ -0,0 +1,56 @@+import { RECORD_INSIGHTS } from './data';+import { hostLookupLoader } from './ips';+import type { ResolvedRecords } from './resolvers/base';++export type RecordContextEntry = {+ description: string;+ url?: string;+};++const getIpsInfo = async (ips: string[]): Promise<Record<string, string[]>> => {+ const hosts = await hostLookupLoader.loadMany(ips);+ return Object.fromEntries(+ ips+ .map((ip, index) => [ip, hosts[index]])+ .filter(([, hosts]) => Array.isArray(hosts))+ );+};++export const getRecordContextEntries = async (records: ResolvedRecords) => {+ const allSubvalues: Record<string, RecordContextEntry[]> = {};++ const ips = records.A.map((r) => r.data).concat(+ records.AAAA.map((r) => r.data)+ );+ const ipsInfo = await getIpsInfo(ips);++ const flatRecords = Object.values(records).flat();+ for (const record of flatRecords) {+ const subvalues: RecordContextEntry[] = [];++ const normalizedRecord = record.data.endsWith('.')+ ? record.data.slice(0, -1)+ : record.data;++ const possibleInsights = RECORD_INSIGHTS[record.type];+ for (const insight of possibleInsights) {+ if (insight.test.test(normalizedRecord)) {+ subvalues.push(insight);+ }+ }++ if (record.data in ipsInfo) {+ subvalues.push(+ ...ipsInfo[record.data].map((h) => ({+ description: h,+ }))+ );+ }++ if (subvalues.length > 0) {+ allSubvalues[record.data] = subvalues;+ }+ }++ return allSubvalues;+};diff --git a/lib/resolvers/utils.ts b/lib/resolvers/utils.tsnew file mode 100644index 0000000..14857e5--- /dev/null+++ b/lib/resolvers/utils.ts@@ -0,0 +1,29 @@+import { AuthoritativeResolver } from './authoritative';+import { CloudflareDoHResolver } from './cloudflare';+import { GoogleDoHResolver } from './google';+import { InternalDoHResolver } from './internal';++export const getResolverFromName = (+ resolverName: string | undefined,+ locationName: string | undefined+) => {+ if (locationName) {+ switch (resolverName) {+ case 'cloudflare':+ return new InternalDoHResolver(locationName, 'cloudflare');+ case 'google':+ return new InternalDoHResolver(locationName, 'google');+ }++ throw new Error('Invalid resolver');+ }++ switch (resolverName) {+ case 'cloudflare':+ return new CloudflareDoHResolver();+ case 'google':+ return new GoogleDoHResolver();+ default:+ return new AuthoritativeResolver();+ }+};diff --git a/lib/whois.ts b/lib/whois.tsnew file mode 100644index 0000000..fbd24bd--- /dev/null+++ b/lib/whois.ts@@ -0,0 +1,104 @@+import { getDomain } from 'tldts';+import whoiser, { type WhoisSearchResult } from 'whoiser';++import { isValidDomain } from './utils';++export const lookupWhois = async (domain: string) => {+ const result = await whoiser(domain, {+ raw: true,+ timeout: 5000,+ });++ const mappedResults: Record<string, string> = {};+ for (const key in result) {+ mappedResults[key] = (result[key] as WhoisSearchResult).__raw as string;+ }++ const filteredResults = Object.entries(mappedResults).filter(+ ([_key, value]) => Boolean(value)+ );++ return filteredResults;+};++const UNREGISTERED_INDICATORS = [+ 'no data found',+ 'no match',+ 'no object found',+ 'not been registered',+ 'not found',+ 'status: free',+];++type WhoisSummary =+ | {+ registered: false;+ }+ | {+ registered: true;+ registrar: string | null;+ createdAt: string | null;+ dnssec: string | null;+ };++export const getWhoisSummary = async (+ domain: string+): Promise<WhoisSummary> => {+ // TODO Allow resolving for TLDs+ if (!isValidDomain(domain)) {+ return {+ registered: true,+ registrar: null,+ createdAt: null,+ dnssec: null,+ };+ }++ const rawDomain = getDomain(domain) || domain;++ try {+ const results = await whoiser(rawDomain, {+ timeout: 5000,+ raw: true,+ });++ const resultsKey = Object.keys(results).find(+ // @ts-expect-error+ (key) => !('error' in results[key])+ );+ if (!resultsKey) {+ throw new Error('No valid results found for domain ' + domain);+ }+ const firstResult = results[resultsKey] as WhoisSearchResult;++ if (+ UNREGISTERED_INDICATORS.some((indicator) =>+ firstResult['__raw'].toString().toLowerCase().includes(indicator)+ )+ ) {+ return {+ registered: false,+ };+ }++ return {+ registered: true,+ registrar: firstResult['Registrar']?.toString(),+ createdAt:+ firstResult && 'Created Date' in firstResult+ ? new Date(firstResult['Created Date'].toString()).toLocaleDateString(+ 'en-US'+ )+ : null,+ dnssec: firstResult['DNSSEC']?.toString(),+ };+ } catch (error) {+ console.error(error);+ return {+ registered: true,+ registrar: null,+ createdAt: null,+ dnssec: null,+ };+ }+};