DomainInspectionService.swift

v5.1.0
domain-dig/DomainInspectionService.swift history · blame · raw

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