DomainDig/DomainDiffService.swift
426 lines · 15081 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 dnsSection(from: oldSnapshot, to: newSnapshot),
47 redirectSection(from: oldSnapshot, to: newSnapshot),
48 tlsSection(from: oldSnapshot, to: newSnapshot),
49 httpSection(from: oldSnapshot, to: newSnapshot),
50 emailSection(from: oldSnapshot, to: newSnapshot)
51 ]
52 .filter { !$0.items.isEmpty }
53 }
54
55 static func summary(
56 from oldSnapshot: LookupSnapshot,
57 to newSnapshot: LookupSnapshot,
58 generatedAt: Date = Date()
59 ) -> DomainChangeSummary {
60 let sections = diff(from: oldSnapshot, to: newSnapshot)
61 let meaningfulItems = sections
62 .flatMap(\.items)
63 .filter(\.isMeaningful)
64 let allChangedItems = sections
65 .flatMap(\.items)
66 .filter(\.hasChanges)
67
68 let highlights = summaryHighlights(from: meaningfulItems)
69 let severity = meaningfulItems.map(\.severity).max() ?? (allChangedItems.isEmpty ? .low : .low)
70 let message = summaryMessage(from: meaningfulItems, highlights: highlights)
71
72 return DomainChangeSummary(
73 hasChanges: !meaningfulItems.isEmpty,
74 changedSections: highlights,
75 message: message,
76 severity: severity,
77 generatedAt: generatedAt
78 )
79 }
80
81 static func certificateWarningLevel(for snapshot: LookupSnapshot) -> CertificateWarningLevel {
82 guard let days = snapshot.sslInfo?.daysUntilExpiry else {
83 return .none
84 }
85 if days < 14 {
86 return .critical
87 }
88 if days < 30 {
89 return .warning
90 }
91 return .none
92 }
93
94 private static func availabilitySection(from oldSnapshot: LookupSnapshot, to newSnapshot: LookupSnapshot) -> DomainDiffSection {
95 DomainDiffSection(
96 title: "Availability",
97 items: [
98 compare(
99 label: "Availability",
100 oldValue: availabilityLabel(oldSnapshot.availabilityResult?.status),
101 newValue: availabilityLabel(newSnapshot.availabilityResult?.status),
102 severity: .high
103 )
104 ].compactMap { $0 }
105 )
106 }
107
108 private static func primaryIPSection(from oldSnapshot: LookupSnapshot, to newSnapshot: LookupSnapshot) -> DomainDiffSection {
109 DomainDiffSection(
110 title: "Primary IP",
111 items: [
112 compare(
113 label: "Primary IP",
114 oldValue: primaryIP(from: oldSnapshot),
115 newValue: primaryIP(from: newSnapshot),
116 severity: .high
117 )
118 ].compactMap { $0 }
119 )
120 }
121
122 private static func dnsSection(from oldSnapshot: LookupSnapshot, to newSnapshot: LookupSnapshot) -> DomainDiffSection {
123 let oldSections = Dictionary(uniqueKeysWithValues: oldSnapshot.dnsSections.map { ($0.recordType, $0) })
124 let newSections = Dictionary(uniqueKeysWithValues: newSnapshot.dnsSections.map { ($0.recordType, $0) })
125 let types = Set(oldSections.keys).union(newSections.keys).sorted { $0.rawValue < $1.rawValue }
126
127 var items: [DomainDiffItem] = []
128 for type in types {
129 let oldSection = oldSections[type]
130 let newSection = newSections[type]
131
132 if let recordChange = compare(
133 label: "\(type.rawValue) Records",
134 oldValue: normalizedRecordValues(for: oldSection),
135 newValue: normalizedRecordValues(for: newSection),
136 severity: .medium
137 ) {
138 items.append(recordChange)
139 }
140
141 if let ttlChange = compare(
142 label: "\(type.rawValue) TTL",
143 oldValue: normalizedTTLValues(for: oldSection),
144 newValue: normalizedTTLValues(for: newSection),
145 severity: .low
146 ), let oldSection, let newSection,
147 normalizedRecordValues(for: oldSection) == normalizedRecordValues(for: newSection) {
148 items.append(ttlChange)
149 }
150 }
151
152 return DomainDiffSection(title: "DNS", items: items)
153 }
154
155 private static func redirectSection(from oldSnapshot: LookupSnapshot, to newSnapshot: LookupSnapshot) -> DomainDiffSection {
156 DomainDiffSection(
157 title: "Redirect",
158 items: [
159 compare(
160 label: "Redirect Target",
161 oldValue: finalRedirectURL(from: oldSnapshot),
162 newValue: finalRedirectURL(from: newSnapshot),
163 severity: .high
164 )
165 ].compactMap { $0 }
166 )
167 }
168
169 private static func tlsSection(from oldSnapshot: LookupSnapshot, to newSnapshot: LookupSnapshot) -> DomainDiffSection {
170 var items: [DomainDiffItem] = []
171
172 if let issuerChange = compare(
173 label: "TLS Issuer",
174 oldValue: normalized(oldSnapshot.sslInfo?.issuer),
175 newValue: normalized(newSnapshot.sslInfo?.issuer),
176 severity: .medium
177 ) {
178 items.append(issuerChange)
179 }
180
181 if let expiryChange = compare(
182 label: "TLS Expiration",
183 oldValue: expirationLabel(oldSnapshot.sslInfo),
184 newValue: expirationLabel(newSnapshot.sslInfo),
185 severity: .medium
186 ) {
187 items.append(expiryChange)
188 }
189
190 let oldWarning = certificateWarningLevel(for: oldSnapshot)
191 let newWarning = certificateWarningLevel(for: newSnapshot)
192 if oldWarning != newWarning, newWarning != .none {
193 let days = newSnapshot.sslInfo?.daysUntilExpiry ?? 0
194 items.append(
195 DomainDiffItem(
196 label: "Certificate Warning",
197 changeType: .changed,
198 oldValue: oldWarning.title,
199 newValue: "Certificate expires in \(days) days",
200 severity: newWarning == .critical ? .high : .medium
201 )
202 )
203 }
204
205 return DomainDiffSection(title: "TLS", items: items)
206 }
207
208 private static func httpSection(from oldSnapshot: LookupSnapshot, to newSnapshot: LookupSnapshot) -> DomainDiffSection {
209 var items: [DomainDiffItem] = []
210
211 if let statusChange = compare(
212 label: "HTTP Status",
213 oldValue: httpStatusSummary(from: oldSnapshot),
214 newValue: httpStatusSummary(from: newSnapshot),
215 severity: .medium
216 ) {
217 items.append(statusChange)
218 }
219
220 if let gradeChange = compare(
221 label: "Security Grade",
222 oldValue: normalized(oldSnapshot.httpSecurityGrade),
223 newValue: normalized(newSnapshot.httpSecurityGrade),
224 severity: .low
225 ) {
226 items.append(gradeChange)
227 }
228
229 if let headerChange = compare(
230 label: "Headers",
231 oldValue: normalizedHeaders(from: oldSnapshot),
232 newValue: normalizedHeaders(from: newSnapshot),
233 severity: .low
234 ) {
235 items.append(headerChange)
236 }
237
238 return DomainDiffSection(title: "HTTP", items: items)
239 }
240
241 private static func emailSection(from oldSnapshot: LookupSnapshot, to newSnapshot: LookupSnapshot) -> DomainDiffSection {
242 DomainDiffSection(
243 title: "Email Security",
244 items: [
245 compare(
246 label: "Email Security",
247 oldValue: normalized(emailSummary(from: oldSnapshot)),
248 newValue: normalized(emailSummary(from: newSnapshot)),
249 severity: .medium
250 )
251 ].compactMap { $0 }
252 )
253 }
254
255 private static func compare(
256 label: String,
257 oldValue: String?,
258 newValue: String?,
259 severity: ChangeSeverity
260 ) -> DomainDiffItem? {
261 let oldValue = normalized(oldValue)
262 let newValue = normalized(newValue)
263 let normalizedOldValue = comparisonValue(oldValue)
264 let normalizedNewValue = comparisonValue(newValue)
265
266 guard oldValue != nil || newValue != nil else {
267 return nil
268 }
269
270 let changeType: DiffChangeType
271 switch (normalizedOldValue, normalizedNewValue) {
272 case let (old?, new?) where old == new:
273 changeType = .unchanged
274 case (nil, _?):
275 changeType = .added
276 case (_?, nil):
277 changeType = .removed
278 default:
279 changeType = .changed
280 }
281
282 return DomainDiffItem(
283 label: label,
284 changeType: changeType,
285 oldValue: oldValue,
286 newValue: newValue,
287 severity: severity
288 )
289 }
290
291 private static func summaryHighlights(from items: [DomainDiffItem]) -> [String] {
292 var highlights: [String] = []
293
294 let labels = Set(items.map(\.label))
295 if labels.contains("Availability") {
296 highlights.append("Availability changed")
297 }
298 if labels.contains("Primary IP"), labels.contains(where: { $0.hasSuffix("Records") }) {
299 highlights.append("IP changed")
300 highlights.append("DNS changed")
301 return highlights
302 }
303 if labels.contains("Primary IP") {
304 highlights.append("IP changed")
305 }
306 if labels.contains("Redirect Target") {
307 highlights.append("Redirect target changed")
308 }
309 if let certificateItem = items.first(where: { $0.label == "Certificate Warning" }),
310 let message = certificateItem.newValue {
311 highlights.append(message)
312 } else if labels.contains("TLS Issuer") {
313 highlights.append("TLS issuer changed")
314 } else if labels.contains("TLS Expiration") {
315 highlights.append("Certificate expiration changed")
316 }
317 if labels.contains(where: { $0.hasSuffix("Records") }) {
318 highlights.append("DNS changed")
319 }
320 if labels.contains("HTTP Status") {
321 highlights.append("HTTP status changed")
322 }
323 if labels.contains("Email Security") {
324 highlights.append("Email security changed")
325 }
326
327 var deduplicated: [String] = []
328 for highlight in highlights where !deduplicated.contains(highlight) {
329 deduplicated.append(highlight)
330 }
331 return deduplicated
332 }
333
334 private static func summaryMessage(from items: [DomainDiffItem], highlights: [String]) -> String {
335 guard !items.isEmpty, !highlights.isEmpty else {
336 return "No meaningful changes"
337 }
338
339 if highlights.count == 1 {
340 return highlights[0]
341 }
342
343 return "\(highlights[0]) and \(highlights[1].lowercased())"
344 }
345
346 private static func normalized(_ value: String?) -> String? {
347 guard let value = value?.trimmingCharacters(in: .whitespacesAndNewlines), !value.isEmpty else {
348 return nil
349 }
350 return value
351 }
352
353 private static func comparisonValue(_ value: String?) -> String? {
354 value?.lowercased()
355 }
356
357 private static func availabilityLabel(_ status: DomainAvailabilityStatus?) -> String? {
358 switch status {
359 case .available:
360 return "available"
361 case .registered:
362 return "registered"
363 case .unknown:
364 return "unknown"
365 case .none:
366 return nil
367 }
368 }
369
370 private static func primaryIP(from snapshot: LookupSnapshot) -> String? {
371 snapshot.dnsSections.first(where: { $0.recordType == .A })?.records.first?.value
372 }
373
374 private static func finalRedirectURL(from snapshot: LookupSnapshot) -> String? {
375 snapshot.redirectChain.last?.url
376 }
377
378 private static func expirationLabel(_ sslInfo: SSLCertificateInfo?) -> String? {
379 guard let sslInfo else { return nil }
380 return "\(sslInfo.validUntil.formatted(date: .abbreviated, time: .omitted)) (\(sslInfo.daysUntilExpiry)d)"
381 }
382
383 private static func httpStatusSummary(from snapshot: LookupSnapshot) -> String? {
384 if let httpStatusCode = snapshot.httpStatusCode {
385 return "\(httpStatusCode)"
386 }
387 return snapshot.httpHeadersError
388 }
389
390 private static func emailSummary(from snapshot: LookupSnapshot) -> String? {
391 if let emailSecurity = snapshot.emailSecurity {
392 return [
393 "spf:\(emailSecurity.spf.found)",
394 "dmarc:\(emailSecurity.dmarc.found)",
395 "dkim:\(emailSecurity.dkim.found)",
396 "bimi:\(emailSecurity.bimi.found)",
397 "mta-sts:\(emailSecurity.mtaSts?.txtFound == true)"
398 ].joined(separator: "|")
399 }
400 return snapshot.emailSecurityError
401 }
402
403 private static func normalizedRecordValues(for section: DNSSection?) -> String? {
404 guard let section else { return nil }
405 let values = (section.records + section.wildcardRecords)
406 .map(\.value)
407 .map { $0.trimmingCharacters(in: .whitespacesAndNewlines).lowercased() }
408 .sorted()
409 return values.isEmpty ? nil : values.joined(separator: ",")
410 }
411
412 private static func normalizedTTLValues(for section: DNSSection?) -> String? {
413 guard let section else { return nil }
414 let values = (section.records + section.wildcardRecords)
415 .map { "\($0.value.trimmingCharacters(in: .whitespacesAndNewlines).lowercased()):\($0.ttl)" }
416 .sorted()
417 return values.isEmpty ? nil : values.joined(separator: ",")
418 }
419
420 private static func normalizedHeaders(from snapshot: LookupSnapshot) -> String? {
421 let headers = snapshot.httpHeaders
422 .map { "\($0.name.lowercased()):\($0.value.trimmingCharacters(in: .whitespacesAndNewlines))" }
423 .sorted()
424 return headers.isEmpty ? nil : headers.joined(separator: "|")
425 }
426}