DomainDig/DomainDiffService.swift

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

539 lines · 20178 bytes

  1import Foundation
  2
  3enum DiffChangeType: String, Codable {
  4    case added
  5    case removed
  6    case changed
  7    case unchanged
  8}
  9
 10struct DomainDiffItem: Identifiable, Equatable {
 11    let id = UUID()
 12    let label: String
 13    let changeType: DiffChangeType
 14    let oldValue: String?
 15    let newValue: String?
 16    let severity: ChangeSeverity
 17
 18    var hasChanges: Bool {
 19        changeType != .unchanged
 20    }
 21
 22    var isMeaningful: Bool {
 23        hasChanges && severity >= .medium
 24    }
 25}
 26
 27struct DomainDiffSection: Identifiable, Equatable {
 28    let id = UUID()
 29    let title: String
 30    let items: [DomainDiffItem]
 31
 32    var hasChanges: Bool {
 33        items.contains(where: \.hasChanges)
 34    }
 35
 36    var severity: ChangeSeverity {
 37        items.map(\.severity).max() ?? .low
 38    }
 39}
 40
 41enum DomainDiffService {
 42    static func diff(from oldSnapshot: LookupSnapshot, to newSnapshot: LookupSnapshot) -> [DomainDiffSection] {
 43        [
 44            availabilitySection(from: oldSnapshot, to: newSnapshot),
 45            primaryIPSection(from: oldSnapshot, to: newSnapshot),
 46            ownershipSection(from: oldSnapshot, to: newSnapshot),
 47            dnsSection(from: oldSnapshot, to: newSnapshot),
 48            redirectSection(from: oldSnapshot, to: newSnapshot),
 49            tlsSection(from: oldSnapshot, to: newSnapshot),
 50            httpSection(from: oldSnapshot, to: newSnapshot),
 51            emailSection(from: oldSnapshot, to: newSnapshot),
 52            subdomainSection(from: oldSnapshot, to: newSnapshot)
 53        ]
 54        .filter { !$0.items.isEmpty }
 55    }
 56
 57    static func summary(
 58        from oldSnapshot: LookupSnapshot,
 59        to newSnapshot: LookupSnapshot,
 60        generatedAt: Date = Date()
 61    ) -> DomainChangeSummary {
 62        let sections = diff(from: oldSnapshot, to: newSnapshot)
 63        let allChangedItems = sections
 64            .flatMap(\.items)
 65            .filter(\.hasChanges)
 66
 67        let highlights = summaryHighlights(from: allChangedItems)
 68        let severity = allChangedItems.map(\.severity).max() ?? .low
 69        let message = summaryMessage(from: allChangedItems, highlights: highlights)
 70        let observedFacts = observedFacts(from: allChangedItems)
 71        let inferredConclusions = highlights.isEmpty ? [] : [message]
 72        let contextNote = comparisonContextNote(from: oldSnapshot, to: newSnapshot)
 73
 74        return DomainChangeSummary(
 75            hasChanges: !allChangedItems.isEmpty,
 76            changedSections: highlights,
 77            message: message,
 78            severity: severity,
 79            generatedAt: generatedAt,
 80            observedFacts: observedFacts,
 81            inferredConclusions: inferredConclusions,
 82            contextNote: contextNote
 83        )
 84    }
 85
 86    static func comparisonContextNote(from oldSnapshot: LookupSnapshot, to newSnapshot: LookupSnapshot) -> String? {
 87        var notes: [String] = []
 88        if oldSnapshot.resolverURLString != newSnapshot.resolverURLString {
 89            notes.append("Compared snapshots used different DNS resolvers.")
 90        }
 91        if oldSnapshot.resultSource != newSnapshot.resultSource {
 92            notes.append("Compared snapshots came from different collection modes.")
 93        }
 94        return notes.isEmpty ? nil : notes.joined(separator: " ")
 95    }
 96
 97    static func certificateWarningLevel(for snapshot: LookupSnapshot) -> CertificateWarningLevel {
 98        guard let days = snapshot.sslInfo?.daysUntilExpiry else {
 99            return .none
100        }
101        if days < 14 {
102            return .critical
103        }
104        if days < 30 {
105            return .warning
106        }
107        return .none
108    }
109
110    private static func availabilitySection(from oldSnapshot: LookupSnapshot, to newSnapshot: LookupSnapshot) -> DomainDiffSection {
111        DomainDiffSection(
112            title: "Availability",
113            items: [
114                compare(
115                    label: "Availability",
116                    oldValue: availabilityLabel(oldSnapshot.availabilityResult?.status),
117                    newValue: availabilityLabel(newSnapshot.availabilityResult?.status),
118                    severity: .high
119                )
120            ].compactMap { $0 }
121        )
122    }
123
124    private static func primaryIPSection(from oldSnapshot: LookupSnapshot, to newSnapshot: LookupSnapshot) -> DomainDiffSection {
125        DomainDiffSection(
126            title: "Primary IP",
127            items: [
128                compare(
129                    label: "Primary IP",
130                    oldValue: primaryIP(from: oldSnapshot),
131                    newValue: primaryIP(from: newSnapshot),
132                    severity: .high
133                )
134            ].compactMap { $0 }
135        )
136    }
137
138    private static func dnsSection(from oldSnapshot: LookupSnapshot, to newSnapshot: LookupSnapshot) -> DomainDiffSection {
139        let oldSections = Dictionary(uniqueKeysWithValues: oldSnapshot.dnsSections.map { ($0.recordType, $0) })
140        let newSections = Dictionary(uniqueKeysWithValues: newSnapshot.dnsSections.map { ($0.recordType, $0) })
141        let types = Set(oldSections.keys).union(newSections.keys).sorted { $0.rawValue < $1.rawValue }
142
143        var items: [DomainDiffItem] = []
144        for type in types {
145            let oldSection = oldSections[type]
146            let newSection = newSections[type]
147
148            if let recordChange = compare(
149                label: "\(type.rawValue) Records",
150                oldValue: normalizedRecordValues(for: oldSection),
151                newValue: normalizedRecordValues(for: newSection),
152                severity: .medium
153            ) {
154                items.append(recordChange)
155            }
156
157            if let ttlChange = compare(
158                label: "\(type.rawValue) TTL",
159                oldValue: normalizedTTLValues(for: oldSection),
160                newValue: normalizedTTLValues(for: newSection),
161                severity: .low
162            ), let oldSection, let newSection,
163               normalizedRecordValues(for: oldSection) == normalizedRecordValues(for: newSection) {
164                items.append(ttlChange)
165            }
166        }
167
168        return DomainDiffSection(title: "DNS", items: items)
169    }
170
171    private static func ownershipSection(from oldSnapshot: LookupSnapshot, to newSnapshot: LookupSnapshot) -> DomainDiffSection {
172        DomainDiffSection(
173            title: "Ownership",
174            items: [
175                compare(
176                    label: "Registrar",
177                    oldValue: normalized(oldSnapshot.ownership?.registrar),
178                    newValue: normalized(newSnapshot.ownership?.registrar),
179                    severity: .high
180                ),
181                compare(
182                    label: "Registration Date",
183                    oldValue: ownershipDateLabel(oldSnapshot.ownership?.createdDate),
184                    newValue: ownershipDateLabel(newSnapshot.ownership?.createdDate),
185                    severity: .low
186                ),
187                compare(
188                    label: "Expiration Date",
189                    oldValue: ownershipDateLabel(oldSnapshot.ownership?.expirationDate),
190                    newValue: ownershipDateLabel(newSnapshot.ownership?.expirationDate),
191                    severity: .low
192                ),
193                compare(
194                    label: "Ownership Status",
195                    oldValue: ownershipList(oldSnapshot.ownership?.status),
196                    newValue: ownershipList(newSnapshot.ownership?.status),
197                    severity: .low
198                ),
199                compare(
200                    label: "Nameservers",
201                    oldValue: ownershipList(oldSnapshot.ownership?.nameservers),
202                    newValue: ownershipList(newSnapshot.ownership?.nameservers),
203                    severity: .medium
204                ),
205                compare(
206                    label: "Abuse Contact",
207                    oldValue: normalized(oldSnapshot.ownership?.abuseEmail),
208                    newValue: normalized(newSnapshot.ownership?.abuseEmail),
209                    severity: .low
210                )
211            ].compactMap { $0 }
212        )
213    }
214
215    private static func redirectSection(from oldSnapshot: LookupSnapshot, to newSnapshot: LookupSnapshot) -> DomainDiffSection {
216        DomainDiffSection(
217            title: "Redirect",
218            items: [
219                compare(
220                    label: "Redirect Target",
221                    oldValue: finalRedirectURL(from: oldSnapshot),
222                    newValue: finalRedirectURL(from: newSnapshot),
223                    severity: .high
224                )
225            ].compactMap { $0 }
226        )
227    }
228
229    private static func tlsSection(from oldSnapshot: LookupSnapshot, to newSnapshot: LookupSnapshot) -> DomainDiffSection {
230        var items: [DomainDiffItem] = []
231
232        if let issuerChange = compare(
233            label: "TLS Issuer",
234            oldValue: normalized(oldSnapshot.sslInfo?.issuer),
235            newValue: normalized(newSnapshot.sslInfo?.issuer),
236            severity: .medium
237        ) {
238            items.append(issuerChange)
239        }
240
241        if let expiryChange = compare(
242            label: "TLS Expiration",
243            oldValue: expirationLabel(oldSnapshot.sslInfo),
244            newValue: expirationLabel(newSnapshot.sslInfo),
245            severity: .medium
246        ) {
247            items.append(expiryChange)
248        }
249
250        let oldWarning = certificateWarningLevel(for: oldSnapshot)
251        let newWarning = certificateWarningLevel(for: newSnapshot)
252        if oldWarning != newWarning, newWarning != .none {
253            let days = newSnapshot.sslInfo?.daysUntilExpiry ?? 0
254            items.append(
255                DomainDiffItem(
256                    label: "Certificate Warning",
257                    changeType: .changed,
258                    oldValue: oldWarning.title,
259                    newValue: "Certificate expires in \(days) days",
260                    severity: newWarning == .critical ? .high : .medium
261                )
262            )
263        }
264
265        return DomainDiffSection(title: "TLS", items: items)
266    }
267
268    private static func httpSection(from oldSnapshot: LookupSnapshot, to newSnapshot: LookupSnapshot) -> DomainDiffSection {
269        var items: [DomainDiffItem] = []
270
271        if let statusChange = compare(
272            label: "HTTP Status",
273            oldValue: httpStatusSummary(from: oldSnapshot),
274            newValue: httpStatusSummary(from: newSnapshot),
275            severity: .medium
276        ) {
277            items.append(statusChange)
278        }
279
280        if let gradeChange = compare(
281            label: "Security Grade",
282            oldValue: normalized(oldSnapshot.httpSecurityGrade),
283            newValue: normalized(newSnapshot.httpSecurityGrade),
284            severity: .low
285        ) {
286            items.append(gradeChange)
287        }
288
289        if let headerChange = compare(
290            label: "Headers",
291            oldValue: normalizedHeaders(from: oldSnapshot),
292            newValue: normalizedHeaders(from: newSnapshot),
293            severity: .low
294        ) {
295            items.append(headerChange)
296        }
297
298        return DomainDiffSection(title: "HTTP", items: items)
299    }
300
301    private static func emailSection(from oldSnapshot: LookupSnapshot, to newSnapshot: LookupSnapshot) -> DomainDiffSection {
302        DomainDiffSection(
303            title: "Email Security",
304            items: [
305                compare(
306                    label: "Email Security",
307                    oldValue: normalized(emailSummary(from: oldSnapshot)),
308                    newValue: normalized(emailSummary(from: newSnapshot)),
309                    severity: .medium
310                )
311            ].compactMap { $0 }
312        )
313    }
314
315    private static func subdomainSection(from oldSnapshot: LookupSnapshot, to newSnapshot: LookupSnapshot) -> DomainDiffSection {
316        DomainDiffSection(
317            title: "Subdomains",
318            items: [
319                compare(
320                    label: "Passive Subdomains",
321                    oldValue: subdomainList(from: oldSnapshot),
322                    newValue: subdomainList(from: newSnapshot),
323                    severity: .low
324                )
325            ].compactMap { $0 }
326        )
327    }
328
329    private static func compare(
330        label: String,
331        oldValue: String?,
332        newValue: String?,
333        severity: ChangeSeverity
334    ) -> DomainDiffItem? {
335        let oldValue = normalized(oldValue)
336        let newValue = normalized(newValue)
337        let normalizedOldValue = comparisonValue(oldValue)
338        let normalizedNewValue = comparisonValue(newValue)
339
340        guard oldValue != nil || newValue != nil else {
341            return nil
342        }
343
344        let changeType: DiffChangeType
345        switch (normalizedOldValue, normalizedNewValue) {
346        case let (old?, new?) where old == new:
347            changeType = .unchanged
348        case (nil, _?):
349            changeType = .added
350        case (_?, nil):
351            changeType = .removed
352        default:
353            changeType = .changed
354        }
355
356        return DomainDiffItem(
357            label: label,
358            changeType: changeType,
359            oldValue: oldValue,
360            newValue: newValue,
361            severity: severity
362        )
363    }
364
365    private static func summaryHighlights(from items: [DomainDiffItem]) -> [String] {
366        var highlights: [String] = []
367
368        let labels = Set(items.map(\.label))
369        if labels.contains("Availability") {
370            highlights.append("Availability changed")
371        }
372        if labels.contains("Primary IP"), labels.contains(where: { $0.hasSuffix("Records") }) {
373            highlights.append("IP changed")
374            highlights.append("DNS changed")
375            return highlights
376        }
377        if labels.contains("Primary IP") {
378            highlights.append("IP changed")
379        }
380        if labels.contains("Redirect Target") {
381            highlights.append("Redirect target changed")
382        }
383        if labels.contains("Registrar") {
384            highlights.append("Registrar changed")
385        } else if labels.contains("Nameservers") {
386            highlights.append("Nameservers changed")
387        } else if labels.contains("Expiration Date") || labels.contains("Registration Date") || labels.contains("Ownership Status") || labels.contains("Abuse Contact") {
388            highlights.append("Ownership metadata changed")
389        }
390        if let certificateItem = items.first(where: { $0.label == "Certificate Warning" }),
391           let message = certificateItem.newValue {
392            highlights.append(message)
393        } else if labels.contains("TLS Issuer") {
394            highlights.append("TLS issuer changed")
395        } else if labels.contains("TLS Expiration") {
396            highlights.append("Certificate expiration changed")
397        }
398        if labels.contains(where: { $0.hasSuffix("Records") }) {
399            highlights.append("DNS changed")
400        }
401        if labels.contains("HTTP Status") {
402            highlights.append("HTTP status changed")
403        }
404        if labels.contains("Email Security") {
405            highlights.append("Email security changed")
406        }
407        if labels.contains("Passive Subdomains") {
408            highlights.append("Subdomains changed")
409        }
410
411        var deduplicated: [String] = []
412        for highlight in highlights where !deduplicated.contains(highlight) {
413            deduplicated.append(highlight)
414        }
415        return deduplicated
416    }
417
418    private static func summaryMessage(from items: [DomainDiffItem], highlights: [String]) -> String {
419        guard !items.isEmpty, !highlights.isEmpty else {
420            return "No meaningful changes"
421        }
422
423        if highlights.count == 1 {
424            return highlights[0]
425        }
426
427        return "\(highlights[0]) and \(highlights[1].lowercased())"
428    }
429
430    private static func observedFacts(from items: [DomainDiffItem]) -> [String] {
431        items.prefix(3).map { item in
432            let oldValue = item.oldValue ?? "none"
433            let newValue = item.newValue ?? "none"
434            return "\(item.label): \(oldValue) -> \(newValue)"
435        }
436    }
437
438    private static func normalized(_ value: String?) -> String? {
439        guard let value = value?.trimmingCharacters(in: .whitespacesAndNewlines), !value.isEmpty else {
440            return nil
441        }
442        return value
443    }
444
445    private static func comparisonValue(_ value: String?) -> String? {
446        value?.lowercased()
447    }
448
449    private static func availabilityLabel(_ status: DomainAvailabilityStatus?) -> String? {
450        switch status {
451        case .available:
452            return "available"
453        case .registered:
454            return "registered"
455        case .unknown:
456            return "unknown"
457        case .none:
458            return nil
459        }
460    }
461
462    private static func primaryIP(from snapshot: LookupSnapshot) -> String? {
463        snapshot.dnsSections.first(where: { $0.recordType == .A })?.records.first?.value
464    }
465
466    private static func finalRedirectURL(from snapshot: LookupSnapshot) -> String? {
467        snapshot.redirectChain.last?.url
468    }
469
470    private static func expirationLabel(_ sslInfo: SSLCertificateInfo?) -> String? {
471        guard let sslInfo else { return nil }
472        return "\(sslInfo.validUntil.formatted(date: .abbreviated, time: .omitted)) (\(sslInfo.daysUntilExpiry)d)"
473    }
474
475    private static func ownershipDateLabel(_ date: Date?) -> String? {
476        date?.formatted(date: .abbreviated, time: .omitted)
477    }
478
479    private static func httpStatusSummary(from snapshot: LookupSnapshot) -> String? {
480        if let httpStatusCode = snapshot.httpStatusCode {
481            return "\(httpStatusCode)"
482        }
483        return snapshot.httpHeadersError
484    }
485
486    private static func emailSummary(from snapshot: LookupSnapshot) -> String? {
487        if let emailSecurity = snapshot.emailSecurity {
488            return [
489                "spf:\(emailSecurity.spf.found)",
490                "dmarc:\(emailSecurity.dmarc.found)",
491                "dkim:\(emailSecurity.dkim.found)",
492                "bimi:\(emailSecurity.bimi.found)",
493                "mta-sts:\(emailSecurity.mtaSts?.txtFound == true)"
494            ].joined(separator: "|")
495        }
496        return snapshot.emailSecurityError
497    }
498
499    private static func normalizedRecordValues(for section: DNSSection?) -> String? {
500        guard let section else { return nil }
501        let values = (section.records + section.wildcardRecords)
502            .map(\.value)
503            .map { $0.trimmingCharacters(in: .whitespacesAndNewlines).lowercased() }
504            .sorted()
505        return values.isEmpty ? nil : values.joined(separator: ",")
506    }
507
508    private static func normalizedTTLValues(for section: DNSSection?) -> String? {
509        guard let section else { return nil }
510        let values = (section.records + section.wildcardRecords)
511            .map { "\($0.value.trimmingCharacters(in: .whitespacesAndNewlines).lowercased()):\($0.ttl)" }
512            .sorted()
513        return values.isEmpty ? nil : values.joined(separator: ",")
514    }
515
516    private static func normalizedHeaders(from snapshot: LookupSnapshot) -> String? {
517        let headers = snapshot.httpHeaders
518            .map { "\($0.name.lowercased()):\($0.value.trimmingCharacters(in: .whitespacesAndNewlines))" }
519            .sorted()
520        return headers.isEmpty ? nil : headers.joined(separator: "|")
521    }
522
523    private static func ownershipList(_ values: [String]?) -> String? {
524        guard let values else { return nil }
525        let normalizedValues = values
526            .map { $0.trimmingCharacters(in: .whitespacesAndNewlines).lowercased() }
527            .filter { !$0.isEmpty }
528            .sorted()
529        return normalizedValues.isEmpty ? nil : normalizedValues.joined(separator: ",")
530    }
531
532    private static func subdomainList(from snapshot: LookupSnapshot) -> String? {
533        let values = snapshot.subdomains
534            .map(\.hostname)
535            .map { $0.trimmingCharacters(in: .whitespacesAndNewlines).lowercased() }
536            .sorted()
537        return values.isEmpty ? nil : values.joined(separator: ",")
538    }
539}