DomainDig/DomainViewModel.swift
1379 lines · 51765 bytes
1import Foundation
2import SwiftUI
3
4enum ResultTone {
5 case primary
6 case secondary
7 case success
8 case warning
9 case failure
10}
11
12struct SummaryFieldViewData: Identifiable {
13 let id = UUID()
14 let label: String
15 let value: String
16 let tone: ResultTone
17}
18
19struct InfoRowViewData: Identifiable {
20 let id = UUID()
21 let label: String
22 let value: String
23 let tone: ResultTone
24}
25
26struct SectionMessageViewData {
27 let text: String
28 let isError: Bool
29}
30
31struct DNSRecordSectionViewData: Identifiable {
32 let id = UUID()
33 let title: String
34 let rows: [InfoRowViewData]
35 let wildcardRows: [InfoRowViewData]
36 let wildcardTitle: String?
37 let message: SectionMessageViewData?
38}
39
40struct EmailRowViewData: Identifiable {
41 let id = UUID()
42 let label: String
43 let status: String
44 let statusTone: ResultTone
45 let detail: String
46 let auxiliaryDetail: String?
47}
48
49struct RedirectHopViewData: Identifiable {
50 let id = UUID()
51 let stepLabel: String
52 let statusCode: String
53 let url: String
54 let isFinal: Bool
55}
56
57struct ReachabilityRowViewData: Identifiable {
58 let id = UUID()
59 let portLabel: String
60 let latencyLabel: String
61 let statusLabel: String
62 let statusTone: ResultTone
63}
64
65struct PortScanRowViewData: Identifiable {
66 let id = UUID()
67 let portLabel: String
68 let service: String
69 let statusLabel: String
70 let statusTone: ResultTone
71 let banner: String?
72 let durationLabel: String?
73}
74
75struct DomainSuggestionViewData: Identifiable {
76 let id: UUID
77 let domain: String
78 let status: String
79 let tone: ResultTone
80}
81
82struct LookupSnapshot {
83 let domain: String
84 let timestamp: Date
85 let resolverDisplayName: String
86 let resolverURLString: String
87 let totalLookupDurationMs: Int?
88 let dnsSections: [DNSSection]
89 let dnsError: String?
90 let availabilityResult: DomainAvailabilityResult?
91 let suggestions: [DomainSuggestionResult]
92 let sslInfo: SSLCertificateInfo?
93 let sslError: String?
94 let hstsPreloaded: Bool?
95 let httpHeaders: [HTTPHeader]
96 let httpSecurityGrade: String?
97 let httpStatusCode: Int?
98 let httpResponseTimeMs: Int?
99 let httpProtocol: String?
100 let http3Advertised: Bool
101 let httpHeadersError: String?
102 let reachabilityResults: [PortReachability]
103 let reachabilityError: String?
104 let ipGeolocation: IPGeolocation?
105 let ipGeolocationError: String?
106 let emailSecurity: EmailSecurityResult?
107 let emailSecurityError: String?
108 let ptrRecord: String?
109 let ptrError: String?
110 let redirectChain: [RedirectHop]
111 let redirectChainError: String?
112 let portScanResults: [PortScanResult]
113 let portScanError: String?
114 let isLive: Bool
115}
116
117extension HistoryEntry {
118 var snapshot: LookupSnapshot {
119 LookupSnapshot(
120 domain: domain,
121 timestamp: timestamp,
122 resolverDisplayName: resolverDisplayName,
123 resolverURLString: resolverURLString,
124 totalLookupDurationMs: totalLookupDurationMs,
125 dnsSections: dnsSections,
126 dnsError: nil,
127 availabilityResult: availabilityResult,
128 suggestions: suggestions,
129 sslInfo: sslInfo,
130 sslError: sslError,
131 hstsPreloaded: hstsPreloaded,
132 httpHeaders: httpHeaders,
133 httpSecurityGrade: HTTPSecurityGrade.grade(for: httpHeaders).rawValue,
134 httpStatusCode: nil,
135 httpResponseTimeMs: nil,
136 httpProtocol: nil,
137 http3Advertised: false,
138 httpHeadersError: httpHeadersError,
139 reachabilityResults: reachabilityResults,
140 reachabilityError: reachabilityError,
141 ipGeolocation: ipGeolocation,
142 ipGeolocationError: ipGeolocationError,
143 emailSecurity: emailSecurity,
144 emailSecurityError: emailSecurityError,
145 ptrRecord: ptrRecord,
146 ptrError: ptrError,
147 redirectChain: redirectChain,
148 redirectChainError: redirectChainError,
149 portScanResults: portScanResults,
150 portScanError: portScanError,
151 isLive: false
152 )
153 }
154}
155
156@MainActor
157@Observable
158final class DomainViewModel {
159 var domain: String = ""
160
161 var dnsSections: [DNSSection] = []
162 var dnsLoading = false
163 var dnsError: String?
164 var availabilityResult: DomainAvailabilityResult?
165 var availabilityLoading = false
166 var suggestions: [DomainSuggestionResult] = []
167 var suggestionsLoading = false
168
169 var sslInfo: SSLCertificateInfo?
170 var sslLoading = false
171 var sslError: String?
172 var hstsPreloaded: Bool?
173 var hstsLoading = false
174
175 var httpHeaders: [HTTPHeader] = []
176 var httpSecurityGrade: String?
177 var httpStatusCode: Int?
178 var httpResponseTimeMs: Int?
179 var httpProtocol: String?
180 var http3Advertised = false
181 var httpHeadersLoading = false
182 var httpHeadersError: String?
183
184 var reachabilityResults: [PortReachability] = []
185 var reachabilityLoading = false
186 var reachabilityError: String?
187
188 var ipGeolocation: IPGeolocation?
189 var ipGeolocationLoading = false
190 var ipGeolocationError: String?
191
192 var emailSecurity: EmailSecurityResult?
193 var emailSecurityLoading = false
194 var emailSecurityError: String?
195
196 var ptrRecord: String?
197 var ptrLoading = false
198 var ptrError: String?
199
200 var redirectChain: [RedirectHop] = []
201 var redirectChainLoading = false
202 var redirectChainError: String?
203
204 var portScanResults: [PortScanResult] = []
205 var portScanLoading = false
206 var portScanError: String?
207 var customPortResults: [PortScanResult] = []
208 var customPortScanLoading = false
209 var customPortScanError: String?
210
211 var hasRun = false
212 private(set) var searchedDomain: String = ""
213 private(set) var lastLookupDurationMs: Int?
214
215 private var lookupTask: Task<Void, Never>?
216 private var customPortScanTask: Task<Void, Never>?
217 private var activeLookupID = UUID()
218 private var lookupStartedAt: Date?
219
220 private static let recentSearchesKey = "recentSearches"
221 private static let maxRecent = 20
222 var recentSearches: [String] = UserDefaults.standard.stringArray(forKey: recentSearchesKey) ?? []
223
224 private static let savedDomainsKey = "savedDomains"
225 var savedDomains: [String] = UserDefaults.standard.stringArray(forKey: savedDomainsKey) ?? []
226
227 private static let watchedDomainsKey = "watchedDomains"
228 var watchedDomains: [WatchedDomain] = {
229 guard let data = UserDefaults.standard.data(forKey: watchedDomainsKey),
230 let domains = try? JSONDecoder().decode([WatchedDomain].self, from: data) else {
231 return []
232 }
233 return domains
234 }()
235
236 private static let historyKey = "lookupHistory"
237 private static let maxHistory = 50
238 var history: [HistoryEntry] = {
239 guard let data = UserDefaults.standard.data(forKey: historyKey),
240 let entries = try? JSONDecoder().decode([HistoryEntry].self, from: data) else {
241 return []
242 }
243 return entries
244 }()
245
246 var trimmedDomain: String {
247 domain
248 .trimmingCharacters(in: .whitespacesAndNewlines)
249 .replacingOccurrences(of: "https://", with: "")
250 .replacingOccurrences(of: "http://", with: "")
251 .components(separatedBy: "/").first ?? ""
252 }
253
254 var resultsLoaded: Bool {
255 hasRun &&
256 !dnsLoading &&
257 !availabilityLoading &&
258 !suggestionsLoading &&
259 !sslLoading &&
260 !hstsLoading &&
261 !httpHeadersLoading &&
262 !reachabilityLoading &&
263 !ipGeolocationLoading &&
264 !emailSecurityLoading &&
265 !ptrLoading &&
266 !redirectChainLoading &&
267 !portScanLoading &&
268 !customPortScanLoading
269 }
270
271 var isCloudflareProxied: Bool {
272 httpHeaders.contains { $0.name.lowercased() == "cf-ray" }
273 }
274
275 var isCurrentDomainSaved: Bool {
276 !searchedDomain.isEmpty && savedDomains.contains(where: { $0.lowercased() == searchedDomain.lowercased() })
277 }
278
279 var isCurrentDomainWatched: Bool {
280 !searchedDomain.isEmpty && watchedDomains.contains(where: { $0.domain.lowercased() == searchedDomain.lowercased() })
281 }
282
283 var resolverDisplayName: String {
284 DNSLookupService.currentResolverDisplayName()
285 }
286
287 var resolverURLString: String {
288 DNSLookupService.currentResolverURLString()
289 }
290
291 var allPortScanResults: [PortScanResult] {
292 (portScanResults + customPortResults).sorted {
293 if $0.kind == $1.kind {
294 return $0.port < $1.port
295 }
296 return $0.kind == .standard
297 }
298 }
299
300 var currentSnapshot: LookupSnapshot {
301 LookupSnapshot(
302 domain: searchedDomain,
303 timestamp: Date(),
304 resolverDisplayName: resolverDisplayName,
305 resolverURLString: resolverURLString,
306 totalLookupDurationMs: lastLookupDurationMs,
307 dnsSections: dnsSections,
308 dnsError: dnsError,
309 availabilityResult: availabilityResult,
310 suggestions: suggestions,
311 sslInfo: sslInfo,
312 sslError: sslError,
313 hstsPreloaded: hstsPreloaded,
314 httpHeaders: httpHeaders,
315 httpSecurityGrade: httpSecurityGrade,
316 httpStatusCode: httpStatusCode,
317 httpResponseTimeMs: httpResponseTimeMs,
318 httpProtocol: httpProtocol,
319 http3Advertised: http3Advertised,
320 httpHeadersError: httpHeadersError,
321 reachabilityResults: reachabilityResults,
322 reachabilityError: reachabilityError,
323 ipGeolocation: ipGeolocation,
324 ipGeolocationError: ipGeolocationError,
325 emailSecurity: emailSecurity,
326 emailSecurityError: emailSecurityError,
327 ptrRecord: ptrRecord,
328 ptrError: ptrError,
329 redirectChain: redirectChain,
330 redirectChainError: redirectChainError,
331 portScanResults: allPortScanResults,
332 portScanError: combinedPortScanError,
333 isLive: true
334 )
335 }
336
337 var summaryFields: [SummaryFieldViewData] {
338 Self.summaryFields(from: currentSnapshot)
339 }
340
341 var domainRows: [InfoRowViewData] {
342 Self.domainRows(from: currentSnapshot)
343 }
344
345 var dnsRows: [DNSRecordSectionViewData] {
346 Self.dnsRows(from: currentSnapshot)
347 }
348
349 var suggestionRows: [DomainSuggestionViewData] {
350 Self.suggestionRows(from: currentSnapshot)
351 }
352
353 var dnssecLabel: String? {
354 Self.dnssecLabel(from: currentSnapshot)
355 }
356
357 var ptrMessage: SectionMessageViewData? {
358 Self.ptrMessage(from: currentSnapshot)
359 }
360
361 var webCertificateRows: [InfoRowViewData] {
362 Self.webCertificateRows(from: currentSnapshot)
363 }
364
365 var webResponseRows: [InfoRowViewData] {
366 Self.webResponseRows(from: currentSnapshot)
367 }
368
369 var redirectRows: [RedirectHopViewData] {
370 Self.redirectRows(from: currentSnapshot)
371 }
372
373 var emailRows: [EmailRowViewData] {
374 Self.emailRows(from: currentSnapshot)
375 }
376
377 var reachabilityRows: [ReachabilityRowViewData] {
378 Self.reachabilityRows(from: currentSnapshot)
379 }
380
381 var locationRows: [InfoRowViewData] {
382 Self.locationRows(from: currentSnapshot)
383 }
384
385 var standardPortRows: [PortScanRowViewData] {
386 Self.portRows(from: currentSnapshot, kind: .standard)
387 }
388
389 var customPortRows: [PortScanRowViewData] {
390 Self.portRows(from: currentSnapshot, kind: .custom)
391 }
392
393 var combinedPortScanError: String? {
394 [portScanError, customPortScanError].compactMap { $0 }.joined(separator: "\n").nilIfEmpty
395 }
396
397 func toggleSavedDomain() {
398 if isCurrentDomainSaved {
399 savedDomains.removeAll { $0.lowercased() == searchedDomain.lowercased() }
400 } else {
401 savedDomains.append(searchedDomain)
402 }
403 UserDefaults.standard.set(savedDomains, forKey: Self.savedDomainsKey)
404 }
405
406 func removeSavedDomains(at offsets: IndexSet) {
407 savedDomains.remove(atOffsets: offsets)
408 UserDefaults.standard.set(savedDomains, forKey: Self.savedDomainsKey)
409 }
410
411 func toggleWatchedDomain() {
412 guard !searchedDomain.isEmpty else { return }
413 toggleWatchedDomain(domain: searchedDomain, availabilityStatus: availabilityResult?.status)
414 }
415
416 func toggleWatchedDomain(domain: String, availabilityStatus: DomainAvailabilityStatus?) {
417 guard !domain.isEmpty else { return }
418
419 if watchedDomains.contains(where: { $0.domain.lowercased() == domain.lowercased() }) {
420 watchedDomains.removeAll { $0.domain.lowercased() == domain.lowercased() }
421 } else {
422 watchedDomains.insert(
423 WatchedDomain(
424 domain: domain,
425 lastKnownAvailability: availabilityStatus
426 ),
427 at: 0
428 )
429 }
430 persistWatchedDomains()
431 }
432
433 func removeWatchedDomains(at offsets: IndexSet) {
434 watchedDomains.remove(atOffsets: offsets)
435 persistWatchedDomains()
436 }
437
438 func removeHistoryEntries(at offsets: IndexSet) {
439 history.remove(atOffsets: offsets)
440 persistHistory()
441 }
442
443 func clearRecentSearches() {
444 recentSearches.removeAll()
445 UserDefaults.standard.removeObject(forKey: Self.recentSearchesKey)
446 }
447
448 func rerunLookup(from entry: HistoryEntry) {
449 UserDefaults.standard.set(entry.resolverURLString, forKey: DNSResolverOption.userDefaultsKey)
450 domain = entry.domain
451 run()
452 }
453
454 func reset() {
455 lookupTask?.cancel()
456 customPortScanTask?.cancel()
457 hasRun = false
458 searchedDomain = ""
459 lastLookupDurationMs = nil
460 clearLookupState()
461 }
462
463 func run() {
464 let target = trimmedDomain
465 guard !target.isEmpty else { return }
466
467 lookupTask?.cancel()
468 customPortScanTask?.cancel()
469
470 let lookupID = UUID()
471 activeLookupID = lookupID
472 lookupStartedAt = Date()
473 lastLookupDurationMs = nil
474 addRecentSearch(target)
475 searchedDomain = target
476 hasRun = true
477 clearLookupState()
478 setAllLoadingStates(true)
479 customPortScanLoading = false
480
481 lookupTask = Task { [weak self] in
482 guard let self else { return }
483 await self.performLookup(domain: target, lookupID: lookupID)
484 }
485 }
486
487 func runCustomPortScan(ports: [UInt16]) async {
488 guard !searchedDomain.isEmpty else {
489 customPortScanError = "Run a domain lookup first"
490 return
491 }
492
493 guard !ports.isEmpty else {
494 customPortScanError = "Enter at least one valid port"
495 customPortResults = []
496 return
497 }
498
499 customPortScanTask?.cancel()
500 let domain = searchedDomain
501 let lookupID = activeLookupID
502
503 customPortScanLoading = true
504 customPortScanError = nil
505 customPortResults = []
506
507 customPortScanTask = Task { [weak self] in
508 guard let self else { return }
509 let result = await PortScanService.scanPorts(domain: domain, ports: ports, timeout: 3.0)
510 guard !Task.isCancelled, self.isCurrentLookup(lookupID) else { return }
511 self.applyCustomPortResult(result)
512 }
513 }
514
515 func exportText() -> String {
516 Self.formatExportText(from: currentSnapshot)
517 }
518
519 private func performLookup(domain: String, lookupID: UUID) async {
520 await withTaskGroup(of: Void.self) { group in
521 group.addTask { await self.runDNS(domain: domain, lookupID: lookupID) }
522 group.addTask { await self.runAvailability(domain: domain, lookupID: lookupID) }
523 group.addTask { await self.runSSL(domain: domain, lookupID: lookupID) }
524 group.addTask { await self.runHSTSPreload(domain: domain, lookupID: lookupID) }
525 group.addTask { await self.runHTTPHeaders(domain: domain, lookupID: lookupID) }
526 group.addTask { await self.runReachability(domain: domain, lookupID: lookupID) }
527 group.addTask { await self.runRedirectChain(domain: domain, lookupID: lookupID) }
528 group.addTask { await self.runPortScan(domain: domain, lookupID: lookupID) }
529 }
530
531 guard !Task.isCancelled, isCurrentLookup(lookupID) else { return }
532
533 let txtRecords = dnsSections.first(where: { $0.recordType == .TXT })?.records ?? []
534 let primaryIP = primaryIPAddress(from: dnsSections)
535
536 await withTaskGroup(of: Void.self) { group in
537 group.addTask { await self.runEmailSecurity(domain: domain, txtRecords: txtRecords, lookupID: lookupID) }
538 if let primaryIP {
539 group.addTask { await self.runReverseDNS(ip: primaryIP, lookupID: lookupID) }
540 group.addTask { await self.runIPGeolocation(ip: primaryIP, lookupID: lookupID) }
541 } else {
542 group.addTask { await self.finishDependentWithoutPrimaryIP(lookupID: lookupID) }
543 }
544 }
545
546 guard !Task.isCancelled, isCurrentLookup(lookupID) else { return }
547
548 if availabilityResult?.status == .registered {
549 await runSuggestions(domain: domain, lookupID: lookupID)
550 } else {
551 suggestions = []
552 suggestionsLoading = false
553 }
554
555 guard !Task.isCancelled, isCurrentLookup(lookupID) else { return }
556 lastLookupDurationMs = lookupStartedAt.map { Int(Date().timeIntervalSince($0) * 1000) }
557 saveHistoryEntry(replaceLatest: false)
558 }
559
560 private func runDNS(domain: String, lookupID: UUID) async {
561 let result = await DNSLookupService.lookupAll(domain: domain)
562 guard !Task.isCancelled, isCurrentLookup(lookupID) else { return }
563 switch result {
564 case let .success(sections):
565 dnsSections = sections
566 dnsError = nil
567 case let .empty(message):
568 dnsSections = []
569 dnsError = message
570 case let .error(message):
571 dnsSections = []
572 dnsError = message
573 }
574 dnsLoading = false
575 }
576
577 private func runAvailability(domain: String, lookupID: UUID) async {
578 let result = await DomainAvailabilityService.check(domain: domain)
579 guard !Task.isCancelled, isCurrentLookup(lookupID) else { return }
580 availabilityResult = result
581 availabilityLoading = false
582 updateWatchedDomainAvailability(for: result.domain, status: result.status)
583 }
584
585 private func runSSL(domain: String, lookupID: UUID) async {
586 let result = await SSLCheckService.check(domain: domain)
587 guard !Task.isCancelled, isCurrentLookup(lookupID) else { return }
588 switch result {
589 case let .success(info):
590 sslInfo = info
591 sslError = nil
592 case let .empty(message):
593 sslInfo = nil
594 sslError = message
595 case let .error(message):
596 sslInfo = nil
597 sslError = message
598 }
599 sslLoading = false
600 }
601
602 private func runHSTSPreload(domain: String, lookupID: UUID) async {
603 let result = await SSLCheckService.checkHSTSPreload(domain: domain)
604 guard !Task.isCancelled, isCurrentLookup(lookupID) else { return }
605 hstsPreloaded = result
606 hstsLoading = false
607 }
608
609 private func runHTTPHeaders(domain: String, lookupID: UUID) async {
610 let result = await HTTPHeadersService.fetch(domain: domain)
611 guard !Task.isCancelled, isCurrentLookup(lookupID) else { return }
612 switch result {
613 case let .success(headersResult):
614 httpHeaders = headersResult.headers
615 httpSecurityGrade = HTTPSecurityGrade.grade(for: headersResult.headers).rawValue
616 httpStatusCode = headersResult.statusCode
617 httpResponseTimeMs = headersResult.responseTimeMs
618 httpProtocol = headersResult.httpProtocol
619 http3Advertised = headersResult.http3Advertised
620 httpHeadersError = nil
621 case let .empty(message):
622 httpHeaders = []
623 httpSecurityGrade = nil
624 httpStatusCode = nil
625 httpResponseTimeMs = nil
626 httpProtocol = nil
627 http3Advertised = false
628 httpHeadersError = message
629 case let .error(message):
630 httpHeaders = []
631 httpSecurityGrade = nil
632 httpStatusCode = nil
633 httpResponseTimeMs = nil
634 httpProtocol = nil
635 http3Advertised = false
636 httpHeadersError = message
637 }
638 httpHeadersLoading = false
639 }
640
641 private func runReachability(domain: String, lookupID: UUID) async {
642 let result = await ReachabilityService.checkAll(domain: domain)
643 guard !Task.isCancelled, isCurrentLookup(lookupID) else { return }
644 switch result {
645 case let .success(results):
646 reachabilityResults = results
647 reachabilityError = nil
648 case let .empty(message):
649 reachabilityResults = []
650 reachabilityError = message
651 case let .error(message):
652 reachabilityResults = []
653 reachabilityError = message
654 }
655 reachabilityLoading = false
656 }
657
658 private func runEmailSecurity(domain: String, txtRecords: [DNSRecord], lookupID: UUID) async {
659 let result = await EmailSecurityService.analyze(domain: domain, txtRecords: txtRecords)
660 guard !Task.isCancelled, isCurrentLookup(lookupID) else { return }
661 switch result {
662 case let .success(emailResult):
663 emailSecurity = emailResult
664 emailSecurityError = nil
665 case let .empty(message):
666 emailSecurity = nil
667 emailSecurityError = message
668 case let .error(message):
669 emailSecurity = nil
670 emailSecurityError = message
671 }
672 emailSecurityLoading = false
673 }
674
675 private func runReverseDNS(ip: String, lookupID: UUID) async {
676 let result = await ReverseDNSService.lookup(ip: ip, resolverURLString: resolverURLString)
677 guard !Task.isCancelled, isCurrentLookup(lookupID) else { return }
678 switch result {
679 case let .success(record):
680 ptrRecord = record
681 ptrError = nil
682 case let .empty(message):
683 ptrRecord = nil
684 ptrError = message
685 case let .error(message):
686 ptrRecord = nil
687 ptrError = message
688 }
689 ptrLoading = false
690 }
691
692 private func runRedirectChain(domain: String, lookupID: UUID) async {
693 let result = await RedirectChainService.trace(domain: domain)
694 guard !Task.isCancelled, isCurrentLookup(lookupID) else { return }
695 switch result {
696 case let .success(hops):
697 redirectChain = hops
698 redirectChainError = nil
699 case let .empty(message):
700 redirectChain = []
701 redirectChainError = message
702 case let .error(message):
703 redirectChain = []
704 redirectChainError = message
705 }
706 redirectChainLoading = false
707 }
708
709 private func runPortScan(domain: String, lookupID: UUID) async {
710 let result = await PortScanService.scanAll(domain: domain)
711 switch result {
712 case let .success(results):
713 let enrichedResults = await enrichOpenPortBanners(in: results, domain: domain)
714 guard !Task.isCancelled, isCurrentLookup(lookupID) else { return }
715 portScanResults = enrichedResults
716 portScanError = nil
717 case let .empty(message):
718 guard !Task.isCancelled, isCurrentLookup(lookupID) else { return }
719 portScanResults = []
720 portScanError = message
721 case let .error(message):
722 guard !Task.isCancelled, isCurrentLookup(lookupID) else { return }
723 portScanResults = []
724 portScanError = message
725 }
726 portScanLoading = false
727 }
728
729 private func runIPGeolocation(ip: String, lookupID: UUID) async {
730 let result = await IPGeolocationService.lookup(ip: ip)
731 guard !Task.isCancelled, isCurrentLookup(lookupID) else { return }
732 switch result {
733 case let .success(geolocation):
734 ipGeolocation = geolocation
735 ipGeolocationError = nil
736 case let .empty(message):
737 ipGeolocation = nil
738 ipGeolocationError = message
739 case let .error(message):
740 ipGeolocation = nil
741 ipGeolocationError = message
742 }
743 ipGeolocationLoading = false
744 }
745
746 private func finishDependentWithoutPrimaryIP(lookupID: UUID) async {
747 guard !Task.isCancelled, isCurrentLookup(lookupID) else { return }
748 ptrLoading = false
749 ptrError = "No A record available"
750 ipGeolocationLoading = false
751 ipGeolocationError = "No A record available"
752 }
753
754 private func runSuggestions(domain: String, lookupID: UUID) async {
755 let results = await DomainAvailabilityService.suggestions(for: domain)
756 guard !Task.isCancelled, isCurrentLookup(lookupID) else { return }
757 suggestions = results
758 suggestionsLoading = false
759 }
760
761 private func applyCustomPortResult(_ result: ServiceResult<[PortScanResult]>) {
762 switch result {
763 case let .success(results):
764 customPortResults = results
765 customPortScanError = nil
766 saveHistoryEntry(replaceLatest: true)
767 case let .empty(message):
768 customPortResults = []
769 customPortScanError = message
770 case let .error(message):
771 customPortResults = []
772 customPortScanError = message
773 }
774 customPortScanLoading = false
775 }
776
777 private func enrichOpenPortBanners(in results: [PortScanResult], domain: String) async -> [PortScanResult] {
778 let banners = await withTaskGroup(of: (UInt16, String?).self, returning: [UInt16: String].self) { group in
779 for result in results where result.open {
780 group.addTask {
781 let banner = await PortScanService.grabBanner(host: domain, port: result.port)
782 return (result.port, banner)
783 }
784 }
785
786 var collected: [UInt16: String] = [:]
787 for await (port, banner) in group {
788 if let banner {
789 collected[port] = banner
790 }
791 }
792 return collected
793 }
794
795 return results.map { result in
796 var updated = result
797 updated.banner = banners[result.port]
798 return updated
799 }
800 }
801
802 private func saveHistoryEntry(replaceLatest: Bool) {
803 guard !searchedDomain.isEmpty else { return }
804 let entry = HistoryEntry(
805 domain: searchedDomain,
806 timestamp: Date(),
807 dnsSections: dnsSections,
808 sslInfo: sslInfo,
809 httpHeaders: httpHeaders,
810 reachabilityResults: reachabilityResults,
811 ipGeolocation: ipGeolocation,
812 emailSecurity: emailSecurity,
813 mtaSts: emailSecurity?.mtaSts,
814 ptrRecord: ptrRecord,
815 redirectChain: redirectChain,
816 portScanResults: allPortScanResults,
817 hstsPreloaded: hstsPreloaded,
818 availabilityResult: availabilityResult,
819 suggestions: suggestions,
820 resolverDisplayName: resolverDisplayName,
821 resolverURLString: resolverURLString,
822 totalLookupDurationMs: lastLookupDurationMs,
823 sslError: sslError,
824 httpHeadersError: httpHeadersError,
825 reachabilityError: reachabilityError,
826 ipGeolocationError: ipGeolocationError,
827 emailSecurityError: emailSecurityError,
828 ptrError: ptrError,
829 redirectChainError: redirectChainError,
830 portScanError: combinedPortScanError
831 )
832
833 if replaceLatest, !history.isEmpty, history[0].domain.caseInsensitiveCompare(searchedDomain) == .orderedSame {
834 history[0] = entry
835 } else {
836 history.insert(entry, at: 0)
837 if history.count > Self.maxHistory {
838 history = Array(history.prefix(Self.maxHistory))
839 }
840 }
841 persistHistory()
842 }
843
844 private func persistHistory() {
845 if let data = try? JSONEncoder().encode(history) {
846 UserDefaults.standard.set(data, forKey: Self.historyKey)
847 }
848 }
849
850 private func persistWatchedDomains() {
851 if let data = try? JSONEncoder().encode(watchedDomains) {
852 UserDefaults.standard.set(data, forKey: Self.watchedDomainsKey)
853 }
854 }
855
856 private func updateWatchedDomainAvailability(for domain: String, status: DomainAvailabilityStatus) {
857 guard let index = watchedDomains.firstIndex(where: { $0.domain.lowercased() == domain.lowercased() }) else {
858 return
859 }
860 watchedDomains[index].lastKnownAvailability = status
861 persistWatchedDomains()
862 }
863
864 private func addRecentSearch(_ domain: String) {
865 recentSearches.removeAll { $0.lowercased() == domain.lowercased() }
866 recentSearches.insert(domain, at: 0)
867 if recentSearches.count > Self.maxRecent {
868 recentSearches = Array(recentSearches.prefix(Self.maxRecent))
869 }
870 UserDefaults.standard.set(recentSearches, forKey: Self.recentSearchesKey)
871 }
872
873 private func clearLookupState() {
874 dnsSections = []
875 dnsError = nil
876 dnsLoading = false
877 availabilityResult = nil
878 availabilityLoading = false
879 suggestions = []
880 suggestionsLoading = false
881 sslInfo = nil
882 sslError = nil
883 sslLoading = false
884 hstsPreloaded = nil
885 hstsLoading = false
886 httpHeaders = []
887 httpSecurityGrade = nil
888 httpStatusCode = nil
889 httpResponseTimeMs = nil
890 httpProtocol = nil
891 http3Advertised = false
892 httpHeadersError = nil
893 httpHeadersLoading = false
894 reachabilityResults = []
895 reachabilityError = nil
896 reachabilityLoading = false
897 ipGeolocation = nil
898 ipGeolocationError = nil
899 ipGeolocationLoading = false
900 emailSecurity = nil
901 emailSecurityError = nil
902 emailSecurityLoading = false
903 ptrRecord = nil
904 ptrError = nil
905 ptrLoading = false
906 redirectChain = []
907 redirectChainError = nil
908 redirectChainLoading = false
909 portScanResults = []
910 portScanError = nil
911 portScanLoading = false
912 customPortResults = []
913 customPortScanError = nil
914 customPortScanLoading = false
915 }
916
917 private func setAllLoadingStates(_ loading: Bool) {
918 dnsLoading = loading
919 availabilityLoading = loading
920 suggestionsLoading = loading
921 sslLoading = loading
922 hstsLoading = loading
923 httpHeadersLoading = loading
924 reachabilityLoading = loading
925 ipGeolocationLoading = loading
926 emailSecurityLoading = loading
927 ptrLoading = loading
928 redirectChainLoading = loading
929 portScanLoading = loading
930 }
931
932 private func primaryIPAddress(from sections: [DNSSection]) -> String? {
933 sections.first(where: { $0.recordType == .A })?.records.first?.value
934 }
935
936 private func isCurrentLookup(_ lookupID: UUID) -> Bool {
937 activeLookupID == lookupID
938 }
939
940 static func summaryFields(from snapshot: LookupSnapshot) -> [SummaryFieldViewData] {
941 [
942 SummaryFieldViewData(label: "Domain", value: snapshot.domain.nonEmpty ?? "Unavailable", tone: .primary),
943 SummaryFieldViewData(label: "Primary IP", value: primaryIPAddress(from: snapshot) ?? "Unavailable", tone: .primary),
944 SummaryFieldViewData(label: "HTTPS", value: httpsSummary(from: snapshot), tone: httpsSummaryTone(from: snapshot)),
945 SummaryFieldViewData(label: "Redirect", value: finalRedirectTarget(from: snapshot) ?? "Unavailable", tone: .secondary),
946 SummaryFieldViewData(label: "Email", value: emailSummary(from: snapshot), tone: .secondary)
947 ]
948 }
949
950 static func domainRows(from snapshot: LookupSnapshot) -> [InfoRowViewData] {
951 var rows = [
952 InfoRowViewData(label: "Domain", value: snapshot.domain, tone: .primary),
953 InfoRowViewData(label: "Resolver", value: snapshot.resolverDisplayName, tone: .secondary),
954 InfoRowViewData(label: snapshot.isLive ? "Result" : "Snapshot", value: snapshot.isLive ? "Live" : "Snapshot", tone: snapshot.isLive ? .success : .warning),
955 InfoRowViewData(label: "Lookup Duration", value: durationLabel(snapshot.totalLookupDurationMs), tone: .secondary)
956 ]
957 rows.insert(
958 InfoRowViewData(
959 label: "Availability",
960 value: availabilityLabel(snapshot.availabilityResult?.status),
961 tone: availabilityTone(snapshot.availabilityResult?.status)
962 ),
963 at: 1
964 )
965 return rows
966 }
967
968 static func suggestionRows(from snapshot: LookupSnapshot) -> [DomainSuggestionViewData] {
969 snapshot.suggestions.map {
970 DomainSuggestionViewData(
971 id: $0.id,
972 domain: $0.domain,
973 status: availabilityLabel($0.status),
974 tone: availabilityTone($0.status)
975 )
976 }
977 }
978
979 static func dnsRows(from snapshot: LookupSnapshot) -> [DNSRecordSectionViewData] {
980 snapshot.dnsSections.map { section in
981 DNSRecordSectionViewData(
982 title: section.recordType.rawValue,
983 rows: section.records.map { InfoRowViewData(label: "TTL \($0.ttl)", value: $0.value, tone: .primary) },
984 wildcardRows: section.wildcardRecords.map { InfoRowViewData(label: "TTL \($0.ttl)", value: $0.value, tone: .primary) },
985 wildcardTitle: section.wildcardRecords.isEmpty ? nil : "*.\(snapshot.domain)",
986 message: section.error.map { SectionMessageViewData(text: $0, isError: true) } ??
987 ((section.records.isEmpty && section.wildcardRecords.isEmpty) ? SectionMessageViewData(text: "No records found", isError: false) : nil)
988 )
989 }
990 }
991
992 static func dnssecLabel(from snapshot: LookupSnapshot) -> String? {
993 guard let signed = snapshot.dnsSections.compactMap(\.dnssecSigned).first else { return nil }
994 return "Resolver-reported DNSSEC (not full validation): \(signed ? "Yes" : "No")"
995 }
996
997 static func ptrMessage(from snapshot: LookupSnapshot) -> SectionMessageViewData? {
998 if let ptrRecord = snapshot.ptrRecord {
999 return SectionMessageViewData(text: ptrRecord, isError: false)
1000 }
1001 if let ptrError = snapshot.ptrError {
1002 return SectionMessageViewData(text: ptrError, isError: ptrError != "No A record available" && ptrError != "No PTR record found")
1003 }
1004 return nil
1005 }
1006
1007 static func webCertificateRows(from snapshot: LookupSnapshot) -> [InfoRowViewData] {
1008 guard let sslInfo = snapshot.sslInfo else { return [] }
1009 var rows = [
1010 InfoRowViewData(label: "Common Name", value: sslInfo.commonName, tone: .primary),
1011 InfoRowViewData(label: "Issuer", value: sslInfo.issuer, tone: .primary),
1012 InfoRowViewData(label: "Valid From", value: certificateDateFormatter.string(from: sslInfo.validFrom), tone: .secondary),
1013 InfoRowViewData(label: "Valid Until", value: certificateDateFormatter.string(from: sslInfo.validUntil), tone: .secondary),
1014 InfoRowViewData(label: "Days Until Expiry", value: "\(sslInfo.daysUntilExpiry)", tone: sslInfo.daysUntilExpiry < 30 ? .failure : (sslInfo.daysUntilExpiry < 60 ? .warning : .success)),
1015 InfoRowViewData(label: "Chain Depth", value: "\(sslInfo.chainDepth)", tone: .secondary)
1016 ]
1017 if let tlsVersion = sslInfo.tlsVersion {
1018 rows.append(InfoRowViewData(label: "TLS Version", value: tlsVersion, tone: .secondary))
1019 }
1020 if let cipherSuite = sslInfo.cipherSuite {
1021 rows.append(InfoRowViewData(label: "Cipher Suite", value: cipherSuite, tone: .secondary))
1022 }
1023 if let hstsPreloaded = snapshot.hstsPreloaded {
1024 rows.append(InfoRowViewData(label: "HSTS Preload", value: hstsPreloaded ? "Preloaded" : "Not preloaded", tone: hstsPreloaded ? .success : .secondary))
1025 }
1026 return rows
1027 }
1028
1029 static func webResponseRows(from snapshot: LookupSnapshot) -> [InfoRowViewData] {
1030 var rows: [InfoRowViewData] = []
1031 if let httpStatusCode = snapshot.httpStatusCode {
1032 rows.append(InfoRowViewData(label: "Status", value: "\(httpStatusCode)", tone: .primary))
1033 }
1034 if let httpResponseTimeMs = snapshot.httpResponseTimeMs {
1035 rows.append(InfoRowViewData(label: "Response Time", value: "\(httpResponseTimeMs) ms", tone: .secondary))
1036 }
1037 if let httpProtocol = snapshot.httpProtocol {
1038 rows.append(InfoRowViewData(label: "Protocol", value: httpProtocol, tone: .secondary))
1039 }
1040 if let httpSecurityGrade = snapshot.httpSecurityGrade {
1041 rows.append(InfoRowViewData(label: "Security Grade", value: httpSecurityGrade, tone: securityGradeTone(httpSecurityGrade)))
1042 }
1043 if snapshot.http3Advertised {
1044 rows.append(InfoRowViewData(label: "HTTP/3", value: "Advertised", tone: .secondary))
1045 }
1046 return rows
1047 }
1048
1049 static func redirectRows(from snapshot: LookupSnapshot) -> [RedirectHopViewData] {
1050 snapshot.redirectChain.map {
1051 RedirectHopViewData(
1052 stepLabel: "\($0.stepNumber)",
1053 statusCode: "\($0.statusCode)",
1054 url: $0.url,
1055 isFinal: $0.isFinal
1056 )
1057 }
1058 }
1059
1060 static func emailRows(from snapshot: LookupSnapshot) -> [EmailRowViewData] {
1061 guard let emailSecurity = snapshot.emailSecurity else { return [] }
1062 return [
1063 EmailRowViewData(label: "SPF", status: emailSecurity.spf.found ? "Present" : "Missing", statusTone: emailSecurity.spf.found ? .success : .warning, detail: emailSecurity.spf.value ?? "No record found", auxiliaryDetail: nil),
1064 EmailRowViewData(label: "DMARC", status: emailSecurity.dmarc.found ? "Present" : "Missing", statusTone: emailSecurity.dmarc.found ? .success : .warning, detail: emailSecurity.dmarc.value ?? "No record found", auxiliaryDetail: nil),
1065 EmailRowViewData(label: "DKIM", status: emailSecurity.dkim.found ? "Present" : "Missing", statusTone: emailSecurity.dkim.found ? .success : .warning, detail: emailSecurity.dkim.value ?? "No record found", auxiliaryDetail: emailSecurity.dkim.matchedSelector.map { "Selector: \($0)" }),
1066 EmailRowViewData(label: "MTA-STS", status: emailSecurity.mtaSts?.txtFound == true ? "Present" : "Missing", statusTone: emailSecurity.mtaSts?.txtFound == true ? .success : .warning, detail: emailSecurity.mtaSts?.policyMode ?? (emailSecurity.mtaSts?.txtFound == true ? "Policy unavailable" : "No record found"), auxiliaryDetail: nil),
1067 EmailRowViewData(label: "BIMI", status: emailSecurity.bimi.found ? "Present" : "Missing", statusTone: emailSecurity.bimi.found ? .success : .warning, detail: emailSecurity.bimi.value ?? "No record found", auxiliaryDetail: nil)
1068 ]
1069 }
1070
1071 static func reachabilityRows(from snapshot: LookupSnapshot) -> [ReachabilityRowViewData] {
1072 snapshot.reachabilityResults.map {
1073 ReachabilityRowViewData(
1074 portLabel: "Port \($0.port)",
1075 latencyLabel: $0.latencyMs.map { "\($0) ms" } ?? "—",
1076 statusLabel: $0.reachable ? "Reachable" : "Unreachable",
1077 statusTone: $0.reachable ? .success : .failure
1078 )
1079 }
1080 }
1081
1082 static func locationRows(from snapshot: LookupSnapshot) -> [InfoRowViewData] {
1083 guard let ipGeolocation = snapshot.ipGeolocation else { return [] }
1084 var rows = [InfoRowViewData(label: "IP", value: ipGeolocation.ip, tone: .primary)]
1085 if let org = ipGeolocation.org {
1086 rows.append(InfoRowViewData(label: "Org / ISP", value: org, tone: .secondary))
1087 }
1088 let location = [ipGeolocation.city, ipGeolocation.region, ipGeolocation.country_name].compactMap { $0 }.joined(separator: ", ")
1089 if !location.isEmpty {
1090 rows.append(InfoRowViewData(label: "Location", value: location, tone: .secondary))
1091 }
1092 if let latitude = ipGeolocation.latitude, let longitude = ipGeolocation.longitude {
1093 rows.append(InfoRowViewData(label: "Coordinates", value: "\(latitude), \(longitude)", tone: .secondary))
1094 }
1095 return rows
1096 }
1097
1098 static func portRows(from snapshot: LookupSnapshot, kind: PortScanKind) -> [PortScanRowViewData] {
1099 snapshot.portScanResults
1100 .filter { $0.kind == kind }
1101 .map {
1102 PortScanRowViewData(
1103 portLabel: "\($0.port)",
1104 service: $0.service,
1105 statusLabel: $0.open ? "Open" : "Closed",
1106 statusTone: $0.open ? .success : .secondary,
1107 banner: $0.banner,
1108 durationLabel: $0.durationMs.map { "\($0) ms" }
1109 )
1110 }
1111 }
1112
1113 static func formatExportText(from snapshot: LookupSnapshot) -> String {
1114 let exportDateFormatter = DateFormatter()
1115 exportDateFormatter.dateFormat = "yyyy-MM-dd HH:mm"
1116
1117 var lines: [String] = [
1118 "DomainDig Export",
1119 "Domain: \(snapshot.domain)",
1120 "Date: \(exportDateFormatter.string(from: snapshot.timestamp))",
1121 "Mode: \(snapshot.isLive ? "Live" : "Snapshot")",
1122 "Resolver: \(snapshot.resolverDisplayName)",
1123 "Lookup Duration: \(durationLabel(snapshot.totalLookupDurationMs))"
1124 ]
1125
1126 func appendSection(_ title: String, body: () -> Void) {
1127 lines.append("")
1128 lines.append(title)
1129 lines.append(String(repeating: "-", count: title.count))
1130 body()
1131 }
1132
1133 appendSection("Summary") {
1134 for item in summaryFields(from: snapshot) {
1135 lines.append(" \(item.label): \(item.value)")
1136 }
1137 }
1138
1139 appendSection("Domain") {
1140 for row in domainRows(from: snapshot) {
1141 lines.append(" \(row.label): \(row.value)")
1142 }
1143 if snapshot.suggestions.isEmpty {
1144 lines.append(" Suggestions: None")
1145 } else {
1146 lines.append(" Suggestions:")
1147 for suggestion in snapshot.suggestions {
1148 lines.append(" \(suggestion.domain): \(availabilityLabel(suggestion.status))")
1149 }
1150 }
1151 }
1152
1153 appendSection("DNS") {
1154 if let dnsError = snapshot.dnsError {
1155 lines.append(" Error: \(dnsError)")
1156 }
1157 if let dnssecLabel = dnssecLabel(from: snapshot) {
1158 lines.append(" \(dnssecLabel)")
1159 }
1160 for section in dnsRows(from: snapshot) {
1161 lines.append(" \(section.title)")
1162 if let message = section.message {
1163 lines.append(" \(message.isError ? "Error" : "Info"): \(message.text)")
1164 }
1165 for row in section.rows {
1166 lines.append(" \(row.value) (\(row.label))")
1167 }
1168 if let wildcardTitle = section.wildcardTitle {
1169 lines.append(" \(wildcardTitle)")
1170 for row in section.wildcardRows {
1171 lines.append(" \(row.value) (\(row.label))")
1172 }
1173 }
1174 }
1175 if let ptrRecord = snapshot.ptrRecord {
1176 lines.append(" PTR: \(ptrRecord)")
1177 } else if let ptrError = snapshot.ptrError {
1178 lines.append(" PTR Error: \(ptrError)")
1179 }
1180 }
1181
1182 appendSection("Web") {
1183 if let sslError = snapshot.sslError {
1184 lines.append(" TLS Error: \(sslError)")
1185 } else {
1186 for row in webCertificateRows(from: snapshot) {
1187 lines.append(" \(row.label): \(row.value)")
1188 }
1189 }
1190
1191 if let httpHeadersError = snapshot.httpHeadersError {
1192 lines.append(" Headers Error: \(httpHeadersError)")
1193 } else {
1194 for row in webResponseRows(from: snapshot) {
1195 lines.append(" \(row.label): \(row.value)")
1196 }
1197 if snapshot.httpHeaders.isEmpty {
1198 lines.append(" Headers: No headers returned")
1199 } else {
1200 lines.append(" Headers:")
1201 for header in snapshot.httpHeaders {
1202 lines.append(" \(header.name): \(header.value)")
1203 }
1204 }
1205 }
1206
1207 if let redirectChainError = snapshot.redirectChainError {
1208 lines.append(" Redirect Error: \(redirectChainError)")
1209 } else if snapshot.redirectChain.isEmpty {
1210 lines.append(" Redirects: No redirect data available")
1211 } else {
1212 lines.append(" Redirects:")
1213 for hop in redirectRows(from: snapshot) {
1214 lines.append(" \(hop.stepLabel). \(hop.statusCode) \(hop.url)\(hop.isFinal ? " (final)" : "")")
1215 }
1216 }
1217 }
1218
1219 appendSection("Email") {
1220 if let emailSecurityError = snapshot.emailSecurityError {
1221 lines.append(" Error: \(emailSecurityError)")
1222 } else if emailRows(from: snapshot).isEmpty {
1223 lines.append(" No email security records found")
1224 } else {
1225 for row in emailRows(from: snapshot) {
1226 lines.append(" \(row.label): \(row.status)")
1227 lines.append(" \(row.detail)")
1228 if let auxiliaryDetail = row.auxiliaryDetail {
1229 lines.append(" \(auxiliaryDetail)")
1230 }
1231 }
1232 }
1233 }
1234
1235 appendSection("Network") {
1236 if let reachabilityError = snapshot.reachabilityError {
1237 lines.append(" Reachability Error: \(reachabilityError)")
1238 } else if reachabilityRows(from: snapshot).isEmpty {
1239 lines.append(" Reachability: No results")
1240 } else {
1241 lines.append(" Reachability:")
1242 for row in reachabilityRows(from: snapshot) {
1243 lines.append(" \(row.portLabel): \(row.statusLabel) \(row.latencyLabel)")
1244 }
1245 }
1246
1247 if let ipGeolocationError = snapshot.ipGeolocationError, snapshot.ipGeolocation == nil {
1248 lines.append(" Location Error: \(ipGeolocationError)")
1249 } else if locationRows(from: snapshot).isEmpty {
1250 lines.append(" Location: No data")
1251 } else {
1252 lines.append(" Location:")
1253 for row in locationRows(from: snapshot) {
1254 lines.append(" \(row.label): \(row.value)")
1255 }
1256 }
1257
1258 if let portScanError = snapshot.portScanError, snapshot.portScanResults.isEmpty {
1259 lines.append(" Port Scan Error: \(portScanError)")
1260 }
1261
1262 lines.append(" Standard Ports:")
1263 let standardRows = portRows(from: snapshot, kind: .standard)
1264 if standardRows.isEmpty {
1265 lines.append(" No results")
1266 } else {
1267 for row in standardRows {
1268 lines.append(" \(row.portLabel) \(row.service): \(row.statusLabel)\(row.durationLabel.map { " \($0)" } ?? "")")
1269 if let banner = row.banner {
1270 lines.append(" Banner: \(banner)")
1271 }
1272 }
1273 }
1274
1275 lines.append(" Custom Ports:")
1276 let customRows = portRows(from: snapshot, kind: .custom)
1277 if customRows.isEmpty {
1278 lines.append(" No results")
1279 } else {
1280 for row in customRows {
1281 lines.append(" \(row.portLabel) \(row.service): \(row.statusLabel)\(row.durationLabel.map { " \($0)" } ?? "")")
1282 if let banner = row.banner {
1283 lines.append(" Banner: \(banner)")
1284 }
1285 }
1286 }
1287 }
1288
1289 return lines.joined(separator: "\n")
1290 }
1291
1292 private static func primaryIPAddress(from snapshot: LookupSnapshot) -> String? {
1293 snapshot.dnsSections.first(where: { $0.recordType == .A })?.records.first?.value
1294 }
1295
1296 private static func finalRedirectTarget(from snapshot: LookupSnapshot) -> String? {
1297 snapshot.redirectChain.last?.url
1298 }
1299
1300 private static func httpsSummary(from snapshot: LookupSnapshot) -> String {
1301 if snapshot.sslInfo != nil {
1302 return "Valid"
1303 }
1304 if let sslError = snapshot.sslError {
1305 return sslError.localizedCaseInsensitiveContains("certificate") ? "Invalid" : "Failed"
1306 }
1307 return "Unavailable"
1308 }
1309
1310 private static func httpsSummaryTone(from snapshot: LookupSnapshot) -> ResultTone {
1311 if snapshot.sslInfo != nil {
1312 return .success
1313 }
1314 return snapshot.sslError == nil ? .secondary : .failure
1315 }
1316
1317 private static func emailSummary(from snapshot: LookupSnapshot) -> String {
1318 guard let emailSecurity = snapshot.emailSecurity else {
1319 return snapshot.emailSecurityError ?? "Unavailable"
1320 }
1321 return "SPF \(emailSecurity.spf.found ? "Yes" : "No") / DMARC \(emailSecurity.dmarc.found ? "Yes" : "No")"
1322 }
1323
1324 private static func availabilityLabel(_ status: DomainAvailabilityStatus?) -> String {
1325 switch status {
1326 case .available:
1327 return "Available"
1328 case .registered:
1329 return "Registered"
1330 case .unknown, .none:
1331 return "Unknown"
1332 }
1333 }
1334
1335 private static func availabilityTone(_ status: DomainAvailabilityStatus?) -> ResultTone {
1336 switch status {
1337 case .available:
1338 return .success
1339 case .registered:
1340 return .warning
1341 case .unknown, .none:
1342 return .secondary
1343 }
1344 }
1345
1346 private static func securityGradeTone(_ grade: String) -> ResultTone {
1347 switch grade {
1348 case "A", "B":
1349 return .success
1350 case "C":
1351 return .warning
1352 case "D", "F":
1353 return .failure
1354 default:
1355 return .secondary
1356 }
1357 }
1358
1359 private static func durationLabel(_ durationMs: Int?) -> String {
1360 durationMs.map { "\($0) ms" } ?? "Unavailable"
1361 }
1362
1363 private static let certificateDateFormatter: DateFormatter = {
1364 let formatter = DateFormatter()
1365 formatter.dateStyle = .medium
1366 formatter.timeStyle = .short
1367 return formatter
1368 }()
1369}
1370
1371private extension String {
1372 var nonEmpty: String? {
1373 isEmpty ? nil : self
1374 }
1375
1376 var nilIfEmpty: String? {
1377 isEmpty ? nil : self
1378 }
1379}