Commit 4294e59fca

4294e59fca70ececae96dcbe3e43145255ab7d27

parent: 06885b336b

Verified · cmc

cmc <hello@cleberg.net> · 2026-10-22 23:51 UTC

Add Qlty config; fix duplicate-key and DER bounds crashes; split exporters

- Dictionary(uniqueKeysWithValues:) trapped on a CSV import with a
  repeated column, on HTTP header names that collide once lowercased, and
  on two DNS sections of one record type in a diff; each keeps the first.
- The DER parser sliced to lengths past the end of the data; such a TLV
  now reads as malformed.
- Removed a dead branch in the report's ownership section.
- Snapshot fallback lives once on LookupSnapshot; port banner enrichment
  once on PortScanService; the audit PDF uses the report PDF renderer.
- Report text, export text, audit markdown, risk scoring, subdomain
  history, SAN parsing and import decoding split into helpers. Output
  matches main over 3,000 generated snapshots, 1,000 with history and
  diffs, 2,000 audit sessions and 189 real certificates.

Layout: unified · split

.qlty/.gitignore added +7
@@ -0,0 +1,7 @@
1*
2!configs
3!configs/**
4!hooks
5!hooks/**
6!qlty.toml
7!.gitignore
.qlty/qlty.toml added +48
@@ -0,0 +1,48 @@
1config_version = "0"
2
3exclude_patterns = [
4 "**/vendor/**",
5 "**/node_modules/**",
6 "**/testdata/**",
7 "**/dist/**",
8 "**/.build/**",
9 "**/build/**",
10 "**/*.min.*",
11 "**/generated/**",
12 ".claude/**",
13 "**/Pods/**",
14]
15
16test_patterns = [
17 "**/test/**",
18 "**/tests/**",
19 "**/Tests/**",
20 "**/*_test.*",
21 "**/test_*.*",
22 "**/*.test.*",
23 "**/*Tests.swift",
24 "e2e/**",
25]
26
27[[source]]
28name = "default"
29default = true
30
31[[plugin]]
32name = "osv-scanner"
33
34[[plugin]]
35name = "trufflehog"
36
37# Early returns are guard clauses, which keep the happy path unindented.
38[smells.return_statements]
39enabled = false
40
41# Total file complexity is the sum of its functions, which function_complexity
42# already checks.
43[smells.file_complexity]
44enabled = false
45
46# Exhaustive switch-over-enum lookup tables share shape but not content.
47[language.swift.smells.duplication]
48filter_patterns = ["(import_declaration _)", "(switch_statement _)"]
DomainDataPortabilityService.swift +36 −57
@@ -305,7 +305,8 @@ enum DataPortabilityCSV {
305 } 305 }
306 306
307 private nonisolated static func dictionary(for row: [String], header: [String]) -> [String: String] { 307 private nonisolated static func dictionary(for row: [String], header: [String]) -> [String: String] {
308 Dictionary(uniqueKeysWithValues: zip(header, row).map { ($0.0, $0.1) }) 308 // A repeated column keeps its first value rather than failing the import.
309 Dictionary(zip(header, row).map { ($0.0, $0.1) }) { first, _ in first }
309 } 310 }
310 311
311 private nonisolated static func csvLine(_ values: [String]) -> String { 312 private nonisolated static func csvLine(_ values: [String]) -> String {
@@ -903,76 +904,54 @@ enum DomainDataPortabilityService {
903 if backup.schemaVersion > DomainDigBackup.currentSchemaVersion { 904 if backup.schemaVersion > DomainDigBackup.currentSchemaVersion {
904 throw DataPortabilityError.unsupportedSchema(backup.schemaVersion) 905 throw DataPortabilityError.unsupportedSchema(backup.schemaVersion)
905 } 906 }
906 let report = DataValidationService.validate(backup: backup) 907 return .backup(backup, try passing(DataValidationService.validate(backup: backup)))
907 if !report.errors.isEmpty {
908 throw DataPortabilityError.validationFailed(report.errors)
909 }
910 return .backup(backup, report)
911 } 908 }
912
913 if let backup = try? decodeLegacyBackup(from: data) { 909 if let backup = try? decodeLegacyBackup(from: data) {
914 let report = DataValidationService.validate(backup: backup) 910 return .backup(backup, try passing(DataValidationService.validate(backup: backup)))
915 if !report.errors.isEmpty {
916 throw DataPortabilityError.validationFailed(report.errors)
917 }
918 return .backup(backup, report)
919 } 911 }
920
921 if let export = try? decoder.decode(TrackedDomainsExport.self, from: data) { 912 if let export = try? decoder.decode(TrackedDomainsExport.self, from: data) {
922 let report = DataValidationService.validate(trackedDomains: export.trackedDomains) 913 return try trackedDomainsPayload(export.trackedDomains)
923 if !report.errors.isEmpty {
924 throw DataPortabilityError.validationFailed(report.errors)
925 }
926 return .trackedDomains(export.trackedDomains, report)
927 } 914 }
928
929 if let export = try? decoder.decode(WorkflowsExport.self, from: data) { 915 if let export = try? decoder.decode(WorkflowsExport.self, from: data) {
930 let report = DataValidationService.validate(workflows: export.workflows) 916 return try workflowsPayload(export.workflows)
931 if !report.errors.isEmpty {
932 throw DataPortabilityError.validationFailed(report.errors)
933 }
934 return .workflows(export.workflows, report)
935 } 917 }
936
937 if let trackedDomains = try? decoder.decode([TrackedDomain].self, from: data) { 918 if let trackedDomains = try? decoder.decode([TrackedDomain].self, from: data) {
938 let report = DataValidationService.validate(trackedDomains: trackedDomains) 919 return try trackedDomainsPayload(trackedDomains)
939 if !report.errors.isEmpty {
940 throw DataPortabilityError.validationFailed(report.errors)
941 }
942 return .trackedDomains(trackedDomains, report)
943 } 920 }
944
945 if let workflows = try? decoder.decode([DomainWorkflow].self, from: data) { 921 if let workflows = try? decoder.decode([DomainWorkflow].self, from: data) {
946 let report = DataValidationService.validate(workflows: workflows) 922 return try workflowsPayload(workflows)
947 if !report.errors.isEmpty {
948 throw DataPortabilityError.validationFailed(report.errors)
949 }
950 return .workflows(workflows, report)
951 } 923 }
924 if fileName.lowercased().hasSuffix(".csv") {
925 return try decodeCSVPayload(from: data, fileName: fileName)
926 }
927 throw DataPortabilityError.unsupportedFormat
928 }
952 929
953 let lowercasedFileName = fileName.lowercased() 930 /// A CSV holds workflows when its name says so, and tracked domains otherwise.
954 if lowercasedFileName.hasSuffix(".csv") { 931 private static func decodeCSVPayload(from data: Data, fileName: String) throws -> ImportPayload {
955 guard let string = String(data: data, encoding: .utf8) else { 932 guard let string = String(data: data, encoding: .utf8) else {
956 throw DataPortabilityError.unreadableFile 933 throw DataPortabilityError.unreadableFile
957 } 934 }
958 if lowercasedFileName.contains("workflow") { 935 if fileName.lowercased().contains("workflow") {
959 let workflows = try DataPortabilityCSV.parseWorkflows(from: string) 936 return try workflowsPayload(DataPortabilityCSV.parseWorkflows(from: string))
960 let report = DataValidationService.validate(workflows: workflows)
961 if !report.errors.isEmpty {
962 throw DataPortabilityError.validationFailed(report.errors)
963 }
964 return .workflows(workflows, report)
965 }
966
967 let trackedDomains = try DataPortabilityCSV.parseTrackedDomains(from: string)
968 let report = DataValidationService.validate(trackedDomains: trackedDomains)
969 if !report.errors.isEmpty {
970 throw DataPortabilityError.validationFailed(report.errors)
971 }
972 return .trackedDomains(trackedDomains, report)
973 } 937 }
938 return try trackedDomainsPayload(DataPortabilityCSV.parseTrackedDomains(from: string))
939 }
974 940
975 throw DataPortabilityError.unsupportedFormat 941 private static func trackedDomainsPayload(_ trackedDomains: [TrackedDomain]) throws -> ImportPayload {
942 .trackedDomains(trackedDomains, try passing(DataValidationService.validate(trackedDomains: trackedDomains)))
943 }
944
945 private static func workflowsPayload(_ workflows: [DomainWorkflow]) throws -> ImportPayload {
946 .workflows(workflows, try passing(DataValidationService.validate(workflows: workflows)))
947 }
948
949 /// `report`, unless it found errors, which fail the import.
950 private static func passing(_ report: DataValidationReport) throws -> DataValidationReport {
951 guard report.errors.isEmpty else {
952 throw DataPortabilityError.validationFailed(report.errors)
953 }
954 return report
976 } 955 }
977 956
978 private static func decodeLegacyBackup(from data: Data) throws -> DomainDigBackup { 957 private static func decodeLegacyBackup(from data: Data) throws -> DomainDigBackup {
DomainDig/DiffService.swift +3 −2
@@ -329,8 +329,9 @@ enum DiffService {
329 } 329 }
330 330
331 private static func dnsSection(from oldReport: DomainReport, to newReport: DomainReport) -> DiffSection { 331 private static func dnsSection(from oldReport: DomainReport, to newReport: DomainReport) -> DiffSection {
332 let oldSections = Dictionary(uniqueKeysWithValues: oldReport.dns.recordSections.map { ($0.recordType, $0) }) 332 // Imported reports are not guaranteed one section per record type.
333 let newSections = Dictionary(uniqueKeysWithValues: newReport.dns.recordSections.map { ($0.recordType, $0) }) 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 }
334 let recordTypes = Set(oldSections.keys).union(newSections.keys).sorted { $0.rawValue < $1.rawValue } 335 let recordTypes = Set(oldSections.keys).union(newSections.keys).sorted { $0.rawValue < $1.rawValue }
335 336
336 var items: [DiffItem] = [ 337 var items: [DiffItem] = [
DomainDig/DomainDig/AuditExporter.swift +54 −68
@@ -48,7 +48,21 @@ enum AuditExporter {
48 lines.append("") 48 lines.append("")
49 } 49 }
50 50
51 lines.append("## Findings Summary") 51 lines += findingsSummaryLines(session)
52 lines += keyRiskLines(session)
53 lines.append("## Checklist")
54 for item in session.checklist {
55 lines.append("- [\(item.isComplete ? "x" : " ")] \(item.title): \(item.detail)")
56 }
57 lines.append("")
58 lines += findingLines(session)
59 lines += evidenceLines(session.evidence)
60
61 return lines.joined(separator: "\n")
62 }
63
64 private static func findingsSummaryLines(_ session: AuditSession) -> [String] {
65 var lines = ["## Findings Summary"]
52 if session.findings.isEmpty { 66 if session.findings.isEmpty {
53 lines.append("No findings recorded.") 67 lines.append("No findings recorded.")
54 } else { 68 } else {
@@ -57,8 +71,11 @@ enum AuditExporter {
57 } 71 }
58 } 72 }
59 lines.append("") 73 lines.append("")
74 return lines
75 }
60 76
61 lines.append("## Key Risks") 77 private static func keyRiskLines(_ session: AuditSession) -> [String] {
78 var lines = ["## Key Risks"]
62 if session.keyRisks.isEmpty { 79 if session.keyRisks.isEmpty {
63 lines.append("No medium or high-severity risks recorded.") 80 lines.append("No medium or high-severity risks recorded.")
64 } else { 81 } else {
@@ -67,46 +84,46 @@ enum AuditExporter {
67 } 84 }
68 } 85 }
69 lines.append("") 86 lines.append("")
87 return lines
88 }
70 89
71 lines.append("## Checklist") 90 private static func findingLines(_ session: AuditSession) -> [String] {
72 for item in session.checklist { 91 var lines = ["## Findings"]
73 lines.append("- [\(item.isComplete ? "x" : " ")] \(item.title): \(item.detail)")
74 }
75 lines.append("")
76
77 lines.append("## Findings")
78 if session.findings.isEmpty { 92 if session.findings.isEmpty {
79 lines.append("No findings recorded.") 93 lines.append("No findings recorded.")
80 } else { 94 }
81 for finding in session.findings { 95 for finding in session.findings {
82 lines.append("### \(finding.title)") 96 lines.append("### \(finding.title)")
83 lines.append("- Severity: \(finding.severity.title)") 97 lines.append("- Severity: \(finding.severity.title)")
84 lines.append("- Status: \(finding.status.title)") 98 lines.append("- Status: \(finding.status.title)")
85 if !finding.checklistAreas.isEmpty { 99 if !finding.checklistAreas.isEmpty {
86 lines.append("- Checklist Areas: \(finding.checklistAreas.map(\.title).joined(separator: ", "))") 100 lines.append("- Checklist Areas: \(finding.checklistAreas.map(\.title).joined(separator: ", "))")
87 }
88 lines.append("- Summary: \(finding.summary)")
89 if !finding.evidenceReferences.isEmpty {
90 lines.append("- Evidence: \(finding.evidenceReferences.joined(separator: " | "))")
91 }
92 if !finding.notes.isEmpty {
93 lines.append("- Notes: \(finding.notes)")
94 }
95 lines.append("")
96 } 101 }
102 lines.append("- Summary: \(finding.summary)")
103 if !finding.evidenceReferences.isEmpty {
104 lines.append("- Evidence: \(finding.evidenceReferences.joined(separator: " | "))")
105 }
106 if !finding.notes.isEmpty {
107 lines.append("- Notes: \(finding.notes)")
108 }
109 lines.append("")
97 } 110 }
111 return lines
112 }
98 113
99 lines.append("## Evidence Snapshot") 114 private static func evidenceLines(_ evidence: AuditEvidenceSnapshot) -> [String] {
100 lines.append("- Availability: \(availabilityTitle(session.evidence.report.availability))") 115 let report = evidence.report
101 lines.append("- Risk Score: \(session.evidence.report.riskAssessment.score) (\(session.evidence.report.riskAssessment.level.title))") 116 return [
102 lines.append("- TLS Status: \(session.evidence.report.web.tlsStatus)") 117 "## Evidence Snapshot",
103 lines.append("- Final URL: \(session.evidence.report.web.finalURL ?? "Unavailable")") 118 "- Availability: \(availabilityTitle(report.availability))",
104 lines.append("- Primary IP: \(session.evidence.report.dns.primaryIP ?? "Unavailable")") 119 "- Risk Score: \(report.riskAssessment.score) (\(report.riskAssessment.level.title))",
105 lines.append("- Reachability: \(session.evidence.report.network.reachabilitySummary)") 120 "- TLS Status: \(report.web.tlsStatus)",
106 lines.append("- Ownership: \(session.evidence.report.ownership?.registrar ?? "Unavailable")") 121 "- Final URL: \(report.web.finalURL ?? "Unavailable")",
107 lines.append("- Historical Context Snapshots: \(session.evidence.historicalContext.count)") 122 "- Primary IP: \(report.dns.primaryIP ?? "Unavailable")",
108 123 "- Reachability: \(report.network.reachabilitySummary)",
109 return lines.joined(separator: "\n") 124 "- Ownership: \(report.ownership?.registrar ?? "Unavailable")",
125 "- Historical Context Snapshots: \(evidence.historicalContext.count)",
126 ]
110 } 127 }
111 128
112 private static func availabilityTitle(_ status: DomainAvailabilityStatus) -> String { 129 private static func availabilityTitle(_ status: DomainAvailabilityStatus) -> String {
@@ -121,37 +138,6 @@ enum AuditExporter {
121 } 138 }
122 139
123 private static func pdfData(for session: AuditSession) throws -> Data { 140 private static func pdfData(for session: AuditSession) throws -> Data {
124 let markdown = markdown(for: session) 141 DomainReportExporter.pdfData(fromMarkdown: markdown(for: session))
125 #if canImport(UIKit)
126 let renderer = UIGraphicsPDFRenderer(bounds: CGRect(x: 0, y: 0, width: 612, height: 792))
127 return renderer.pdfData { context in
128 let lines = markdown.components(separatedBy: .newlines)
129 let paragraphStyle = NSMutableParagraphStyle()
130 paragraphStyle.lineBreakMode = .byWordWrapping
131 let attributes: [NSAttributedString.Key: Any] = [
132 .font: UIFont.monospacedSystemFont(ofSize: 11, weight: .regular),
133 .paragraphStyle: paragraphStyle
134 ]
135
136 var yOffset: CGFloat = 36
137 context.beginPage()
138
139 for line in lines {
140 if yOffset > 744 {
141 context.beginPage()
142 yOffset = 36
143 }
144
145 let renderedLine = NSString(string: line.isEmpty ? " " : line)
146 renderedLine.draw(
147 in: CGRect(x: 36, y: yOffset, width: 540, height: 22),
148 withAttributes: attributes
149 )
150 yOffset += 16
151 }
152 }
153 #else
154 return Data(markdown.utf8)
155 #endif
156 } 142 }
157} 143}
DomainDig/DomainInsightEngine.swift +117 −104
@@ -176,158 +176,171 @@ enum DomainInsightEngine {
176 tlsAssessment: TLSSummaryAssessment, 176 tlsAssessment: TLSSummaryAssessment,
177 subdomainGroups: [SubdomainGroup] 177 subdomainGroups: [SubdomainGroup]
178 ) -> DomainRiskAssessment { 178 ) -> DomainRiskAssessment {
179 var tally = RiskTally()
180 scoreAvailability(snapshot, into: &tally)
181 scoreDNS(snapshot, patterns: dnsPatterns, into: &tally)
182 scoreTLS(snapshot, assessment: tlsAssessment, into: &tally)
183 scoreRedirects(snapshot, into: &tally)
184 scoreEmail(snapshot, assessment: emailAssessment, into: &tally)
185 scorePorts(snapshot, into: &tally)
186 scoreSubdomains(snapshot, groups: subdomainGroups, into: &tally)
187 scoreGeolocation(snapshot, into: &tally)
188 // Compares against the score so far, so it runs after the snapshot's own factors.
189 if let previousSnapshot {
190 let delta = tally.score - analyze(snapshot: previousSnapshot).riskAssessment.score
191 if delta >= 15 {
192 tally.add(4, "Observed risk has increased materially since the previous snapshot", .negative)
193 }
194 }
195 scoreReputation(snapshot, into: &tally)
196
197 let clampedScore = min(max(tally.score, 0), 100)
198 let level: RiskLevel
199 switch clampedScore {
200 case 0..<35:
201 level = .low
202 case 35..<65:
203 level = .medium
204 default:
205 level = .high
206 }
207
208 return DomainRiskAssessment(score: clampedScore, level: level, factors: tally.factors)
209 }
210
211 /// A risk score in progress, from a baseline of 18, and the factors behind it.
212 private struct RiskTally {
179 var score = 18 213 var score = 18
180 var factors: [RiskFactor] = [] 214 var factors: [RiskFactor] = []
181 215
216 mutating func add(_ points: Int, _ description: String, _ impact: RiskImpact) {
217 score += points
218 factors.append(RiskFactor(description: description, impact: impact))
219 }
220 }
221
222 private static func scoreAvailability(_ snapshot: LookupSnapshot, into tally: inout RiskTally) {
182 switch snapshot.availabilityResult?.status ?? .unknown { 223 switch snapshot.availabilityResult?.status ?? .unknown {
183 case .available: 224 case .available:
184 score -= 12 225 tally.add(-12, "Domain appears available rather than actively deployed", .positive)
185 factors.append(.init(description: "Domain appears available rather than actively deployed", impact: .positive))
186 case .unknown: 226 case .unknown:
187 score += 8 227 tally.add(8, "Ownership and availability could not be confirmed", .negative)
188 factors.append(.init(description: "Ownership and availability could not be confirmed", impact: .negative))
189 case .registered: 228 case .registered:
190 if !snapshot.dnsSections.isEmpty || snapshot.sslInfo != nil || !snapshot.redirectChain.isEmpty { 229 if !snapshot.dnsSections.isEmpty || snapshot.sslInfo != nil || !snapshot.redirectChain.isEmpty {
191 score += 6 230 tally.add(6, "Registered domain exposes active infrastructure", .negative)
192 factors.append(.init(description: "Registered domain exposes active infrastructure", impact: .negative))
193 } else { 231 } else {
194 factors.append(.init(description: "Registered domain with limited active surface detected", impact: .neutral)) 232 tally.add(0, "Registered domain with limited active surface detected", .neutral)
195 } 233 }
196 } 234 }
235 }
197 236
237 private static func scoreDNS(_ snapshot: LookupSnapshot, patterns: DNSPatternSummary, into tally: inout RiskTally) {
198 let recordTypes = snapshot.dnsSections.filter { !$0.records.isEmpty || !$0.wildcardRecords.isEmpty }.count 238 let recordTypes = snapshot.dnsSections.filter { !$0.records.isEmpty || !$0.wildcardRecords.isEmpty }.count
199 if recordTypes >= 5 { 239 if recordTypes >= 5 {
200 score += 8 240 tally.add(8, "DNS configuration is broad across multiple record types", .negative)
201 factors.append(.init(description: "DNS configuration is broad across multiple record types", impact: .negative))
202 } 241 }
203 if dnsPatterns.wildcardDetected { 242 if patterns.wildcardDetected {
204 score += 12 243 tally.add(12, "Wildcard DNS is enabled", .negative)
205 factors.append(.init(description: "Wildcard DNS is enabled", impact: .negative))
206 } 244 }
207 if let firstPattern = dnsPatterns.patterns.first { 245 if let firstPattern = patterns.patterns.first {
208 factors.append(.init(description: firstPattern, impact: .neutral)) 246 tally.add(0, firstPattern, .neutral)
209 } 247 }
248 }
210 249
211 switch tlsAssessment.grade { 250 private static func scoreTLS(_ snapshot: LookupSnapshot, assessment: TLSSummaryAssessment, into tally: inout RiskTally) {
251 switch assessment.grade {
212 case .a: 252 case .a:
213 score -= 8 253 tally.add(-8, "TLS configuration looks current and stable", .positive)
214 factors.append(.init(description: "TLS configuration looks current and stable", impact: .positive))
215 case .b: 254 case .b:
216 score -= 3 255 tally.add(-3, "TLS is valid with minor concerns", .positive)
217 factors.append(.init(description: "TLS is valid with minor concerns", impact: .positive))
218 case .c: 256 case .c:
219 score += 10 257 tally.add(10, "TLS configuration has visible weaknesses", .negative)
220 factors.append(.init(description: "TLS configuration has visible weaknesses", impact: .negative))
221 case .f: 258 case .f:
222 score += 22 259 tally.add(22, "TLS is missing, invalid, or near failure", .negative)
223 factors.append(.init(description: "TLS is missing, invalid, or near failure", impact: .negative))
224 } 260 }
225
226 if let daysUntilExpiry = snapshot.sslInfo?.daysUntilExpiry, daysUntilExpiry <= 14 { 261 if let daysUntilExpiry = snapshot.sslInfo?.daysUntilExpiry, daysUntilExpiry <= 14 {
227 score += 10 262 tally.add(10, "Certificate expires within 14 days", .negative)
228 factors.append(.init(description: "Certificate expires within 14 days", impact: .negative))
229 } 263 }
264 }
230 265
266 private static func scoreRedirects(_ snapshot: LookupSnapshot, into tally: inout RiskTally) {
231 if snapshot.redirectChain.count >= 3 { 267 if snapshot.redirectChain.count >= 3 {
232 score += 8 268 tally.add(8, "Redirect chain is longer than expected", .negative)
233 factors.append(.init(description: "Redirect chain is longer than expected", impact: .negative))
234 } 269 }
235
236 if redirectLooksSensitive(snapshot.redirectChain.last?.url) { 270 if redirectLooksSensitive(snapshot.redirectChain.last?.url) {
237 score += 6 271 tally.add(6, "Redirect target looks like an auth or account gateway", .negative)
238 factors.append(.init(description: "Redirect target looks like an auth or account gateway", impact: .negative)) 272 }
239 } 273 }
240 274
241 if let emailAssessment { 275 private static func scoreEmail(
242 switch emailAssessment.grade { 276 _ snapshot: LookupSnapshot,
243 case .a: 277 assessment: EmailSecurityAssessment?,
244 score -= 10 278 into tally: inout RiskTally
245 factors.append(.init(description: "Email protections are strong and aligned", impact: .positive)) 279 ) {
246 case .b: 280 guard let assessment else {
247 score -= 4 281 if hasMXRecords(snapshot) {
248 factors.append(.init(description: "Email protections are present with minor gaps", impact: .positive)) 282 tally.add(14, "Mail is configured without enough email security evidence", .negative)
249 case .c:
250 score += 8
251 factors.append(.init(description: "Email protections are partial", impact: .negative))
252 case .f:
253 score += 18
254 factors.append(.init(description: "Email security protections are weak or absent", impact: .negative))
255 } 283 }
256 } else if hasMXRecords(snapshot) { 284 return
257 score += 14
258 factors.append(.init(description: "Mail is configured without enough email security evidence", impact: .negative))
259 } 285 }
286 switch assessment.grade {
287 case .a:
288 tally.add(-10, "Email protections are strong and aligned", .positive)
289 case .b:
290 tally.add(-4, "Email protections are present with minor gaps", .positive)
291 case .c:
292 tally.add(8, "Email protections are partial", .negative)
293 case .f:
294 tally.add(18, "Email security protections are weak or absent", .negative)
295 }
296 }
260 297
298 private static func scorePorts(_ snapshot: LookupSnapshot, into tally: inout RiskTally) {
261 let openPorts = snapshot.portScanResults.filter(\.open).map(\.port) 299 let openPorts = snapshot.portScanResults.filter(\.open).map(\.port)
262 let sensitivePorts: Set<UInt16> = [21, 22, 23, 25, 3389, 5900] 300 let sensitivePorts: Set<UInt16> = [21, 22, 23, 25, 3389, 5900]
263 let exposedSensitivePorts = openPorts.filter { sensitivePorts.contains($0) } 301 let exposedSensitivePorts = openPorts.filter { sensitivePorts.contains($0) }
264 if !exposedSensitivePorts.isEmpty { 302 if !exposedSensitivePorts.isEmpty {
265 score += min(18, exposedSensitivePorts.count * 6) 303 tally.add(min(18, exposedSensitivePorts.count * 6), "Sensitive management or mail ports are exposed", .negative)
266 factors.append(.init(description: "Sensitive management or mail ports are exposed", impact: .negative))
267 } else if Set(openPorts) == Set([80, 443]) { 304 } else if Set(openPorts) == Set([80, 443]) {
268 factors.append(.init(description: "Exposure is limited to standard web ports", impact: .positive)) 305 tally.add(0, "Exposure is limited to standard web ports", .positive)
269 } else if openPorts.count >= 3 { 306 } else if openPorts.count >= 3 {
270 score += 8 307 tally.add(8, "Multiple open services expand the attack surface", .negative)
271 factors.append(.init(description: "Multiple open services expand the attack surface", impact: .negative))
272 } 308 }
309 }
273 310
274 if !subdomainGroups.isEmpty { 311 private static func scoreSubdomains(_ snapshot: LookupSnapshot, groups: [SubdomainGroup], into tally: inout RiskTally) {
275 let labels = Set(subdomainGroups.map(\.label)) 312 guard !groups.isEmpty else { return }
276 if labels.contains("dev") || labels.contains("staging") { 313 let labels = Set(groups.map(\.label))
277 score += 8 314 if labels.contains("dev") || labels.contains("staging") {
278 factors.append(.init(description: "Development or staging subdomains are discoverable", impact: .negative)) 315 tally.add(8, "Development or staging subdomains are discoverable", .negative)
279 }
280 if labels.contains("admin") {
281 score += 10
282 factors.append(.init(description: "Administrative subdomains are discoverable", impact: .negative))
283 }
284 if snapshot.subdomains.count >= 8 {
285 score += 6
286 factors.append(.init(description: "Large passive subdomain footprint detected", impact: .negative))
287 }
288 } 316 }
317 if labels.contains("admin") {
318 tally.add(10, "Administrative subdomains are discoverable", .negative)
319 }
320 if snapshot.subdomains.count >= 8 {
321 tally.add(6, "Large passive subdomain footprint detected", .negative)
322 }
323 }
289 324
325 private static func scoreGeolocation(_ snapshot: LookupSnapshot, into tally: inout RiskTally) {
290 if snapshot.ipGeolocation == nil, 326 if snapshot.ipGeolocation == nil,
291 snapshot.availabilityResult?.status == .registered, 327 snapshot.availabilityResult?.status == .registered,
292 snapshot.dnsSections.contains(where: { $0.recordType == .A && !$0.records.isEmpty }) { 328 snapshot.dnsSections.contains(where: { $0.recordType == .A && !$0.records.isEmpty }) {
293 score += 4 329 tally.add(4, "Active host could not be geolocated", .neutral)
294 factors.append(.init(description: "Active host could not be geolocated", impact: .neutral))
295 }
296
297 if let previousSnapshot {
298 let previousAnalysis = analyze(snapshot: previousSnapshot)
299 let delta = score - previousAnalysis.riskAssessment.score
300 if delta >= 15 {
301 score += 4
302 factors.append(.init(description: "Observed risk has increased materially since the previous snapshot", impact: .negative))
303 }
304 }
305
306 if let reputation = snapshot.reputation {
307 switch reputation.status {
308 case .listed:
309 score += 25
310 let sourceList = reputation.listedSources.isEmpty ? "" : " (\(reputation.listedSources.joined(separator: ", ")))"
311 factors.append(.init(description: "Domain is flagged by a configured reputation source\(sourceList)", impact: .negative))
312 case .clean:
313 factors.append(.init(description: "Domain is clean against the configured reputation source", impact: .positive))
314 case .unknown:
315 break
316 }
317 } 330 }
331 }
318 332
319 let clampedScore = min(max(score, 0), 100) 333 private static func scoreReputation(_ snapshot: LookupSnapshot, into tally: inout RiskTally) {
320 let level: RiskLevel 334 guard let reputation = snapshot.reputation else { return }
321 switch clampedScore { 335 switch reputation.status {
322 case 0..<35: 336 case .listed:
323 level = .low 337 let sourceList = reputation.listedSources.isEmpty ? "" : " (\(reputation.listedSources.joined(separator: ", ")))"
324 case 35..<65: 338 tally.add(25, "Domain is flagged by a configured reputation source\(sourceList)", .negative)
325 level = .medium 339 case .clean:
326 default: 340 tally.add(0, "Domain is clean against the configured reputation source", .positive)
327 level = .high 341 case .unknown:
342 break
328 } 343 }
329
330 return DomainRiskAssessment(score: clampedScore, level: level, factors: factors)
331 } 344 }
332 345
333 private static func insights( 346 private static func insights(
DomainDig/DomainMonitoringService.swift +3 −118
@@ -290,11 +290,11 @@ final class DomainMonitoringService {
290 domain: trackedDomain.domain, 290 domain: trackedDomain.domain,
291 previousSnapshot: previousSnapshot 291 previousSnapshot: previousSnapshot
292 ) 292 )
293 let snapshot = Self.resolvedSnapshotAfterFallback(inspectedSnapshot, previousSnapshot: previousSnapshot) 293 let snapshot = inspectedSnapshot.resolvedAfterFallback(to: previousSnapshot)
294 // When the fallback fires, `snapshot` *is* `previousSnapshot`, so 294 // When the fallback fires, `snapshot` *is* `previousSnapshot`, so
295 // every comparison below is old-against-old and would otherwise 295 // every comparison below is old-against-old and would otherwise
296 // report "No meaningful changes" for a domain we never reached. 296 // report "No meaningful changes" for a domain we never reached.
297 let unreachableReason = (previousSnapshot != nil && Self.shouldFallbackToSnapshot(inspectedSnapshot)) 297 let unreachableReason = (previousSnapshot != nil && inspectedSnapshot.needsFallback)
298 ? Self.firstErrorMessage(in: inspectedSnapshot) 298 ? Self.firstErrorMessage(in: inspectedSnapshot)
299 : nil 299 : nil
300 let savedEntry: HistoryEntry? 300 let savedEntry: HistoryEntry?
@@ -844,95 +844,8 @@ final class DomainMonitoringService {
844 } 844 }
845 } 845 }
846 846
847 private static func resolvedSnapshotAfterFallback(
848 _ snapshot: LookupSnapshot,
849 previousSnapshot: LookupSnapshot?
850 ) -> LookupSnapshot {
851 guard shouldFallbackToSnapshot(snapshot), let previousSnapshot else {
852 return snapshot
853 }
854
855 return LookupSnapshot(
856 historyEntryID: previousSnapshot.historyEntryID,
857 domain: previousSnapshot.domain,
858 timestamp: previousSnapshot.timestamp,
859 trackedDomainID: previousSnapshot.trackedDomainID,
860 note: previousSnapshot.note,
861 appVersion: previousSnapshot.appVersion,
862 resolverDisplayName: previousSnapshot.resolverDisplayName,
863 resolverURLString: previousSnapshot.resolverURLString,
864 dataSources: previousSnapshot.dataSources,
865 provenanceBySection: previousSnapshot.provenanceBySection,
866 availabilityConfidence: previousSnapshot.availabilityConfidence,
867 ownershipConfidence: previousSnapshot.ownershipConfidence,
868 subdomainConfidence: previousSnapshot.subdomainConfidence,
869 emailSecurityConfidence: previousSnapshot.emailSecurityConfidence,
870 geolocationConfidence: previousSnapshot.geolocationConfidence,
871 errorDetails: previousSnapshot.errorDetails,
872 isPartialSnapshot: previousSnapshot.isPartialSnapshot,
873 validationIssues: previousSnapshot.validationIssues,
874 totalLookupDurationMs: previousSnapshot.totalLookupDurationMs,
875 snapshotIndex: previousSnapshot.snapshotIndex,
876 previousSnapshotID: previousSnapshot.previousSnapshotID,
877 changeCount: previousSnapshot.changeCount,
878 severitySummary: previousSnapshot.severitySummary,
879 dnsSections: previousSnapshot.dnsSections,
880 dnsError: previousSnapshot.dnsError,
881 availabilityResult: previousSnapshot.availabilityResult,
882 suggestions: previousSnapshot.suggestions,
883 sslInfo: previousSnapshot.sslInfo,
884 sslError: previousSnapshot.sslError,
885 hstsPreloaded: previousSnapshot.hstsPreloaded,
886 httpHeaders: previousSnapshot.httpHeaders,
887 httpSecurityGrade: previousSnapshot.httpSecurityGrade,
888 httpStatusCode: previousSnapshot.httpStatusCode,
889 httpResponseTimeMs: previousSnapshot.httpResponseTimeMs,
890 httpProtocol: previousSnapshot.httpProtocol,
891 http3Advertised: previousSnapshot.http3Advertised,
892 httpHeadersError: previousSnapshot.httpHeadersError,
893 reachabilityResults: previousSnapshot.reachabilityResults,
894 reachabilityError: previousSnapshot.reachabilityError,
895 ipGeolocation: previousSnapshot.ipGeolocation,
896 ipGeolocationError: previousSnapshot.ipGeolocationError,
897 emailSecurity: previousSnapshot.emailSecurity,
898 emailSecurityError: previousSnapshot.emailSecurityError,
899 ownership: previousSnapshot.ownership,
900 ownershipError: previousSnapshot.ownershipError,
901 ownershipHistory: previousSnapshot.ownershipHistory,
902 ownershipHistoryError: previousSnapshot.ownershipHistoryError,
903 inferredProvider: previousSnapshot.inferredProvider,
904 priorProviders: previousSnapshot.priorProviders,
905 domainClassification: previousSnapshot.domainClassification,
906 ownershipTransitions: previousSnapshot.ownershipTransitions,
907 hostingTransitions: previousSnapshot.hostingTransitions,
908 subdomainHistory: previousSnapshot.subdomainHistory,
909 riskSignals: previousSnapshot.riskSignals,
910 intelligenceTimeline: previousSnapshot.intelligenceTimeline,
911 ptrRecord: previousSnapshot.ptrRecord,
912 ptrError: previousSnapshot.ptrError,
913 redirectChain: previousSnapshot.redirectChain,
914 redirectChainError: previousSnapshot.redirectChainError,
915 subdomains: previousSnapshot.subdomains,
916 subdomainsError: previousSnapshot.subdomainsError,
917 extendedSubdomains: previousSnapshot.extendedSubdomains,
918 extendedSubdomainsError: previousSnapshot.extendedSubdomainsError,
919 dnsHistory: previousSnapshot.dnsHistory,
920 dnsHistoryError: previousSnapshot.dnsHistoryError,
921 domainPricing: previousSnapshot.domainPricing,
922 domainPricingError: previousSnapshot.domainPricingError,
923 reputation: previousSnapshot.reputation,
924 reputationError: previousSnapshot.reputationError,
925 portScanResults: previousSnapshot.portScanResults,
926 portScanError: previousSnapshot.portScanError,
927 changeSummary: previousSnapshot.changeSummary,
928 resultSource: .snapshot,
929 cachedSections: [],
930 statusMessage: "Last known result • \(previousSnapshot.timestamp.formatted(date: .abbreviated, time: .shortened))"
931 )
932 }
933
934 /// First reported error on a snapshot, used to explain a fallback. Mirrors 847 /// First reported error on a snapshot, used to explain a fallback. Mirrors
935 /// the ordering `shouldFallbackToSnapshot` inspects. 848 /// the ordering `LookupSnapshot.needsFallback` inspects.
936 private static func firstErrorMessage(in snapshot: LookupSnapshot) -> String { 849 private static func firstErrorMessage(in snapshot: LookupSnapshot) -> String {
937 [ 850 [
938 snapshot.dnsError, 851 snapshot.dnsError,
@@ -947,34 +860,6 @@ final class DomainMonitoringService {
947 .first ?? "The lookup could not reach the domain." 860 .first ?? "The lookup could not reach the domain."
948 } 861 }
949 862
950 private static func shouldFallbackToSnapshot(_ snapshot: LookupSnapshot) -> Bool {
951 let candidateMessages = [
952 snapshot.dnsError,
953 snapshot.httpHeadersError,
954 snapshot.sslError,
955 snapshot.ownershipError,
956 snapshot.subdomainsError,
957 snapshot.redirectChainError,
958 snapshot.ipGeolocationError
959 ]
960 .compactMap { $0?.lowercased() }
961
962 guard !candidateMessages.isEmpty else { return false }
963 let connectivityFailure = candidateMessages.allSatisfy { message in
964 message.hasPrefix("network error:")
965 || message.hasPrefix("timeout:")
966 || message.hasPrefix("rate limit:")
967 }
968
969 let hasMaterialData = !snapshot.dnsSections.isEmpty
970 || !snapshot.httpHeaders.isEmpty
971 || snapshot.sslInfo != nil
972 || snapshot.ownership != nil
973 || !snapshot.subdomains.isEmpty
974
975 return connectivityFailure && !hasMaterialData
976 }
977
978 private static func primaryIPAddress(from snapshot: LookupSnapshot) -> String? { 863 private static func primaryIPAddress(from snapshot: LookupSnapshot) -> String? {
979 snapshot.dnsSections.first(where: { $0.recordType == .A })?.records.first?.value 864 snapshot.dnsSections.first(where: { $0.recordType == .A })?.records.first?.value
980 } 865 }
DomainDig/DomainViewModel.swift +276 −382
@@ -1395,7 +1395,7 @@ final class DomainViewModel {
1395 DomainDebugLog.debug("DomainViewModel.performLookup inspectionReturned domain=\(domain)") 1395 DomainDebugLog.debug("DomainViewModel.performLookup inspectionReturned domain=\(domain)")
1396 guard !Task.isCancelled, isCurrentLookup(lookupID) else { return nil } 1396 guard !Task.isCancelled, isCurrentLookup(lookupID) else { return nil }
1397 1397
1398 let snapshot = Self.resolvedSnapshotAfterFallback(inspectedSnapshot, previousSnapshot: previous) 1398 let snapshot = inspectedSnapshot.resolvedAfterFallback(to: previous)
1399 let applyStartedAt = DomainDebugLog.signpostStart("DomainViewModel.applySnapshot", domain: domain) 1399 let applyStartedAt = DomainDebugLog.signpostStart("DomainViewModel.applySnapshot", domain: domain)
1400 applySnapshot(snapshot) 1400 applySnapshot(snapshot)
1401 DomainDebugLog.signpostEnd("DomainViewModel.applySnapshot", start: applyStartedAt, domain: domain) 1401 DomainDebugLog.signpostEnd("DomainViewModel.applySnapshot", start: applyStartedAt, domain: domain)
@@ -1506,119 +1506,6 @@ final class DomainViewModel {
1506 customPortScanLoading = false 1506 customPortScanLoading = false
1507 } 1507 }
1508 1508
1509 private static func resolvedSnapshotAfterFallback(
1510 _ snapshot: LookupSnapshot,
1511 previousSnapshot: LookupSnapshot?
1512 ) -> LookupSnapshot {
1513 guard shouldFallbackToSnapshot(snapshot), let previousSnapshot else {
1514 return snapshot
1515 }
1516
1517 return LookupSnapshot(
1518 historyEntryID: previousSnapshot.historyEntryID,
1519 domain: previousSnapshot.domain,
1520 timestamp: previousSnapshot.timestamp,
1521 trackedDomainID: previousSnapshot.trackedDomainID,
1522 note: previousSnapshot.note,
1523 appVersion: previousSnapshot.appVersion,
1524 resolverDisplayName: previousSnapshot.resolverDisplayName,
1525 resolverURLString: previousSnapshot.resolverURLString,
1526 dataSources: previousSnapshot.dataSources,
1527 provenanceBySection: previousSnapshot.provenanceBySection,
1528 availabilityConfidence: previousSnapshot.availabilityConfidence,
1529 ownershipConfidence: previousSnapshot.ownershipConfidence,
1530 subdomainConfidence: previousSnapshot.subdomainConfidence,
1531 emailSecurityConfidence: previousSnapshot.emailSecurityConfidence,
1532 geolocationConfidence: previousSnapshot.geolocationConfidence,
1533 errorDetails: previousSnapshot.errorDetails,
1534 isPartialSnapshot: previousSnapshot.isPartialSnapshot,
1535 validationIssues: previousSnapshot.validationIssues,
1536 totalLookupDurationMs: previousSnapshot.totalLookupDurationMs,
1537 snapshotIndex: previousSnapshot.snapshotIndex,
1538 previousSnapshotID: previousSnapshot.previousSnapshotID,
1539 changeCount: previousSnapshot.changeCount,
1540 severitySummary: previousSnapshot.severitySummary,
1541 dnsSections: previousSnapshot.dnsSections,
1542 dnsError: previousSnapshot.dnsError,
1543 availabilityResult: previousSnapshot.availabilityResult,
1544 suggestions: previousSnapshot.suggestions,
1545 sslInfo: previousSnapshot.sslInfo,
1546 sslError: previousSnapshot.sslError,
1547 hstsPreloaded: previousSnapshot.hstsPreloaded,
1548 httpHeaders: previousSnapshot.httpHeaders,
1549 httpSecurityGrade: previousSnapshot.httpSecurityGrade,
1550 httpStatusCode: previousSnapshot.httpStatusCode,
1551 httpResponseTimeMs: previousSnapshot.httpResponseTimeMs,
1552 httpProtocol: previousSnapshot.httpProtocol,
1553 http3Advertised: previousSnapshot.http3Advertised,
1554 httpHeadersError: previousSnapshot.httpHeadersError,
1555 reachabilityResults: previousSnapshot.reachabilityResults,
1556 reachabilityError: previousSnapshot.reachabilityError,
1557 ipGeolocation: previousSnapshot.ipGeolocation,
1558 ipGeolocationError: previousSnapshot.ipGeolocationError,
1559 emailSecurity: previousSnapshot.emailSecurity,
1560 emailSecurityError: previousSnapshot.emailSecurityError,
1561 ownership: previousSnapshot.ownership,
1562 ownershipError: previousSnapshot.ownershipError,
1563 ownershipHistory: previousSnapshot.ownershipHistory,
1564 ownershipHistoryError: previousSnapshot.ownershipHistoryError,
1565 inferredProvider: previousSnapshot.inferredProvider,
1566 priorProviders: previousSnapshot.priorProviders,
1567 domainClassification: previousSnapshot.domainClassification,
1568 ownershipTransitions: previousSnapshot.ownershipTransitions,
1569 hostingTransitions: previousSnapshot.hostingTransitions,
1570 subdomainHistory: previousSnapshot.subdomainHistory,
1571 riskSignals: previousSnapshot.riskSignals,
1572 intelligenceTimeline: previousSnapshot.intelligenceTimeline,
1573 ptrRecord: previousSnapshot.ptrRecord,
1574 ptrError: previousSnapshot.ptrError,
1575 redirectChain: previousSnapshot.redirectChain,
1576 redirectChainError: previousSnapshot.redirectChainError,
1577 subdomains: previousSnapshot.subdomains,
1578 subdomainsError: previousSnapshot.subdomainsError,
1579 extendedSubdomains: previousSnapshot.extendedSubdomains,
1580 extendedSubdomainsError: previousSnapshot.extendedSubdomainsError,
1581 dnsHistory: previousSnapshot.dnsHistory,
1582 dnsHistoryError: previousSnapshot.dnsHistoryError,
1583 domainPricing: previousSnapshot.domainPricing,
1584 domainPricingError: previousSnapshot.domainPricingError,
1585 reputation: previousSnapshot.reputation,
1586 reputationError: previousSnapshot.reputationError,
1587 portScanResults: previousSnapshot.portScanResults,
1588 portScanError: previousSnapshot.portScanError,
1589 changeSummary: previousSnapshot.changeSummary,
1590 resultSource: .snapshot,
1591 cachedSections: [],
1592 statusMessage: "Last known result • \(previousSnapshot.timestamp.formatted(date: .abbreviated, time: .shortened))"
1593 )
1594 }
1595
1596 private static func shouldFallbackToSnapshot(_ snapshot: LookupSnapshot) -> Bool {
1597 let candidateMessages = [
1598 snapshot.dnsError,
1599 snapshot.httpHeadersError,
1600 snapshot.sslError,
1601 snapshot.ownershipError,
1602 snapshot.subdomainsError,
1603 snapshot.redirectChainError,
1604 snapshot.ipGeolocationError
1605 ]
1606 .compactMap { $0?.lowercased() }
1607
1608 guard !candidateMessages.isEmpty else { return false }
1609 let failedDueToConnectivity = candidateMessages.allSatisfy { message in
1610 message.hasPrefix("network error:") || message.hasPrefix("timeout:") || message.hasPrefix("rate limit:")
1611 }
1612
1613 let hasMaterialData = !snapshot.dnsSections.isEmpty
1614 || !snapshot.httpHeaders.isEmpty
1615 || snapshot.sslInfo != nil
1616 || snapshot.ownership != nil
1617 || !snapshot.subdomains.isEmpty
1618
1619 return failedDueToConnectivity && !hasMaterialData
1620 }
1621
1622 private func runDNS(domain: String, lookupID: UUID) async { 1509 private func runDNS(domain: String, lookupID: UUID) async {
1623 let result = await DNSLookupService.lookupAll(domain: domain) 1510 let result = await DNSLookupService.lookupAll(domain: domain)
1624 guard !Task.isCancelled, isCurrentLookup(lookupID) else { return } 1511 guard !Task.isCancelled, isCurrentLookup(lookupID) else { return }
@@ -1774,7 +1661,7 @@ final class DomainViewModel {
1774 let result = await PortScanService.scanAll(domain: domain) 1661 let result = await PortScanService.scanAll(domain: domain)
1775 switch result { 1662 switch result {
1776 case let .success(results): 1663 case let .success(results):
1777 let enrichedResults = await enrichOpenPortBanners(in: results, domain: domain) 1664 let enrichedResults = await PortScanService.withBanners(results, host: domain)
1778 guard !Task.isCancelled, isCurrentLookup(lookupID) else { return } 1665 guard !Task.isCancelled, isCurrentLookup(lookupID) else { return }
1779 portScanResults = enrichedResults 1666 portScanResults = enrichedResults
1780 portScanError = nil 1667 portScanError = nil
@@ -1833,36 +1720,7 @@ final class DomainViewModel {
1833 let inspectionService = DomainInspectionService() 1720 let inspectionService = DomainInspectionService()
1834 let snapshot = await inspectionService.inspectSnapshot(domain: domain, previousSnapshot: previousSnapshot) 1721 let snapshot = await inspectionService.inspectSnapshot(domain: domain, previousSnapshot: previousSnapshot)
1835 guard !Task.isCancelled else { return nil } 1722 guard !Task.isCancelled else { return nil }
1836 return BatchLookupPayload(snapshot: resolvedSnapshotAfterFallback(snapshot, previousSnapshot: previousSnapshot)) 1723 return BatchLookupPayload(snapshot: snapshot.resolvedAfterFallback(to: previousSnapshot))
1837 }
1838
1839 private static func enrichOpenPortBanners(_ results: [PortScanResult], domain: String) async -> [PortScanResult] {
1840 let banners = await withTaskGroup(of: (UInt16, String?).self, returning: [UInt16: String].self) { group in
1841 for result in results where result.open {
1842 group.addTask {
1843 let banner = await PortScanService.grabBanner(host: domain, port: result.port)
1844 return (result.port, banner)
1845 }
1846 }
1847
1848 var collected: [UInt16: String] = [:]
1849 for await (port, banner) in group {
1850 if let banner {
1851 collected[port] = banner
1852 }
1853 }
1854 return collected
1855 }
1856
1857 return results.map { result in
1858 var updated = result
1859 updated.banner = banners[result.port]
1860 return updated
1861 }
1862 }
1863
1864 private func enrichOpenPortBanners(in results: [PortScanResult], domain: String) async -> [PortScanResult] {
1865 await Self.enrichOpenPortBanners(results, domain: domain)
1866 } 1724 }
1867 1725
1868 @discardableResult 1726 @discardableResult
@@ -2840,32 +2698,7 @@ final class DomainViewModel {
2840 private func buildAttentionQueue(from domainStates: [PortfolioDomainStatus]) -> [PortfolioAttentionItem] { 2698 private func buildAttentionQueue(from domainStates: [PortfolioDomainStatus]) -> [PortfolioAttentionItem] {
2841 domainStates.compactMap { state in 2699 domainStates.compactMap { state in
2842 guard state.health != .healthy else { return nil } 2700 guard state.health != .healthy else { return nil }
2843 let reason: String 2701 let (reason, timestamp) = Self.attentionReason(for: state)
2844 let timestamp: Date
2845
2846 if state.isUnreachable {
2847 reason = "Endpoint is unreachable"
2848 timestamp = state.lastMonitoringFailure ?? state.trackedDomain.updatedAt
2849 } else if state.certificateExpiryState == .critical {
2850 reason = "Certificate is expiring in under 14 days"
2851 timestamp = state.lastChangeDate ?? state.trackedDomain.updatedAt
2852 } else if state.certificateExpiryState == .warning {
2853 reason = "Certificate expires within 30 days"
2854 timestamp = state.lastChangeDate ?? state.trackedDomain.updatedAt
2855 } else if state.recentFailureCount >= 2 || state.instabilityScore >= 70 {
2856 reason = "Repeated instability detected"
2857 timestamp = state.lastMonitoringFailure ?? state.trackedDomain.updatedAt
2858 } else if state.recentDNSChange {
2859 reason = "DNS changed recently"
2860 timestamp = state.lastChangeDate ?? state.trackedDomain.updatedAt
2861 } else if state.recentCriticalChange {
2862 reason = "Recent critical change detected"
2863 timestamp = state.lastChangeDate ?? state.trackedDomain.updatedAt
2864 } else {
2865 reason = "Needs attention"
2866 timestamp = state.trackedDomain.updatedAt
2867 }
2868
2869 return PortfolioAttentionItem( 2702 return PortfolioAttentionItem(
2870 id: "\(state.trackedDomain.id.uuidString)|\(reason)", 2703 id: "\(state.trackedDomain.id.uuidString)|\(reason)",
2871 trackedDomainID: state.trackedDomain.id, 2704 trackedDomainID: state.trackedDomain.id,
@@ -2883,6 +2716,32 @@ final class DomainViewModel {
2883 } 2716 }
2884 } 2717 }
2885 2718
2719 /// Why an unhealthy domain needs attention, most urgent cause first, and
2720 /// when that cause was last seen.
2721 private static func attentionReason(for state: PortfolioDomainStatus) -> (reason: String, timestamp: Date) {
2722 let changedAt = state.lastChangeDate ?? state.trackedDomain.updatedAt
2723 let failedAt = state.lastMonitoringFailure ?? state.trackedDomain.updatedAt
2724 if state.isUnreachable {
2725 return ("Endpoint is unreachable", failedAt)
2726 }
2727 if state.certificateExpiryState == .critical {
2728 return ("Certificate is expiring in under 14 days", changedAt)
2729 }
2730 if state.certificateExpiryState == .warning {
2731 return ("Certificate expires within 30 days", changedAt)
2732 }
2733 if state.recentFailureCount >= 2 || state.instabilityScore >= 70 {
2734 return ("Repeated instability detected", failedAt)
2735 }
2736 if state.recentDNSChange {
2737 return ("DNS changed recently", changedAt)
2738 }
2739 if state.recentCriticalChange {
2740 return ("Recent critical change detected", changedAt)
2741 }
2742 return ("Needs attention", state.trackedDomain.updatedAt)
2743 }
2744
2886 private func buildPortfolioGroups(from domainStates: [PortfolioDomainStatus]) -> [PortfolioGroup] { 2745 private func buildPortfolioGroups(from domainStates: [PortfolioDomainStatus]) -> [PortfolioGroup] {
2887 Dictionary(grouping: domainStates, by: \.apexDomain) 2746 Dictionary(grouping: domainStates, by: \.apexDomain)
2888 .map { apexDomain, domains in 2747 .map { apexDomain, domains in
@@ -3329,40 +3188,10 @@ final class DomainViewModel {
3329 ) 3188 )
3330 } 3189 }
3331 if let pricing = snapshot.domainPricing { 3190 if let pricing = snapshot.domainPricing {
3332 rows.append( 3191 rows += pricingRows(pricing)
3333 InfoRowViewData(
3334 label: "External Price",
3335 value: pricing.estimatedPrice ?? "Unavailable",
3336 tone: .secondary
3337 )
3338 )
3339 if let premiumIndicator = pricing.premiumIndicator {
3340 rows.append(
3341 InfoRowViewData(
3342 label: "Premium",
3343 value: premiumIndicator ? "Yes" : "No",
3344 tone: premiumIndicator ? .warning : .secondary
3345 )
3346 )
3347 }
3348 if let resaleSignal = pricing.resaleSignal {
3349 rows.append(InfoRowViewData(label: "Resale", value: resaleSignal, tone: .secondary))
3350 }
3351 if let auctionSignal = pricing.auctionSignal {
3352 rows.append(InfoRowViewData(label: "Auction", value: auctionSignal, tone: .secondary))
3353 }
3354 } 3192 }
3355 if let reputation = snapshot.reputation { 3193 if let reputation = snapshot.reputation {
3356 let tone: ResultTone 3194 rows.append(reputationRow(reputation))
3357 switch reputation.status {
3358 case .clean: tone = .success
3359 case .listed: tone = .failure
3360 case .unknown: tone = .secondary
3361 }
3362 let value = reputation.status == .listed && !reputation.listedSources.isEmpty
3363 ? "\(reputation.status.title) (\(reputation.listedSources.joined(separator: ", ")))"
3364 : reputation.status.title
3365 rows.append(InfoRowViewData(label: "Reputation", value: value, tone: tone))
3366 } 3195 }
3367 if let certificateStatus = certificateBadgeLabel(from: snapshot) { 3196 if let certificateStatus = certificateBadgeLabel(from: snapshot) {
3368 rows.insert( 3197 rows.insert(
@@ -3377,6 +3206,39 @@ final class DomainViewModel {
3377 return rows 3206 return rows
3378 } 3207 }
3379 3208
3209 private static func pricingRows(_ pricing: DomainPricingInsight) -> [InfoRowViewData] {
3210 var rows = [InfoRowViewData(label: "External Price", value: pricing.estimatedPrice ?? "Unavailable", tone: .secondary)]
3211 if let premiumIndicator = pricing.premiumIndicator {
3212 rows.append(
3213 InfoRowViewData(
3214 label: "Premium",
3215 value: premiumIndicator ? "Yes" : "No",
3216 tone: premiumIndicator ? .warning : .secondary
3217 )
3218 )
3219 }
3220 if let resaleSignal = pricing.resaleSignal {
3221 rows.append(InfoRowViewData(label: "Resale", value: resaleSignal, tone: .secondary))
3222 }
3223 if let auctionSignal = pricing.auctionSignal {
3224 rows.append(InfoRowViewData(label: "Auction", value: auctionSignal, tone: .secondary))
3225 }
3226 return rows
3227 }
3228
3229 private static func reputationRow(_ reputation: DomainReputationResult) -> InfoRowViewData {
3230 let tone: ResultTone
3231 switch reputation.status {
3232 case .clean: tone = .success
3233 case .listed: tone = .failure
3234 case .unknown: tone = .secondary
3235 }
3236 let value = reputation.status == .listed && !reputation.listedSources.isEmpty
3237 ? "\(reputation.status.title) (\(reputation.listedSources.joined(separator: ", ")))"
3238 : reputation.status.title
3239 return InfoRowViewData(label: "Reputation", value: value, tone: tone)
3240 }
3241
3380 static func suggestionRows(from snapshot: LookupSnapshot) -> [DomainSuggestionViewData] { 3242 static func suggestionRows(from snapshot: LookupSnapshot) -> [DomainSuggestionViewData] {
3381 snapshot.suggestions.map { 3243 snapshot.suggestions.map {
3382 DomainSuggestionViewData( 3244 DomainSuggestionViewData(
@@ -3647,229 +3509,261 @@ final class DomainViewModel {
3647 lines.append("Tracking Note: \(note)") 3509 lines.append("Tracking Note: \(note)")
3648 } 3510 }
3649 3511
3650 func appendSection(_ title: String, body: () -> Void) { 3512 func appendSection(_ title: String, _ body: [String]) {
3651 lines.append("") 3513 lines.append("")
3652 lines.append(title) 3514 lines.append(title)
3653 lines.append(String(repeating: "-", count: title.count)) 3515 lines.append(String(repeating: "-", count: title.count))
3654 body() 3516 lines += body
3655 } 3517 }
3656 3518
3657 appendSection("Summary") { 3519 appendSection("Summary", exportSummaryLines(snapshot, changeSummary: changeSummary, exportDateFormatter: exportDateFormatter))
3658 for item in summaryFields(from: snapshot) { 3520 appendSection("Tracking", exportTrackingLines(trackedDomain, exportDateFormatter: exportDateFormatter))
3659 lines.append(" \(item.label): \(item.value)") 3521 appendSection("Diff Summary", exportDiffSummaryLines(diffSections))
3660 } 3522 appendSection("Domain", exportDomainLines(snapshot))
3661 if let changeSummary { 3523 appendSection("Ownership", exportOwnershipLines(snapshot))
3662 lines.append(" Change Summary: \(changeSummary.message)") 3524 appendSection("Subdomains", exportSubdomainsLines(snapshot))
3663 lines.append(" Severity: \(changeSummary.severity.title)") 3525 appendSection("DNS", exportDnsLines(snapshot))
3664 lines.append(" Changed Sections: \(changeSummary.changedSections.isEmpty ? "None" : changeSummary.changedSections.joined(separator: ", "))") 3526 appendSection("Web", exportWebLines(snapshot))
3665 lines.append(" Compared At: \(exportDateFormatter.string(from: changeSummary.generatedAt))") 3527 appendSection("Email", exportEmailLines(snapshot))
3666 } 3528 appendSection("Network", exportNetworkLines(snapshot))
3667 }
3668 3529
3669 appendSection("Tracking") { 3530 return lines.joined(separator: "\n")
3670 if let trackedDomain { 3531 }
3671 lines.append(" Pinned: \(trackedDomain.isPinned ? "Yes" : "No")") 3532
3672 lines.append(" Last Refresh: \(exportDateFormatter.string(from: trackedDomain.updatedAt))") 3533 private static func exportSummaryLines(
3673 lines.append(" Last Known Availability: \(availabilityLabel(trackedDomain.lastKnownAvailability))") 3534 _ snapshot: LookupSnapshot,
3674 if let note = trackedDomain.note?.nilIfEmpty { 3535 changeSummary: DomainChangeSummary?,
3675 lines.append(" Note: \(note)") 3536 exportDateFormatter: DateFormatter
3676 } 3537 ) -> [String] {
3677 } else { 3538 var lines: [String] = []
3678 lines.append(" This domain is not currently tracked.") 3539 for item in summaryFields(from: snapshot) {
3540 lines.append(" \(item.label): \(item.value)")
3541 }
3542 if let changeSummary {
3543 lines.append(" Change Summary: \(changeSummary.message)")
3544 lines.append(" Severity: \(changeSummary.severity.title)")
3545 lines.append(" Changed Sections: \(changeSummary.changedSections.isEmpty ? "None" : changeSummary.changedSections.joined(separator: ", "))")
3546 lines.append(" Compared At: \(exportDateFormatter.string(from: changeSummary.generatedAt))")
3547 }
3548 return lines
3549 }
3550
3551 private static func exportTrackingLines(_ trackedDomain: TrackedDomain?, exportDateFormatter: DateFormatter) -> [String] {
3552 var lines: [String] = []
3553 if let trackedDomain {
3554 lines.append(" Pinned: \(trackedDomain.isPinned ? "Yes" : "No")")
3555 lines.append(" Last Refresh: \(exportDateFormatter.string(from: trackedDomain.updatedAt))")
3556 lines.append(" Last Known Availability: \(availabilityLabel(trackedDomain.lastKnownAvailability))")
3557 if let note = trackedDomain.note?.nilIfEmpty {
3558 lines.append(" Note: \(note)")
3679 } 3559 }
3560 } else {
3561 lines.append(" This domain is not currently tracked.")
3680 } 3562 }
3563 return lines
3564 }
3681 3565
3682 appendSection("Diff Summary") { 3566 private static func exportDiffSummaryLines(_ diffSections: [DomainDiffSection]) -> [String] {
3683 if diffSections.isEmpty { 3567 var lines: [String] = []
3684 lines.append(" No comparison available") 3568 if diffSections.isEmpty {
3685 } else { 3569 lines.append(" No comparison available")
3686 for section in diffSections where section.items.contains(where: { $0.changeType != .unchanged }) { 3570 } else {
3687 lines.append(" \(section.title)") 3571 for section in diffSections where section.items.contains(where: { $0.changeType != .unchanged }) {
3688 for item in section.items where item.changeType != .unchanged { 3572 lines.append(" \(section.title)")
3689 lines.append(" [\(item.changeType.rawValue.capitalized)] \(item.label): \(item.oldValue ?? "None") -> \(item.newValue ?? "None")") 3573 for item in section.items where item.changeType != .unchanged {
3690 } 3574 lines.append(" [\(item.changeType.rawValue.capitalized)] \(item.label): \(item.oldValue ?? "None") -> \(item.newValue ?? "None")")
3691 } 3575 }
3692 } 3576 }
3693 } 3577 }
3578 return lines
3579 }
3694 3580
3695 appendSection("Domain") { 3581 private static func exportDomainLines(_ snapshot: LookupSnapshot) -> [String] {
3696 for row in domainRows(from: snapshot) { 3582 var lines: [String] = []
3697 lines.append(" \(row.label): \(row.value)") 3583 for row in domainRows(from: snapshot) {
3698 } 3584 lines.append(" \(row.label): \(row.value)")
3699 if snapshot.suggestions.isEmpty { 3585 }
3700 lines.append(" Suggestions: None") 3586 if snapshot.suggestions.isEmpty {
3701 } else { 3587 lines.append(" Suggestions: None")
3702 lines.append(" Suggestions:") 3588 } else {
3703 for suggestion in snapshot.suggestions { 3589 lines.append(" Suggestions:")
3704 lines.append(" \(suggestion.domain): \(availabilityLabel(suggestion.status))") 3590 for suggestion in snapshot.suggestions {
3705 } 3591 lines.append(" \(suggestion.domain): \(availabilityLabel(suggestion.status))")
3706 } 3592 }
3707 } 3593 }
3594 return lines
3595 }
3708 3596
3709 appendSection("Ownership") { 3597 private static func exportOwnershipLines(_ snapshot: LookupSnapshot) -> [String] {
3710 for row in ownershipRows(from: snapshot) { 3598 var lines: [String] = []
3711 lines.append(" \(row.label): \(row.value)") 3599 for row in ownershipRows(from: snapshot) {
3712 } 3600 lines.append(" \(row.label): \(row.value)")
3713 if let ownershipError = snapshot.ownershipError, snapshot.ownership == nil {
3714 lines.append(" Source: \(ownershipError)")
3715 }
3716 if !DataAccessService.hasAccess(to: .ownershipHistory) {
3717 lines.append(" Ownership history (coming soon)")
3718 }
3719 } 3601 }
3602 if let ownershipError = snapshot.ownershipError, snapshot.ownership == nil {
3603 lines.append(" Source: \(ownershipError)")
3604 }
3605 if !DataAccessService.hasAccess(to: .ownershipHistory) {
3606 lines.append(" Ownership history (coming soon)")
3607 }
3608 return lines
3609 }
3720 3610
3721 appendSection("Subdomains") { 3611 private static func exportSubdomainsLines(_ snapshot: LookupSnapshot) -> [String] {
3722 lines.append(" Count: \(snapshot.subdomains.count)") 3612 var lines: [String] = []
3723 if snapshot.subdomains.isEmpty { 3613 lines.append(" Count: \(snapshot.subdomains.count)")
3724 lines.append(" \(snapshot.subdomainsError ?? "No passive subdomains found")") 3614 if snapshot.subdomains.isEmpty {
3725 } else { 3615 lines.append(" \(snapshot.subdomainsError ?? "No passive subdomains found")")
3726 for subdomain in subdomainRows(from: snapshot) { 3616 } else {
3727 let marker = subdomain.isInteresting ? " [interesting]" : "" 3617 for subdomain in subdomainRows(from: snapshot) {
3728 lines.append(" \(subdomain.hostname)\(marker)") 3618 let marker = subdomain.isInteresting ? " [interesting]" : ""
3729 } 3619 lines.append(" \(subdomain.hostname)\(marker)")
3730 }
3731 if !DataAccessService.hasAccess(to: .extendedSubdomains) {
3732 lines.append(" Extended subdomain discovery (Pro+)")
3733 } 3620 }
3734 } 3621 }
3622 if !DataAccessService.hasAccess(to: .extendedSubdomains) {
3623 lines.append(" Extended subdomain discovery (Pro+)")
3624 }
3625 return lines
3626 }
3735 3627
3736 appendSection("DNS") { 3628 private static func exportDnsLines(_ snapshot: LookupSnapshot) -> [String] {
3737 if let dnsError = snapshot.dnsError { 3629 var lines: [String] = []
3738 lines.append(" Error: \(dnsError)") 3630 if let dnsError = snapshot.dnsError {
3739 } 3631 lines.append(" Error: \(dnsError)")
3740 if let dnssecLabel = dnssecLabel(from: snapshot) { 3632 }
3741 lines.append(" \(dnssecLabel)") 3633 if let dnssecLabel = dnssecLabel(from: snapshot) {
3742 } 3634 lines.append(" \(dnssecLabel)")
3743 for section in dnsRows(from: snapshot) { 3635 }
3744 lines.append(" \(section.title)") 3636 for section in dnsRows(from: snapshot) {
3745 if let message = section.message { 3637 lines += exportDNSSectionLines(section)
3746 lines.append(" \(message.isError ? "Error" : "Info"): \(message.text)")
3747 }
3748 for row in section.rows {
3749 lines.append(" \(row.value) (\(row.label))")
3750 }
3751 if let wildcardTitle = section.wildcardTitle {
3752 lines.append(" \(wildcardTitle)")
3753 for row in section.wildcardRows {
3754 lines.append(" \(row.value) (\(row.label))")
3755 }
3756 }
3757 }
3758 if let ptrRecord = snapshot.ptrRecord {
3759 lines.append(" PTR: \(ptrRecord)")
3760 } else if let ptrError = snapshot.ptrError {
3761 lines.append(" PTR Error: \(ptrError)")
3762 }
3763 } 3638 }
3639 if let ptrRecord = snapshot.ptrRecord {
3640 lines.append(" PTR: \(ptrRecord)")
3641 } else if let ptrError = snapshot.ptrError {
3642 lines.append(" PTR Error: \(ptrError)")
3643 }
3644 return lines
3645 }
3764 3646
3765 appendSection("Web") { 3647 private static func exportDNSSectionLines(_ section: DNSRecordSectionViewData) -> [String] {
3766 if let sslError = snapshot.sslError { 3648 var lines = [" \(section.title)"]
3767 lines.append(" TLS Error: \(sslError)") 3649 if let message = section.message {
3768 } else { 3650 lines.append(" \(message.isError ? "Error" : "Info"): \(message.text)")
3769 for row in webCertificateRows(from: snapshot) { 3651 }
3770 lines.append(" \(row.label): \(row.value)") 3652 for row in section.rows {
3771 } 3653 lines.append(" \(row.value) (\(row.label))")
3654 }
3655 if let wildcardTitle = section.wildcardTitle {
3656 lines.append(" \(wildcardTitle)")
3657 for row in section.wildcardRows {
3658 lines.append(" \(row.value) (\(row.label))")
3772 } 3659 }
3660 }
3661 return lines
3662 }
3773 3663
3774 if let httpHeadersError = snapshot.httpHeadersError { 3664 private static func exportResponseLines(_ snapshot: LookupSnapshot) -> [String] {
3775 lines.append(" Headers Error: \(httpHeadersError)") 3665 if let httpHeadersError = snapshot.httpHeadersError {
3776 } else { 3666 return [" Headers Error: \(httpHeadersError)"]
3777 for row in webResponseRows(from: snapshot) { 3667 }
3778 lines.append(" \(row.label): \(row.value)") 3668 var lines = webResponseRows(from: snapshot).map { " \($0.label): \($0.value)" }
3779 } 3669 if snapshot.httpHeaders.isEmpty {
3780 if snapshot.httpHeaders.isEmpty { 3670 lines.append(" Headers: No headers returned")
3781 lines.append(" Headers: No headers returned") 3671 } else {
3782 } else { 3672 lines.append(" Headers:")
3783 lines.append(" Headers:") 3673 for header in snapshot.httpHeaders {
3784 for header in snapshot.httpHeaders { 3674 lines.append(" \(header.name): \(header.value)")
3785 lines.append(" \(header.name): \(header.value)")
3786 }
3787 }
3788 } 3675 }
3676 }
3677 return lines
3678 }
3789 3679
3790 if let redirectChainError = snapshot.redirectChainError { 3680 private static func exportWebLines(_ snapshot: LookupSnapshot) -> [String] {
3791 lines.append(" Redirect Error: \(redirectChainError)") 3681 var lines: [String] = []
3792 } else if snapshot.redirectChain.isEmpty { 3682 if let sslError = snapshot.sslError {
3793 lines.append(" Redirects: No redirect data available") 3683 lines.append(" TLS Error: \(sslError)")
3794 } else { 3684 } else {
3795 lines.append(" Redirects:") 3685 for row in webCertificateRows(from: snapshot) {
3796 for hop in redirectRows(from: snapshot) { 3686 lines.append(" \(row.label): \(row.value)")
3797 lines.append(" \(hop.stepLabel). \(hop.statusCode) \(hop.url)\(hop.isFinal ? " (final)" : "")")
3798 }
3799 } 3687 }
3800 } 3688 }
3689 lines += exportResponseLines(snapshot)
3801 3690
3802 appendSection("Email") { 3691 if let redirectChainError = snapshot.redirectChainError {
3803 if let emailSecurityError = snapshot.emailSecurityError { 3692 lines.append(" Redirect Error: \(redirectChainError)")
3804 lines.append(" Error: \(emailSecurityError)") 3693 } else if snapshot.redirectChain.isEmpty {
3805 } else if emailRows(from: snapshot).isEmpty { 3694 lines.append(" Redirects: No redirect data available")
3806 lines.append(" No email security records found") 3695 } else {
3807 } else { 3696 lines.append(" Redirects:")
3808 for row in emailRows(from: snapshot) { 3697 for hop in redirectRows(from: snapshot) {
3809 lines.append(" \(row.label): \(row.status)") 3698 lines.append(" \(hop.stepLabel). \(hop.statusCode) \(hop.url)\(hop.isFinal ? " (final)" : "")")
3810 lines.append(" \(row.detail)")
3811 if let auxiliaryDetail = row.auxiliaryDetail {
3812 lines.append(" \(auxiliaryDetail)")
3813 }
3814 }
3815 } 3699 }
3816 } 3700 }
3701 return lines
3702 }
3817 3703
3818 appendSection("Network") { 3704 private static func exportEmailLines(_ snapshot: LookupSnapshot) -> [String] {
3819 if let reachabilityError = snapshot.reachabilityError { 3705 var lines: [String] = []
3820 lines.append(" Reachability Error: \(reachabilityError)") 3706 if let emailSecurityError = snapshot.emailSecurityError {
3821 } else if reachabilityRows(from: snapshot).isEmpty { 3707 lines.append(" Error: \(emailSecurityError)")
3822 lines.append(" Reachability: No results") 3708 } else if emailRows(from: snapshot).isEmpty {
3823 } else { 3709 lines.append(" No email security records found")
3824 lines.append(" Reachability:") 3710 } else {
3825 for row in reachabilityRows(from: snapshot) { 3711 for row in emailRows(from: snapshot) {
3826 lines.append(" \(row.portLabel): \(row.statusLabel) \(row.latencyLabel)") 3712 lines.append(" \(row.label): \(row.status)")
3713 lines.append(" \(row.detail)")
3714 if let auxiliaryDetail = row.auxiliaryDetail {
3715 lines.append(" \(auxiliaryDetail)")
3827 } 3716 }
3828 } 3717 }
3718 }
3719 return lines
3720 }
3829 3721
3830 if let ipGeolocationError = snapshot.ipGeolocationError, snapshot.ipGeolocation == nil { 3722 private static func exportPortLines(_ rows: [PortScanRowViewData]) -> [String] {
3831 lines.append(" Location Error: \(ipGeolocationError)") 3723 guard !rows.isEmpty else { return [" No results"] }
3832 } else if locationRows(from: snapshot).isEmpty { 3724 var lines: [String] = []
3833 lines.append(" Location: No data") 3725 for row in rows {
3834 } else { 3726 lines.append(" \(row.portLabel) \(row.service): \(row.statusLabel)\(row.durationLabel.map { " \($0)" } ?? "")")
3835 lines.append(" Location:") 3727 if let banner = row.banner {
3836 for row in locationRows(from: snapshot) { 3728 lines.append(" Banner: \(banner)")
3837 lines.append(" \(row.label): \(row.value)")
3838 }
3839 } 3729 }
3730 }
3731 return lines
3732 }
3840 3733
3841 if let portScanError = snapshot.portScanError, snapshot.portScanResults.isEmpty { 3734 private static func exportNetworkLines(_ snapshot: LookupSnapshot) -> [String] {
3842 lines.append(" Port Scan Error: \(portScanError)") 3735 var lines: [String] = []
3736 if let reachabilityError = snapshot.reachabilityError {
3737 lines.append(" Reachability Error: \(reachabilityError)")
3738 } else if reachabilityRows(from: snapshot).isEmpty {
3739 lines.append(" Reachability: No results")
3740 } else {
3741 lines.append(" Reachability:")
3742 for row in reachabilityRows(from: snapshot) {
3743 lines.append(" \(row.portLabel): \(row.statusLabel) \(row.latencyLabel)")
3843 } 3744 }
3745 }
3844 3746
3845 lines.append(" Standard Ports:") 3747 if let ipGeolocationError = snapshot.ipGeolocationError, snapshot.ipGeolocation == nil {
3846 let standardRows = portRows(from: snapshot, kind: .standard) 3748 lines.append(" Location Error: \(ipGeolocationError)")
3847 if standardRows.isEmpty { 3749 } else if locationRows(from: snapshot).isEmpty {
3848 lines.append(" No results") 3750 lines.append(" Location: No data")
3849 } else { 3751 } else {
3850 for row in standardRows { 3752 lines.append(" Location:")
3851 lines.append(" \(row.portLabel) \(row.service): \(row.statusLabel)\(row.durationLabel.map { " \($0)" } ?? "")") 3753 for row in locationRows(from: snapshot) {
3852 if let banner = row.banner { 3754 lines.append(" \(row.label): \(row.value)")
3853 lines.append(" Banner: \(banner)")
3854 }
3855 }
3856 } 3755 }
3756 }
3857 3757
3858 lines.append(" Custom Ports:") 3758 if let portScanError = snapshot.portScanError, snapshot.portScanResults.isEmpty {
3859 let customRows = portRows(from: snapshot, kind: .custom) 3759 lines.append(" Port Scan Error: \(portScanError)")
3860 if customRows.isEmpty {
3861 lines.append(" No results")
3862 } else {
3863 for row in customRows {
3864 lines.append(" \(row.portLabel) \(row.service): \(row.statusLabel)\(row.durationLabel.map { " \($0)" } ?? "")")
3865 if let banner = row.banner {
3866 lines.append(" Banner: \(banner)")
3867 }
3868 }
3869 }
3870 } 3760 }
3871 3761
3872 return lines.joined(separator: "\n") 3762 lines.append(" Standard Ports:")
3763 lines += exportPortLines(portRows(from: snapshot, kind: .standard))
3764 lines.append(" Custom Ports:")
3765 lines += exportPortLines(portRows(from: snapshot, kind: .custom))
3766 return lines
3873 } 3767 }
3874 3768
3875 private static func primaryIPAddress(from snapshot: LookupSnapshot) -> String? { 3769 private static func primaryIPAddress(from snapshot: LookupSnapshot) -> String? {
DomainDig/PortScanService.swift +26
@@ -74,6 +74,32 @@ struct PortScanService {
74 .pipe { $0.isEmpty ? .empty("No custom port scan results") : .success($0) } 74 .pipe { $0.isEmpty ? .empty("No custom port scan results") : .success($0) }
75 } 75 }
76 76
77 /// `results` with each open port's banner, grabbed concurrently.
78 static func withBanners(_ results: [PortScanResult], host: String) async -> [PortScanResult] {
79 let banners = await withTaskGroup(of: (UInt16, String?).self, returning: [UInt16: String].self) { group in
80 for result in results where result.open {
81 group.addTask {
82 let banner = await grabBanner(host: host, port: result.port)
83 return (result.port, banner)
84 }
85 }
86
87 var collected: [UInt16: String] = [:]
88 for await (port, banner) in group {
89 if let banner {
90 collected[port] = banner
91 }
92 }
93 return collected
94 }
95
96 return results.map { result in
97 var updated = result
98 updated.banner = banners[result.port]
99 return updated
100 }
101 }
102
77 static func grabBanner(host: String, port: UInt16, timeout: TimeInterval = 3.0) async -> String? { 103 static func grabBanner(host: String, port: UInt16, timeout: TimeInterval = 3.0) async -> String? {
78 await withCheckedContinuation { continuation in 104 await withCheckedContinuation { continuation in
79 guard let nwPort = NWEndpoint.Port(rawValue: port) else { 105 guard let nwPort = NWEndpoint.Port(rawValue: port) else {
DomainDig/SSLCheckService.swift +42 −43
@@ -228,24 +228,15 @@ private enum DERCertificateParser {
228 while pos < end { 228 while pos < end {
229 // Each SET in the issuer 229 // Each SET in the issuer
230 guard let setTL = readTagAndLength(bytes, offset: pos) else { break } 230 guard let setTL = readTagAndLength(bytes, offset: pos) else { break }
231 let setEnd = setTL.contentStart + setTL.length 231 pos = setTL.contentStart + setTL.length
232 232
233 // Inside the SET is a SEQUENCE with OID + value 233 // Inside the SET is a SEQUENCE with OID + value
234 if let seqTL = readTagAndLength(bytes, offset: setTL.contentStart) { 234 guard let seqTL = readTagAndLength(bytes, offset: setTL.contentStart),
235 let seqEnd = seqTL.contentStart + seqTL.length 235 let oidTL = readTagAndLength(bytes, offset: seqTL.contentStart),
236 if let oidTL = readTagAndLength(bytes, offset: seqTL.contentStart) { 236 content(of: oidTL, in: bytes).elementsEqual(cnOID),
237 let oidBytes = Array(bytes[oidTL.contentStart..<oidTL.contentStart + oidTL.length]) 237 let valueTL = readTagAndLength(bytes, offset: oidTL.contentStart + oidTL.length)
238 if oidBytes == cnOID { 238 else { continue }
239 let valueStart = oidTL.contentStart + oidTL.length 239 return String(bytes: content(of: valueTL, in: bytes), encoding: .utf8)
240 if let valueTL = readTagAndLength(bytes, offset: valueStart) {
241 let strBytes = bytes[valueTL.contentStart..<valueTL.contentStart + valueTL.length]
242 return String(bytes: strBytes, encoding: .utf8)
243 }
244 }
245 _ = seqEnd // suppress unused warning
246 }
247 }
248 pos = setEnd
249 } 240 }
250 return nil 241 return nil
251 } 242 }
@@ -260,39 +251,41 @@ private enum DERCertificateParser {
260 let extEnd = extSeq.contentStart + extSeq.length 251 let extEnd = extSeq.contentStart + extSeq.length
261 252
262 // Each extension is SEQUENCE { OID, [critical], value } 253 // Each extension is SEQUENCE { OID, [critical], value }
263 if let oidTL = readTagAndLength(bytes, offset: extSeq.contentStart) { 254 if let oidTL = readTagAndLength(bytes, offset: extSeq.contentStart), content(of: oidTL, in: bytes).elementsEqual(sanOID) {
264 let oidBytes = Array(bytes[oidTL.contentStart..<oidTL.contentStart + oidTL.length]) 255 sans += sanDNSNames(bytes, valueStart: oidTL.contentStart + oidTL.length, extensionEnd: extEnd)
265 if oidBytes == sanOID {
266 var valuePos = oidTL.contentStart + oidTL.length
267 // Skip optional critical BOOLEAN
268 if valuePos < extEnd, bytes[valuePos] == 0x01,
269 let boolTL = readTagAndLength(bytes, offset: valuePos) {
270 valuePos = boolTL.contentStart + boolTL.length
271 }
272 // The value is an OCTET STRING wrapping a SEQUENCE of GeneralNames
273 if let octetTL = readTagAndLength(bytes, offset: valuePos),
274 let sanSeq = readTagAndLength(bytes, offset: octetTL.contentStart) {
275 let sanEnd = sanSeq.contentStart + sanSeq.length
276 var sanPos = sanSeq.contentStart
277 while sanPos < sanEnd {
278 guard let nameTL = readTagAndLength(bytes, offset: sanPos) else { break }
279 // Context tag [2] = dNSName (IA5String)
280 if (bytes[sanPos] & 0x1F) == 2 {
281 let nameBytes = bytes[nameTL.contentStart..<nameTL.contentStart + nameTL.length]
282 if let name = String(bytes: nameBytes, encoding: .ascii) {
283 sans.append(name)
284 }
285 }
286 sanPos = nameTL.contentStart + nameTL.length
287 }
288 }
289 }
290 } 256 }
291 pos = extEnd 257 pos = extEnd
292 } 258 }
293 return sans 259 return sans
294 } 260 }
295 261
262 /// The dNSName entries of a subjectAltName extension whose value starts at `valueStart`.
263 private static func sanDNSNames(_ bytes: [UInt8], valueStart: Int, extensionEnd: Int) -> [String] {
264 var valuePos = valueStart
265 // Skip optional critical BOOLEAN
266 if valuePos < extensionEnd, bytes[valuePos] == 0x01,
267 let boolTL = readTagAndLength(bytes, offset: valuePos) {
268 valuePos = boolTL.contentStart + boolTL.length
269 }
270 // The value is an OCTET STRING wrapping a SEQUENCE of GeneralNames
271 guard let octetTL = readTagAndLength(bytes, offset: valuePos),
272 let sanSeq = readTagAndLength(bytes, offset: octetTL.contentStart)
273 else { return [] }
274
275 let sanEnd = sanSeq.contentStart + sanSeq.length
276 var sanPos = sanSeq.contentStart
277 var names: [String] = []
278 while sanPos < sanEnd {
279 guard let nameTL = readTagAndLength(bytes, offset: sanPos) else { break }
280 // Context tag [2] = dNSName (IA5String)
281 if (bytes[sanPos] & 0x1F) == 2, let name = String(bytes: content(of: nameTL, in: bytes), encoding: .ascii) {
282 names.append(name)
283 }
284 sanPos = nameTL.contentStart + nameTL.length
285 }
286 return names
287 }
288
296 private static func extractValidity(_ bytes: [UInt8], sequenceStart: Int, length: Int) -> (Date?, Date?) { 289 private static func extractValidity(_ bytes: [UInt8], sequenceStart: Int, length: Int) -> (Date?, Date?) {
297 let end = sequenceStart + length 290 let end = sequenceStart + length
298 var position = sequenceStart 291 var position = sequenceStart
@@ -362,8 +355,14 @@ private enum DERCertificateParser {
362 length = len 355 length = len
363 } 356 }
364 357
358 // A length past the end of the data is malformed, and slicing to it would trap.
359 guard length <= bytes.count - pos else { return nil }
365 return TLV(contentStart: pos, length: length) 360 return TLV(contentStart: pos, length: length)
366 } 361 }
362
363 private static func content(of tlv: TLV, in bytes: [UInt8]) -> ArraySlice<UInt8> {
364 bytes[tlv.contentStart..<tlv.contentStart + tlv.length]
365 }
367} 366}
368 367
369enum SSLError: LocalizedError { 368enum SSLError: LocalizedError {
DomainInspectionService.swift +1 −26
@@ -678,7 +678,7 @@ struct DomainInspectionService {
678 private func mapPortScanResult(_ result: ServiceResult<[PortScanResult]>, domain: String) async -> (value: [PortScanResult], message: String?) { 678 private func mapPortScanResult(_ result: ServiceResult<[PortScanResult]>, domain: String) async -> (value: [PortScanResult], message: String?) {
679 switch result { 679 switch result {
680 case let .success(results): 680 case let .success(results):
681 return (await enrichOpenPortBanners(in: results, domain: domain), nil) 681 return (await PortScanService.withBanners(results, host: domain), nil)
682 case let .empty(message), let .error(message): 682 case let .empty(message), let .error(message):
683 return ([], message) 683 return ([], message)
684 } 684 }
@@ -716,29 +716,4 @@ struct DomainInspectionService {
716 ) 716 )
717 } 717 }
718 } 718 }
719
720 private func enrichOpenPortBanners(in results: [PortScanResult], domain: String) async -> [PortScanResult] {
721 let banners = await withTaskGroup(of: (UInt16, String?).self, returning: [UInt16: String].self) { group in
722 for result in results where result.open {
723 group.addTask {
724 let banner = await PortScanService.grabBanner(host: domain, port: result.port)
725 return (result.port, banner)
726 }
727 }
728
729 var collected: [UInt16: String] = [:]
730 for await (port, banner) in group {
731 if let banner {
732 collected[port] = banner
733 }
734 }
735 return collected
736 }
737
738 return results.map { result in
739 var updated = result
740 updated.banner = banners[result.port]
741 return updated
742 }
743 }
744} 719}
DomainReportBuilder.swift +47 −42
@@ -521,7 +521,8 @@ enum DomainIntelligenceService {
521 } 521 }
522 522
523 private static func inferProvider(from snapshot: LookupSnapshot) -> InferredProviderFingerprint? { 523 private static func inferProvider(from snapshot: LookupSnapshot) -> InferredProviderFingerprint? {
524 let headerMap = Dictionary(uniqueKeysWithValues: snapshot.httpHeaders.map { ($0.name.lowercased(), $0.value.lowercased()) }) 524 // A stored or imported snapshot can repeat a header name in another case.
525 let headerMap = Dictionary(snapshot.httpHeaders.map { ($0.name.lowercased(), $0.value.lowercased()) }) { first, _ in first }
525 let dnsProviders = dnsValues(for: .NS, in: snapshot.dnsSections) + dnsValues(for: .CNAME, in: snapshot.dnsSections) 526 let dnsProviders = dnsValues(for: .NS, in: snapshot.dnsSections) + dnsValues(for: .CNAME, in: snapshot.dnsSections)
526 let issuer = snapshot.sslInfo?.issuer.lowercased() ?? "" 527 let issuer = snapshot.sslInfo?.issuer.lowercased() ?? ""
527 let org = snapshot.ipGeolocation?.org?.lowercased() ?? "" 528 let org = snapshot.ipGeolocation?.org?.lowercased() ?? ""
@@ -626,59 +627,63 @@ enum DomainIntelligenceService {
626 } 627 }
627 628
628 private static func buildSubdomainHistory(from snapshots: [LookupSnapshot]) -> [SubdomainHistoryEntry] { 629 private static func buildSubdomainHistory(from snapshots: [LookupSnapshot]) -> [SubdomainHistoryEntry] {
629 struct WorkingState { 630 var states: [String: SubdomainPresence] = [:]
630 var firstSeen: Date
631 var lastSeen: Date
632 var recurrenceCount: Int
633 var statusChangeCount: Int
634 var lastSeenInPreviousSnapshot: Bool
635 }
636
637 var states: [String: WorkingState] = [:]
638 for snapshot in snapshots { 631 for snapshot in snapshots {
639 let currentHosts = Set((snapshot.subdomains + snapshot.extendedSubdomains).map { $0.hostname.lowercased() }) 632 let currentHosts = Set((snapshot.subdomains + snapshot.extendedSubdomains).map { $0.hostname.lowercased() })
640 let knownHosts = Set(states.keys).union(currentHosts) 633 let knownHosts = Set(states.keys).union(currentHosts)
641 for host in knownHosts { 634 for host in knownHosts {
642 let isPresent = currentHosts.contains(host) 635 let isPresent = currentHosts.contains(host)
643 if var state = states[host] { 636 if states[host] != nil {
644 if isPresent { 637 states[host]?.observe(isPresent: isPresent, at: snapshot.timestamp)
645 state.lastSeen = snapshot.timestamp
646 state.recurrenceCount += 1
647 }
648 if state.lastSeenInPreviousSnapshot != isPresent {
649 state.statusChangeCount += 1
650 }
651 state.lastSeenInPreviousSnapshot = isPresent
652 states[host] = state
653 } else if isPresent { 638 } else if isPresent {
654 states[host] = WorkingState( 639 states[host] = SubdomainPresence(firstSeen: snapshot.timestamp)
655 firstSeen: snapshot.timestamp,
656 lastSeen: snapshot.timestamp,
657 recurrenceCount: 1,
658 statusChangeCount: 0,
659 lastSeenInPreviousSnapshot: true
660 )
661 } 640 }
662 } 641 }
663 } 642 }
664 643
665 return states.map { host, state in 644 return states.map { host, state in state.entry(hostname: host) }
666 let isEphemeral = state.recurrenceCount <= 2 || state.statusChangeCount >= 2 645 .sorted { lhs, rhs in
667 return SubdomainHistoryEntry( 646 if lhs.isEphemeral != rhs.isEphemeral {
668 hostname: host, 647 return lhs.isEphemeral && !rhs.isEphemeral
669 firstSeen: state.firstSeen, 648 }
670 lastSeen: state.lastSeen, 649 return lhs.hostname < rhs.hostname
671 recurrenceCount: state.recurrenceCount, 650 }
672 statusChangeCount: state.statusChangeCount, 651 }
673 lastKnownStatus: state.lastSeenInPreviousSnapshot ? "Active" : "Inactive", 652
674 isEphemeral: isEphemeral 653 /// One subdomain's presence across a run of snapshots, from the first that saw it.
675 ) 654 private struct SubdomainPresence {
655 var firstSeen: Date
656 var lastSeen: Date
657 var recurrenceCount = 1
658 var statusChangeCount = 0
659 var lastSeenInPreviousSnapshot = true
660
661 init(firstSeen: Date) {
662 self.firstSeen = firstSeen
663 lastSeen = firstSeen
676 } 664 }
677 .sorted { lhs, rhs in 665
678 if lhs.isEphemeral != rhs.isEphemeral { 666 mutating func observe(isPresent: Bool, at timestamp: Date) {
679 return lhs.isEphemeral && !rhs.isEphemeral 667 if isPresent {
668 lastSeen = timestamp
669 recurrenceCount += 1
680 } 670 }
681 return lhs.hostname < rhs.hostname 671 if lastSeenInPreviousSnapshot != isPresent {
672 statusChangeCount += 1
673 }
674 lastSeenInPreviousSnapshot = isPresent
675 }
676
677 func entry(hostname: String) -> SubdomainHistoryEntry {
678 SubdomainHistoryEntry(
679 hostname: hostname,
680 firstSeen: firstSeen,
681 lastSeen: lastSeen,
682 recurrenceCount: recurrenceCount,
683 statusChangeCount: statusChangeCount,
684 lastKnownStatus: lastSeenInPreviousSnapshot ? "Active" : "Inactive",
685 isEphemeral: recurrenceCount <= 2 || statusChangeCount >= 2
686 )
682 } 687 }
683 } 688 }
684 689
DomainReportExporter.swift +266 −250
@@ -156,6 +156,25 @@ enum DomainReportExporter {
156 } 156 }
157 157
158 static func text(for report: DomainReport) -> String { 158 static func text(for report: DomainReport) -> String {
159 var lines = headerLines(report)
160 appendSection("Summary", to: &lines) { summarySection(report) }
161 appendSection("Risk", to: &lines) { riskSection(report) }
162 appendSection("Insights", to: &lines) { insightsSection(report) }
163 appendSection("Ownership", to: &lines) { ownershipSection(report) }
164 appendSection("Ownership History", to: &lines) { ownershipHistorySection(report) }
165 appendSection("DNS", to: &lines) { dnsSection(report) }
166 appendSection("DNS History", to: &lines) { dnsHistorySection(report) }
167 appendSection("Web", to: &lines) { webSection(report) }
168 appendSection("Email", to: &lines) { emailSection(report) }
169 appendSection("Network", to: &lines) { networkSection(report) }
170 appendSection("Subdomains", to: &lines) { subdomainsSection(report) }
171 appendSection("Pricing", to: &lines) { pricingSection(report) }
172 appendSection("Changes", to: &lines) { changesSection(report) }
173 return lines.joined(separator: "\n")
174 }
175
176 /// The report's title block: what was looked up, when, how, and with what caveats.
177 private static func headerLines(_ report: DomainReport) -> [String] {
159 var lines = [ 178 var lines = [
160 "DomainDig Report", 179 "DomainDig Report",
161 "Domain: \(report.domain)", 180 "Domain: \(report.domain)",
@@ -183,288 +202,285 @@ enum DomainReportExporter {
183 if let workflowContext = report.workflowContext { 202 if let workflowContext = report.workflowContext {
184 lines.append("Workflow Context: \(workflowContext.workflowName ?? workflowContext.source)") 203 lines.append("Workflow Context: \(workflowContext.workflowName ?? workflowContext.source)")
185 } 204 }
205 return lines
206 }
186 207
187 appendSection("Summary", to: &lines) { 208 private static func summarySection(_ report: DomainReport) -> [String] {
188 [ 209 [
189 "Primary IP: \(report.dns.primaryIP ?? "Unavailable")", 210 "Primary IP: \(report.dns.primaryIP ?? "Unavailable")",
190 "Risk Score: \(report.riskAssessment.score) (\(report.riskAssessment.level.title))", 211 "Risk Score: \(report.riskAssessment.score) (\(report.riskAssessment.level.title))",
191 "TLS Status: \(report.web.tlsStatus)", 212 "TLS Status: \(report.web.tlsStatus)",
192 "HTTP: \(httpSummary(for: report))", 213 "HTTP: \(httpSummary(for: report))",
193 "Email: \(report.email.summary)", 214 "Email: \(report.email.summary)",
194 "Subdomains: \(report.subdomains.count)", 215 "Subdomains: \(report.subdomains.count)",
195 "Extended Subdomains: \(report.extendedSubdomains.count)", 216 "Extended Subdomains: \(report.extendedSubdomains.count)",
196 "External Price: \(report.domainPricing?.estimatedPrice ?? "Unavailable")", 217 "External Price: \(report.domainPricing?.estimatedPrice ?? "Unavailable")",
197 "Reputation: \(report.reputation?.status.title ?? "Unavailable")" 218 "Reputation: \(report.reputation?.status.title ?? "Unavailable")"
198 ] 219 ]
199 } 220 }
200 221
201 appendSection("Risk", to: &lines) { 222 private static func riskSection(_ report: DomainReport) -> [String] {
202 var values = [ 223 var values = [
203 "Score: \(report.riskAssessment.score)", 224 "Score: \(report.riskAssessment.score)",
204 "Level: \(report.riskAssessment.level.title)" 225 "Level: \(report.riskAssessment.level.title)"
205 ] 226 ]
206 if report.riskAssessment.factors.isEmpty { 227 if report.riskAssessment.factors.isEmpty {
207 values.append("Factors: None") 228 values.append("Factors: None")
208 } else { 229 } else {
209 values.append("Factors:") 230 values.append("Factors:")
210 for factor in report.riskAssessment.factors { 231 for factor in report.riskAssessment.factors {
211 values.append(" [\(factor.impact.rawValue)] \(factor.description)") 232 values.append(" [\(factor.impact.rawValue)] \(factor.description)")
212 }
213 } 233 }
214 return values
215 } 234 }
235 return values
236 }
216 237
217 appendSection("Insights", to: &lines) { 238 private static func insightsSection(_ report: DomainReport) -> [String] {
218 report.insights.isEmpty ? ["No deterministic insights triggered"] : report.insights.map { "- \($0)" } 239 report.insights.isEmpty ? ["No deterministic insights triggered"] : report.insights.map { "- \($0)" }
219 } 240 }
220 241
221 appendSection("Ownership", to: &lines) { 242 private static func ownershipSection(_ report: DomainReport) -> [String] {
222 var ownershipLines = [ 243 var ownershipLines = [
223 "Registrar: \(report.ownership?.registrar ?? "Unavailable")", 244 "Registrar: \(report.ownership?.registrar ?? "Unavailable")",
224 "Confidence: \(report.ownershipConfidence?.title ?? "N/A")", 245 "Confidence: \(report.ownershipConfidence?.title ?? "N/A")",
225 "Created: \(ownershipDateLabel(report.ownership?.createdDate))", 246 "Created: \(ownershipDateLabel(report.ownership?.createdDate))",
226 "Expires: \(ownershipDateLabel(report.ownership?.expirationDate))", 247 "Expires: \(ownershipDateLabel(report.ownership?.expirationDate))",
227 "Registrant: \(report.ownership?.registrant ?? "Unavailable")", 248 "Registrant: \(report.ownership?.registrant ?? "Unavailable")",
228 "Nameservers: \(joined(report.ownership?.nameservers) ?? "Unavailable")", 249 "Nameservers: \(joined(report.ownership?.nameservers) ?? "Unavailable")",
229 "Status: \(joined(report.ownership?.status) ?? "Unavailable")", 250 "Status: \(joined(report.ownership?.status) ?? "Unavailable")",
230 "Abuse Contact: \(report.ownership?.abuseEmail ?? "Unavailable")" 251 "Abuse Contact: \(report.ownership?.abuseEmail ?? "Unavailable")"
231 ] 252 ]
232 if let provenance = report.sectionProvenance[.ownership] { 253 if let provenance = report.sectionProvenance[.ownership] {
233 ownershipLines.append("Provenance: \(provenanceLabel(provenance))") 254 ownershipLines.append("Provenance: \(provenanceLabel(provenance))")
234 }
235 if let error = report.dns.error, report.ownership == nil {
236 ownershipLines.append("Error: \(error)")
237 } else if let error = report.changeSummary?.message, report.ownership == nil, report.ownership == nil {
238 _ = error
239 }
240 return ownershipLines
241 } 255 }
256 if let error = report.dns.error, report.ownership == nil {
257 ownershipLines.append("Error: \(error)")
258 }
259 return ownershipLines
260 }
242 261
243 appendSection("Ownership History", to: &lines) { 262 private static func ownershipHistorySection(_ report: DomainReport) -> [String] {
244 guard !report.ownershipHistory.isEmpty else { 263 guard !report.ownershipHistory.isEmpty else {
245 return ["No ownership history available"] 264 return ["No ownership history available"]
246 }
247
248 return report.ownershipHistory.map { event in
249 [
250 textDateFormatter.string(from: event.date),
251 event.summary,
252 "source=\(event.source)"
253 ].joined(separator: " | ")
254 }
255 } 265 }
256 266
257 appendSection("DNS", to: &lines) { 267 return report.ownershipHistory.map { event in
258 var dnsLines = [ 268 [
259 "Lookup Duration: \(durationLabel(report.dns.lookupDurationMs))", 269 textDateFormatter.string(from: event.date),
260 "Primary IP: \(report.dns.primaryIP ?? "Unavailable")", 270 event.summary,
261 "PTR: \(report.dns.ptrRecord ?? report.dns.ptrError ?? "Unavailable")", 271 "source=\(event.source)"
262 "DNSSEC: \(dnssecLabel(report.dns.dnssecSigned))", 272 ].joined(separator: " | ")
263 "Patterns: \(report.dns.patternSummary.patterns.joined(separator: " | ").nilIfEmpty ?? "None")"
264 ]
265 if let provenance = report.sectionProvenance[.dns] {
266 dnsLines.append("Provenance: \(provenanceLabel(provenance))")
267 }
268 if let error = report.dns.error {
269 dnsLines.append("Error: \(error)")
270 }
271 if report.dns.recordSections.isEmpty {
272 dnsLines.append("Records: None")
273 } else {
274 dnsLines.append("Records:")
275 for section in report.dns.recordSections {
276 var seen: Set<String> = []
277 let values = (section.records + section.wildcardRecords)
278 .map(\.value)
279 .filter { seen.insert($0).inserted }
280 let renderedValues = values.isEmpty ? "None" : values.joined(separator: " | ")
281 dnsLines.append(" \(section.recordType.rawValue): \(renderedValues)")
282 }
283 }
284 return dnsLines
285 } 273 }
274 }
286 275
287 appendSection("DNS History", to: &lines) { 276 private static func dnsSection(_ report: DomainReport) -> [String] {
288 guard !report.dnsHistory.isEmpty else { 277 var dnsLines = [
289 return ["No DNS history available"] 278 "Lookup Duration: \(durationLabel(report.dns.lookupDurationMs))",
290 } 279 "Primary IP: \(report.dns.primaryIP ?? "Unavailable")",
280 "PTR: \(report.dns.ptrRecord ?? report.dns.ptrError ?? "Unavailable")",
281 "DNSSEC: \(dnssecLabel(report.dns.dnssecSigned))",
282 "Patterns: \(report.dns.patternSummary.patterns.joined(separator: " | ").nilIfEmpty ?? "None")"
283 ]
284 if let provenance = report.sectionProvenance[.dns] {
285 dnsLines.append("Provenance: \(provenanceLabel(provenance))")
286 }
287 if let error = report.dns.error {
288 dnsLines.append("Error: \(error)")
289 }
290 if report.dns.recordSections.isEmpty {
291 dnsLines.append("Records: None")
292 } else {
293 dnsLines.append("Records:")
294 for section in report.dns.recordSections {
295 var seen: Set<String> = []
296 let values = (section.records + section.wildcardRecords)
297 .map(\.value)
298 .filter { seen.insert($0).inserted }
299 let renderedValues = values.isEmpty ? "None" : values.joined(separator: " | ")
300 dnsLines.append(" \(section.recordType.rawValue): \(renderedValues)")
301 }
302 }
303 return dnsLines
304 }
291 305
292 return report.dnsHistory.map { event in 306 private static func dnsHistorySection(_ report: DomainReport) -> [String] {
293 [ 307 guard !report.dnsHistory.isEmpty else {
294 textDateFormatter.string(from: event.date), 308 return ["No DNS history available"]
295 event.summary,
296 "A=\(event.aRecords.joined(separator: " | ").nilIfEmpty ?? "-")",
297 "NS=\(event.nameservers.joined(separator: " | ").nilIfEmpty ?? "-")",
298 "source=\(event.source)"
299 ].joined(separator: " | ")
300 }
301 } 309 }
302 310
303 appendSection("Web", to: &lines) { 311 return report.dnsHistory.map { event in
304 var webLines = [ 312 [
305 "TLS Status: \(report.web.tlsStatus)", 313 textDateFormatter.string(from: event.date),
306 "TLS Grade: \(report.web.tlsGrade.rawValue)", 314 event.summary,
307 "TLS Highlights: \(report.web.tlsHighlights.joined(separator: " | "))", 315 "A=\(event.aRecords.joined(separator: " | ").nilIfEmpty ?? "-")",
308 "Certificate Warning: \(report.web.certificateWarningLevel.title)", 316 "NS=\(event.nameservers.joined(separator: " | ").nilIfEmpty ?? "-")",
309 "Security Grade: \(report.web.securityGrade ?? "Unavailable")", 317 "source=\(event.source)"
310 "HTTP Status: \(report.web.statusCode.map(String.init) ?? "Unavailable")", 318 ].joined(separator: " | ")
311 "Protocol: \(report.web.httpProtocol ?? "Unavailable")",
312 "HTTP/3 Advertised: \(report.web.http3Advertised ? "Yes" : "No")",
313 "Final URL: \(report.web.finalURL ?? "Unavailable")",
314 "HSTS Preloaded: \(booleanLabel(report.web.hstsPreloaded))",
315 "Header Count: \(report.web.headerCount)"
316 ]
317 if let provenance = report.sectionProvenance[.ssl] {
318 webLines.append("TLS Provenance: \(provenanceLabel(provenance))")
319 }
320 if let provenance = report.sectionProvenance[.httpHeaders] {
321 webLines.append("HTTP Provenance: \(provenanceLabel(provenance))")
322 }
323 if let provenance = report.sectionProvenance[.redirectChain] {
324 webLines.append("Redirect Provenance: \(provenanceLabel(provenance))")
325 }
326 if let tlsError = report.web.tlsError {
327 webLines.append("TLS Error: \(tlsError)")
328 }
329 if let headersError = report.web.headersError {
330 webLines.append("Headers Error: \(headersError)")
331 }
332 if let redirectError = report.web.redirectError {
333 webLines.append("Redirect Error: \(redirectError)")
334 }
335 if !report.web.headers.isEmpty {
336 webLines.append("Headers:")
337 for header in report.web.headers {
338 webLines.append(" \(header.name): \(header.value)")
339 }
340 }
341 if !report.web.redirectChain.isEmpty {
342 webLines.append("Redirect Chain:")
343 for hop in report.web.redirectChain {
344 webLines.append(" \(hop.stepNumber). \(hop.statusCode) \(hop.url)\(hop.isFinal ? " (final)" : "")")
345 }
346 }
347 return webLines
348 } 319 }
320 }
349 321
350 appendSection("Email", to: &lines) { 322 private static func webSection(_ report: DomainReport) -> [String] {
351 var emailLines = [report.email.summary] 323 var webLines = [
352 if let grade = report.email.grade { 324 "TLS Status: \(report.web.tlsStatus)",
353 emailLines.append("Grade: \(grade.rawValue)") 325 "TLS Grade: \(report.web.tlsGrade.rawValue)",
354 } 326 "TLS Highlights: \(report.web.tlsHighlights.joined(separator: " | "))",
355 if !report.email.reasons.isEmpty { 327 "Certificate Warning: \(report.web.certificateWarningLevel.title)",
356 emailLines.append("Why: \(report.email.reasons.joined(separator: " | "))") 328 "Security Grade: \(report.web.securityGrade ?? "Unavailable")",
357 } 329 "HTTP Status: \(report.web.statusCode.map(String.init) ?? "Unavailable")",
358 emailLines.append("Confidence: \(report.emailConfidence?.title ?? "N/A")") 330 "Protocol: \(report.web.httpProtocol ?? "Unavailable")",
359 if let provenance = report.sectionProvenance[.emailSecurity] { 331 "HTTP/3 Advertised: \(report.web.http3Advertised ? "Yes" : "No")",
360 emailLines.append("Provenance: \(provenanceLabel(provenance))") 332 "Final URL: \(report.web.finalURL ?? "Unavailable")",
361 } 333 "HSTS Preloaded: \(booleanLabel(report.web.hstsPreloaded))",
362 if let records = report.email.records { 334 "Header Count: \(report.web.headerCount)"
363 emailLines.append("SPF: \(recordLabel(records.spf))") 335 ]
364 emailLines.append("DMARC: \(recordLabel(records.dmarc))") 336 if let provenance = report.sectionProvenance[.ssl] {
365 emailLines.append("DKIM: \(recordLabel(records.dkim))") 337 webLines.append("TLS Provenance: \(provenanceLabel(provenance))")
366 emailLines.append("BIMI: \(recordLabel(records.bimi))") 338 }
367 emailLines.append("MTA-STS: \(records.mtaSts?.txtFound == true ? records.mtaSts?.policyMode ?? "found" : "Unavailable")") 339 if let provenance = report.sectionProvenance[.httpHeaders] {
340 webLines.append("HTTP Provenance: \(provenanceLabel(provenance))")
341 }
342 if let provenance = report.sectionProvenance[.redirectChain] {
343 webLines.append("Redirect Provenance: \(provenanceLabel(provenance))")
344 }
345 if let tlsError = report.web.tlsError {
346 webLines.append("TLS Error: \(tlsError)")
347 }
348 if let headersError = report.web.headersError {
349 webLines.append("Headers Error: \(headersError)")
350 }
351 if let redirectError = report.web.redirectError {
352 webLines.append("Redirect Error: \(redirectError)")
353 }
354 if !report.web.headers.isEmpty {
355 webLines.append("Headers:")
356 for header in report.web.headers {
357 webLines.append(" \(header.name): \(header.value)")
368 } 358 }
369 if let error = report.email.error { 359 }
370 emailLines.append("Error: \(error)") 360 if !report.web.redirectChain.isEmpty {
361 webLines.append("Redirect Chain:")
362 for hop in report.web.redirectChain {
363 webLines.append(" \(hop.stepNumber). \(hop.statusCode) \(hop.url)\(hop.isFinal ? " (final)" : "")")
371 } 364 }
372 return emailLines
373 } 365 }
366 return webLines
367 }
374 368
375 appendSection("Network", to: &lines) { 369 private static func emailSection(_ report: DomainReport) -> [String] {
376 var networkLines = [ 370 var emailLines = [report.email.summary]
377 "Reachability: \(report.network.reachabilitySummary)", 371 if let grade = report.email.grade {
378 "Geolocation: \(report.network.geolocationSummary)", 372 emailLines.append("Grade: \(grade.rawValue)")
379 "Geolocation Confidence: \(report.geolocationConfidence?.title ?? "N/A")", 373 }
380 "Open Ports: \(report.network.openPorts.map(String.init).joined(separator: ", ").nilIfEmpty ?? "None")" 374 if !report.email.reasons.isEmpty {
381 ] 375 emailLines.append("Why: \(report.email.reasons.joined(separator: " | "))")
382 if let provenance = report.sectionProvenance[.ipGeolocation] { 376 }
383 networkLines.append("Geolocation Provenance: \(provenanceLabel(provenance))") 377 emailLines.append("Confidence: \(report.emailConfidence?.title ?? "N/A")")
384 } 378 if let provenance = report.sectionProvenance[.emailSecurity] {
385 if let error = report.network.reachabilityError { 379 emailLines.append("Provenance: \(provenanceLabel(provenance))")
386 networkLines.append("Reachability Error: \(error)")
387 }
388 if let error = report.network.geolocationError {
389 networkLines.append("Geolocation Error: \(error)")
390 }
391 if let error = report.network.portScanError {
392 networkLines.append("Port Scan Error: \(error)")
393 }
394 if !report.network.portScan.isEmpty {
395 networkLines.append("Port Scan:")
396 for result in report.network.portScan {
397 networkLines.append(
398 " \(result.port) \(result.service): \(result.open ? "open" : "closed")\(result.banner.map { " banner=\($0)" } ?? "")"
399 )
400 }
401 }
402 return networkLines
403 } 380 }
381 if let records = report.email.records {
382 emailLines.append("SPF: \(recordLabel(records.spf))")
383 emailLines.append("DMARC: \(recordLabel(records.dmarc))")
384 emailLines.append("DKIM: \(recordLabel(records.dkim))")
385 emailLines.append("BIMI: \(recordLabel(records.bimi))")
386 emailLines.append("MTA-STS: \(records.mtaSts?.txtFound == true ? records.mtaSts?.policyMode ?? "found" : "Unavailable")")
387 }
388 if let error = report.email.error {
389 emailLines.append("Error: \(error)")
390 }
391 return emailLines
392 }
404 393
405 appendSection("Subdomains", to: &lines) { 394 private static func networkSection(_ report: DomainReport) -> [String] {
406 var values = ["Confidence: \(report.subdomainConfidence?.title ?? "N/A")"] 395 var networkLines = [
407 if let provenance = report.sectionProvenance[.subdomains] { 396 "Reachability: \(report.network.reachabilitySummary)",
408 values.append("Provenance: \(provenanceLabel(provenance))") 397 "Geolocation: \(report.network.geolocationSummary)",
409 } 398 "Geolocation Confidence: \(report.geolocationConfidence?.title ?? "N/A")",
410 if report.subdomains.isEmpty { 399 "Open Ports: \(report.network.openPorts.map(String.init).joined(separator: ", ").nilIfEmpty ?? "None")"
411 values.append("None") 400 ]
412 return values 401 if let provenance = report.sectionProvenance[.ipGeolocation] {
413 } 402 networkLines.append("Geolocation Provenance: \(provenanceLabel(provenance))")
414 if !report.subdomainGroups.isEmpty { 403 }
415 values.append("Groups: \(report.subdomainGroups.map { "\($0.label): \($0.subdomains.count)" }.joined(separator: " | "))") 404 if let error = report.network.reachabilityError {
416 } 405 networkLines.append("Reachability Error: \(error)")
417 values.append(contentsOf: report.subdomains.map { "- \($0)" }) 406 }
418 if !report.extendedSubdomains.isEmpty { 407 if let error = report.network.geolocationError {
419 values.append("Extended:") 408 networkLines.append("Geolocation Error: \(error)")
420 values.append(contentsOf: report.extendedSubdomains.map { "- \($0)" }) 409 }
410 if let error = report.network.portScanError {
411 networkLines.append("Port Scan Error: \(error)")
412 }
413 if !report.network.portScan.isEmpty {
414 networkLines.append("Port Scan:")
415 for result in report.network.portScan {
416 networkLines.append(
417 " \(result.port) \(result.service): \(result.open ? "open" : "closed")\(result.banner.map { " banner=\($0)" } ?? "")"
418 )
421 } 419 }
422 return values
423 } 420 }
421 return networkLines
422 }
424 423
425 appendSection("Pricing", to: &lines) { 424 private static func subdomainsSection(_ report: DomainReport) -> [String] {
426 guard let pricing = report.domainPricing else { 425 var values = ["Confidence: \(report.subdomainConfidence?.title ?? "N/A")"]
427 return ["External pricing unavailable"] 426 if let provenance = report.sectionProvenance[.subdomains] {
428 } 427 values.append("Provenance: \(provenanceLabel(provenance))")
428 }
429 if report.subdomains.isEmpty {
430 values.append("None")
431 return values
432 }
433 if !report.subdomainGroups.isEmpty {
434 values.append("Groups: \(report.subdomainGroups.map { "\($0.label): \($0.subdomains.count)" }.joined(separator: " | "))")
435 }
436 values.append(contentsOf: report.subdomains.map { "- \($0)" })
437 if !report.extendedSubdomains.isEmpty {
438 values.append("Extended:")
439 values.append(contentsOf: report.extendedSubdomains.map { "- \($0)" })
440 }
441 return values
442 }
429 443
430 return [ 444 private static func pricingSection(_ report: DomainReport) -> [String] {
431 "Estimated Price: \(pricing.estimatedPrice ?? "Unavailable")", 445 guard let pricing = report.domainPricing else {
432 "Premium: \(pricing.premiumIndicator == true ? "Yes" : "No")", 446 return ["External pricing unavailable"]
433 "Resale: \(pricing.resaleSignal ?? "Unavailable")",
434 "Auction: \(pricing.auctionSignal ?? "Unavailable")",
435 "Source: \(pricing.source)",
436 "Collected: \(textDateFormatter.string(from: pricing.collectedAt))"
437 ]
438 } 447 }
439 448
440 appendSection("Changes", to: &lines) { 449 return [
441 guard let changeSummary = report.changeSummary else { 450 "Estimated Price: \(pricing.estimatedPrice ?? "Unavailable")",
442 return ["No comparison available"] 451 "Premium: \(pricing.premiumIndicator == true ? "Yes" : "No")",
443 } 452 "Resale: \(pricing.resaleSignal ?? "Unavailable")",
453 "Auction: \(pricing.auctionSignal ?? "Unavailable")",
454 "Source: \(pricing.source)",
455 "Collected: \(textDateFormatter.string(from: pricing.collectedAt))"
456 ]
457 }
444 458
445 var values = [ 459 private static func changesSection(_ report: DomainReport) -> [String] {
446 "Has Changes: \(changeSummary.hasChanges ? "Yes" : "No")", 460 guard let changeSummary = report.changeSummary else {
447 "Severity: \(changeSummary.severity.title)", 461 return ["No comparison available"]
448 "Impact: \(changeSummary.impactClassification.title)",
449 "Inferred Summary: \(changeSummary.message)",
450 "Changed Sections: \(changeSummary.changedSections.isEmpty ? "None" : changeSummary.changedSections.joined(separator: ", "))"
451 ]
452 if let riskScoreDelta = changeSummary.riskScoreDelta {
453 values.append("Risk Delta: \(riskScoreDelta >= 0 ? "+" : "")\(riskScoreDelta)")
454 }
455 if !changeSummary.insights.isEmpty {
456 values.append("Insights: \(changeSummary.insights.joined(separator: " | "))")
457 }
458 if !changeSummary.observedFacts.isEmpty {
459 values.append("Observed: \(changeSummary.observedFacts.joined(separator: " | "))")
460 }
461 if let contextNote = changeSummary.contextNote {
462 values.append("Context: \(contextNote)")
463 }
464 return values
465 } 462 }
466 463
467 return lines.joined(separator: "\n") 464 var values = [
465 "Has Changes: \(changeSummary.hasChanges ? "Yes" : "No")",
466 "Severity: \(changeSummary.severity.title)",
467 "Impact: \(changeSummary.impactClassification.title)",
468 "Inferred Summary: \(changeSummary.message)",
469 "Changed Sections: \(changeSummary.changedSections.isEmpty ? "None" : changeSummary.changedSections.joined(separator: ", "))"
470 ]
471 if let riskScoreDelta = changeSummary.riskScoreDelta {
472 values.append("Risk Delta: \(riskScoreDelta >= 0 ? "+" : "")\(riskScoreDelta)")
473 }
474 if !changeSummary.insights.isEmpty {
475 values.append("Insights: \(changeSummary.insights.joined(separator: " | "))")
476 }
477 if !changeSummary.observedFacts.isEmpty {
478 values.append("Observed: \(changeSummary.observedFacts.joined(separator: " | "))")
479 }
480 if let contextNote = changeSummary.contextNote {
481 values.append("Context: \(contextNote)")
482 }
483 return values
468 } 484 }
469 485
470 static func batchText(for reports: [DomainReport], title: String) -> String { 486 static func batchText(for reports: [DomainReport], title: String) -> String {
LookupSnapshot.swift +119
@@ -163,3 +163,122 @@ extension HistoryEntry {
163 ) 163 )
164 } 164 }
165} 165}
166
167extension LookupSnapshot {
168 /// Whether every section that failed did so for want of a connection (a
169 /// network error, a timeout, a rate limit) and nothing worth showing came
170 /// back, so the last snapshot should stand in for this one.
171 var needsFallback: Bool {
172 let candidateMessages = [
173 dnsError,
174 httpHeadersError,
175 sslError,
176 ownershipError,
177 subdomainsError,
178 redirectChainError,
179 ipGeolocationError
180 ]
181 .compactMap { $0?.lowercased() }
182
183 guard !candidateMessages.isEmpty else { return false }
184 let connectivityFailure = candidateMessages.allSatisfy { message in
185 message.hasPrefix("network error:")
186 || message.hasPrefix("timeout:")
187 || message.hasPrefix("rate limit:")
188 }
189
190 let hasMaterialData = !dnsSections.isEmpty
191 || !httpHeaders.isEmpty
192 || sslInfo != nil
193 || ownership != nil
194 || !subdomains.isEmpty
195
196 return connectivityFailure && !hasMaterialData
197 }
198
199 /// `previous`, marked as the last known result, when this lookup
200 /// ``needsFallback``; otherwise this lookup.
201 func resolvedAfterFallback(to previous: LookupSnapshot?) -> LookupSnapshot {
202 guard needsFallback, let previous else {
203 return self
204 }
205
206 return LookupSnapshot(
207 historyEntryID: previous.historyEntryID,
208 domain: previous.domain,
209 timestamp: previous.timestamp,
210 trackedDomainID: previous.trackedDomainID,
211 note: previous.note,
212 appVersion: previous.appVersion,
213 resolverDisplayName: previous.resolverDisplayName,
214 resolverURLString: previous.resolverURLString,
215 dataSources: previous.dataSources,
216 provenanceBySection: previous.provenanceBySection,
217 availabilityConfidence: previous.availabilityConfidence,
218 ownershipConfidence: previous.ownershipConfidence,
219 subdomainConfidence: previous.subdomainConfidence,
220 emailSecurityConfidence: previous.emailSecurityConfidence,
221 geolocationConfidence: previous.geolocationConfidence,
222 errorDetails: previous.errorDetails,
223 isPartialSnapshot: previous.isPartialSnapshot,
224 validationIssues: previous.validationIssues,
225 totalLookupDurationMs: previous.totalLookupDurationMs,
226 snapshotIndex: previous.snapshotIndex,
227 previousSnapshotID: previous.previousSnapshotID,
228 changeCount: previous.changeCount,
229 severitySummary: previous.severitySummary,
230 dnsSections: previous.dnsSections,
231 dnsError: previous.dnsError,
232 availabilityResult: previous.availabilityResult,
233 suggestions: previous.suggestions,
234 sslInfo: previous.sslInfo,
235 sslError: previous.sslError,
236 hstsPreloaded: previous.hstsPreloaded,
237 httpHeaders: previous.httpHeaders,
238 httpSecurityGrade: previous.httpSecurityGrade,
239 httpStatusCode: previous.httpStatusCode,
240 httpResponseTimeMs: previous.httpResponseTimeMs,
241 httpProtocol: previous.httpProtocol,
242 http3Advertised: previous.http3Advertised,
243 httpHeadersError: previous.httpHeadersError,
244 reachabilityResults: previous.reachabilityResults,
245 reachabilityError: previous.reachabilityError,
246 ipGeolocation: previous.ipGeolocation,
247 ipGeolocationError: previous.ipGeolocationError,
248 emailSecurity: previous.emailSecurity,
249 emailSecurityError: previous.emailSecurityError,
250 ownership: previous.ownership,
251 ownershipError: previous.ownershipError,
252 ownershipHistory: previous.ownershipHistory,
253 ownershipHistoryError: previous.ownershipHistoryError,
254 inferredProvider: previous.inferredProvider,
255 priorProviders: previous.priorProviders,
256 domainClassification: previous.domainClassification,
257 ownershipTransitions: previous.ownershipTransitions,
258 hostingTransitions: previous.hostingTransitions,
259 subdomainHistory: previous.subdomainHistory,
260 riskSignals: previous.riskSignals,
261 intelligenceTimeline: previous.intelligenceTimeline,
262 ptrRecord: previous.ptrRecord,
263 ptrError: previous.ptrError,
264 redirectChain: previous.redirectChain,
265 redirectChainError: previous.redirectChainError,
266 subdomains: previous.subdomains,
267 subdomainsError: previous.subdomainsError,
268 extendedSubdomains: previous.extendedSubdomains,
269 extendedSubdomainsError: previous.extendedSubdomainsError,
270 dnsHistory: previous.dnsHistory,
271 dnsHistoryError: previous.dnsHistoryError,
272 domainPricing: previous.domainPricing,
273 domainPricingError: previous.domainPricingError,
274 reputation: previous.reputation,
275 reputationError: previous.reputationError,
276 portScanResults: previous.portScanResults,
277 portScanError: previous.portScanError,
278 changeSummary: previous.changeSummary,
279 resultSource: .snapshot,
280 cachedSections: [],
281 statusMessage: "Last known result • \(previous.timestamp.formatted(date: .abbreviated, time: .shortened))"
282 )
283 }
284}