Full Toolkit for Next-Level Domain Analysis
Add more tests π¨βπ¬
Felix Wotschofsky6d627e02c2d9
diff --git a/app/lookup/[domain]/map/page.tsx b/app/lookup/[domain]/map/page.tsxindex 23961da..0a93256 100644--- a/app/lookup/[domain]/map/page.tsx+++ b/app/lookup/[domain]/map/page.tsx@@ -5,6 +5,7 @@ import type { FC } from 'react';import { isUserBot } from '@/lib/api';import { getGlobalLookupResults, getHasDifferences } from '@/lib/map';+import { InternalDoHResolver } from '@/lib/resolvers/internal';import { BaseAlert } from './_components/base-alert';import { ResultsGlobe } from './_components/results-globe';@@ -45,7 +46,10 @@ const MapResultsPage: FC<MapResultsPageProps> = async ({);}- const lookupResults = await getGlobalLookupResults(domain);+ const lookupResults = await getGlobalLookupResults(+ domain,+ (code) => new InternalDoHResolver(code, 'cloudflare')+ );const hasDifferences = getHasDifferences(lookupResults.map((m) => m.results));return (@@ -64,7 +68,9 @@ const MapResultsPage: FC<MapResultsPageProps> = async ({</BaseAlert>)}- <ResultsGlobe domain={domain} markers={lookupResults} />+ <div className="mx-[-2rem]">+ <ResultsGlobe domain={domain} markers={lookupResults} />+ </div></>);};diff --git a/lib/api.test.ts b/lib/api.test.tsnew file mode 100644index 0000000..d313879--- /dev/null+++ b/lib/api.test.ts@@ -0,0 +1,57 @@+import { describe, expect, it } from 'vitest';++import { getVisitorIp, isUserBot } from './api';++describe('getVisitorIp', () => {+ it('should extract the first IP from x-forwarded-for', () => {+ const headers = new Headers({+ 'x-forwarded-for': '192.168.1.1, 192.168.1.2',+ });++ const ip = getVisitorIp(headers);+ expect(ip).toBe('192.168.1.1');+ });++ it('should default to 127.0.0.1 if x-forwarded-for is not present', () => {+ const headers = new Headers();++ const ip = getVisitorIp(headers);+ expect(ip).toBe('127.0.0.1');+ });+});++describe('isUserBot', () => {+ it('should identify a user as a bot based on user-agent', () => {+ const headers = new Headers({+ 'User-Agent':+ 'Mozilla/5.0 (compatible; Googlebot/2.1; +http://www.google.com/bot.html)',+ });++ const { isBot, userAgent } = isUserBot(headers);+ expect(isBot).toBe(true);+ expect(userAgent).toBe(+ 'Mozilla/5.0 (compatible; Googlebot/2.1; +http://www.google.com/bot.html)'+ );+ });++ it('should identify a human user based on user-agent', () => {+ const headers = new Headers({+ 'User-Agent':+ 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.36',+ });++ const { isBot, userAgent } = isUserBot(headers);+ expect(isBot).toBe(false);+ expect(userAgent).toBe(+ 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.36'+ );+ });++ it('should default to isBot=true when user-agent header is missing', () => {+ const headers = new Headers();++ const { isBot, userAgent } = isUserBot(headers);+ expect(isBot).toBe(true);+ expect(userAgent).toBeNull();+ });+});diff --git a/lib/ips.test.ts b/lib/ips.test.tsindex cff8e9a..91431eb 100644--- a/lib/ips.test.ts+++ b/lib/ips.test.ts@@ -1,6 +1,75 @@-import { describe, expect, it } from 'vitest';+import { describe, expect, it, vi } from 'vitest';-import { normalizeIpEnding } from './ips';+import {+ ipToDnsName,+ ipv4ToDnsName,+ ipv6ToDnsName,+ lookupReverse,+ normalizeIpEnding,+} from './ips';++describe('ipv4ToDnsName', () => {+ it('should convert an IPv4 address to a reverse DNS lookup format', () => {+ expect(ipv4ToDnsName('8.8.8.8')).toBe('8.8.8.8.in-addr.arpa');+ });+});++describe('ipv6ToDnsName', () => {+ it('should convert an IPv6 address to a reverse DNS lookup format', () => {+ expect(ipv6ToDnsName('2001:db8::1')).toBe(+ '1.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.8.b.d.0.1.0.0.2.ip6.arpa'+ );+ });+});++describe('ipToDnsName', () => {+ it('should convert an IPv4 address to a reverse DNS lookup format', () => {+ expect(ipToDnsName('8.8.8.8')).toBe('8.8.8.8.in-addr.arpa');+ });++ it('should convert an IPv6 address to a reverse DNS lookup format', () => {+ expect(ipToDnsName('2001:db8::1')).toBe(+ '1.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.8.b.d.0.1.0.0.2.ip6.arpa'+ );+ });+});++describe('lookupReverse', () => {+ it('should return an array of domain names from reverse DNS lookups', async () => {+ const fakeResponse = {+ json: vi.fn().mockResolvedValue({+ Answer: [{ data: 'dns.google.' }, { data: 'another.dns.google.' }],+ }),+ ok: true,+ };+ global.fetch = vi.fn().mockResolvedValue(fakeResponse);++ const results = await lookupReverse('8.8.8.8');+ expect(results).toEqual(['dns.google', 'another.dns.google']);+ });++ it('should return an empty array if no answers are found in the DNS lookup', async () => {+ const fakeResponse = {+ json: vi.fn().mockResolvedValue({}),+ ok: true,+ };+ global.fetch = vi.fn().mockResolvedValue(fakeResponse);++ const results = await lookupReverse('8.8.4.4');+ expect(results).toEqual([]);+ });++ it('should throw an error when the API call for DNS lookup fails', async () => {+ global.fetch = vi.fn().mockResolvedValue({+ ok: false,+ statusText: 'Service Unavailable',+ });++ await expect(lookupReverse('8.8.4.4')).rejects.toThrow(+ 'Error fetching DNS records: Service Unavailable'+ );+ });+});describe('normalizeIpEnding', () => {it('should normalize the last octet of an IPv4 address to .0', () => {diff --git a/lib/ips.ts b/lib/ips.tsindex f017a63..c2b5364 100644--- a/lib/ips.ts+++ b/lib/ips.ts@@ -28,10 +28,10 @@ export const getIpDetails = async (ip: string) => {return data as IpDetails;};-const ipv4ToDnsName = (ipv4: string) =>+export const ipv4ToDnsName = (ipv4: string) =>ipv4.split('.').reverse().join('.') + '.in-addr.arpa';-const ipv6ToDnsName = (ipv6: string) => {+export 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'));@@ -52,7 +52,7 @@ const ipv6ToDnsName = (ipv6: string) => {);};-const ipToDnsName = (ip: string) =>+export const ipToDnsName = (ip: string) =>ip.includes(':') ? ipv6ToDnsName(ip) : ipv4ToDnsName(ip);export const lookupReverse = async (ip: string): Promise<string[]> => {diff --git a/lib/map.test.ts b/lib/map.test.tsnew file mode 100644index 0000000..7cc891f--- /dev/null+++ b/lib/map.test.ts@@ -0,0 +1,77 @@+import { describe, expect, it, vi } from 'vitest';++import { getGlobalLookupResults, getHasDifferences } from './map';++vi.mock('./data', () => ({+ REGIONS: {+ fra: { lat: 50.033333, lng: 8.570556, name: 'π©πͺ Frankfurt, Germany' },+ iad: { lat: 38.944, lng: -77.456, name: 'πΊπΈ Washington, USA' },+ },+}));++const mockResolveRecordTypes = vi.fn().mockImplementation(() => ({+ A: [{ data: '1.2.3.4' }],+ AAAA: [{ data: '2001:0db8:85a3:0000:0000:8a2e:0370:7334' }],+ CNAME: [{ data: 'alias.example.com' }],+}));++const resolverFactory = vi.fn().mockImplementation(() => ({+ resolveRecordTypes: mockResolveRecordTypes,+}));++describe('getGlobalLookupResults', () => {+ it('should resolve DNS records for all regions and format results', async () => {+ const results = await getGlobalLookupResults(+ 'example.com',+ resolverFactory+ );+ expect(resolverFactory).toHaveBeenCalledTimes(2);+ expect(mockResolveRecordTypes).toHaveBeenCalledWith('example.com', [+ 'A',+ 'AAAA',+ 'CNAME',+ ]);+ expect(results).toEqual([+ {+ code: 'fra',+ lat: 50.033333,+ lng: 8.570556,+ name: 'π©πͺ Frankfurt, Germany',+ results: {+ A: ['1.2.3.4'],+ AAAA: ['2001:0db8:85a3:0000:0000:8a2e:0370:7334'],+ CNAME: ['alias.example.com'],+ },+ },+ {+ code: 'iad',+ lat: 38.944,+ lng: -77.456,+ name: 'πΊπΈ Washington, USA',+ results: {+ A: ['1.2.3.4'],+ AAAA: ['2001:0db8:85a3:0000:0000:8a2e:0370:7334'],+ CNAME: ['alias.example.com'],+ },+ },+ ]);+ });+});++describe('getHasDifferences', () => {+ it('should detect differences between DNS record sets', () => {+ const markers = [+ { A: ['1.2.3.4'], AAAA: ['2001:db8::1'], CNAME: ['alias.example.com'] },+ { A: ['1.2.3.5'], AAAA: ['2001:db8::1'], CNAME: ['alias.example.com'] },+ ];+ expect(getHasDifferences(markers)).toBe(true);+ });++ it('should detect no differences when all record sets are identical', () => {+ const markers = [+ { A: ['1.2.3.4'], AAAA: ['2001:db8::1'], CNAME: ['alias.example.com'] },+ { A: ['1.2.3.4'], AAAA: ['2001:db8::1'], CNAME: ['alias.example.com'] },+ ];+ expect(getHasDifferences(markers)).toBe(false);+ });+});diff --git a/lib/map.ts b/lib/map.tsindex fc96000..28f09aa 100644--- a/lib/map.ts+++ b/lib/map.ts@@ -1,13 +1,15 @@import { REGIONS } from '@/lib/data';-import { InternalDoHResolver } from '@/lib/resolvers/internal';+import type { DnsResolver } from '@/lib/resolvers/base';const DISPLAYED_RECORD_TYPES = ['A', 'AAAA', 'CNAME'] as const;-export const getGlobalLookupResults = (domain: string) =>+export const getGlobalLookupResults = (+ domain: string,+ resolverFactory: (regionCode: string) => DnsResolver+) =>Promise.all(Object.entries(REGIONS).map(async ([code, data]) => {- const resolver = new InternalDoHResolver(code, 'cloudflare');- // TODO Optimize this to only required records+ const resolver = resolverFactory(code);const results = await resolver.resolveRecordTypes(domain,DISPLAYED_RECORD_TYPESdiff --git a/lib/resolvers/internal.test.ts b/lib/resolvers/internal.test.tsnew file mode 100644index 0000000..d3a355e--- /dev/null+++ b/lib/resolvers/internal.test.ts@@ -0,0 +1,91 @@+import { afterAll, beforeAll, describe, expect, it, vi } from 'vitest';++import { InternalDoHResolver } from './internal';++global.fetch = vi.fn();++describe('InternalDoHResolver', () => {+ beforeAll(() => {+ vi.stubEnv('SITE_URL', 'https://example.com');+ vi.stubEnv('INTERNAL_API_SECRET', 'secret');+ });++ afterAll(() => {+ vi.unstubAllEnvs();+ });++ it('should successfully resolve DNS records', async () => {+ const resolver = new InternalDoHResolver('cdg', 'google');+ const mockRawRecord = [{ data: '192.168.1.1' }];+ const mockResponse = {+ ok: true,+ json: () => Promise.resolve({ A: mockRawRecord }),+ status: 200,+ statusText: 'OK',+ };++ vi.mocked(fetch).mockResolvedValue(mockResponse as Response);++ const records = await resolver.resolveRecordType('example.com', 'A');+ expect(records).toEqual(mockRawRecord);+ expect(fetch).toHaveBeenCalledWith(+ new URL(+ 'https://example.com/api/internal/resolve/cdg?resolver=google&type=A&domain=example.com'+ ),+ {+ headers: {+ Authorization: 'secret',+ },+ }+ );+ });++ it('should throw an error on failed DNS resolution', async () => {+ const resolver = new InternalDoHResolver('lhr', 'google');+ const mockResponse = {+ ok: false,+ status: 500,+ statusText: 'Internal Server Error',+ };++ vi.mocked(fetch).mockResolvedValue(mockResponse as Response);++ await expect(+ resolver.resolveRecordType('example.com', 'A')+ ).rejects.toThrow(+ 'Failed to fetch results for lhr from https://example.com/api/internal/resolve/lhr?resolver=google&type=A&domain=example.com: 500 Internal Server Error'+ );+ });++ it('should handle multiple DNS record types', async () => {+ const resolver = new InternalDoHResolver('hkg', 'cloudflare');+ const mockRecords = {+ A: [{ data: '192.168.1.1' }],+ AAAA: [{ data: '::1' }],+ };+ const mockResponse = {+ ok: true,+ json: () => Promise.resolve(mockRecords),+ status: 200,+ statusText: 'OK',+ };++ vi.mocked(fetch).mockResolvedValue(mockResponse as Response);++ const records = await resolver.resolveRecordTypes('example.com', [+ 'A',+ 'AAAA',+ ]);+ expect(records).toEqual(mockRecords);+ expect(fetch).toHaveBeenCalledWith(+ new URL(+ 'https://example.com/api/internal/resolve/hkg?resolver=cloudflare&type=A&type=AAAA&domain=example.com'+ ),+ {+ headers: {+ Authorization: 'secret',+ },+ }+ );+ });+});diff --git a/lib/resolvers/utils.test.ts b/lib/resolvers/utils.test.tsnew file mode 100644index 0000000..ee7099c--- /dev/null+++ b/lib/resolvers/utils.test.ts@@ -0,0 +1,44 @@+import { describe, expect, it } from 'vitest';++import { AuthoritativeResolver } from './authoritative';+import { CloudflareDoHResolver } from './cloudflare';+import { GoogleDoHResolver } from './google';+import { InternalDoHResolver } from './internal';+import { getResolverFromName } from './utils';++describe('getResolverFromName', () => {+ it('should return an instance of CloudflareDoHResolver when resolver name is "cloudflare" and location is undefined', () => {+ const resolver = getResolverFromName('cloudflare', undefined);+ expect(resolver).toBeInstanceOf(CloudflareDoHResolver);+ });++ it('should return an instance of GoogleDoHResolver when resolver name is "google" and location is undefined', () => {+ const resolver = getResolverFromName('google', undefined);+ expect(resolver).toBeInstanceOf(GoogleDoHResolver);+ });++ it('should return an instance of AuthoritativeResolver when resolver name is not recognized and location is undefined', () => {+ const resolver = getResolverFromName('unknown', undefined);+ expect(resolver).toBeInstanceOf(AuthoritativeResolver);+ });++ it('should return an instance of InternalDoHResolver with type "cloudflare" when resolver name is "cloudflare" and location is defined', () => {+ const resolver = getResolverFromName('cloudflare', 'sfo1');+ expect(resolver).toBeInstanceOf(InternalDoHResolver);+ expect(resolver).toHaveProperty('resolver', 'cloudflare');+ expect(resolver).toHaveProperty('location', 'sfo1');+ });++ it('should return an instance of InternalDoHResolver with type "google" when resolver name is "google" and location is defined', () => {+ const resolver = getResolverFromName('google', 'iad1');+ expect(resolver).toBeInstanceOf(InternalDoHResolver);+ expect(resolver).toHaveProperty('resolver', 'google');+ expect(resolver).toHaveProperty('location', 'iad1');+ });++ it('should throw an error when an invalid resolver name is provided and location is defined', () => {+ expect(() => getResolverFromName('invalid', 'iad1')).toThrow(+ 'Invalid resolver'+ );+ });+});diff --git a/vitest.config.ts b/vitest.config.tsindex a9f5456..c18e174 100644--- a/vitest.config.ts+++ b/vitest.config.ts@@ -3,5 +3,8 @@ import { defineConfig } from 'vitest/config';export default defineConfig({test: {environment: 'happy-dom',+ alias: {+ '@/': new URL('./', import.meta.url).pathname,+ },},});