DomainDig/DiffService.swift
630 lines · 27617 bytes
45 symbols in this file
DiffChangeTypeDiffItemDiffSectionDomainDiffDomainDiffItemDomainDiffSectionDomainComparisonResultDiffServicecomparecomparesummarycomparecomparisonContextNotecomparisonContextNotecertificateWarningLevelavailabilitySectionownershipSectiondnsSectionwebSectionemailSectionnetworkSectionsubdomainsSectionriskSectionintelligenceSectioncomparesummaryMessagenormalizedavailabilityLabelownershipDateLabelexpirationLabeljoinednormalizedRecordValuesnormalizedTTLValuesnormalizedHeadersredirectChainSummaryportScanSummarygroupSummaryrecordLabelmtaStsLabeldnssecLabelDomainDiffServicediffsummarycomparisonContextNotecertificateWarningLevel
1import Foundation
2
3enum DiffChangeType: String, Codable {
4 case added
5 case removed
6 case changed
7 case unchanged
8
9 var marker: String {
10 switch self {
11 case .added:
12 return "+"
13 case .removed:
14 return "-"
15 case .changed:
16 return "~"
17 case .unchanged:
18 return "="
19 }
20 }
21
22 var title: String {
23 switch self {
24 case .added:
25 return "Added"
26 case .removed:
27 return "Removed"
28 case .changed:
29 return "Changed"
30 case .unchanged:
31 return "Unchanged"
32 }
33 }
34}
35
36struct DiffItem: Identifiable, Equatable, Codable {
37 let id: String
38 let label: String
39 let changeType: DiffChangeType
40 let oldValue: String?
41 let newValue: String?
42 let severity: ChangeSeverity
43
44 init(
45 id: String,
46 label: String,
47 changeType: DiffChangeType,
48 oldValue: String?,
49 newValue: String?,
50 severity: ChangeSeverity
51 ) {
52 self.id = id
53 self.label = label
54 self.changeType = changeType
55 self.oldValue = oldValue
56 self.newValue = newValue
57 self.severity = severity
58 }
59
60 var hasChanges: Bool {
61 changeType != .unchanged
62 }
63}
64
65struct DiffSection: Identifiable, Equatable, Codable {
66 let id: String
67 let title: String
68 let items: [DiffItem]
69
70 var hasChanges: Bool {
71 items.contains(where: \.hasChanges)
72 }
73
74 var severity: ChangeSeverity {
75 items.map(\.severity).max() ?? .low
76 }
77
78 var changeCount: Int {
79 items.filter(\.hasChanges).count
80 }
81}
82
83struct DomainDiff: Identifiable, Equatable, Codable {
84 let domain: String
85 let fromTimestamp: Date
86 let toTimestamp: Date
87 let sections: [DiffSection]
88 let changedSectionIDs: [String]
89 let changedSectionTitles: [String]
90 let contextNote: String?
91
92 var id: String {
93 "\(domain)-\(fromTimestamp.timeIntervalSince1970)-\(toTimestamp.timeIntervalSince1970)"
94 }
95
96 var changeCount: Int {
97 sections.reduce(0) { $0 + $1.changeCount }
98 }
99
100 var severity: ChangeSeverity {
101 sections.map(\.severity).max() ?? .low
102 }
103}
104
105typealias DomainDiffItem = DiffItem
106typealias DomainDiffSection = DiffSection
107
108/// Result of comparing two distinct domains' latest reports side by side, as
109/// opposed to `DomainDiff`, which compares the same domain across time.
110struct DomainComparisonResult: Identifiable, Equatable {
111 let domainA: String
112 let domainB: String
113 let generatedAt: Date
114 let sections: [DiffSection]
115 let contextNote: String?
116
117 var id: String {
118 "\(domainA)-\(domainB)-\(generatedAt.timeIntervalSince1970)"
119 }
120
121 var changedSections: [DiffSection] {
122 sections.filter(\.hasChanges)
123 }
124
125 var changeCount: Int {
126 sections.reduce(0) { $0 + $1.changeCount }
127 }
128
129 var severity: ChangeSeverity {
130 sections.map(\.severity).max() ?? .low
131 }
132}
133
134enum DiffService {
135 static func compare(from oldReport: DomainReport, to newReport: DomainReport) -> DomainDiff {
136 let sections = [
137 availabilitySection(from: oldReport, to: newReport),
138 ownershipSection(from: oldReport, to: newReport),
139 dnsSection(from: oldReport, to: newReport),
140 webSection(from: oldReport, to: newReport),
141 emailSection(from: oldReport, to: newReport),
142 networkSection(from: oldReport, to: newReport),
143 subdomainsSection(from: oldReport, to: newReport),
144 intelligenceSection(from: oldReport, to: newReport),
145 riskSection(from: oldReport, to: newReport)
146 ]
147
148 let changedSections = sections.filter(\.hasChanges)
149 return DomainDiff(
150 domain: newReport.domain,
151 fromTimestamp: oldReport.timestamp,
152 toTimestamp: newReport.timestamp,
153 sections: sections,
154 changedSectionIDs: changedSections.map(\.id),
155 changedSectionTitles: changedSections.map(\.title),
156 contextNote: comparisonContextNote(from: oldReport, to: newReport)
157 )
158 }
159
160 static func compare(from oldSnapshot: LookupSnapshot, to newSnapshot: LookupSnapshot) -> DomainDiff {
161 let builder = DomainReportBuilder()
162 let oldReport = builder.build(from: oldSnapshot, deriveChangeSummary: false)
163 let newReport = builder.build(from: newSnapshot, previousSnapshot: oldSnapshot, deriveChangeSummary: false)
164 return compare(from: oldReport, to: newReport)
165 }
166
167 static func summary(
168 from oldSnapshot: LookupSnapshot,
169 to newSnapshot: LookupSnapshot,
170 generatedAt: Date = Date(),
171 riskAssessment: DomainRiskAssessment? = nil,
172 insights: [String]? = nil
173 ) -> DomainChangeSummary {
174 let diff = compare(from: oldSnapshot, to: newSnapshot)
175 let changedItems = diff.sections.flatMap(\.items).filter(\.hasChanges)
176 let highlights = diff.changedSectionTitles
177 let severity = changedItems.map(\.severity).max() ?? .low
178 let message = summaryMessage(from: highlights, changeCount: changedItems.count)
179 let observedFacts = changedItems.prefix(4).map { item in
180 "\(item.label): \(item.oldValue ?? "none") -> \(item.newValue ?? "none")"
181 }
182
183 let analysis = DomainInsightEngine.analyze(snapshot: newSnapshot, previousSnapshot: oldSnapshot)
184 let currentRiskAssessment = riskAssessment ?? analysis.riskAssessment
185 let currentInsights = insights ?? analysis.insights
186 let previousRiskScore = DomainInsightEngine.analyze(snapshot: oldSnapshot).riskAssessment.score
187 let riskScoreDelta = currentRiskAssessment.score - previousRiskScore
188 let impactClassification = DomainInsightEngine.impactClassification(
189 severity: severity,
190 riskDelta: riskScoreDelta,
191 changedSections: highlights
192 )
193
194 return DomainChangeSummary(
195 hasChanges: !changedItems.isEmpty,
196 changedSections: highlights,
197 message: message,
198 severity: severity,
199 impactClassification: impactClassification,
200 generatedAt: generatedAt,
201 observedFacts: observedFacts,
202 inferredConclusions: highlights.isEmpty ? [] : [message],
203 contextNote: diff.contextNote,
204 riskAssessment: currentRiskAssessment,
205 insights: currentInsights,
206 riskScoreDelta: riskScoreDelta
207 )
208 }
209
210 /// Compares two distinct domains' reports section by section. Reuses the same
211 /// field-level diff logic as time-based comparison; the two reports are simply
212 /// unrelated domains rather than the same domain at different times.
213 static func compare(domainA: DomainReport, domainB: DomainReport) -> DomainComparisonResult {
214 let sections = [
215 availabilitySection(from: domainA, to: domainB),
216 ownershipSection(from: domainA, to: domainB),
217 dnsSection(from: domainA, to: domainB),
218 webSection(from: domainA, to: domainB),
219 emailSection(from: domainA, to: domainB),
220 networkSection(from: domainA, to: domainB),
221 subdomainsSection(from: domainA, to: domainB),
222 intelligenceSection(from: domainA, to: domainB),
223 riskSection(from: domainA, to: domainB)
224 ]
225
226 return DomainComparisonResult(
227 domainA: domainA.domain,
228 domainB: domainB.domain,
229 generatedAt: Date(),
230 sections: sections,
231 contextNote: comparisonContextNote(from: domainA, to: domainB)
232 )
233 }
234
235 static func comparisonContextNote(from oldReport: DomainReport, to newReport: DomainReport) -> String? {
236 var notes: [String] = []
237 if oldReport.resolverURLString != newReport.resolverURLString {
238 notes.append("Compared snapshots used different DNS resolvers.")
239 }
240 if oldReport.resultSource != newReport.resultSource {
241 notes.append("Compared snapshots came from different collection modes.")
242 }
243 return notes.isEmpty ? nil : notes.joined(separator: " ")
244 }
245
246 static func comparisonContextNote(from oldSnapshot: LookupSnapshot, to newSnapshot: LookupSnapshot) -> String? {
247 comparisonContextNote(
248 from: DomainReportBuilder().build(from: oldSnapshot, deriveChangeSummary: false),
249 to: DomainReportBuilder().build(from: newSnapshot, previousSnapshot: oldSnapshot, deriveChangeSummary: false)
250 )
251 }
252
253 static func certificateWarningLevel(for snapshot: LookupSnapshot) -> CertificateWarningLevel {
254 guard let days = snapshot.sslInfo?.daysUntilExpiry else {
255 return .none
256 }
257 if days < 14 {
258 return .critical
259 }
260 if days < 30 {
261 return .warning
262 }
263 return .none
264 }
265
266 private static func availabilitySection(from oldReport: DomainReport, to newReport: DomainReport) -> DiffSection {
267 DiffSection(
268 id: "availability",
269 title: "Domain / Availability",
270 items: [
271 compare(id: "domain", label: "Domain", oldValue: oldReport.domain, newValue: newReport.domain, severity: .low),
272 compare(
273 id: "availability",
274 label: "Availability",
275 oldValue: availabilityLabel(oldReport.availability),
276 newValue: availabilityLabel(newReport.availability),
277 severity: .high
278 ),
279 compare(id: "primary-ip", label: "Primary IP", oldValue: oldReport.dns.primaryIP, newValue: newReport.dns.primaryIP, severity: .high),
280 compare(
281 id: "tls-status",
282 label: "TLS Status",
283 oldValue: oldReport.web.tlsStatus,
284 newValue: newReport.web.tlsStatus,
285 severity: .medium
286 )
287 ].compactMap { $0 }
288 )
289 }
290
291 private static func ownershipSection(from oldReport: DomainReport, to newReport: DomainReport) -> DiffSection {
292 DiffSection(
293 id: "ownership",
294 title: "Ownership",
295 items: [
296 compare(id: "registrar", label: "Registrar", oldValue: oldReport.ownership?.registrar, newValue: newReport.ownership?.registrar, severity: .high),
297 compare(id: "registrant", label: "Registrant", oldValue: oldReport.ownership?.registrant, newValue: newReport.ownership?.registrant, severity: .medium),
298 compare(
299 id: "ownership-created",
300 label: "Registration Date",
301 oldValue: ownershipDateLabel(oldReport.ownership?.createdDate),
302 newValue: ownershipDateLabel(newReport.ownership?.createdDate),
303 severity: .low
304 ),
305 compare(
306 id: "ownership-expires",
307 label: "Expiration Date",
308 oldValue: ownershipDateLabel(oldReport.ownership?.expirationDate),
309 newValue: ownershipDateLabel(newReport.ownership?.expirationDate),
310 severity: .medium
311 ),
312 compare(
313 id: "ownership-status",
314 label: "Status",
315 oldValue: joined(oldReport.ownership?.status),
316 newValue: joined(newReport.ownership?.status),
317 severity: .low
318 ),
319 compare(
320 id: "ownership-nameservers",
321 label: "Nameservers",
322 oldValue: joined(oldReport.ownership?.nameservers),
323 newValue: joined(newReport.ownership?.nameservers),
324 severity: .medium
325 ),
326 compare(id: "ownership-abuse", label: "Abuse Contact", oldValue: oldReport.ownership?.abuseEmail, newValue: newReport.ownership?.abuseEmail, severity: .low)
327 ].compactMap { $0 }
328 )
329 }
330
331 private static func dnsSection(from oldReport: DomainReport, to newReport: DomainReport) -> DiffSection {
332 // Imported reports are not guaranteed one section per record type.
333 let oldSections = Dictionary(oldReport.dns.recordSections.map { ($0.recordType, $0) }) { first, _ in first }
334 let newSections = Dictionary(newReport.dns.recordSections.map { ($0.recordType, $0) }) { first, _ in first }
335 let recordTypes = Set(oldSections.keys).union(newSections.keys).sorted { $0.rawValue < $1.rawValue }
336
337 var items: [DiffItem] = [
338 compare(id: "dnssec", label: "DNSSEC", oldValue: dnssecLabel(oldReport.dns.dnssecSigned), newValue: dnssecLabel(newReport.dns.dnssecSigned), severity: .medium),
339 compare(id: "ptr", label: "PTR", oldValue: oldReport.dns.ptrRecord, newValue: newReport.dns.ptrRecord, severity: .low)
340 ].compactMap { $0 }
341
342 for type in recordTypes {
343 items.append(
344 compare(
345 id: "dns-\(type.rawValue.lowercased())-records",
346 label: "\(type.rawValue) Records",
347 oldValue: normalizedRecordValues(for: oldSections[type]),
348 newValue: normalizedRecordValues(for: newSections[type]),
349 severity: type == .A || type == .NS ? .high : .medium
350 ) ?? DiffItem(id: "", label: "", changeType: .unchanged, oldValue: nil, newValue: nil, severity: .low)
351 )
352 if let ttlChange = compare(
353 id: "dns-\(type.rawValue.lowercased())-ttl",
354 label: "\(type.rawValue) TTL",
355 oldValue: normalizedTTLValues(for: oldSections[type]),
356 newValue: normalizedTTLValues(for: newSections[type]),
357 severity: .low
358 ) {
359 items.append(ttlChange)
360 }
361 }
362
363 return DiffSection(
364 id: "dns",
365 title: "DNS",
366 items: items.filter { !$0.id.isEmpty }
367 )
368 }
369
370 private static func webSection(from oldReport: DomainReport, to newReport: DomainReport) -> DiffSection {
371 DiffSection(
372 id: "web",
373 title: "Web",
374 items: [
375 compare(id: "web-status", label: "HTTP Status", oldValue: oldReport.web.statusCode.map(String.init), newValue: newReport.web.statusCode.map(String.init), severity: .medium),
376 compare(id: "web-grade", label: "Security Grade", oldValue: oldReport.web.securityGrade, newValue: newReport.web.securityGrade, severity: .medium),
377 compare(id: "web-final-url", label: "Final URL", oldValue: oldReport.web.finalURL, newValue: newReport.web.finalURL, severity: .high),
378 compare(id: "web-tls-issuer", label: "TLS Issuer", oldValue: oldReport.web.tls?.issuer, newValue: newReport.web.tls?.issuer, severity: .medium),
379 compare(id: "web-tls-expiry", label: "TLS Expiration", oldValue: expirationLabel(oldReport.web.tls), newValue: expirationLabel(newReport.web.tls), severity: .medium),
380 compare(id: "web-headers", label: "Headers", oldValue: normalizedHeaders(oldReport.web.headers), newValue: normalizedHeaders(newReport.web.headers), severity: .low),
381 compare(id: "web-redirects", label: "Redirect Chain", oldValue: redirectChainSummary(oldReport.web.redirectChain), newValue: redirectChainSummary(newReport.web.redirectChain), severity: .medium)
382 ].compactMap { $0 }
383 )
384 }
385
386 private static func emailSection(from oldReport: DomainReport, to newReport: DomainReport) -> DiffSection {
387 DiffSection(
388 id: "email",
389 title: "Email Security",
390 items: [
391 compare(id: "email-summary", label: "Summary", oldValue: oldReport.email.summary, newValue: newReport.email.summary, severity: .medium),
392 compare(id: "email-grade", label: "Grade", oldValue: oldReport.email.grade?.rawValue, newValue: newReport.email.grade?.rawValue, severity: .medium),
393 compare(id: "email-spf", label: "SPF", oldValue: recordLabel(oldReport.email.records?.spf), newValue: recordLabel(newReport.email.records?.spf), severity: .medium),
394 compare(id: "email-dmarc", label: "DMARC", oldValue: recordLabel(oldReport.email.records?.dmarc), newValue: recordLabel(newReport.email.records?.dmarc), severity: .high),
395 compare(id: "email-dkim", label: "DKIM", oldValue: recordLabel(oldReport.email.records?.dkim), newValue: recordLabel(newReport.email.records?.dkim), severity: .medium),
396 compare(id: "email-bimi", label: "BIMI", oldValue: recordLabel(oldReport.email.records?.bimi), newValue: recordLabel(newReport.email.records?.bimi), severity: .low),
397 compare(id: "email-mta-sts", label: "MTA-STS", oldValue: mtaStsLabel(oldReport.email.records?.mtaSts), newValue: mtaStsLabel(newReport.email.records?.mtaSts), severity: .medium)
398 ].compactMap { $0 }
399 )
400 }
401
402 private static func networkSection(from oldReport: DomainReport, to newReport: DomainReport) -> DiffSection {
403 DiffSection(
404 id: "network",
405 title: "Network",
406 items: [
407 compare(id: "network-reachability", label: "Reachability", oldValue: oldReport.network.reachabilitySummary, newValue: newReport.network.reachabilitySummary, severity: .medium),
408 compare(id: "network-geolocation", label: "Geolocation", oldValue: oldReport.network.geolocationSummary, newValue: newReport.network.geolocationSummary, severity: .medium),
409 compare(id: "network-open-ports", label: "Open Ports", oldValue: joined(oldReport.network.openPorts.map(String.init)), newValue: joined(newReport.network.openPorts.map(String.init)), severity: .high),
410 compare(id: "network-port-scan", label: "Port Scan", oldValue: portScanSummary(oldReport.network.portScan), newValue: portScanSummary(newReport.network.portScan), severity: .medium)
411 ].compactMap { $0 }
412 )
413 }
414
415 private static func subdomainsSection(from oldReport: DomainReport, to newReport: DomainReport) -> DiffSection {
416 DiffSection(
417 id: "subdomains",
418 title: "Subdomains",
419 items: [
420 compare(id: "subdomains-primary", label: "Primary Subdomains", oldValue: joined(oldReport.subdomains), newValue: joined(newReport.subdomains), severity: .low),
421 compare(id: "subdomains-extended", label: "Extended Subdomains", oldValue: joined(oldReport.extendedSubdomains), newValue: joined(newReport.extendedSubdomains), severity: .low),
422 compare(id: "subdomains-groups", label: "Groups", oldValue: groupSummary(oldReport.subdomainGroups), newValue: groupSummary(newReport.subdomainGroups), severity: .low)
423 ].compactMap { $0 }
424 )
425 }
426
427 private static func riskSection(from oldReport: DomainReport, to newReport: DomainReport) -> DiffSection {
428 DiffSection(
429 id: "risk",
430 title: "Risk / Insights",
431 items: [
432 compare(id: "risk-score", label: "Risk Score", oldValue: "\(oldReport.riskAssessment.score)", newValue: "\(newReport.riskAssessment.score)", severity: .high),
433 compare(id: "risk-level", label: "Risk Level", oldValue: oldReport.riskAssessment.level.title, newValue: newReport.riskAssessment.level.title, severity: .high),
434 compare(id: "risk-factors", label: "Risk Factors", oldValue: joined(oldReport.riskAssessment.factors.map(\.description)), newValue: joined(newReport.riskAssessment.factors.map(\.description)), severity: .medium),
435 compare(id: "risk-insights", label: "Insights", oldValue: joined(oldReport.insights), newValue: joined(newReport.insights), severity: .medium)
436 ].compactMap { $0 }
437 )
438 }
439
440 private static func intelligenceSection(from oldReport: DomainReport, to newReport: DomainReport) -> DiffSection {
441 DiffSection(
442 id: "intelligence",
443 title: "Data+ Intelligence",
444 items: [
445 compare(id: "intel-provider", label: "Provider", oldValue: oldReport.inferredProvider?.name, newValue: newReport.inferredProvider?.name, severity: .medium),
446 compare(id: "intel-classification", label: "Classification", oldValue: oldReport.domainClassification?.kind.title, newValue: newReport.domainClassification?.kind.title, severity: .medium),
447 compare(id: "intel-hosting-history", label: "Hosting Transitions", oldValue: joined(oldReport.hostingTransitions.map(\.summary)), newValue: joined(newReport.hostingTransitions.map(\.summary)), severity: .medium),
448 compare(id: "intel-ownership-history", label: "Ownership Transitions", oldValue: joined(oldReport.ownershipTransitions.map(\.summary)), newValue: joined(newReport.ownershipTransitions.map(\.summary)), severity: .high),
449 compare(id: "intel-risk-signals", label: "Risk Signals", oldValue: joined(oldReport.riskSignals.map(\.title)), newValue: joined(newReport.riskSignals.map(\.title)), severity: .medium)
450 ].compactMap { $0 }
451 )
452 }
453
454 private static func compare(
455 id: String,
456 label: String,
457 oldValue: String?,
458 newValue: String?,
459 severity: ChangeSeverity
460 ) -> DiffItem? {
461 let oldValue = normalized(oldValue)
462 let newValue = normalized(newValue)
463
464 guard oldValue != nil || newValue != nil else {
465 return nil
466 }
467
468 let changeType: DiffChangeType
469 switch (oldValue?.lowercased(), newValue?.lowercased()) {
470 case let (old?, new?) where old == new:
471 changeType = .unchanged
472 case (nil, _?):
473 changeType = .added
474 case (_?, nil):
475 changeType = .removed
476 default:
477 changeType = .changed
478 }
479
480 return DiffItem(
481 id: id,
482 label: label,
483 changeType: changeType,
484 oldValue: oldValue,
485 newValue: newValue,
486 severity: severity
487 )
488 }
489
490 static func summaryMessage(from sectionTitles: [String], changeCount: Int) -> String {
491 guard !sectionTitles.isEmpty else {
492 return "No meaningful changes"
493 }
494 if sectionTitles.count == 1 {
495 return "\(sectionTitles[0]) changed"
496 }
497 return "\(sectionTitles[0]) and \(sectionTitles[1].lowercased()) changed (\(changeCount) items)"
498 }
499
500 private static func normalized(_ value: String?) -> String? {
501 guard let value = value?.trimmingCharacters(in: .whitespacesAndNewlines), !value.isEmpty else {
502 return nil
503 }
504 return value
505 }
506
507 private static func availabilityLabel(_ status: DomainAvailabilityStatus) -> String {
508 switch status {
509 case .available:
510 return "Available"
511 case .registered:
512 return "Registered"
513 case .unknown:
514 return "Unknown"
515 }
516 }
517
518 private static func ownershipDateLabel(_ date: Date?) -> String? {
519 date?.formatted(date: .abbreviated, time: .omitted)
520 }
521
522 private static func expirationLabel(_ certificate: SSLCertificateInfo?) -> String? {
523 guard let certificate else { return nil }
524 return "\(certificate.validUntil.formatted(date: .abbreviated, time: .omitted)) (\(certificate.daysUntilExpiry)d)"
525 }
526
527 private static func joined(_ values: [String]?) -> String? {
528 guard let values else { return nil }
529 let normalizedValues = values
530 .map { $0.trimmingCharacters(in: .whitespacesAndNewlines) }
531 .filter { !$0.isEmpty }
532 .sorted()
533 return normalizedValues.isEmpty ? nil : normalizedValues.joined(separator: ", ")
534 }
535
536 private static func normalizedRecordValues(for section: DNSSection?) -> String? {
537 guard let section else { return nil }
538 let values = (section.records + section.wildcardRecords)
539 .map(\.value)
540 .map { $0.trimmingCharacters(in: .whitespacesAndNewlines).lowercased() }
541 .sorted()
542 return values.isEmpty ? nil : values.joined(separator: ", ")
543 }
544
545 private static func normalizedTTLValues(for section: DNSSection?) -> String? {
546 guard let section else { return nil }
547 let values = (section.records + section.wildcardRecords)
548 .map { "\($0.value.lowercased()):\($0.ttl)" }
549 .sorted()
550 return values.isEmpty ? nil : values.joined(separator: ", ")
551 }
552
553 private static func normalizedHeaders(_ headers: [HTTPHeader]) -> String? {
554 let values = headers
555 .map { "\($0.name.lowercased()): \($0.value.trimmingCharacters(in: .whitespacesAndNewlines))" }
556 .sorted()
557 return values.isEmpty ? nil : values.joined(separator: " | ")
558 }
559
560 private static func redirectChainSummary(_ redirects: [RedirectHop]) -> String? {
561 let values = redirects.map { "\($0.statusCode) \($0.url)" }
562 return values.isEmpty ? nil : values.joined(separator: " -> ")
563 }
564
565 private static func portScanSummary(_ results: [PortScanResult]) -> String? {
566 let values = results
567 .sorted { $0.port < $1.port }
568 .map { "\($0.port):\($0.open ? "open" : "closed")" }
569 return values.isEmpty ? nil : values.joined(separator: ", ")
570 }
571
572 private static func groupSummary(_ groups: [SubdomainGroup]) -> String? {
573 joined(groups.map { "\($0.label): \($0.subdomains.count)" })
574 }
575
576 private static func recordLabel(_ record: EmailSecurityRecord?) -> String? {
577 guard let record else { return nil }
578 if record.found {
579 return record.value ?? "Present"
580 }
581 return "Missing"
582 }
583
584 private static func mtaStsLabel(_ result: MTASTSResult?) -> String? {
585 guard let result else { return nil }
586 guard result.txtFound else { return "Missing" }
587 return result.policyMode ?? "Present"
588 }
589
590 private static func dnssecLabel(_ value: Bool?) -> String? {
591 switch value {
592 case true:
593 return "Signed"
594 case false:
595 return "Unsigned"
596 case nil:
597 return nil
598 }
599 }
600}
601
602enum DomainDiffService {
603 static func diff(from oldSnapshot: LookupSnapshot, to newSnapshot: LookupSnapshot) -> [DomainDiffSection] {
604 DiffService.compare(from: oldSnapshot, to: newSnapshot).sections
605 }
606
607 static func summary(
608 from oldSnapshot: LookupSnapshot,
609 to newSnapshot: LookupSnapshot,
610 generatedAt: Date = Date(),
611 riskAssessment: DomainRiskAssessment? = nil,
612 insights: [String]? = nil
613 ) -> DomainChangeSummary {
614 DiffService.summary(
615 from: oldSnapshot,
616 to: newSnapshot,
617 generatedAt: generatedAt,
618 riskAssessment: riskAssessment,
619 insights: insights
620 )
621 }
622
623 static func comparisonContextNote(from oldSnapshot: LookupSnapshot, to newSnapshot: LookupSnapshot) -> String? {
624 DiffService.comparisonContextNote(from: oldSnapshot, to: newSnapshot)
625 }
626
627 static func certificateWarningLevel(for snapshot: LookupSnapshot) -> CertificateWarningLevel {
628 DiffService.certificateWarningLevel(for: snapshot)
629 }
630}