DomainInspectionService.swift

cc69cbd7e589ec4b065ce74d8c5e7714a040cfc5
domain-dig/DomainInspectionService.swift history · blame · raw

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