DomainReportExporter.swift
771 lines · 32232 bytes
1import Foundation
2
3#if canImport(UIKit)
4import UIKit
5#endif
6
7enum DomainExportFormat: String, CaseIterable, Identifiable, Codable {
8 case text = "txt"
9 case csv = "csv"
10 case json = "json"
11 case markdown = "md"
12 case pdf = "pdf"
13
14 var id: String { rawValue }
15 var fileExtension: String { rawValue }
16
17 var title: String {
18 switch self {
19 case .text: return "TXT"
20 case .csv: return "CSV"
21 case .json: return "JSON"
22 case .markdown: return "Markdown"
23 case .pdf: return "PDF"
24 }
25 }
26}
27
28enum DomainReportExporter {
29 static func data(for report: DomainReport, format: DomainExportFormat) throws -> Data {
30 switch format {
31 case .text:
32 return Data(text(for: report).utf8)
33 case .csv:
34 return Data(csv(for: [report]).utf8)
35 case .json:
36 return try jsonEncoder.encode(report)
37 case .markdown:
38 return Data(markdown(for: report).utf8)
39 case .pdf:
40 return pdfData(fromMarkdown: markdown(for: report))
41 }
42 }
43
44 static func data(for reports: [DomainReport], format: DomainExportFormat, title: String) throws -> Data {
45 switch format {
46 case .text:
47 return Data(batchText(for: reports, title: title).utf8)
48 case .csv:
49 return Data(csv(for: reports).utf8)
50 case .json:
51 return try jsonEncoder.encode(reports)
52 case .markdown:
53 return Data(batchMarkdown(for: reports, title: title).utf8)
54 case .pdf:
55 return pdfData(fromMarkdown: batchMarkdown(for: reports, title: title))
56 }
57 }
58
59 /// Renders `text(for:)`'s content as Markdown: the leading title becomes an
60 /// H1, `appendSection`'s "Title\n----" underlines become H2 headers, and
61 /// other non-empty lines that aren't already list items become bullets.
62 /// This reuses the exact same section content as the text export rather
63 /// than re-deriving it, so the two formats never drift.
64 static func markdown(for report: DomainReport) -> String {
65 markdown(fromPlainText: text(for: report), title: "DomainDig Report")
66 }
67
68 static func batchMarkdown(for reports: [DomainReport], title: String) -> String {
69 markdown(fromPlainText: batchText(for: reports, title: title), title: title)
70 }
71
72 private static func markdown(fromPlainText text: String, title: String) -> String {
73 let lines = text.components(separatedBy: "\n")
74 var output: [String] = ["# \(title)", ""]
75 var index = 0
76 while index < lines.count {
77 let line = lines[index]
78 if index == 0, line == title {
79 index += 1
80 continue
81 }
82 if index + 1 < lines.count, !line.isEmpty, lines[index + 1] == String(repeating: "-", count: line.count) {
83 output.append("")
84 output.append("## \(line)")
85 index += 2
86 continue
87 }
88 if line.isEmpty || line.hasPrefix("-") || line.hasPrefix(" ") {
89 output.append(line)
90 } else {
91 output.append("- \(line)")
92 }
93 index += 1
94 }
95 return output.joined(separator: "\n")
96 }
97
98 /// Renders Markdown as a simple monospaced multi-page PDF. Foundation-only
99 /// consumers (no UIKit available) get the Markdown bytes back instead.
100 static func pdfData(fromMarkdown markdown: String) -> Data {
101 #if canImport(UIKit)
102 let renderer = UIGraphicsPDFRenderer(bounds: CGRect(x: 0, y: 0, width: 612, height: 792))
103 return renderer.pdfData { context in
104 let lines = markdown.components(separatedBy: .newlines)
105 let paragraphStyle = NSMutableParagraphStyle()
106 paragraphStyle.lineBreakMode = .byWordWrapping
107 let attributes: [NSAttributedString.Key: Any] = [
108 .font: UIFont.monospacedSystemFont(ofSize: 11, weight: .regular),
109 .paragraphStyle: paragraphStyle
110 ]
111
112 var yOffset: CGFloat = 36
113 context.beginPage()
114
115 for line in lines {
116 if yOffset > 744 {
117 context.beginPage()
118 yOffset = 36
119 }
120
121 let renderedLine = NSString(string: line.isEmpty ? " " : line)
122 renderedLine.draw(
123 in: CGRect(x: 36, y: yOffset, width: 540, height: 22),
124 withAttributes: attributes
125 )
126 yOffset += 16
127 }
128 }
129 #else
130 return Data(markdown.utf8)
131 #endif
132 }
133
134 static func text(for report: DomainReport) -> String {
135 var lines = [
136 "DomainDig Report",
137 "Domain: \(report.domain)",
138 "Timestamp: \(textDateFormatter.string(from: report.timestamp))",
139 "App Version: \(report.metadata.appVersion)",
140 "Resolver: \(report.metadata.resolverDisplayName)",
141 "Resolver URL: \(report.metadata.resolverURLString)",
142 "Source: \(report.provenance.source.label)",
143 "Availability: \(availabilityLabel(report.availability))",
144 "Availability Confidence: \(report.availabilityConfidence?.title ?? "N/A")"
145 ]
146
147 if report.metadata.isPartialSnapshot {
148 lines.append("Snapshot Integrity: Partial snapshot")
149 }
150 if let auditNote = report.metadata.auditNote, !auditNote.isEmpty {
151 lines.append("Audit Note: \(auditNote)")
152 }
153 if !report.provenance.dataSources.isEmpty {
154 lines.append("Data Sources: \(report.provenance.dataSources.joined(separator: ", "))")
155 }
156 if !report.metadata.validationIssues.isEmpty {
157 lines.append("Validation: \(report.metadata.validationIssues.joined(separator: " | "))")
158 }
159 if let workflowContext = report.workflowContext {
160 lines.append("Workflow Context: \(workflowContext.workflowName ?? workflowContext.source)")
161 }
162
163 appendSection("Summary", to: &lines) {
164 [
165 "Primary IP: \(report.dns.primaryIP ?? "Unavailable")",
166 "Risk Score: \(report.riskAssessment.score) (\(report.riskAssessment.level.title))",
167 "TLS Status: \(report.web.tlsStatus)",
168 "HTTP: \(httpSummary(for: report))",
169 "Email: \(report.email.summary)",
170 "Subdomains: \(report.subdomains.count)",
171 "Extended Subdomains: \(report.extendedSubdomains.count)",
172 "External Price: \(report.domainPricing?.estimatedPrice ?? "Unavailable")",
173 "Reputation: \(report.reputation?.status.title ?? "Unavailable")"
174 ]
175 }
176
177 appendSection("Risk", to: &lines) {
178 var values = [
179 "Score: \(report.riskAssessment.score)",
180 "Level: \(report.riskAssessment.level.title)"
181 ]
182 if report.riskAssessment.factors.isEmpty {
183 values.append("Factors: None")
184 } else {
185 values.append("Factors:")
186 for factor in report.riskAssessment.factors {
187 values.append(" [\(factor.impact.rawValue)] \(factor.description)")
188 }
189 }
190 return values
191 }
192
193 appendSection("Insights", to: &lines) {
194 report.insights.isEmpty ? ["No deterministic insights triggered"] : report.insights.map { "- \($0)" }
195 }
196
197 appendSection("Ownership", to: &lines) {
198 var ownershipLines = [
199 "Registrar: \(report.ownership?.registrar ?? "Unavailable")",
200 "Confidence: \(report.ownershipConfidence?.title ?? "N/A")",
201 "Created: \(ownershipDateLabel(report.ownership?.createdDate))",
202 "Expires: \(ownershipDateLabel(report.ownership?.expirationDate))",
203 "Registrant: \(report.ownership?.registrant ?? "Unavailable")",
204 "Nameservers: \(joined(report.ownership?.nameservers) ?? "Unavailable")",
205 "Status: \(joined(report.ownership?.status) ?? "Unavailable")",
206 "Abuse Contact: \(report.ownership?.abuseEmail ?? "Unavailable")"
207 ]
208 if let provenance = report.sectionProvenance[.ownership] {
209 ownershipLines.append("Provenance: \(provenanceLabel(provenance))")
210 }
211 if let error = report.dns.error, report.ownership == nil {
212 ownershipLines.append("Error: \(error)")
213 } else if let error = report.changeSummary?.message, report.ownership == nil, report.ownership == nil {
214 _ = error
215 }
216 return ownershipLines
217 }
218
219 appendSection("Ownership History", to: &lines) {
220 guard !report.ownershipHistory.isEmpty else {
221 return ["No ownership history available"]
222 }
223
224 return report.ownershipHistory.map { event in
225 [
226 textDateFormatter.string(from: event.date),
227 event.summary,
228 "source=\(event.source)"
229 ].joined(separator: " | ")
230 }
231 }
232
233 appendSection("DNS", to: &lines) {
234 var dnsLines = [
235 "Lookup Duration: \(durationLabel(report.dns.lookupDurationMs))",
236 "Primary IP: \(report.dns.primaryIP ?? "Unavailable")",
237 "PTR: \(report.dns.ptrRecord ?? report.dns.ptrError ?? "Unavailable")",
238 "DNSSEC: \(dnssecLabel(report.dns.dnssecSigned))",
239 "Patterns: \(report.dns.patternSummary.patterns.joined(separator: " | ").nilIfEmpty ?? "None")"
240 ]
241 if let provenance = report.sectionProvenance[.dns] {
242 dnsLines.append("Provenance: \(provenanceLabel(provenance))")
243 }
244 if let error = report.dns.error {
245 dnsLines.append("Error: \(error)")
246 }
247 if report.dns.recordSections.isEmpty {
248 dnsLines.append("Records: None")
249 } else {
250 dnsLines.append("Records:")
251 for section in report.dns.recordSections {
252 let values = (section.records + section.wildcardRecords).map(\.value)
253 let renderedValues = values.isEmpty ? "None" : values.joined(separator: " | ")
254 dnsLines.append(" \(section.recordType.rawValue): \(renderedValues)")
255 }
256 }
257 return dnsLines
258 }
259
260 appendSection("DNS History", to: &lines) {
261 guard !report.dnsHistory.isEmpty else {
262 return ["No DNS history available"]
263 }
264
265 return report.dnsHistory.map { event in
266 [
267 textDateFormatter.string(from: event.date),
268 event.summary,
269 "A=\(event.aRecords.joined(separator: " | ").nilIfEmpty ?? "-")",
270 "NS=\(event.nameservers.joined(separator: " | ").nilIfEmpty ?? "-")",
271 "source=\(event.source)"
272 ].joined(separator: " | ")
273 }
274 }
275
276 appendSection("Web", to: &lines) {
277 var webLines = [
278 "TLS Status: \(report.web.tlsStatus)",
279 "TLS Grade: \(report.web.tlsGrade.rawValue)",
280 "TLS Highlights: \(report.web.tlsHighlights.joined(separator: " | "))",
281 "Certificate Warning: \(report.web.certificateWarningLevel.title)",
282 "Security Grade: \(report.web.securityGrade ?? "Unavailable")",
283 "HTTP Status: \(report.web.statusCode.map(String.init) ?? "Unavailable")",
284 "Protocol: \(report.web.httpProtocol ?? "Unavailable")",
285 "HTTP/3 Advertised: \(report.web.http3Advertised ? "Yes" : "No")",
286 "Final URL: \(report.web.finalURL ?? "Unavailable")",
287 "HSTS Preloaded: \(booleanLabel(report.web.hstsPreloaded))",
288 "Header Count: \(report.web.headerCount)"
289 ]
290 if let provenance = report.sectionProvenance[.ssl] {
291 webLines.append("TLS Provenance: \(provenanceLabel(provenance))")
292 }
293 if let provenance = report.sectionProvenance[.httpHeaders] {
294 webLines.append("HTTP Provenance: \(provenanceLabel(provenance))")
295 }
296 if let provenance = report.sectionProvenance[.redirectChain] {
297 webLines.append("Redirect Provenance: \(provenanceLabel(provenance))")
298 }
299 if let tlsError = report.web.tlsError {
300 webLines.append("TLS Error: \(tlsError)")
301 }
302 if let headersError = report.web.headersError {
303 webLines.append("Headers Error: \(headersError)")
304 }
305 if let redirectError = report.web.redirectError {
306 webLines.append("Redirect Error: \(redirectError)")
307 }
308 if !report.web.headers.isEmpty {
309 webLines.append("Headers:")
310 for header in report.web.headers {
311 webLines.append(" \(header.name): \(header.value)")
312 }
313 }
314 if !report.web.redirectChain.isEmpty {
315 webLines.append("Redirect Chain:")
316 for hop in report.web.redirectChain {
317 webLines.append(" \(hop.stepNumber). \(hop.statusCode) \(hop.url)\(hop.isFinal ? " (final)" : "")")
318 }
319 }
320 return webLines
321 }
322
323 appendSection("Email", to: &lines) {
324 var emailLines = [report.email.summary]
325 if let grade = report.email.grade {
326 emailLines.append("Grade: \(grade.rawValue)")
327 }
328 if !report.email.reasons.isEmpty {
329 emailLines.append("Why: \(report.email.reasons.joined(separator: " | "))")
330 }
331 emailLines.append("Confidence: \(report.emailConfidence?.title ?? "N/A")")
332 if let provenance = report.sectionProvenance[.emailSecurity] {
333 emailLines.append("Provenance: \(provenanceLabel(provenance))")
334 }
335 if let records = report.email.records {
336 emailLines.append("SPF: \(recordLabel(records.spf))")
337 emailLines.append("DMARC: \(recordLabel(records.dmarc))")
338 emailLines.append("DKIM: \(recordLabel(records.dkim))")
339 emailLines.append("BIMI: \(recordLabel(records.bimi))")
340 emailLines.append("MTA-STS: \(records.mtaSts?.txtFound == true ? records.mtaSts?.policyMode ?? "found" : "Unavailable")")
341 }
342 if let error = report.email.error {
343 emailLines.append("Error: \(error)")
344 }
345 return emailLines
346 }
347
348 appendSection("Network", to: &lines) {
349 var networkLines = [
350 "Reachability: \(report.network.reachabilitySummary)",
351 "Geolocation: \(report.network.geolocationSummary)",
352 "Geolocation Confidence: \(report.geolocationConfidence?.title ?? "N/A")",
353 "Open Ports: \(report.network.openPorts.map(String.init).joined(separator: ", ").nilIfEmpty ?? "None")"
354 ]
355 if let provenance = report.sectionProvenance[.ipGeolocation] {
356 networkLines.append("Geolocation Provenance: \(provenanceLabel(provenance))")
357 }
358 if let error = report.network.reachabilityError {
359 networkLines.append("Reachability Error: \(error)")
360 }
361 if let error = report.network.geolocationError {
362 networkLines.append("Geolocation Error: \(error)")
363 }
364 if let error = report.network.portScanError {
365 networkLines.append("Port Scan Error: \(error)")
366 }
367 if !report.network.portScan.isEmpty {
368 networkLines.append("Port Scan:")
369 for result in report.network.portScan {
370 networkLines.append(
371 " \(result.port) \(result.service): \(result.open ? "open" : "closed")\(result.banner.map { " banner=\($0)" } ?? "")"
372 )
373 }
374 }
375 return networkLines
376 }
377
378 appendSection("Subdomains", to: &lines) {
379 var values = ["Confidence: \(report.subdomainConfidence?.title ?? "N/A")"]
380 if let provenance = report.sectionProvenance[.subdomains] {
381 values.append("Provenance: \(provenanceLabel(provenance))")
382 }
383 if report.subdomains.isEmpty {
384 values.append("None")
385 return values
386 }
387 if !report.subdomainGroups.isEmpty {
388 values.append("Groups: \(report.subdomainGroups.map { "\($0.label): \($0.subdomains.count)" }.joined(separator: " | "))")
389 }
390 values.append(contentsOf: report.subdomains.map { "- \($0)" })
391 if !report.extendedSubdomains.isEmpty {
392 values.append("Extended:")
393 values.append(contentsOf: report.extendedSubdomains.map { "- \($0)" })
394 }
395 return values
396 }
397
398 appendSection("Pricing", to: &lines) {
399 guard let pricing = report.domainPricing else {
400 return ["External pricing unavailable"]
401 }
402
403 return [
404 "Estimated Price: \(pricing.estimatedPrice ?? "Unavailable")",
405 "Premium: \(pricing.premiumIndicator == true ? "Yes" : "No")",
406 "Resale: \(pricing.resaleSignal ?? "Unavailable")",
407 "Auction: \(pricing.auctionSignal ?? "Unavailable")",
408 "Source: \(pricing.source)",
409 "Collected: \(textDateFormatter.string(from: pricing.collectedAt))"
410 ]
411 }
412
413 appendSection("Changes", to: &lines) {
414 guard let changeSummary = report.changeSummary else {
415 return ["No comparison available"]
416 }
417
418 var values = [
419 "Has Changes: \(changeSummary.hasChanges ? "Yes" : "No")",
420 "Severity: \(changeSummary.severity.title)",
421 "Impact: \(changeSummary.impactClassification.title)",
422 "Inferred Summary: \(changeSummary.message)",
423 "Changed Sections: \(changeSummary.changedSections.isEmpty ? "None" : changeSummary.changedSections.joined(separator: ", "))"
424 ]
425 if let riskScoreDelta = changeSummary.riskScoreDelta {
426 values.append("Risk Delta: \(riskScoreDelta >= 0 ? "+" : "")\(riskScoreDelta)")
427 }
428 if !changeSummary.insights.isEmpty {
429 values.append("Insights: \(changeSummary.insights.joined(separator: " | "))")
430 }
431 if !changeSummary.observedFacts.isEmpty {
432 values.append("Observed: \(changeSummary.observedFacts.joined(separator: " | "))")
433 }
434 if let contextNote = changeSummary.contextNote {
435 values.append("Context: \(contextNote)")
436 }
437 return values
438 }
439
440 return lines.joined(separator: "\n")
441 }
442
443 static func batchText(for reports: [DomainReport], title: String) -> String {
444 guard !reports.isEmpty else {
445 return "\(title)\nNo results available."
446 }
447
448 var lines = [title, String(repeating: "=", count: title.count), ""]
449 for (index, report) in reports.enumerated() {
450 if index > 0 {
451 lines.append("")
452 lines.append(String(repeating: "=", count: 48))
453 lines.append("")
454 }
455 lines.append(text(for: report))
456 }
457 return lines.joined(separator: "\n")
458 }
459
460 static func csv(for reports: [DomainReport]) -> String {
461 csv(for: reports, workflowInsights: [])
462 }
463
464 static func csv(for reports: [DomainReport], workflowInsights: [WorkflowInsight]) -> String {
465 let workflowInsightSummary = workflowInsights.map(\.description).joined(separator: " | ")
466 let headers = [
467 "domain",
468 "timestamp",
469 "app_version",
470 "result_source",
471 "resolver",
472 "availability",
473 "risk_score",
474 "risk_level",
475 "risk_factors",
476 "insights",
477 "availability_confidence",
478 "registrar",
479 "ownership_confidence",
480 "ownership_expires",
481 "nameservers",
482 "primary_ip",
483 "ptr_record",
484 "dnssec_signed",
485 "dns_patterns",
486 "tls_status",
487 "tls_grade",
488 "tls_highlights",
489 "certificate_warning_level",
490 "hsts_preloaded",
491 "http_status",
492 "http_security_grade",
493 "final_url",
494 "email_summary",
495 "email_grade",
496 "email_confidence",
497 "subdomain_count",
498 "extended_subdomain_count",
499 "subdomain_groups",
500 "subdomain_confidence",
501 "subdomains",
502 "extended_subdomains",
503 "ownership_history",
504 "dns_history",
505 "pricing_estimated",
506 "pricing_premium",
507 "pricing_resale_signal",
508 "pricing_auction_signal",
509 "pricing_source",
510 "reputation_status",
511 "reputation_listed_sources",
512 "open_ports",
513 "reachability_summary",
514 "geolocation_summary",
515 "geolocation_confidence",
516 "data_sources",
517 "audit_note",
518 "partial_snapshot",
519 "workflow_name",
520 "workflow_source",
521 "cached_sections",
522 "change_summary",
523 "change_impact",
524 "workflow_insights"
525 ]
526
527 let rows = reports.map { report in
528 let expirationDate = report.ownership?.expirationDate.map(csvDateFormatter.string(from:)) ?? ""
529 let nameservers = joined(report.ownership?.nameservers) ?? ""
530 let dnssecSigned = report.dns.dnssecSigned.map { $0 ? "true" : "false" } ?? ""
531 let hstsPreloaded = report.web.hstsPreloaded.map { $0 ? "true" : "false" } ?? ""
532 let httpStatus = report.web.statusCode.map(String.init) ?? ""
533 let subdomainCount = String(report.subdomains.count)
534 let subdomains = report.subdomains.joined(separator: " | ")
535 let extendedSubdomains = report.extendedSubdomains.joined(separator: " | ")
536 let openPorts = report.network.openPorts.map(String.init).joined(separator: " | ")
537 let riskFactors = report.riskAssessment.factors.map(\.description).joined(separator: " | ")
538 let insights = report.insights.joined(separator: " | ")
539 let dnsPatterns = report.dns.patternSummary.patterns.joined(separator: " | ")
540 let tlsHighlights = report.web.tlsHighlights.joined(separator: " | ")
541 let subdomainGroups = report.subdomainGroups.map { "\($0.label):\($0.subdomains.count)" }.joined(separator: " | ")
542 let ownershipHistory = report.ownershipHistory.map { "\($0.date.ISO8601Format()) \($0.summary)" }.joined(separator: " | ")
543 let dnsHistory = report.dnsHistory.map { "\($0.date.ISO8601Format()) \($0.summary)" }.joined(separator: " | ")
544 let reputationStatus = report.reputation?.status.rawValue ?? ""
545 let reputationListedSources = report.reputation?.listedSources.joined(separator: " | ") ?? ""
546
547 return [
548 report.domain,
549 csvDateFormatter.string(from: report.timestamp),
550 report.appVersion,
551 report.resultSource.rawValue,
552 report.resolverDisplayName,
553 availabilityLabel(report.availability),
554 "\(report.riskAssessment.score)",
555 report.riskAssessment.level.rawValue,
556 riskFactors,
557 insights,
558 report.availabilityConfidence?.rawValue ?? "",
559 report.ownership?.registrar ?? "",
560 report.ownershipConfidence?.rawValue ?? "",
561 expirationDate,
562 nameservers,
563 report.dns.primaryIP ?? "",
564 report.dns.ptrRecord ?? "",
565 dnssecSigned,
566 dnsPatterns,
567 report.web.tlsStatus,
568 report.web.tlsGrade.rawValue,
569 tlsHighlights,
570 report.web.certificateWarningLevel.rawValue,
571 hstsPreloaded,
572 httpStatus,
573 report.web.securityGrade ?? "",
574 report.web.finalURL ?? "",
575 report.email.summary,
576 report.email.grade?.rawValue ?? "",
577 report.emailConfidence?.rawValue ?? "",
578 subdomainCount,
579 String(report.extendedSubdomains.count),
580 subdomainGroups,
581 report.subdomainConfidence?.rawValue ?? "",
582 subdomains,
583 extendedSubdomains,
584 ownershipHistory,
585 dnsHistory,
586 report.domainPricing?.estimatedPrice ?? "",
587 report.domainPricing?.premiumIndicator == true ? "true" : "false",
588 report.domainPricing?.resaleSignal ?? "",
589 report.domainPricing?.auctionSignal ?? "",
590 report.domainPricing?.source ?? "",
591 reputationStatus,
592 reputationListedSources,
593 openPorts,
594 report.network.reachabilitySummary,
595 report.network.geolocationSummary,
596 report.geolocationConfidence?.rawValue ?? "",
597 report.provenance.dataSources.joined(separator: " | "),
598 report.metadata.auditNote ?? "",
599 report.metadata.isPartialSnapshot ? "true" : "false",
600 report.workflowContext?.workflowName ?? "",
601 report.workflowContext?.source ?? "",
602 report.metadata.cachedSections.map(\.rawValue).joined(separator: " | "),
603 report.changeSummary?.message ?? "",
604 report.changeSummary?.impactClassification.rawValue ?? "",
605 workflowInsightSummary
606 ]
607 }
608
609 return ([headers] + rows)
610 .map { row in row.map(csvEscaped).joined(separator: ",") }
611 .joined(separator: "\n")
612 }
613
614 static func timelineText(for reports: [DomainReport], domain: String, includeDiffSummary: Bool) -> String {
615 guard !reports.isEmpty else {
616 return "Timeline Export\nNo snapshots available for \(domain)."
617 }
618
619 var lines = [
620 "DomainDig Timeline Export",
621 "Domain: \(domain)",
622 "Snapshots: \(reports.count)"
623 ]
624
625 for report in reports.sorted(by: { $0.timestamp > $1.timestamp }) {
626 lines.append("")
627 lines.append("\(textDateFormatter.string(from: report.timestamp))")
628 lines.append("Summary: \(report.changeSummary?.message ?? "No change summary")")
629 lines.append("Severity: \(report.changeSummary?.severity.title ?? "N/A")")
630 if includeDiffSummary, let changeSummary = report.changeSummary {
631 lines.append("Changed Sections: \(changeSummary.changedSections.joined(separator: ", ").nilIfEmpty ?? "None")")
632 }
633 }
634
635 return lines.joined(separator: "\n")
636 }
637
638 static func timelineData(for reports: [DomainReport], domain: String, includeDiffSummary: Bool) throws -> Data {
639 struct TimelineExportEntry: Codable {
640 let timestamp: Date
641 let summary: String?
642 let severity: String?
643 let changedSections: [String]?
644 }
645
646 struct TimelineExportPayload: Codable {
647 let domain: String
648 let exportedAt: Date
649 let snapshots: [TimelineExportEntry]
650 }
651
652 let payload = TimelineExportPayload(
653 domain: domain,
654 exportedAt: Date(),
655 snapshots: reports
656 .sorted(by: { $0.timestamp > $1.timestamp })
657 .map { report in
658 TimelineExportEntry(
659 timestamp: report.timestamp,
660 summary: report.changeSummary?.message,
661 severity: report.changeSummary?.severity.title,
662 changedSections: includeDiffSummary ? report.changeSummary?.changedSections : nil
663 )
664 }
665 )
666
667 return try jsonEncoder.encode(payload)
668 }
669
670 private static func appendSection(_ title: String, to lines: inout [String], body: () -> [String]) {
671 lines.append("")
672 lines.append(title)
673 lines.append(String(repeating: "-", count: title.count))
674 lines.append(contentsOf: body())
675 }
676
677 private static func availabilityLabel(_ status: DomainAvailabilityStatus) -> String {
678 switch status {
679 case .available:
680 return "Available"
681 case .registered:
682 return "Registered"
683 case .unknown:
684 return "Unknown"
685 }
686 }
687
688 private static func joined(_ values: [String]?) -> String? {
689 guard let values, !values.isEmpty else { return nil }
690 return values.joined(separator: " | ")
691 }
692
693 private static func dnssecLabel(_ value: Bool?) -> String {
694 switch value {
695 case true:
696 return "Signed"
697 case false:
698 return "Unsigned"
699 case nil:
700 return "Unavailable"
701 }
702 }
703
704 private static func ownershipDateLabel(_ date: Date?) -> String {
705 guard let date else { return "Unavailable" }
706 return textDateFormatter.string(from: date)
707 }
708
709 private static func durationLabel(_ durationMs: Int?) -> String {
710 durationMs.map { "\($0) ms" } ?? "Unavailable"
711 }
712
713 private static func httpSummary(for report: DomainReport) -> String {
714 let parts = [report.web.statusCode.map(String.init), report.web.securityGrade].compactMap { $0 }
715 return parts.isEmpty ? report.web.headersError ?? "Unavailable" : parts.joined(separator: " / ")
716 }
717
718 private static func booleanLabel(_ value: Bool?) -> String {
719 guard let value else { return "Unavailable" }
720 return value ? "Yes" : "No"
721 }
722
723 private static func recordLabel(_ record: EmailSecurityRecord) -> String {
724 if record.found {
725 return record.value ?? "Present"
726 }
727 return "Unavailable"
728 }
729
730 private static func provenanceLabel(_ provenance: SectionProvenance) -> String {
731 [
732 provenance.source,
733 provenance.provider,
734 provenance.resolver.map { "resolver=\($0)" },
735 provenance.resultSource.label.lowercased(),
736 textDateFormatter.string(from: provenance.collectedAt)
737 ]
738 .compactMap { $0 }
739 .joined(separator: " | ")
740 }
741
742 private static let textDateFormatter: DateFormatter = {
743 let formatter = DateFormatter()
744 formatter.dateFormat = "yyyy-MM-dd HH:mm:ss"
745 return formatter
746 }()
747
748 private static let csvDateFormatter: ISO8601DateFormatter = {
749 let formatter = ISO8601DateFormatter()
750 formatter.formatOptions = [.withInternetDateTime]
751 return formatter
752 }()
753
754 private static let jsonEncoder: JSONEncoder = {
755 let encoder = JSONEncoder()
756 encoder.outputFormatting = [.prettyPrinted, .sortedKeys]
757 encoder.dateEncodingStrategy = .iso8601
758 return encoder
759 }()
760
761 nonisolated private static func csvEscaped(_ value: String) -> String {
762 let escaped = value.replacingOccurrences(of: "\"", with: "\"\"")
763 return "\"\(escaped)\""
764 }
765}
766
767private extension String {
768 var nilIfEmpty: String? {
769 isEmpty ? nil : self
770 }
771}