DomainInspectionService.swift

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

225 lines · 9540 bytes

  1import Foundation
  2
  3struct DomainInspectionService {
  4    private let reportBuilder = DomainReportBuilder()
  5
  6    func inspect(domain: String) async -> DomainReport {
  7        let snapshot = await inspectSnapshot(domain: domain)
  8        return reportBuilder.build(from: snapshot)
  9    }
 10
 11    func inspectSnapshot(domain: String) async -> LookupSnapshot {
 12        let normalizedDomain = normalize(domain)
 13        let startedAt = Date()
 14        let resolverDisplayName = DNSLookupService.currentResolverDisplayName()
 15        let resolverURLString = DNSLookupService.currentResolverURLString()
 16
 17        async let dnsResult = DNSLookupService.lookupAll(domain: normalizedDomain)
 18        async let availabilityResult = DomainAvailabilityService.check(domain: normalizedDomain)
 19        async let sslResult = SSLCheckService.check(domain: normalizedDomain)
 20        async let hstsResult = SSLCheckService.checkHSTSPreload(domain: normalizedDomain)
 21        async let httpResult = HTTPHeadersService.fetch(domain: normalizedDomain)
 22        async let reachabilityResult = ReachabilityService.checkAll(domain: normalizedDomain)
 23        async let ownershipResult = DomainOwnershipService.lookup(domain: normalizedDomain)
 24        async let redirectResult = RedirectChainService.trace(domain: normalizedDomain)
 25        async let subdomainResult = SubdomainDiscoveryService.discover(for: normalizedDomain)
 26        async let portScanResult = PortScanService.scanAll(domain: normalizedDomain)
 27
 28        let resolvedDNS = await dnsResult
 29        let availability = await availabilityResult
 30        let resolvedSSL = await sslResult
 31        let hsts = await hstsResult
 32        let http = await httpResult
 33        let reachability = await reachabilityResult
 34        let resolvedOwnership = await ownershipResult
 35        let redirects = await redirectResult
 36        let resolvedSubdomains = await subdomainResult
 37        let ports = await portScanResult
 38
 39        let dnsSections = mapServiceResult(resolvedDNS, emptyValue: [])
 40        let sslInfo = mapOptionalValueServiceResult(resolvedSSL)
 41        let httpHeadersResult = mapHTTPResult(http)
 42        let reachabilityResultValue = mapServiceResult(reachability, emptyValue: [])
 43        let redirectChain = mapServiceResult(redirects, emptyValue: [])
 44        let ownership = mapOptionalValueServiceResult(resolvedOwnership)
 45        let subdomains = mapServiceResult(resolvedSubdomains, emptyValue: [])
 46        let portScanResults = await mapPortScanResult(ports, domain: normalizedDomain)
 47
 48        let txtRecords = dnsSections.value.first(where: { $0.recordType == .TXT })?.records ?? []
 49        let primaryIP = dnsSections.value.first(where: { $0.recordType == .A })?.records.first?.value
 50
 51        async let emailResult = EmailSecurityService.analyze(domain: normalizedDomain, txtRecords: txtRecords)
 52        async let suggestions = availability.status == .registered
 53            ? DomainAvailabilityService.suggestions(for: normalizedDomain)
 54            : []
 55
 56        let resolvedEmail = await emailResult
 57        let resolvedSuggestions = await suggestions
 58
 59        let ptrResult: ServiceResult<String>?
 60        let geoResult: ServiceResult<IPGeolocation>?
 61        if let primaryIP {
 62            ptrResult = await ReverseDNSService.lookup(ip: primaryIP, resolverURLString: resolverURLString)
 63            geoResult = await IPGeolocationService.lookup(ip: primaryIP)
 64        } else {
 65            ptrResult = nil
 66            geoResult = nil
 67        }
 68
 69        let emailSecurity = mapOptionalValueServiceResult(resolvedEmail)
 70        let ptrRecord = mapOptionalServiceResult(ptrResult, missingMessage: "No A record available")
 71        let geolocation = mapOptionalServiceResult(geoResult, missingMessage: "No A record available")
 72
 73        return LookupSnapshot(
 74            historyEntryID: nil,
 75            domain: availability.domain,
 76            timestamp: Date(),
 77            trackedDomainID: nil,
 78            resolverDisplayName: resolverDisplayName,
 79            resolverURLString: resolverURLString,
 80            totalLookupDurationMs: Int(Date().timeIntervalSince(startedAt) * 1000),
 81            dnsSections: dnsSections.value,
 82            dnsError: dnsSections.message,
 83            availabilityResult: availability,
 84            suggestions: resolvedSuggestions,
 85            sslInfo: sslInfo.value,
 86            sslError: sslInfo.message,
 87            hstsPreloaded: hsts,
 88            httpHeaders: httpHeadersResult.headers,
 89            httpSecurityGrade: httpHeadersResult.securityGrade,
 90            httpStatusCode: httpHeadersResult.statusCode,
 91            httpResponseTimeMs: httpHeadersResult.responseTimeMs,
 92            httpProtocol: httpHeadersResult.httpProtocol,
 93            http3Advertised: httpHeadersResult.http3Advertised,
 94            httpHeadersError: httpHeadersResult.error,
 95            reachabilityResults: reachabilityResultValue.value,
 96            reachabilityError: reachabilityResultValue.message,
 97            ipGeolocation: geolocation.value,
 98            ipGeolocationError: geolocation.message,
 99            emailSecurity: emailSecurity.value,
100            emailSecurityError: emailSecurity.message,
101            ownership: ownership.value,
102            ownershipError: ownership.message,
103            ptrRecord: ptrRecord.value,
104            ptrError: ptrRecord.message,
105            redirectChain: redirectChain.value,
106            redirectChainError: redirectChain.message,
107            subdomains: subdomains.value,
108            subdomainsError: subdomains.message,
109            portScanResults: portScanResults.value,
110            portScanError: portScanResults.message,
111            changeSummary: nil,
112            isLive: false
113        )
114    }
115
116    private func normalize(_ domain: String) -> String {
117        domain
118            .trimmingCharacters(in: .whitespacesAndNewlines)
119            .replacingOccurrences(of: "https://", with: "")
120            .replacingOccurrences(of: "http://", with: "")
121            .components(separatedBy: "/").first?
122            .lowercased() ?? domain.lowercased()
123    }
124
125    private func mapServiceResult<Value>(_ result: ServiceResult<Value>, emptyValue: Value) -> (value: Value, message: String?) {
126        switch result {
127        case let .success(value):
128            return (value, nil)
129        case let .empty(message), let .error(message):
130            return (emptyValue, message)
131        }
132    }
133
134    private func mapOptionalValueServiceResult<Value>(_ result: ServiceResult<Value>) -> (value: Value?, message: String?) {
135        switch result {
136        case let .success(value):
137            return (value, nil)
138        case let .empty(message), let .error(message):
139            return (nil, message)
140        }
141    }
142
143    private func mapOptionalServiceResult<Value>(
144        _ result: ServiceResult<Value>?,
145        missingMessage: String
146    ) -> (value: Value?, message: String?) {
147        guard let result else {
148            return (nil, missingMessage)
149        }
150
151        switch result {
152        case let .success(value):
153            return (value, nil)
154        case let .empty(message), let .error(message):
155            return (nil, message)
156        }
157    }
158
159    private func mapPortScanResult(_ result: ServiceResult<[PortScanResult]>, domain: String) async -> (value: [PortScanResult], message: String?) {
160        switch result {
161        case let .success(results):
162            return (await enrichOpenPortBanners(in: results, domain: domain), nil)
163        case let .empty(message), let .error(message):
164            return ([], message)
165        }
166    }
167
168    private func mapHTTPResult(_ result: ServiceResult<HTTPHeadersResult>) -> (
169        headers: [HTTPHeader],
170        securityGrade: String?,
171        statusCode: Int?,
172        responseTimeMs: Int?,
173        httpProtocol: String?,
174        http3Advertised: Bool,
175        error: String?
176    ) {
177        switch result {
178        case let .success(value):
179            return (
180                headers: value.headers,
181                securityGrade: HTTPSecurityGrade.grade(for: value.headers).rawValue,
182                statusCode: value.statusCode,
183                responseTimeMs: value.responseTimeMs,
184                httpProtocol: value.httpProtocol,
185                http3Advertised: value.http3Advertised,
186                error: nil
187            )
188        case let .empty(message), let .error(message):
189            return (
190                headers: [],
191                securityGrade: nil,
192                statusCode: nil,
193                responseTimeMs: nil,
194                httpProtocol: nil,
195                http3Advertised: false,
196                error: message
197            )
198        }
199    }
200
201    private func enrichOpenPortBanners(in results: [PortScanResult], domain: String) async -> [PortScanResult] {
202        let banners = await withTaskGroup(of: (UInt16, String?).self, returning: [UInt16: String].self) { group in
203            for result in results where result.open {
204                group.addTask {
205                    let banner = await PortScanService.grabBanner(host: domain, port: result.port)
206                    return (result.port, banner)
207                }
208            }
209
210            var collected: [UInt16: String] = [:]
211            for await (port, banner) in group {
212                if let banner {
213                    collected[port] = banner
214                }
215            }
216            return collected
217        }
218
219        return results.map { result in
220            var updated = result
221            updated.banner = banners[result.port]
222            return updated
223        }
224    }
225}