From edcc27f8569d4f7071b0b0d66ff63c8ed0b43924 Mon Sep 17 00:00:00 2001 From: Alicia Sykes Date: Tue, 7 Oct 2025 18:58:43 +0100 Subject: [PATCH] Completed dns perf analyzer --- .../components/tools/IPv6SolicitedNode.svelte | 4 +- .../components/tools/PTRSweepPlanner.svelte | 2 +- src/lib/constants/icon-map.ts | 54 ++-- src/lib/content/dns-performance.ts | 18 +- .../diagnostics/dns-performance/+server.ts | 19 +- .../dns/query-performance/+page.svelte | 262 ++++++++++++------ src/styles/variables.scss | 2 +- 7 files changed, 233 insertions(+), 128 deletions(-) diff --git a/src/lib/components/tools/IPv6SolicitedNode.svelte b/src/lib/components/tools/IPv6SolicitedNode.svelte index 2a5fc07..ab72fdb 100644 --- a/src/lib/components/tools/IPv6SolicitedNode.svelte +++ b/src/lib/components/tools/IPv6SolicitedNode.svelte @@ -267,7 +267,7 @@ for="ipv6-input" use:tooltip={'Enter a valid IPv6 unicast address (not multicast) to calculate its solicited-node multicast address'} > - + IPv6 Unicast Address
- + Unicast Address
diff --git a/src/lib/components/tools/PTRSweepPlanner.svelte b/src/lib/components/tools/PTRSweepPlanner.svelte index 27abb4b..e1b8795 100644 --- a/src/lib/components/tools/PTRSweepPlanner.svelte +++ b/src/lib/components/tools/PTRSweepPlanner.svelte @@ -447,7 +447,7 @@ {#if namingPattern.trim() && results.analysis.patternMatches < results.analysis.totalAddresses - results.analysis.missingPTRs.length}
- + Fix Naming Pattern Violations
diff --git a/src/lib/constants/icon-map.ts b/src/lib/constants/icon-map.ts index d3c0de7..46226e3 100644 --- a/src/lib/constants/icon-map.ts +++ b/src/lib/constants/icon-map.ts @@ -253,33 +253,33 @@ export const iconMap: Record = { 'dnssec-chain': ``, signature: ``, blacklist: ``, + 'info-circle': ``, // '': ``, - // pie-chart - // help-circle - // balance-scale - // code - // test - // performance - // security - // globe-2 - // users - // list-ordered - // tunnel - // user - // flag - // book-open - // shuffle - // template - // share - // list-checks - // clipboard-list - // edit-3 - // mail-check - // eye - // star - // wifi - // play-circle - // formula - // default + // 'pie-chart': ``, + // 'help-circle': ``, + // 'balance-scale': ``, + // 'code': ``, + // 'test': ``, + // 'performance': ``, + // 'security': ``, + // 'users': ``, + // 'list-ordered': ``, + // 'tunnel': ``, + // 'user': ``, + // 'flag': ``, + // 'book-open': ``, + // 'shuffle': ``, + // 'template': ``, + // 'share': ``, + // 'list-checks': ``, + // 'clipboard-list': ``, + // 'edit-3': ``, + // 'mail-check': ``, + // 'eye': ``, + // 'star': ``, + // 'wifi': ``, + // 'play-circle': ``, + // 'formula': ``, + // 'default': ``, }; diff --git a/src/lib/content/dns-performance.ts b/src/lib/content/dns-performance.ts index 9a401cd..9068fce 100644 --- a/src/lib/content/dns-performance.ts +++ b/src/lib/content/dns-performance.ts @@ -75,42 +75,48 @@ A slow DNS resolver can add hundreds of milliseconds to every page load, making title: 'Public DNS Resolvers', resolvers: [ { - name: 'Cloudflare (1.1.1.1)', + name: 'Cloudflare', + ip: '1.1.1.1', description: 'Privacy-focused, claims to be fastest', pros: ['Very fast', 'Strong privacy policy', 'No logging', 'Global anycast network'], cons: ['Relatively new (2018)', 'Some ISPs may block it'], bestFor: 'Privacy-conscious users wanting speed', }, { - name: 'Google (8.8.8.8)', + name: 'Google', + ip: '8.8.8.8', description: 'Most widely used public resolver', pros: ['Excellent reliability', 'Fast response times', 'Good global coverage', 'Well-established'], cons: ['Privacy concerns (Google)', 'Logs queries', 'May track usage'], bestFor: 'Users prioritizing reliability over privacy', }, { - name: 'Quad9 (9.9.9.9)', + name: 'Quad9', + ip: '9.9.9.9', description: 'Security and privacy focused', pros: ['Blocks malware domains', 'No logging', 'Privacy-focused', 'Threat intelligence'], cons: ['Slightly slower than top competitors', 'Blocking may cause issues'], bestFor: 'Security-conscious users', }, { - name: 'OpenDNS (208.67.222.222)', + name: 'OpenDNS', + ip: '208.67.222.222', description: 'Cisco-owned, customizable filtering', pros: ['Content filtering options', 'Phishing protection', 'Reliable', 'Dashboard for monitoring'], cons: ['Logs queries', 'Redirects NXDOMAIN', 'Can be slower'], bestFor: 'Families wanting content filtering', }, { - name: 'ControlD (76.76.2.0)', + name: 'ControlD', + ip: '76.76.2.0', description: 'Modern resolver with extensive customization', pros: ['Highly customizable', 'Multiple blocking lists', 'Fast', 'Detailed analytics'], cons: ['Newer service', 'Some features require account', 'Less proven'], bestFor: 'Advanced users wanting control', }, { - name: 'AdGuard (94.140.14.14)', + name: 'AdGuard', + ip: '94.140.14.14', description: 'Ad-blocking DNS service', pros: ['Blocks ads and trackers', 'Privacy-focused', 'No logging', 'Multiple variants'], cons: ['May break some sites', 'Can be slower', 'Aggressive blocking'], diff --git a/src/routes/api/internal/diagnostics/dns-performance/+server.ts b/src/routes/api/internal/diagnostics/dns-performance/+server.ts index 5f9a8c4..93de09d 100644 --- a/src/routes/api/internal/diagnostics/dns-performance/+server.ts +++ b/src/routes/api/internal/diagnostics/dns-performance/+server.ts @@ -43,6 +43,8 @@ const RESOLVERS = [ const DNS_TIMEOUT_MS = 5000; const RECORD_TYPES = ['A', 'AAAA', 'MX', 'TXT', 'NS', 'CNAME', 'SOA'] as const; +const MAX_DOMAIN_LENGTH = 253; +const DOMAIN_PATTERN = /^([a-zA-Z0-9_]([a-zA-Z0-9_-]{0,61}[a-zA-Z0-9_])?\.)+[a-zA-Z]{2,}$/; function withTimeout(promise: Promise, ms = DNS_TIMEOUT_MS): Promise { return Promise.race([ @@ -53,6 +55,11 @@ function withTimeout(promise: Promise, ms = DNS_TIMEOUT_MS): Promise { ]); } +function validateDomain(domain: string): boolean { + if (!domain || domain.length > MAX_DOMAIN_LENGTH) return false; + return DOMAIN_PATTERN.test(domain); +} + async function queryResolver( domain: string, recordType: string, @@ -104,7 +111,12 @@ async function queryResolver( export const POST: RequestHandler = async ({ request }) => { try { - const body: DNSPerformanceRequest = await request.json(); + let body: DNSPerformanceRequest; + try { + body = await request.json(); + } catch { + throw error(400, 'Invalid JSON in request body'); + } const { domain, recordType = 'A' } = body; if (!domain || typeof domain !== 'string' || !domain.trim()) { @@ -113,6 +125,11 @@ export const POST: RequestHandler = async ({ request }) => { const trimmedDomain = domain.trim().toLowerCase(); + // Validate domain format + if (!validateDomain(trimmedDomain)) { + throw error(400, 'Invalid domain name format'); + } + // Validate record type if (!RECORD_TYPES.includes(recordType.toUpperCase() as any)) { throw error(400, `Invalid record type. Supported types: ${RECORD_TYPES.join(', ')}`); diff --git a/src/routes/diagnostics/dns/query-performance/+page.svelte b/src/routes/diagnostics/dns/query-performance/+page.svelte index 1fb7e3d..005bb55 100644 --- a/src/routes/diagnostics/dns/query-performance/+page.svelte +++ b/src/routes/diagnostics/dns/query-performance/+page.svelte @@ -2,91 +2,150 @@ import { tooltip } from '$lib/actions/tooltip'; import Icon from '$lib/components/global/Icon.svelte'; import { dnsPerformanceContent } from '$lib/content/dns-performance'; - import '../../../../styles/diagnostics-pages.scss'; + import '$lib/../styles/diagnostics-pages.scss'; - let domain = $state(''); - let recordType = $state('A'); - let loading = $state(false); - let results = $state(null); - let error = $state(null); - let selectedExampleIndex = $state(null); + type ResolverResult = { + resolver: string; + resolverName: string; + success: boolean; + responseTime: number; + records?: string[]; + error?: string; + }; - const examples = [ + type PerfStats = { + fastest: { resolver: string; time: number }; + slowest: { resolver: string; time: number }; + average: number; + median: number; + successRate: number; + }; + + type PerfResponse = { + domain: string; + recordType: string; + timestamp: string; + results: ResolverResult[]; + statistics: PerfStats; + }; + + const API_ENDPOINT = '/api/internal/diagnostics/dns-performance'; + const RECORD_TYPES = ['A', 'AAAA', 'MX', 'TXT', 'NS', 'CNAME', 'SOA'] as const; + const EXAMPLES = [ { domain: 'google.com', type: 'A', description: 'Google.com A records' }, { domain: 'cloudflare.com', type: 'AAAA', description: 'Cloudflare IPv6' }, { domain: 'github.com', type: 'MX', description: 'GitHub mail servers' }, { domain: 'example.com', type: 'NS', description: 'Example.com nameservers' }, - ]; + ] as const; - const recordTypes = ['A', 'AAAA', 'MX', 'TXT', 'NS', 'CNAME', 'SOA']; + const PERF_RANGES = [ + { max: 20, class: 'excellent', label: 'Excellent' }, + { max: 50, class: 'good', label: 'Good' }, + { max: 100, class: 'acceptable', label: 'Acceptable' }, + { max: 200, class: 'slow', label: 'Slow' }, + { max: Infinity, class: 'very-slow', label: 'Very Slow' }, + ] as const; + + let domain = $state(''); + let recordType = $state('A'); + let loading = $state(false); + let results = $state(null); + let error = $state(null); + let selectedExampleIndex = $state(null); + let abortController = $state(null); + let requestId = $state(0); const isInputValid = $derived.by(() => { const trimmed = domain.trim(); if (!trimmed) return false; - const domainPattern = /^([a-zA-Z0-9]([a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?\.)+[a-zA-Z]{2,}$/; + // Support underscores for _acme-challenge and similar + const domainPattern = /^([a-zA-Z0-9_]([a-zA-Z0-9_-]{0,61}[a-zA-Z0-9_])?\.)+[a-zA-Z]{2,}$/; return domainPattern.test(trimmed); }); const sortedResults = $derived.by(() => { if (!results?.results) return []; - return [...results.results].sort((a: any, b: any) => + return [...results.results].sort((a, b) => a.success && b.success ? a.responseTime - b.responseTime : a.success ? -1 : 1 ); }); - function getPerformanceClass(time: number): string { - if (time < 20) return 'excellent'; - if (time < 50) return 'good'; - if (time < 100) return 'acceptable'; - if (time < 200) return 'slow'; - return 'very-slow'; - } + const successCount = $derived(results?.results.filter((r) => r.success).length ?? 0); + const totalCount = $derived(results?.results.length ?? 0); + const formattedTimestamp = $derived( + results?.timestamp ? new Date(results.timestamp).toLocaleString() : '' + ); + const totalRecords = $derived( + sortedResults.reduce((sum, r) => sum + (r.records?.length ?? 0), 0) + ); + const fastestResolver = $derived(results?.statistics.fastest.resolver ?? ''); + const performanceSpread = $derived( + results + ? Math.round( + (results.statistics.slowest.time - results.statistics.fastest.time) * 100 + ) / 100 + : 0 + ); - function getPerformanceLabel(time: number): string { - if (time < 20) return 'Excellent'; - if (time < 50) return 'Good'; - if (time < 100) return 'Acceptable'; - if (time < 200) return 'Slow'; - return 'Very Slow'; + function getPerformance(time: number) { + const range = PERF_RANGES.find((r) => time < r.max)!; + return { class: range.class, label: range.label }; } async function testPerformance() { if (!isInputValid) return; + // Cancel previous request + abortController?.abort(); + const controller = new AbortController(); + abortController = controller; + + const currentRequestId = ++requestId; loading = true; error = null; results = null; try { - const response = await fetch('/api/internal/diagnostics/dns-performance', { + const response = await fetch(API_ENDPOINT, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ domain: domain.trim(), recordType }), + signal: controller.signal, }); + // Ignore stale responses + if (currentRequestId !== requestId) return; + if (!response.ok) { - const data = await response.json(); - throw new Error(data.message || 'Failed to test DNS performance'); + let errorMsg = 'Failed to test DNS performance'; + try { + const data = await response.json(); + errorMsg = data.message || errorMsg; + } catch { + errorMsg = await response.text(); + } + throw new Error(errorMsg); } results = await response.json(); } catch (err) { + if (currentRequestId !== requestId) return; + if (err instanceof Error && err.name === 'AbortError') return; error = err instanceof Error ? err.message : 'An unexpected error occurred'; } finally { - loading = false; + if (currentRequestId === requestId) { + loading = false; + } } } - function loadExample(example: (typeof examples)[0], index: number) { + function loadExample(index: number) { + const example = EXAMPLES[index]; domain = example.domain; recordType = example.type; selectedExampleIndex = index; testPerformance(); } - - function clearExampleSelection() { - selectedExampleIndex = null; - } @@ -115,11 +174,11 @@

Quick Examples

- {#each examples as example, i (i)} + {#each EXAMPLES as example, i (i)}