DomainDig/DomainDiffService.swift

22ecca12b4fe0e0850401754c674632f322d919d
domain-dig/DomainDig/DomainDiffService.swift history · blame · raw

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