DomainInspectionService.swift

9384a668bf36f23f71e25d05b490d1040d308845
domain-dig/DomainInspectionService.swift history · blame · raw

685 lines · 32373 bytes

  1import Foundation
  2
  3struct DomainInspectionService {
  4    private let reportBuilder = DomainReportBuilder()
  5    private let runtime: LookupRuntime
  6
  7    init(runtime: LookupRuntime = .shared) {
  8        self.runtime = runtime
  9    }
 10
 11    func inspect(domain: String, previousSnapshot: LookupSnapshot? = nil) async -> DomainReport {
 12        let snapshot = await inspectSnapshot(domain: domain, previousSnapshot: previousSnapshot)
 13        return reportBuilder.build(from: snapshot)
 14    }
 15
 16    func inspectSnapshot(domain: String, previousSnapshot: LookupSnapshot? = nil) async -> LookupSnapshot {
 17        let normalizedDomain = normalize(domain)
 18        let startedAt = Date()
 19        let resolverDisplayName = DNSLookupService.currentResolverDisplayName()
 20        let resolverURLString = DNSLookupService.currentResolverURLString()
 21        var cachedSections = Set<LookupSectionKind>()
 22        var sectionSources: [LookupResultSource] = []
 23        var provenanceBySection: [LookupSectionKind: SectionProvenance] = [:]
 24        var dataSources = Set<String>()
 25        var errorDetails: [LookupSectionKind: InspectionFailure] = [:]
 26
 27        async let dnsFetch = runtime.dns(domain: normalizedDomain)
 28        async let availabilityFetch = runtime.availability(domain: normalizedDomain)
 29        async let sslFetch = runtime.ssl(domain: normalizedDomain)
 30        async let hstsFetch = runtime.hsts(domain: normalizedDomain)
 31        async let httpFetch = runtime.http(domain: normalizedDomain)
 32        async let reachabilityFetch = runtime.reachability(domain: normalizedDomain)
 33        async let ownershipFetch = runtime.ownership(domain: normalizedDomain)
 34        async let redirectFetch = runtime.redirectChain(domain: normalizedDomain)
 35        async let subdomainFetch = runtime.subdomains(domain: normalizedDomain)
 36        async let portScanFetch = runtime.portScan(domain: normalizedDomain)
 37
 38        let resolvedDNS = await dnsFetch
 39        let dnsResult = normalizeErrors(in: resolvedDNS.value)
 40        track(
 41            .dns,
 42            source: resolvedDNS.source,
 43            provenance: provenance(for: .dns, source: resolvedDNS.source, collectedAt: Date(), resolverDisplayName: resolverDisplayName),
 44            cachedSections: &cachedSections,
 45            sectionSources: &sectionSources,
 46            provenanceBySection: &provenanceBySection,
 47            dataSources: &dataSources
 48        )
 49        captureFailure(for: .dns, result: dnsResult, into: &errorDetails)
 50
 51        let availability = await availabilityFetch
 52        track(
 53            .availability,
 54            source: availability.source,
 55            provenance: provenance(for: .availability, source: availability.source, collectedAt: Date(), resolverDisplayName: resolverDisplayName),
 56            cachedSections: &cachedSections,
 57            sectionSources: &sectionSources,
 58            provenanceBySection: &provenanceBySection,
 59            dataSources: &dataSources
 60        )
 61
 62        let resolvedSSL = await sslFetch
 63        let sslResult = normalizeErrors(in: resolvedSSL.value)
 64        track(
 65            .ssl,
 66            source: resolvedSSL.source,
 67            provenance: provenance(for: .ssl, source: resolvedSSL.source, collectedAt: Date(), resolverDisplayName: resolverDisplayName),
 68            cachedSections: &cachedSections,
 69            sectionSources: &sectionSources,
 70            provenanceBySection: &provenanceBySection,
 71            dataSources: &dataSources
 72        )
 73        captureFailure(for: .ssl, result: sslResult, into: &errorDetails)
 74
 75        let hsts = await hstsFetch
 76        track(
 77            .hsts,
 78            source: hsts.source,
 79            provenance: provenance(for: .hsts, source: hsts.source, collectedAt: Date(), resolverDisplayName: resolverDisplayName),
 80            cachedSections: &cachedSections,
 81            sectionSources: &sectionSources,
 82            provenanceBySection: &provenanceBySection,
 83            dataSources: &dataSources
 84        )
 85
 86        let http = await httpFetch
 87        let httpResult = normalizeErrors(in: http.value)
 88        track(
 89            .httpHeaders,
 90            source: http.source,
 91            provenance: provenance(for: .httpHeaders, source: http.source, collectedAt: Date(), resolverDisplayName: resolverDisplayName),
 92            cachedSections: &cachedSections,
 93            sectionSources: &sectionSources,
 94            provenanceBySection: &provenanceBySection,
 95            dataSources: &dataSources
 96        )
 97        captureFailure(for: .httpHeaders, result: httpResult, into: &errorDetails)
 98
 99        let reachability = await reachabilityFetch
100        let reachabilityResult = normalizeErrors(in: reachability.value)
101        track(
102            .reachability,
103            source: reachability.source,
104            provenance: provenance(for: .reachability, source: reachability.source, collectedAt: Date(), resolverDisplayName: resolverDisplayName),
105            cachedSections: &cachedSections,
106            sectionSources: &sectionSources,
107            provenanceBySection: &provenanceBySection,
108            dataSources: &dataSources
109        )
110        captureFailure(for: .reachability, result: reachabilityResult, into: &errorDetails)
111
112        let resolvedOwnership = await ownershipFetch
113        let ownershipResult = normalizeErrors(in: resolvedOwnership.value)
114        track(
115            .ownership,
116            source: resolvedOwnership.source,
117            provenance: provenance(for: .ownership, source: resolvedOwnership.source, collectedAt: Date(), resolverDisplayName: resolverDisplayName),
118            cachedSections: &cachedSections,
119            sectionSources: &sectionSources,
120            provenanceBySection: &provenanceBySection,
121            dataSources: &dataSources
122        )
123        captureFailure(for: .ownership, result: ownershipResult, into: &errorDetails)
124
125        let redirects = await redirectFetch
126        let redirectResult = normalizeErrors(in: redirects.value)
127        track(
128            .redirectChain,
129            source: redirects.source,
130            provenance: provenance(for: .redirectChain, source: redirects.source, collectedAt: Date(), resolverDisplayName: resolverDisplayName),
131            cachedSections: &cachedSections,
132            sectionSources: &sectionSources,
133            provenanceBySection: &provenanceBySection,
134            dataSources: &dataSources
135        )
136        captureFailure(for: .redirectChain, result: redirectResult, into: &errorDetails)
137
138        let resolvedSubdomains = await subdomainFetch
139        let subdomainResult = normalizeErrors(in: resolvedSubdomains.value)
140        track(
141            .subdomains,
142            source: resolvedSubdomains.source,
143            provenance: provenance(for: .subdomains, source: resolvedSubdomains.source, collectedAt: Date(), resolverDisplayName: resolverDisplayName),
144            cachedSections: &cachedSections,
145            sectionSources: &sectionSources,
146            provenanceBySection: &provenanceBySection,
147            dataSources: &dataSources
148        )
149        captureFailure(for: .subdomains, result: subdomainResult, into: &errorDetails)
150
151        let ports = await portScanFetch
152        let portScanResult = normalizeErrors(in: ports.value)
153        track(
154            .portScan,
155            source: ports.source,
156            provenance: provenance(for: .portScan, source: ports.source, collectedAt: Date(), resolverDisplayName: resolverDisplayName),
157            cachedSections: &cachedSections,
158            sectionSources: &sectionSources,
159            provenanceBySection: &provenanceBySection,
160            dataSources: &dataSources
161        )
162        captureFailure(for: .portScan, result: portScanResult, into: &errorDetails)
163
164        let dnsSections = mapServiceResult(dnsResult, emptyValue: [])
165        let sslInfo = mapOptionalValueServiceResult(sslResult)
166        let httpHeadersResult = mapHTTPResult(httpResult)
167        let reachabilityResultValue = mapServiceResult(reachabilityResult, emptyValue: [])
168        let redirectChain = mapServiceResult(redirectResult, emptyValue: [])
169        let ownership = mapOptionalValueServiceResult(ownershipResult)
170        let subdomains = mapServiceResult(subdomainResult, emptyValue: [])
171        let portScanResults = await mapPortScanResult(portScanResult, domain: normalizedDomain)
172
173        let txtRecords = dnsSections.value.first(where: { $0.recordType == .TXT })?.records ?? []
174        let primaryIP = dnsSections.value.first(where: { $0.recordType == .A })?.records.first?.value
175        let canReuseDNSDependents = canReuseDependentSections(from: previousSnapshot, dnsSections: dnsSections.value)
176        let canReuseIPDependents = canReuseIPBasedSections(from: previousSnapshot, primaryIP: primaryIP)
177
178        let emailOutcome: CachedLookupResult<ServiceResult<EmailSecurityResult>>
179        if canReuseDNSDependents, let previousSnapshot, let emailSecurity = previousSnapshot.emailSecurity {
180            emailOutcome = CachedLookupResult(value: .success(emailSecurity), source: .cached)
181        } else if canReuseDNSDependents, let previousSnapshot, let error = previousSnapshot.emailSecurityError {
182            emailOutcome = CachedLookupResult(value: .error(error), source: .cached)
183        } else {
184            emailOutcome = await runtime.email(domain: normalizedDomain, txtRecords: txtRecords)
185        }
186        let normalizedEmailResult = normalizeErrors(in: emailOutcome.value)
187        track(
188            .emailSecurity,
189            source: emailOutcome.source,
190            provenance: provenance(for: .emailSecurity, source: emailOutcome.source, collectedAt: Date(), resolverDisplayName: resolverDisplayName),
191            cachedSections: &cachedSections,
192            sectionSources: &sectionSources,
193            provenanceBySection: &provenanceBySection,
194            dataSources: &dataSources
195        )
196        captureFailure(for: .emailSecurity, result: normalizedEmailResult, into: &errorDetails)
197
198        let suggestionsOutcome: CachedLookupResult<[DomainSuggestionResult]>
199        if availability.value.status == .registered {
200            suggestionsOutcome = await runtime.suggestions(domain: normalizedDomain)
201            track(
202                .suggestions,
203                source: suggestionsOutcome.source,
204                provenance: provenance(for: .suggestions, source: suggestionsOutcome.source, collectedAt: Date(), resolverDisplayName: resolverDisplayName),
205                cachedSections: &cachedSections,
206                sectionSources: &sectionSources,
207                provenanceBySection: &provenanceBySection,
208                dataSources: &dataSources
209            )
210        } else {
211            suggestionsOutcome = CachedLookupResult(value: [], source: .live)
212        }
213
214        let ptrOutcome: CachedLookupResult<ServiceResult<String>>?
215        let geoOutcome: CachedLookupResult<ServiceResult<IPGeolocation>>?
216        if let primaryIP {
217            if canReuseIPDependents, let previousSnapshot, let ptrRecord = previousSnapshot.ptrRecord {
218                ptrOutcome = CachedLookupResult(value: .success(ptrRecord), source: .cached)
219            } else if canReuseIPDependents, let previousSnapshot, let ptrError = previousSnapshot.ptrError {
220                ptrOutcome = CachedLookupResult(value: .error(ptrError), source: .cached)
221            } else {
222                ptrOutcome = await runtime.ptr(ip: primaryIP, resolverURLString: resolverURLString)
223            }
224
225            if canReuseIPDependents, let previousSnapshot, let ipGeolocation = previousSnapshot.ipGeolocation {
226                geoOutcome = CachedLookupResult(value: .success(ipGeolocation), source: .cached)
227            } else if canReuseIPDependents, let previousSnapshot, let ipGeolocationError = previousSnapshot.ipGeolocationError {
228                geoOutcome = CachedLookupResult(value: .error(ipGeolocationError), source: .cached)
229            } else {
230                geoOutcome = await runtime.ipGeolocation(ip: primaryIP)
231            }
232
233            if let ptrOutcome {
234                let normalizedPTRResult = normalizeErrors(in: ptrOutcome.value)
235                track(
236                    .ptr,
237                    source: ptrOutcome.source,
238                    provenance: provenance(for: .ptr, source: ptrOutcome.source, collectedAt: Date(), resolverDisplayName: resolverDisplayName),
239                    cachedSections: &cachedSections,
240                    sectionSources: &sectionSources,
241                    provenanceBySection: &provenanceBySection,
242                    dataSources: &dataSources
243                )
244                captureFailure(for: .ptr, result: normalizedPTRResult, into: &errorDetails)
245            }
246            if let geoOutcome {
247                let normalizedGeoResult = normalizeErrors(in: geoOutcome.value)
248                track(
249                    .ipGeolocation,
250                    source: geoOutcome.source,
251                    provenance: provenance(for: .ipGeolocation, source: geoOutcome.source, collectedAt: Date(), resolverDisplayName: resolverDisplayName),
252                    cachedSections: &cachedSections,
253                    sectionSources: &sectionSources,
254                    provenanceBySection: &provenanceBySection,
255                    dataSources: &dataSources
256                )
257                captureFailure(for: .ipGeolocation, result: normalizedGeoResult, into: &errorDetails)
258            }
259        } else {
260            ptrOutcome = nil
261            geoOutcome = nil
262        }
263
264        let emailSecurity = mapOptionalValueServiceResult(normalizedEmailResult)
265        let ptrRecord = mapOptionalServiceResult(ptrOutcome.map { normalizeErrors(in: $0.value) }, missingMessage: "No A record available")
266        let geolocation = mapOptionalServiceResult(geoOutcome.map { normalizeErrors(in: $0.value) }, missingMessage: "No A record available")
267        let availabilityConfidence = confidenceForAvailability(result: availability.value, provenance: provenanceBySection[.availability])
268        let ownershipConfidence = confidenceForOwnership(result: ownership.value, error: ownership.message)
269        let subdomainConfidence = confidenceForSubdomains(results: subdomains.value, error: subdomains.message)
270        let emailConfidence = confidenceForEmail(result: emailSecurity.value, error: emailSecurity.message)
271        let geolocationConfidence = confidenceForGeolocation(result: geolocation.value, error: geolocation.message)
272        let validationIssues = validationIssues(for: normalizedDomain, snapshotTimestamp: startedAt, availability: availability.value, dnsSections: dnsSections.value, provenanceBySection: provenanceBySection)
273
274        return LookupSnapshot(
275            historyEntryID: nil,
276            domain: availability.value.domain,
277            timestamp: Date(),
278            trackedDomainID: previousSnapshot?.trackedDomainID,
279            note: previousSnapshot?.note,
280            appVersion: AppVersion.current,
281            resolverDisplayName: resolverDisplayName,
282            resolverURLString: resolverURLString,
283            dataSources: Array(dataSources).sorted(),
284            provenanceBySection: provenanceBySection,
285            availabilityConfidence: availabilityConfidence,
286            ownershipConfidence: ownershipConfidence,
287            subdomainConfidence: subdomainConfidence,
288            emailSecurityConfidence: emailConfidence,
289            geolocationConfidence: geolocationConfidence,
290            errorDetails: errorDetails,
291            isPartialSnapshot: !validationIssues.isEmpty,
292            validationIssues: validationIssues,
293            totalLookupDurationMs: Int(Date().timeIntervalSince(startedAt) * 1000),
294            dnsSections: dnsSections.value,
295            dnsError: dnsSections.message,
296            availabilityResult: availability.value,
297            suggestions: suggestionsOutcome.value,
298            sslInfo: sslInfo.value,
299            sslError: sslInfo.message,
300            hstsPreloaded: hsts.value,
301            httpHeaders: httpHeadersResult.headers,
302            httpSecurityGrade: httpHeadersResult.securityGrade,
303            httpStatusCode: httpHeadersResult.statusCode,
304            httpResponseTimeMs: httpHeadersResult.responseTimeMs,
305            httpProtocol: httpHeadersResult.httpProtocol,
306            http3Advertised: httpHeadersResult.http3Advertised,
307            httpHeadersError: httpHeadersResult.error,
308            reachabilityResults: reachabilityResultValue.value,
309            reachabilityError: reachabilityResultValue.message,
310            ipGeolocation: geolocation.value,
311            ipGeolocationError: geolocation.message,
312            emailSecurity: emailSecurity.value,
313            emailSecurityError: emailSecurity.message,
314            ownership: ownership.value,
315            ownershipError: ownership.message,
316            ptrRecord: ptrRecord.value,
317            ptrError: ptrRecord.message,
318            redirectChain: redirectChain.value,
319            redirectChainError: redirectChain.message,
320            subdomains: subdomains.value,
321            subdomainsError: subdomains.message,
322            portScanResults: portScanResults.value,
323            portScanError: portScanResults.message,
324            changeSummary: nil,
325            resultSource: aggregateSource(sectionSources),
326            cachedSections: Array(cachedSections).sorted { $0.rawValue < $1.rawValue },
327            statusMessage: nil
328        )
329    }
330
331    private func normalize(_ domain: String) -> String {
332        domain
333            .trimmingCharacters(in: .whitespacesAndNewlines)
334            .replacingOccurrences(of: "https://", with: "")
335            .replacingOccurrences(of: "http://", with: "")
336            .components(separatedBy: "/").first?
337            .lowercased() ?? domain.lowercased()
338    }
339
340    private func track(
341        _ section: LookupSectionKind,
342        source: LookupResultSource,
343        provenance: SectionProvenance,
344        cachedSections: inout Set<LookupSectionKind>,
345        sectionSources: inout [LookupResultSource],
346        provenanceBySection: inout [LookupSectionKind: SectionProvenance],
347        dataSources: inout Set<String>
348    ) {
349        sectionSources.append(source)
350        provenanceBySection[section] = provenance
351        dataSources.insert(provenance.provider ?? provenance.source)
352        if source != .live {
353            cachedSections.insert(section)
354        }
355    }
356
357    private func provenance(
358        for section: LookupSectionKind,
359        source: LookupResultSource,
360        collectedAt: Date,
361        resolverDisplayName: String
362    ) -> SectionProvenance {
363        switch section {
364        case .dns, .ptr:
365            return SectionProvenance(
366                source: "DNS-over-HTTPS query",
367                collectedAt: collectedAt,
368                provider: "Selected DoH resolver",
369                resolver: resolverDisplayName,
370                resultSource: source
371            )
372        case .availability:
373            return SectionProvenance(
374                source: "RDAP lookup with DNS fallback",
375                collectedAt: collectedAt,
376                provider: "rdap.org / selected resolver",
377                resolver: resolverDisplayName,
378                resultSource: source
379            )
380        case .ssl:
381            return SectionProvenance(source: "Direct TLS handshake", collectedAt: collectedAt, provider: "Target host", resolver: nil, resultSource: source)
382        case .hsts, .httpHeaders, .redirectChain:
383            return SectionProvenance(source: "HTTP request", collectedAt: collectedAt, provider: "Target host", resolver: nil, resultSource: source)
384        case .reachability:
385            return SectionProvenance(source: "TCP reachability probe", collectedAt: collectedAt, provider: "Target host", resolver: nil, resultSource: source)
386        case .ipGeolocation:
387            return SectionProvenance(source: "IP geolocation lookup", collectedAt: collectedAt, provider: "ipapi.co", resolver: nil, resultSource: source)
388        case .emailSecurity:
389            return SectionProvenance(source: "DNS TXT inspection", collectedAt: collectedAt, provider: "Selected DoH resolver", resolver: resolverDisplayName, resultSource: source)
390        case .ownership:
391            return SectionProvenance(source: "RDAP domain lookup", collectedAt: collectedAt, provider: "rdap.org", resolver: nil, resultSource: source)
392        case .subdomains:
393            return SectionProvenance(source: "Certificate transparency search", collectedAt: collectedAt, provider: "crt.sh", resolver: nil, resultSource: source)
394        case .portScan:
395            return SectionProvenance(source: "TCP port scan", collectedAt: collectedAt, provider: "Target host", resolver: nil, resultSource: source)
396        case .suggestions:
397            return SectionProvenance(source: "Availability suggestions", collectedAt: collectedAt, provider: "DomainDig heuristic", resolver: resolverDisplayName, resultSource: source)
398        }
399    }
400
401    private func aggregateSource(_ sectionSources: [LookupResultSource]) -> LookupResultSource {
402        let normalizedSources = sectionSources.map { source -> LookupResultSource in
403            source == .mixed ? .cached : source
404        }
405
406        let hasLive = normalizedSources.contains(.live)
407        let hasCached = normalizedSources.contains(.cached)
408
409        switch (hasLive, hasCached) {
410        case (true, true):
411            return .mixed
412        case (false, true):
413            return .cached
414        default:
415            return .live
416        }
417    }
418
419    private func canReuseDependentSections(from previousSnapshot: LookupSnapshot?, dnsSections: [DNSSection]) -> Bool {
420        guard let previousSnapshot else { return false }
421        return dnsSignature(for: previousSnapshot.dnsSections) == dnsSignature(for: dnsSections)
422    }
423
424    private func canReuseIPBasedSections(from previousSnapshot: LookupSnapshot?, primaryIP: String?) -> Bool {
425        guard let previousSnapshot else { return false }
426        let previousIP = previousSnapshot.dnsSections.first(where: { $0.recordType == .A })?.records.first?.value
427        return primaryIP == previousIP
428    }
429
430    private func dnsSignature(for sections: [DNSSection]) -> String {
431        sections
432            .sorted { $0.recordType.rawValue < $1.recordType.rawValue }
433            .map { section in
434                let records = section.records
435                    .sorted { $0.value < $1.value }
436                    .map { "\($0.value)|\($0.ttl)" }
437                    .joined(separator: ",")
438                let wildcardRecords = section.wildcardRecords
439                    .sorted { $0.value < $1.value }
440                    .map { "\($0.value)|\($0.ttl)" }
441                    .joined(separator: ",")
442                return [
443                    section.recordType.rawValue,
444                    records,
445                    wildcardRecords,
446                    section.dnssecSigned.map { $0 ? "signed" : "unsigned" } ?? "unknown",
447                    section.error ?? ""
448                ].joined(separator: "#")
449            }
450            .joined(separator: "||")
451    }
452
453    private func normalizeErrors<Value>(in result: ServiceResult<Value>) -> ServiceResult<Value> {
454        switch result {
455        case let .success(value):
456            return .success(value)
457        case let .empty(message):
458            return .empty(classifyFailure(from: message, defaultKind: .unavailable).message)
459        case let .error(message):
460            return .error(classifyFailure(from: message).message)
461        }
462    }
463
464    private func classifyFailure(from message: String, defaultKind: InspectionErrorKind = .unknown) -> InspectionFailure {
465        let normalizedMessage = message.trimmingCharacters(in: .whitespacesAndNewlines)
466        let lowercasedMessage = normalizedMessage.lowercased()
467        if lowercasedMessage.contains("timed out") {
468            return InspectionFailure(kind: .timeout, message: "Timed out", details: normalizedMessage)
469        }
470        if lowercasedMessage.contains("429")
471            || lowercasedMessage.contains("too many requests")
472            || lowercasedMessage.contains("rate limit") {
473            return InspectionFailure(kind: .rateLimited, message: "Rate limited", details: normalizedMessage)
474        }
475        if lowercasedMessage.contains("cannot parse")
476            || lowercasedMessage.contains("decoding")
477            || lowercasedMessage.contains("json") {
478            return InspectionFailure(kind: .parsing, message: "Could not parse response", details: normalizedMessage)
479        }
480        if lowercasedMessage.contains("offline")
481            || lowercasedMessage.contains("internet connection")
482            || lowercasedMessage.contains("not connected")
483            || lowercasedMessage.contains("network connection") {
484            return InspectionFailure(kind: .network, message: "Network unavailable", details: normalizedMessage)
485        }
486        if lowercasedMessage.contains("unsupported") {
487            return InspectionFailure(kind: .unsupported, message: "Unsupported for this target", details: normalizedMessage)
488        }
489        if lowercasedMessage == "unavailable" || lowercasedMessage.contains("no a record available") {
490            return InspectionFailure(kind: .unavailable, message: normalizedMessage, details: nil)
491        }
492        if defaultKind == .unavailable {
493            return InspectionFailure(kind: .unavailable, message: normalizedMessage, details: nil)
494        }
495        return InspectionFailure(kind: .unknown, message: normalizedMessage.isEmpty ? defaultKind.title : normalizedMessage, details: normalizedMessage)
496    }
497
498    private func captureFailure<Value>(
499        for section: LookupSectionKind,
500        result: ServiceResult<Value>,
501        into errorDetails: inout [LookupSectionKind: InspectionFailure]
502    ) {
503        switch result {
504        case .success:
505            return
506        case let .empty(message):
507            errorDetails[section] = classifyFailure(from: message, defaultKind: .unavailable)
508        case let .error(message):
509            errorDetails[section] = classifyFailure(from: message)
510        }
511    }
512
513    private func confidenceForAvailability(result: DomainAvailabilityResult, provenance: SectionProvenance?) -> ConfidenceLevel {
514        guard result.status != .unknown else { return .low }
515        if provenance?.provider?.localizedCaseInsensitiveContains("rdap.org") == true, result.status == .registered {
516            return .high
517        }
518        if result.status == .registered {
519            return .medium
520        }
521        return .low
522    }
523
524    private func confidenceForOwnership(result: DomainOwnership?, error: String?) -> ConfidenceLevel {
525        guard let result else { return error == nil ? .low : .low }
526        let hasDirectRegistrationData = result.registrar != nil || result.createdDate != nil || result.expirationDate != nil
527        return hasDirectRegistrationData ? .high : .medium
528    }
529
530    private func confidenceForSubdomains(results: [DiscoveredSubdomain], error: String?) -> ConfidenceLevel {
531        if !results.isEmpty {
532            return .medium
533        }
534        return error == nil ? .low : .low
535    }
536
537    private func confidenceForEmail(result: EmailSecurityResult?, error: String?) -> ConfidenceLevel {
538        guard let result else { return error == nil ? .low : .low }
539        let foundCount = [result.spf.found, result.dmarc.found, result.dkim.found, result.bimi.found, result.mtaSts?.txtFound == true]
540            .filter { $0 }
541            .count
542        if foundCount >= 3 {
543            return .high
544        }
545        if foundCount >= 1 {
546            return .medium
547        }
548        return .low
549    }
550
551    private func confidenceForGeolocation(result: IPGeolocation?, error: String?) -> ConfidenceLevel {
552        guard let result else { return error == nil ? .low : .low }
553        if result.city != nil && result.country_name != nil && result.latitude != nil && result.longitude != nil {
554            return .high
555        }
556        if result.country_name != nil || result.org != nil {
557            return .medium
558        }
559        return .low
560    }
561
562    private func validationIssues(
563        for domain: String,
564        snapshotTimestamp: Date,
565        availability: DomainAvailabilityResult,
566        dnsSections: [DNSSection],
567        provenanceBySection: [LookupSectionKind: SectionProvenance]
568    ) -> [String] {
569        var issues: [String] = []
570        if domain.isEmpty {
571            issues.append("Missing normalized domain")
572        }
573        if availability.domain.isEmpty {
574            issues.append("Missing normalized availability domain")
575        }
576        if dnsSections.isEmpty && provenanceBySection[.dns] == nil {
577            issues.append("Missing DNS provenance")
578        }
579        if snapshotTimestamp > Date().addingTimeInterval(5) {
580            issues.append("Snapshot timestamp is in the future")
581        }
582        return issues
583    }
584
585    private func mapServiceResult<Value>(_ result: ServiceResult<Value>, emptyValue: Value) -> (value: Value, message: String?) {
586        switch result {
587        case let .success(value):
588            return (value, nil)
589        case let .empty(message), let .error(message):
590            return (emptyValue, message)
591        }
592    }
593
594    private func mapOptionalValueServiceResult<Value>(_ result: ServiceResult<Value>) -> (value: Value?, message: String?) {
595        switch result {
596        case let .success(value):
597            return (value, nil)
598        case let .empty(message), let .error(message):
599            return (nil, message)
600        }
601    }
602
603    private func mapOptionalServiceResult<Value>(
604        _ result: ServiceResult<Value>?,
605        missingMessage: String
606    ) -> (value: Value?, message: String?) {
607        guard let result else {
608            return (nil, missingMessage)
609        }
610
611        switch result {
612        case let .success(value):
613            return (value, nil)
614        case let .empty(message), let .error(message):
615            return (nil, message)
616        }
617    }
618
619    private func mapPortScanResult(_ result: ServiceResult<[PortScanResult]>, domain: String) async -> (value: [PortScanResult], message: String?) {
620        switch result {
621        case let .success(results):
622            return (await enrichOpenPortBanners(in: results, domain: domain), nil)
623        case let .empty(message), let .error(message):
624            return ([], message)
625        }
626    }
627
628    private func mapHTTPResult(_ result: ServiceResult<HTTPHeadersResult>) -> (
629        headers: [HTTPHeader],
630        securityGrade: String?,
631        statusCode: Int?,
632        responseTimeMs: Int?,
633        httpProtocol: String?,
634        http3Advertised: Bool,
635        error: String?
636    ) {
637        switch result {
638        case let .success(value):
639            return (
640                headers: value.headers,
641                securityGrade: HTTPSecurityGrade.grade(for: value.headers).rawValue,
642                statusCode: value.statusCode,
643                responseTimeMs: value.responseTimeMs,
644                httpProtocol: value.httpProtocol,
645                http3Advertised: value.http3Advertised,
646                error: nil
647            )
648        case let .empty(message), let .error(message):
649            return (
650                headers: [],
651                securityGrade: nil,
652                statusCode: nil,
653                responseTimeMs: nil,
654                httpProtocol: nil,
655                http3Advertised: false,
656                error: message
657            )
658        }
659    }
660
661    private func enrichOpenPortBanners(in results: [PortScanResult], domain: String) async -> [PortScanResult] {
662        let banners = await withTaskGroup(of: (UInt16, String?).self, returning: [UInt16: String].self) { group in
663            for result in results where result.open {
664                group.addTask {
665                    let banner = await PortScanService.grabBanner(host: domain, port: result.port)
666                    return (result.port, banner)
667                }
668            }
669
670            var collected: [UInt16: String] = [:]
671            for await (port, banner) in group {
672                if let banner {
673                    collected[port] = banner
674                }
675            }
676            return collected
677        }
678
679        return results.map { result in
680            var updated = result
681            updated.banner = banners[result.port]
682            return updated
683        }
684    }
685}