summaryrefslogtreecommitdiff
path: root/DomainDigCLI.swift
blob: a6d2cf3de91aeb83110888fa9e6a329e8faa1d7c (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
import Foundation

@main
struct DomainDigCLI {
    static func main() async {
        let arguments = Array(CommandLine.arguments.dropFirst())

        guard let command = CommandLine.arguments.first else {
            fputs("usage: domaindig <domain> [--json] [--ownership-history] [--dns-history] [--extended-subdomains] [--pricing] [--show-usage]\n", stderr)
            Foundation.exit(1)
        }
        _ = command

        let wantsJSON = arguments.contains("--json") || arguments.contains("-j")
        let wantsOwnershipHistory = arguments.contains("--ownership-history")
        let wantsDNSHistory = arguments.contains("--dns-history")
        let wantsExtendedSubdomains = arguments.contains("--extended-subdomains")
        let wantsPricing = arguments.contains("--pricing")
        let wantsUsage = arguments.contains("--show-usage")
        let domains = arguments.filter { !$0.hasPrefix("-") }

        let requestedDomains = domains
            .map { $0.trimmingCharacters(in: .whitespacesAndNewlines) }
            .filter { !$0.isEmpty }

        guard !requestedDomains.isEmpty else {
            fputs("usage: domaindig <domain> [--json] [--ownership-history] [--dns-history] [--extended-subdomains] [--pricing] [--show-usage]\n", stderr)
            Foundation.exit(1)
        }

        let inspectionService = DomainInspectionService()
        let reportBuilder = DomainReportBuilder()
        var reports: [DomainReport] = []
        var seen = Set<String>()
        var usageImpact: [String] = []

        for domain in requestedDomains {
            let normalizedDomain = domain.lowercased()
            guard seen.insert(normalizedDomain).inserted else { continue }
            let snapshot = await inspectionService.inspectSnapshot(domain: domain)
            let enrichedSnapshot = await enrichSnapshot(
                snapshot,
                wantsOwnershipHistory: wantsOwnershipHistory,
                wantsDNSHistory: wantsDNSHistory,
                wantsExtendedSubdomains: wantsExtendedSubdomains,
                wantsPricing: wantsPricing,
                usageImpact: &usageImpact
            )
            reports.append(reportBuilder.build(from: enrichedSnapshot))
        }

        do {
            let data: Data
            if reports.count == 1, let report = reports.first {
                data = try DomainReportExporter.data(
                    for: report,
                    format: wantsJSON ? .json : .text
                )
            } else {
                data = try DomainReportExporter.data(
                    for: reports,
                    format: wantsJSON ? .json : .text,
                    title: "DomainDig Batch Report"
                )
            }
            if wantsUsage, !usageImpact.isEmpty {
                FileHandle.standardError.write(Data(("Data+ usage impact: " + usageImpact.joined(separator: ", ") + "\n").utf8))
            }
            FileHandle.standardOutput.write(data)
            if data.last != 0x0A {
                FileHandle.standardOutput.write(Data([0x0A]))
            }
        } catch {
            fputs("domaindig: \(error.localizedDescription)\n", stderr)
            Foundation.exit(1)
        }
    }

    private static func enrichSnapshot(
        _ snapshot: LookupSnapshot,
        wantsOwnershipHistory: Bool,
        wantsDNSHistory: Bool,
        wantsExtendedSubdomains: Bool,
        wantsPricing: Bool,
        usageImpact: inout [String]
    ) async -> LookupSnapshot {
        guard FeatureAccessService.currentTier == .dataPlus else {
            return snapshot
        }

        let historyEntries = loadHistoryEntries()
        var ownershipHistory = snapshot.ownershipHistory
        var ownershipHistoryError = snapshot.ownershipHistoryError
        var dnsHistory = snapshot.dnsHistory
        var dnsHistoryError = snapshot.dnsHistoryError
        var extendedSubdomains = snapshot.extendedSubdomains
        var extendedSubdomainsError = snapshot.extendedSubdomainsError
        var domainPricing = snapshot.domainPricing
        var domainPricingError = snapshot.domainPricingError

        if wantsOwnershipHistory,
           await UsageCreditService.shared.canUse(.ownershipHistory) {
            let outcome = await ExternalDataService.shared.ownershipHistory(
                domain: snapshot.domain,
                currentOwnership: snapshot.ownership,
                historyEntries: historyEntries
            )
            switch outcome.value {
            case let .success(events):
                ownershipHistory = events
                ownershipHistoryError = nil
                if outcome.source != .cached {
                    _ = await UsageCreditService.shared.consume(.ownershipHistory)
                    usageImpact.append("ownership history -1")
                }
            case let .empty(message):
                ownershipHistoryError = message
                if outcome.source != .cached {
                    _ = await UsageCreditService.shared.consume(.ownershipHistory)
                    usageImpact.append("ownership history -1")
                }
            case let .error(message):
                ownershipHistoryError = message
            }
        }

        if wantsDNSHistory,
           await UsageCreditService.shared.canUse(.dnsHistory) {
            let outcome = await ExternalDataService.shared.dnsHistory(
                domain: snapshot.domain,
                dnsSections: snapshot.dnsSections,
                historyEntries: historyEntries
            )
            switch outcome.value {
            case let .success(events):
                dnsHistory = events
                dnsHistoryError = nil
                if outcome.source != .cached {
                    _ = await UsageCreditService.shared.consume(.dnsHistory)
                    usageImpact.append("dns history -1")
                }
            case let .empty(message):
                dnsHistoryError = message
                if outcome.source != .cached {
                    _ = await UsageCreditService.shared.consume(.dnsHistory)
                    usageImpact.append("dns history -1")
                }
            case let .error(message):
                dnsHistoryError = message
            }
        }

        if wantsExtendedSubdomains,
           await UsageCreditService.shared.canUse(.extendedSubdomains) {
            let outcome = await ExternalDataService.shared.extendedSubdomains(
                domain: snapshot.domain,
                existing: snapshot.subdomains
            )
            switch outcome.value {
            case let .success(results):
                extendedSubdomains = results
                extendedSubdomainsError = nil
                if outcome.source != .cached {
                    _ = await UsageCreditService.shared.consume(.extendedSubdomains)
                    usageImpact.append("extended subdomains -1")
                }
            case let .empty(message):
                extendedSubdomainsError = message
                if outcome.source != .cached {
                    _ = await UsageCreditService.shared.consume(.extendedSubdomains)
                    usageImpact.append("extended subdomains -1")
                }
            case let .error(message):
                extendedSubdomainsError = message
            }
        }

        if wantsPricing {
            let outcome = await ExternalDataService.shared.pricing(domain: snapshot.domain)
            switch outcome.value {
            case let .success(pricing):
                domainPricing = pricing
                domainPricingError = nil
            case let .empty(message), let .error(message):
                domainPricingError = message
            }
        }

        return LookupSnapshot(
            historyEntryID: snapshot.historyEntryID,
            domain: snapshot.domain,
            timestamp: snapshot.timestamp,
            trackedDomainID: snapshot.trackedDomainID,
            note: snapshot.note,
            appVersion: snapshot.appVersion,
            resolverDisplayName: snapshot.resolverDisplayName,
            resolverURLString: snapshot.resolverURLString,
            dataSources: snapshot.dataSources,
            provenanceBySection: snapshot.provenanceBySection,
            availabilityConfidence: snapshot.availabilityConfidence,
            ownershipConfidence: snapshot.ownershipConfidence,
            subdomainConfidence: snapshot.subdomainConfidence,
            emailSecurityConfidence: snapshot.emailSecurityConfidence,
            geolocationConfidence: snapshot.geolocationConfidence,
            errorDetails: snapshot.errorDetails,
            isPartialSnapshot: snapshot.isPartialSnapshot,
            validationIssues: snapshot.validationIssues,
            totalLookupDurationMs: snapshot.totalLookupDurationMs,
            dnsSections: snapshot.dnsSections,
            dnsError: snapshot.dnsError,
            availabilityResult: snapshot.availabilityResult,
            suggestions: snapshot.suggestions,
            sslInfo: snapshot.sslInfo,
            sslError: snapshot.sslError,
            hstsPreloaded: snapshot.hstsPreloaded,
            httpHeaders: snapshot.httpHeaders,
            httpSecurityGrade: snapshot.httpSecurityGrade,
            httpStatusCode: snapshot.httpStatusCode,
            httpResponseTimeMs: snapshot.httpResponseTimeMs,
            httpProtocol: snapshot.httpProtocol,
            http3Advertised: snapshot.http3Advertised,
            httpHeadersError: snapshot.httpHeadersError,
            reachabilityResults: snapshot.reachabilityResults,
            reachabilityError: snapshot.reachabilityError,
            ipGeolocation: snapshot.ipGeolocation,
            ipGeolocationError: snapshot.ipGeolocationError,
            emailSecurity: snapshot.emailSecurity,
            emailSecurityError: snapshot.emailSecurityError,
            ownership: snapshot.ownership,
            ownershipError: snapshot.ownershipError,
            ownershipHistory: ownershipHistory,
            ownershipHistoryError: ownershipHistoryError,
            ptrRecord: snapshot.ptrRecord,
            ptrError: snapshot.ptrError,
            redirectChain: snapshot.redirectChain,
            redirectChainError: snapshot.redirectChainError,
            subdomains: snapshot.subdomains,
            subdomainsError: snapshot.subdomainsError,
            extendedSubdomains: extendedSubdomains,
            extendedSubdomainsError: extendedSubdomainsError,
            dnsHistory: dnsHistory,
            dnsHistoryError: dnsHistoryError,
            domainPricing: domainPricing,
            domainPricingError: domainPricingError,
            portScanResults: snapshot.portScanResults,
            portScanError: snapshot.portScanError,
            changeSummary: snapshot.changeSummary,
            resultSource: snapshot.resultSource,
            cachedSections: snapshot.cachedSections,
            statusMessage: snapshot.statusMessage
        )
    }

    private static func loadHistoryEntries() -> [HistoryEntry] {
        guard let data = UserDefaults.standard.data(forKey: "lookupHistory"),
              let entries = try? JSONDecoder().decode([HistoryEntry].self, from: data) else {
            return []
        }
        return entries
    }
}