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 {
305305 }
306306
307307 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 }
309310 }
310311
311312 private nonisolated static func csvLine(_ values: [String]) -> String {
@@ -903,76 +904,54 @@ enum DomainDataPortabilityService {
903904 if backup.schemaVersion > DomainDigBackup.currentSchemaVersion {
904905 throw DataPortabilityError.unsupportedSchema(backup.schemaVersion)
905906 }
906 let report = DataValidationService.validate(backup: backup)
907 if !report.errors.isEmpty {
908 throw DataPortabilityError.validationFailed(report.errors)
909 }
910 return .backup(backup, report)
907 return .backup(backup, try passing(DataValidationService.validate(backup: backup)))
911908 }
912
913909 if let backup = try? decodeLegacyBackup(from: data) {
914 let report = DataValidationService.validate(backup: backup)
915 if !report.errors.isEmpty {
916 throw DataPortabilityError.validationFailed(report.errors)
917 }
918 return .backup(backup, report)
910 return .backup(backup, try passing(DataValidationService.validate(backup: backup)))
919911 }
920
921912 if let export = try? decoder.decode(TrackedDomainsExport.self, from: data) {
922 let report = DataValidationService.validate(trackedDomains: export.trackedDomains)
923 if !report.errors.isEmpty {
924 throw DataPortabilityError.validationFailed(report.errors)
925 }
926 return .trackedDomains(export.trackedDomains, report)
913 return try trackedDomainsPayload(export.trackedDomains)
927914 }
928
929915 if let export = try? decoder.decode(WorkflowsExport.self, from: data) {
930 let report = DataValidationService.validate(workflows: export.workflows)
931 if !report.errors.isEmpty {
932 throw DataPortabilityError.validationFailed(report.errors)
933 }
934 return .workflows(export.workflows, report)
916 return try workflowsPayload(export.workflows)
935917 }
936
937918 if let trackedDomains = try? decoder.decode([TrackedDomain].self, from: data) {
938 let report = DataValidationService.validate(trackedDomains: trackedDomains)
939 if !report.errors.isEmpty {
940 throw DataPortabilityError.validationFailed(report.errors)
941 }
942 return .trackedDomains(trackedDomains, report)
919 return try trackedDomainsPayload(trackedDomains)
943920 }
944
945921 if let workflows = try? decoder.decode([DomainWorkflow].self, from: data) {
946 let report = DataValidationService.validate(workflows: workflows)
947 if !report.errors.isEmpty {
948 throw DataPortabilityError.validationFailed(report.errors)
949 }
950 return .workflows(workflows, report)
922 return try workflowsPayload(workflows)
951923 }
924 if fileName.lowercased().hasSuffix(".csv") {
925 return try decodeCSVPayload(from: data, fileName: fileName)
926 }
927 throw DataPortabilityError.unsupportedFormat
928 }
952929
953 let lowercasedFileName = fileName.lowercased()
954 if lowercasedFileName.hasSuffix(".csv") {
955 guard let string = String(data: data, encoding: .utf8) else {
956 throw DataPortabilityError.unreadableFile
957 }
958 if lowercasedFileName.contains("workflow") {
959 let workflows = try 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)
930 /// A CSV holds workflows when its name says so, and tracked domains otherwise.
931 private static func decodeCSVPayload(from data: Data, fileName: String) throws -> ImportPayload {
932 guard let string = String(data: data, encoding: .utf8) else {
933 throw DataPortabilityError.unreadableFile
934 }
935 if fileName.lowercased().contains("workflow") {
936 return try workflowsPayload(DataPortabilityCSV.parseWorkflows(from: string))
973937 }
938 return try trackedDomainsPayload(DataPortabilityCSV.parseTrackedDomains(from: string))
939 }
974940
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
976955 }
977956
978957 private static func decodeLegacyBackup(from data: Data) throws -> DomainDigBackup {
DomainDig/DiffService.swift +3 −2
@@ -329,8 +329,9 @@ enum DiffService {
329329 }
330330
331331 private static func dnsSection(from oldReport: DomainReport, to newReport: DomainReport) -> DiffSection {
332 let oldSections = Dictionary(uniqueKeysWithValues: oldReport.dns.recordSections.map { ($0.recordType, $0) })
333 let newSections = Dictionary(uniqueKeysWithValues: newReport.dns.recordSections.map { ($0.recordType, $0) })
332 // Imported reports are not guaranteed one section per record type.
333 let oldSections = Dictionary(oldReport.dns.recordSections.map { ($0.recordType, $0) }) { first, _ in first }
334 let newSections = Dictionary(newReport.dns.recordSections.map { ($0.recordType, $0) }) { first, _ in first }
334335 let recordTypes = Set(oldSections.keys).union(newSections.keys).sorted { $0.rawValue < $1.rawValue }
335336
336337 var items: [DiffItem] = [
DomainDig/DomainDig/AuditExporter.swift +54 −68
@@ -48,7 +48,21 @@ enum AuditExporter {
4848 lines.append("")
4949 }
5050
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"]
5266 if session.findings.isEmpty {
5367 lines.append("No findings recorded.")
5468 } else {
@@ -57,8 +71,11 @@ enum AuditExporter {
5771 }
5872 }
5973 lines.append("")
74 return lines
75 }
6076
61 lines.append("## Key Risks")
77 private static func keyRiskLines(_ session: AuditSession) -> [String] {
78 var lines = ["## Key Risks"]
6279 if session.keyRisks.isEmpty {
6380 lines.append("No medium or high-severity risks recorded.")
6481 } else {
@@ -67,46 +84,46 @@ enum AuditExporter {
6784 }
6885 }
6986 lines.append("")
87 return lines
88 }
7089
71 lines.append("## Checklist")
72 for item in session.checklist {
73 lines.append("- [\(item.isComplete ? "x" : " ")] \(item.title): \(item.detail)")
74 }
75 lines.append("")
76
77 lines.append("## Findings")
90 private static func findingLines(_ session: AuditSession) -> [String] {
91 var lines = ["## Findings"]
7892 if session.findings.isEmpty {
7993 lines.append("No findings recorded.")
80 } else {
81 for finding in session.findings {
82 lines.append("### \(finding.title)")
83 lines.append("- Severity: \(finding.severity.title)")
84 lines.append("- Status: \(finding.status.title)")
85 if !finding.checklistAreas.isEmpty {
86 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("")
94 }
95 for finding in session.findings {
96 lines.append("### \(finding.title)")
97 lines.append("- Severity: \(finding.severity.title)")
98 lines.append("- Status: \(finding.status.title)")
99 if !finding.checklistAreas.isEmpty {
100 lines.append("- Checklist Areas: \(finding.checklistAreas.map(\.title).joined(separator: ", "))")
96101 }
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("")
97110 }
111 return lines
112 }
98113
99 lines.append("## Evidence Snapshot")
100 lines.append("- Availability: \(availabilityTitle(session.evidence.report.availability))")
101 lines.append("- Risk Score: \(session.evidence.report.riskAssessment.score) (\(session.evidence.report.riskAssessment.level.title))")
102 lines.append("- TLS Status: \(session.evidence.report.web.tlsStatus)")
103 lines.append("- Final URL: \(session.evidence.report.web.finalURL ?? "Unavailable")")
104 lines.append("- Primary IP: \(session.evidence.report.dns.primaryIP ?? "Unavailable")")
105 lines.append("- Reachability: \(session.evidence.report.network.reachabilitySummary)")
106 lines.append("- Ownership: \(session.evidence.report.ownership?.registrar ?? "Unavailable")")
107 lines.append("- Historical Context Snapshots: \(session.evidence.historicalContext.count)")
108
109 return lines.joined(separator: "\n")
114 private static func evidenceLines(_ evidence: AuditEvidenceSnapshot) -> [String] {
115 let report = evidence.report
116 return [
117 "## Evidence Snapshot",
118 "- Availability: \(availabilityTitle(report.availability))",
119 "- Risk Score: \(report.riskAssessment.score) (\(report.riskAssessment.level.title))",
120 "- TLS Status: \(report.web.tlsStatus)",
121 "- Final URL: \(report.web.finalURL ?? "Unavailable")",
122 "- Primary IP: \(report.dns.primaryIP ?? "Unavailable")",
123 "- Reachability: \(report.network.reachabilitySummary)",
124 "- Ownership: \(report.ownership?.registrar ?? "Unavailable")",
125 "- Historical Context Snapshots: \(evidence.historicalContext.count)",
126 ]
110127 }
111128
112129 private static func availabilityTitle(_ status: DomainAvailabilityStatus) -> String {
@@ -121,37 +138,6 @@ enum AuditExporter {
121138 }
122139
123140 private static func pdfData(for session: AuditSession) throws -> Data {
124 let markdown = 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
141 DomainReportExporter.pdfData(fromMarkdown: markdown(for: session))
156142 }
157143}
DomainDig/DomainInsightEngine.swift +117 −104
@@ -176,158 +176,171 @@ enum DomainInsightEngine {
176176 tlsAssessment: TLSSummaryAssessment,
177177 subdomainGroups: [SubdomainGroup]
178178 ) -> 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 {
179213 var score = 18
180214 var factors: [RiskFactor] = []
181215
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) {
182223 switch snapshot.availabilityResult?.status ?? .unknown {
183224 case .available:
184 score -= 12
185 factors.append(.init(description: "Domain appears available rather than actively deployed", impact: .positive))
225 tally.add(-12, "Domain appears available rather than actively deployed", .positive)
186226 case .unknown:
187 score += 8
188 factors.append(.init(description: "Ownership and availability could not be confirmed", impact: .negative))
227 tally.add(8, "Ownership and availability could not be confirmed", .negative)
189228 case .registered:
190229 if !snapshot.dnsSections.isEmpty || snapshot.sslInfo != nil || !snapshot.redirectChain.isEmpty {
191 score += 6
192 factors.append(.init(description: "Registered domain exposes active infrastructure", impact: .negative))
230 tally.add(6, "Registered domain exposes active infrastructure", .negative)
193231 } 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)
195233 }
196234 }
235 }
197236
237 private static func scoreDNS(_ snapshot: LookupSnapshot, patterns: DNSPatternSummary, into tally: inout RiskTally) {
198238 let recordTypes = snapshot.dnsSections.filter { !$0.records.isEmpty || !$0.wildcardRecords.isEmpty }.count
199239 if recordTypes >= 5 {
200 score += 8
201 factors.append(.init(description: "DNS configuration is broad across multiple record types", impact: .negative))
240 tally.add(8, "DNS configuration is broad across multiple record types", .negative)
202241 }
203 if dnsPatterns.wildcardDetected {
204 score += 12
205 factors.append(.init(description: "Wildcard DNS is enabled", impact: .negative))
242 if patterns.wildcardDetected {
243 tally.add(12, "Wildcard DNS is enabled", .negative)
206244 }
207 if let firstPattern = dnsPatterns.patterns.first {
208 factors.append(.init(description: firstPattern, impact: .neutral))
245 if let firstPattern = patterns.patterns.first {
246 tally.add(0, firstPattern, .neutral)
209247 }
248 }
210249
211 switch tlsAssessment.grade {
250 private static func scoreTLS(_ snapshot: LookupSnapshot, assessment: TLSSummaryAssessment, into tally: inout RiskTally) {
251 switch assessment.grade {
212252 case .a:
213 score -= 8
214 factors.append(.init(description: "TLS configuration looks current and stable", impact: .positive))
253 tally.add(-8, "TLS configuration looks current and stable", .positive)
215254 case .b:
216 score -= 3
217 factors.append(.init(description: "TLS is valid with minor concerns", impact: .positive))
255 tally.add(-3, "TLS is valid with minor concerns", .positive)
218256 case .c:
219 score += 10
220 factors.append(.init(description: "TLS configuration has visible weaknesses", impact: .negative))
257 tally.add(10, "TLS configuration has visible weaknesses", .negative)
221258 case .f:
222 score += 22
223 factors.append(.init(description: "TLS is missing, invalid, or near failure", impact: .negative))
259 tally.add(22, "TLS is missing, invalid, or near failure", .negative)
224260 }
225
226261 if let daysUntilExpiry = snapshot.sslInfo?.daysUntilExpiry, daysUntilExpiry <= 14 {
227 score += 10
228 factors.append(.init(description: "Certificate expires within 14 days", impact: .negative))
262 tally.add(10, "Certificate expires within 14 days", .negative)
229263 }
264 }
230265
266 private static func scoreRedirects(_ snapshot: LookupSnapshot, into tally: inout RiskTally) {
231267 if snapshot.redirectChain.count >= 3 {
232 score += 8
233 factors.append(.init(description: "Redirect chain is longer than expected", impact: .negative))
268 tally.add(8, "Redirect chain is longer than expected", .negative)
234269 }
235
236270 if redirectLooksSensitive(snapshot.redirectChain.last?.url) {
237 score += 6
238 factors.append(.init(description: "Redirect target looks like an auth or account gateway", impact: .negative))
239 }
240
241 if let emailAssessment {
242 switch emailAssessment.grade {
243 case .a:
244 score -= 10
245 factors.append(.init(description: "Email protections are strong and aligned", impact: .positive))
246 case .b:
247 score -= 4
248 factors.append(.init(description: "Email protections are present with minor gaps", impact: .positive))
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))
271 tally.add(6, "Redirect target looks like an auth or account gateway", .negative)
272 }
273 }
274
275 private static func scoreEmail(
276 _ snapshot: LookupSnapshot,
277 assessment: EmailSecurityAssessment?,
278 into tally: inout RiskTally
279 ) {
280 guard let assessment else {
281 if hasMXRecords(snapshot) {
282 tally.add(14, "Mail is configured without enough email security evidence", .negative)
255283 }
256 } else if hasMXRecords(snapshot) {
257 score += 14
258 factors.append(.init(description: "Mail is configured without enough email security evidence", impact: .negative))
284 return
259285 }
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 }
260297
298 private static func scorePorts(_ snapshot: LookupSnapshot, into tally: inout RiskTally) {
261299 let openPorts = snapshot.portScanResults.filter(\.open).map(\.port)
262300 let sensitivePorts: Set<UInt16> = [21, 22, 23, 25, 3389, 5900]
263301 let exposedSensitivePorts = openPorts.filter { sensitivePorts.contains($0) }
264302 if !exposedSensitivePorts.isEmpty {
265 score += min(18, exposedSensitivePorts.count * 6)
266 factors.append(.init(description: "Sensitive management or mail ports are exposed", impact: .negative))
303 tally.add(min(18, exposedSensitivePorts.count * 6), "Sensitive management or mail ports are exposed", .negative)
267304 } 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)
269306 } else if openPorts.count >= 3 {
270 score += 8
271 factors.append(.init(description: "Multiple open services expand the attack surface", impact: .negative))
307 tally.add(8, "Multiple open services expand the attack surface", .negative)
272308 }
309 }
273310
274 if !subdomainGroups.isEmpty {
275 let labels = Set(subdomainGroups.map(\.label))
276 if labels.contains("dev") || labels.contains("staging") {
277 score += 8
278 factors.append(.init(description: "Development or staging subdomains are discoverable", impact: .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 }
311 private static func scoreSubdomains(_ snapshot: LookupSnapshot, groups: [SubdomainGroup], into tally: inout RiskTally) {
312 guard !groups.isEmpty else { return }
313 let labels = Set(groups.map(\.label))
314 if labels.contains("dev") || labels.contains("staging") {
315 tally.add(8, "Development or staging subdomains are discoverable", .negative)
288316 }
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 }
289324
325 private static func scoreGeolocation(_ snapshot: LookupSnapshot, into tally: inout RiskTally) {
290326 if snapshot.ipGeolocation == nil,
291327 snapshot.availabilityResult?.status == .registered,
292328 snapshot.dnsSections.contains(where: { $0.recordType == .A && !$0.records.isEmpty }) {
293 score += 4
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 }
329 tally.add(4, "Active host could not be geolocated", .neutral)
317330 }
331 }
318332
319 let clampedScore = min(max(score, 0), 100)
320 let level: RiskLevel
321 switch clampedScore {
322 case 0..<35:
323 level = .low
324 case 35..<65:
325 level = .medium
326 default:
327 level = .high
333 private static func scoreReputation(_ snapshot: LookupSnapshot, into tally: inout RiskTally) {
334 guard let reputation = snapshot.reputation else { return }
335 switch reputation.status {
336 case .listed:
337 let sourceList = reputation.listedSources.isEmpty ? "" : " (\(reputation.listedSources.joined(separator: ", ")))"
338 tally.add(25, "Domain is flagged by a configured reputation source\(sourceList)", .negative)
339 case .clean:
340 tally.add(0, "Domain is clean against the configured reputation source", .positive)
341 case .unknown:
342 break
328343 }
329
330 return DomainRiskAssessment(score: clampedScore, level: level, factors: factors)
331344 }
332345
333346 private static func insights(
DomainDig/DomainMonitoringService.swift +3 −118
@@ -290,11 +290,11 @@ final class DomainMonitoringService {
290290 domain: trackedDomain.domain,
291291 previousSnapshot: previousSnapshot
292292 )
293 let snapshot = Self.resolvedSnapshotAfterFallback(inspectedSnapshot, previousSnapshot: previousSnapshot)
293 let snapshot = inspectedSnapshot.resolvedAfterFallback(to: previousSnapshot)
294294 // When the fallback fires, `snapshot` *is* `previousSnapshot`, so
295295 // every comparison below is old-against-old and would otherwise
296296 // 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)
298298 ? Self.firstErrorMessage(in: inspectedSnapshot)
299299 : nil
300300 let savedEntry: HistoryEntry?
@@ -844,95 +844,8 @@ final class DomainMonitoringService {
844844 }
845845 }
846846
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
934847 /// First reported error on a snapshot, used to explain a fallback. Mirrors
935 /// the ordering `shouldFallbackToSnapshot` inspects.
848 /// the ordering `LookupSnapshot.needsFallback` inspects.
936849 private static func firstErrorMessage(in snapshot: LookupSnapshot) -> String {
937850 [
938851 snapshot.dnsError,
@@ -947,34 +860,6 @@ final class DomainMonitoringService {
947860 .first ?? "The lookup could not reach the domain."
948861 }
949862
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
978863 private static func primaryIPAddress(from snapshot: LookupSnapshot) -> String? {
979864 snapshot.dnsSections.first(where: { $0.recordType == .A })?.records.first?.value
980865 }
DomainDig/DomainViewModel.swift +276 −382
@@ -1395,7 +1395,7 @@ final class DomainViewModel {
13951395 DomainDebugLog.debug("DomainViewModel.performLookup inspectionReturned domain=\(domain)")
13961396 guard !Task.isCancelled, isCurrentLookup(lookupID) else { return nil }
13971397
1398 let snapshot = Self.resolvedSnapshotAfterFallback(inspectedSnapshot, previousSnapshot: previous)
1398 let snapshot = inspectedSnapshot.resolvedAfterFallback(to: previous)
13991399 let applyStartedAt = DomainDebugLog.signpostStart("DomainViewModel.applySnapshot", domain: domain)
14001400 applySnapshot(snapshot)
14011401 DomainDebugLog.signpostEnd("DomainViewModel.applySnapshot", start: applyStartedAt, domain: domain)
@@ -1506,119 +1506,6 @@ final class DomainViewModel {
15061506 customPortScanLoading = false
15071507 }
15081508
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
16221509 private func runDNS(domain: String, lookupID: UUID) async {
16231510 let result = await DNSLookupService.lookupAll(domain: domain)
16241511 guard !Task.isCancelled, isCurrentLookup(lookupID) else { return }
@@ -1774,7 +1661,7 @@ final class DomainViewModel {
17741661 let result = await PortScanService.scanAll(domain: domain)
17751662 switch result {
17761663 case let .success(results):
1777 let enrichedResults = await enrichOpenPortBanners(in: results, domain: domain)
1664 let enrichedResults = await PortScanService.withBanners(results, host: domain)
17781665 guard !Task.isCancelled, isCurrentLookup(lookupID) else { return }
17791666 portScanResults = enrichedResults
17801667 portScanError = nil
@@ -1833,36 +1720,7 @@ final class DomainViewModel {
18331720 let inspectionService = DomainInspectionService()
18341721 let snapshot = await inspectionService.inspectSnapshot(domain: domain, previousSnapshot: previousSnapshot)
18351722 guard !Task.isCancelled else { return nil }
1836 return BatchLookupPayload(snapshot: resolvedSnapshotAfterFallback(snapshot, previousSnapshot: 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)
1723 return BatchLookupPayload(snapshot: snapshot.resolvedAfterFallback(to: previousSnapshot))
18661724 }
18671725
18681726 @discardableResult
@@ -2840,32 +2698,7 @@ final class DomainViewModel {
28402698 private func buildAttentionQueue(from domainStates: [PortfolioDomainStatus]) -> [PortfolioAttentionItem] {
28412699 domainStates.compactMap { state in
28422700 guard state.health != .healthy else { return nil }
2843 let reason: String
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
2701 let (reason, timestamp) = Self.attentionReason(for: state)
28692702 return PortfolioAttentionItem(
28702703 id: "\(state.trackedDomain.id.uuidString)|\(reason)",
28712704 trackedDomainID: state.trackedDomain.id,
@@ -2883,6 +2716,32 @@ final class DomainViewModel {
28832716 }
28842717 }
28852718
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
28862745 private func buildPortfolioGroups(from domainStates: [PortfolioDomainStatus]) -> [PortfolioGroup] {
28872746 Dictionary(grouping: domainStates, by: \.apexDomain)
28882747 .map { apexDomain, domains in
@@ -3329,40 +3188,10 @@ final class DomainViewModel {
33293188 )
33303189 }
33313190 if let pricing = snapshot.domainPricing {
3332 rows.append(
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 }
3191 rows += pricingRows(pricing)
33543192 }
33553193 if let reputation = snapshot.reputation {
3356 let tone: ResultTone
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))
3194 rows.append(reputationRow(reputation))
33663195 }
33673196 if let certificateStatus = certificateBadgeLabel(from: snapshot) {
33683197 rows.insert(
@@ -3377,6 +3206,39 @@ final class DomainViewModel {
33773206 return rows
33783207 }
33793208
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
33803242 static func suggestionRows(from snapshot: LookupSnapshot) -> [DomainSuggestionViewData] {
33813243 snapshot.suggestions.map {
33823244 DomainSuggestionViewData(
@@ -3647,229 +3509,261 @@ final class DomainViewModel {
36473509 lines.append("Tracking Note: \(note)")
36483510 }
36493511
3650 func appendSection(_ title: String, body: () -> Void) {
3512 func appendSection(_ title: String, _ body: [String]) {
36513513 lines.append("")
36523514 lines.append(title)
36533515 lines.append(String(repeating: "-", count: title.count))
3654 body()
3516 lines += body
36553517 }
36563518
3657 appendSection("Summary") {
3658 for item in summaryFields(from: snapshot) {
3659 lines.append(" \(item.label): \(item.value)")
3660 }
3661 if let changeSummary {
3662 lines.append(" Change Summary: \(changeSummary.message)")
3663 lines.append(" Severity: \(changeSummary.severity.title)")
3664 lines.append(" Changed Sections: \(changeSummary.changedSections.isEmpty ? "None" : changeSummary.changedSections.joined(separator: ", "))")
3665 lines.append(" Compared At: \(exportDateFormatter.string(from: changeSummary.generatedAt))")
3666 }
3667 }
3519 appendSection("Summary", exportSummaryLines(snapshot, changeSummary: changeSummary, exportDateFormatter: exportDateFormatter))
3520 appendSection("Tracking", exportTrackingLines(trackedDomain, exportDateFormatter: exportDateFormatter))
3521 appendSection("Diff Summary", exportDiffSummaryLines(diffSections))
3522 appendSection("Domain", exportDomainLines(snapshot))
3523 appendSection("Ownership", exportOwnershipLines(snapshot))
3524 appendSection("Subdomains", exportSubdomainsLines(snapshot))
3525 appendSection("DNS", exportDnsLines(snapshot))
3526 appendSection("Web", exportWebLines(snapshot))
3527 appendSection("Email", exportEmailLines(snapshot))
3528 appendSection("Network", exportNetworkLines(snapshot))
36683529
3669 appendSection("Tracking") {
3670 if let trackedDomain {
3671 lines.append(" Pinned: \(trackedDomain.isPinned ? "Yes" : "No")")
3672 lines.append(" Last Refresh: \(exportDateFormatter.string(from: trackedDomain.updatedAt))")
3673 lines.append(" Last Known Availability: \(availabilityLabel(trackedDomain.lastKnownAvailability))")
3674 if let note = trackedDomain.note?.nilIfEmpty {
3675 lines.append(" Note: \(note)")
3676 }
3677 } else {
3678 lines.append(" This domain is not currently tracked.")
3530 return lines.joined(separator: "\n")
3531 }
3532
3533 private static func exportSummaryLines(
3534 _ snapshot: LookupSnapshot,
3535 changeSummary: DomainChangeSummary?,
3536 exportDateFormatter: DateFormatter
3537 ) -> [String] {
3538 var lines: [String] = []
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)")
36793559 }
3560 } else {
3561 lines.append(" This domain is not currently tracked.")
36803562 }
3563 return lines
3564 }
36813565
3682 appendSection("Diff Summary") {
3683 if diffSections.isEmpty {
3684 lines.append(" No comparison available")
3685 } else {
3686 for section in diffSections where section.items.contains(where: { $0.changeType != .unchanged }) {
3687 lines.append(" \(section.title)")
3688 for item in section.items where item.changeType != .unchanged {
3689 lines.append(" [\(item.changeType.rawValue.capitalized)] \(item.label): \(item.oldValue ?? "None") -> \(item.newValue ?? "None")")
3690 }
3566 private static func exportDiffSummaryLines(_ diffSections: [DomainDiffSection]) -> [String] {
3567 var lines: [String] = []
3568 if diffSections.isEmpty {
3569 lines.append(" No comparison available")
3570 } else {
3571 for section in diffSections where section.items.contains(where: { $0.changeType != .unchanged }) {
3572 lines.append(" \(section.title)")
3573 for item in section.items where item.changeType != .unchanged {
3574 lines.append(" [\(item.changeType.rawValue.capitalized)] \(item.label): \(item.oldValue ?? "None") -> \(item.newValue ?? "None")")
36913575 }
36923576 }
36933577 }
3578 return lines
3579 }
36943580
3695 appendSection("Domain") {
3696 for row in domainRows(from: snapshot) {
3697 lines.append(" \(row.label): \(row.value)")
3698 }
3699 if snapshot.suggestions.isEmpty {
3700 lines.append(" Suggestions: None")
3701 } else {
3702 lines.append(" Suggestions:")
3703 for suggestion in snapshot.suggestions {
3704 lines.append(" \(suggestion.domain): \(availabilityLabel(suggestion.status))")
3705 }
3581 private static func exportDomainLines(_ snapshot: LookupSnapshot) -> [String] {
3582 var lines: [String] = []
3583 for row in domainRows(from: snapshot) {
3584 lines.append(" \(row.label): \(row.value)")
3585 }
3586 if snapshot.suggestions.isEmpty {
3587 lines.append(" Suggestions: None")
3588 } else {
3589 lines.append(" Suggestions:")
3590 for suggestion in snapshot.suggestions {
3591 lines.append(" \(suggestion.domain): \(availabilityLabel(suggestion.status))")
37063592 }
37073593 }
3594 return lines
3595 }
37083596
3709 appendSection("Ownership") {
3710 for row in ownershipRows(from: snapshot) {
3711 lines.append(" \(row.label): \(row.value)")
3712 }
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 }
3597 private static func exportOwnershipLines(_ snapshot: LookupSnapshot) -> [String] {
3598 var lines: [String] = []
3599 for row in ownershipRows(from: snapshot) {
3600 lines.append(" \(row.label): \(row.value)")
37193601 }
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 }
37203610
3721 appendSection("Subdomains") {
3722 lines.append(" Count: \(snapshot.subdomains.count)")
3723 if snapshot.subdomains.isEmpty {
3724 lines.append(" \(snapshot.subdomainsError ?? "No passive subdomains found")")
3725 } else {
3726 for subdomain in subdomainRows(from: snapshot) {
3727 let marker = subdomain.isInteresting ? " [interesting]" : ""
3728 lines.append(" \(subdomain.hostname)\(marker)")
3729 }
3730 }
3731 if !DataAccessService.hasAccess(to: .extendedSubdomains) {
3732 lines.append(" Extended subdomain discovery (Pro+)")
3611 private static func exportSubdomainsLines(_ snapshot: LookupSnapshot) -> [String] {
3612 var lines: [String] = []
3613 lines.append(" Count: \(snapshot.subdomains.count)")
3614 if snapshot.subdomains.isEmpty {
3615 lines.append(" \(snapshot.subdomainsError ?? "No passive subdomains found")")
3616 } else {
3617 for subdomain in subdomainRows(from: snapshot) {
3618 let marker = subdomain.isInteresting ? " [interesting]" : ""
3619 lines.append(" \(subdomain.hostname)\(marker)")
37333620 }
37343621 }
3622 if !DataAccessService.hasAccess(to: .extendedSubdomains) {
3623 lines.append(" Extended subdomain discovery (Pro+)")
3624 }
3625 return lines
3626 }
37353627
3736 appendSection("DNS") {
3737 if let dnsError = snapshot.dnsError {
3738 lines.append(" Error: \(dnsError)")
3739 }
3740 if let dnssecLabel = dnssecLabel(from: snapshot) {
3741 lines.append(" \(dnssecLabel)")
3742 }
3743 for section in dnsRows(from: snapshot) {
3744 lines.append(" \(section.title)")
3745 if let message = section.message {
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 }
3628 private static func exportDnsLines(_ snapshot: LookupSnapshot) -> [String] {
3629 var lines: [String] = []
3630 if let dnsError = snapshot.dnsError {
3631 lines.append(" Error: \(dnsError)")
3632 }
3633 if let dnssecLabel = dnssecLabel(from: snapshot) {
3634 lines.append(" \(dnssecLabel)")
3635 }
3636 for section in dnsRows(from: snapshot) {
3637 lines += exportDNSSectionLines(section)
37633638 }
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 }
37643646
3765 appendSection("Web") {
3766 if let sslError = snapshot.sslError {
3767 lines.append(" TLS Error: \(sslError)")
3768 } else {
3769 for row in webCertificateRows(from: snapshot) {
3770 lines.append(" \(row.label): \(row.value)")
3771 }
3647 private static func exportDNSSectionLines(_ section: DNSRecordSectionViewData) -> [String] {
3648 var lines = [" \(section.title)"]
3649 if let message = section.message {
3650 lines.append(" \(message.isError ? "Error" : "Info"): \(message.text)")
3651 }
3652 for row in section.rows {
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))")
37723659 }
3660 }
3661 return lines
3662 }
37733663
3774 if let httpHeadersError = snapshot.httpHeadersError {
3775 lines.append(" Headers Error: \(httpHeadersError)")
3776 } else {
3777 for row in webResponseRows(from: snapshot) {
3778 lines.append(" \(row.label): \(row.value)")
3779 }
3780 if snapshot.httpHeaders.isEmpty {
3781 lines.append(" Headers: No headers returned")
3782 } else {
3783 lines.append(" Headers:")
3784 for header in snapshot.httpHeaders {
3785 lines.append(" \(header.name): \(header.value)")
3786 }
3787 }
3664 private static func exportResponseLines(_ snapshot: LookupSnapshot) -> [String] {
3665 if let httpHeadersError = snapshot.httpHeadersError {
3666 return [" Headers Error: \(httpHeadersError)"]
3667 }
3668 var lines = webResponseRows(from: snapshot).map { " \($0.label): \($0.value)" }
3669 if snapshot.httpHeaders.isEmpty {
3670 lines.append(" Headers: No headers returned")
3671 } else {
3672 lines.append(" Headers:")
3673 for header in snapshot.httpHeaders {
3674 lines.append(" \(header.name): \(header.value)")
37883675 }
3676 }
3677 return lines
3678 }
37893679
3790 if let redirectChainError = snapshot.redirectChainError {
3791 lines.append(" Redirect Error: \(redirectChainError)")
3792 } else if snapshot.redirectChain.isEmpty {
3793 lines.append(" Redirects: No redirect data available")
3794 } else {
3795 lines.append(" Redirects:")
3796 for hop in redirectRows(from: snapshot) {
3797 lines.append(" \(hop.stepLabel). \(hop.statusCode) \(hop.url)\(hop.isFinal ? " (final)" : "")")
3798 }
3680 private static func exportWebLines(_ snapshot: LookupSnapshot) -> [String] {
3681 var lines: [String] = []
3682 if let sslError = snapshot.sslError {
3683 lines.append(" TLS Error: \(sslError)")
3684 } else {
3685 for row in webCertificateRows(from: snapshot) {
3686 lines.append(" \(row.label): \(row.value)")
37993687 }
38003688 }
3689 lines += exportResponseLines(snapshot)
38013690
3802 appendSection("Email") {
3803 if let emailSecurityError = snapshot.emailSecurityError {
3804 lines.append(" Error: \(emailSecurityError)")
3805 } else if emailRows(from: snapshot).isEmpty {
3806 lines.append(" No email security records found")
3807 } else {
3808 for row in emailRows(from: snapshot) {
3809 lines.append(" \(row.label): \(row.status)")
3810 lines.append(" \(row.detail)")
3811 if let auxiliaryDetail = row.auxiliaryDetail {
3812 lines.append(" \(auxiliaryDetail)")
3813 }
3814 }
3691 if let redirectChainError = snapshot.redirectChainError {
3692 lines.append(" Redirect Error: \(redirectChainError)")
3693 } else if snapshot.redirectChain.isEmpty {
3694 lines.append(" Redirects: No redirect data available")
3695 } else {
3696 lines.append(" Redirects:")
3697 for hop in redirectRows(from: snapshot) {
3698 lines.append(" \(hop.stepLabel). \(hop.statusCode) \(hop.url)\(hop.isFinal ? " (final)" : "")")
38153699 }
38163700 }
3701 return lines
3702 }
38173703
3818 appendSection("Network") {
3819 if let reachabilityError = snapshot.reachabilityError {
3820 lines.append(" Reachability Error: \(reachabilityError)")
3821 } else if reachabilityRows(from: snapshot).isEmpty {
3822 lines.append(" Reachability: No results")
3823 } else {
3824 lines.append(" Reachability:")
3825 for row in reachabilityRows(from: snapshot) {
3826 lines.append(" \(row.portLabel): \(row.statusLabel) \(row.latencyLabel)")
3704 private static func exportEmailLines(_ snapshot: LookupSnapshot) -> [String] {
3705 var lines: [String] = []
3706 if let emailSecurityError = snapshot.emailSecurityError {
3707 lines.append(" Error: \(emailSecurityError)")
3708 } else if emailRows(from: snapshot).isEmpty {
3709 lines.append(" No email security records found")
3710 } else {
3711 for row in emailRows(from: snapshot) {
3712 lines.append(" \(row.label): \(row.status)")
3713 lines.append(" \(row.detail)")
3714 if let auxiliaryDetail = row.auxiliaryDetail {
3715 lines.append(" \(auxiliaryDetail)")
38273716 }
38283717 }
3718 }
3719 return lines
3720 }
38293721
3830 if let ipGeolocationError = snapshot.ipGeolocationError, snapshot.ipGeolocation == nil {
3831 lines.append(" Location Error: \(ipGeolocationError)")
3832 } else if locationRows(from: snapshot).isEmpty {
3833 lines.append(" Location: No data")
3834 } else {
3835 lines.append(" Location:")
3836 for row in locationRows(from: snapshot) {
3837 lines.append(" \(row.label): \(row.value)")
3838 }
3722 private static func exportPortLines(_ rows: [PortScanRowViewData]) -> [String] {
3723 guard !rows.isEmpty else { return [" No results"] }
3724 var lines: [String] = []
3725 for row in rows {
3726 lines.append(" \(row.portLabel) \(row.service): \(row.statusLabel)\(row.durationLabel.map { " \($0)" } ?? "")")
3727 if let banner = row.banner {
3728 lines.append(" Banner: \(banner)")
38393729 }
3730 }
3731 return lines
3732 }
38403733
3841 if let portScanError = snapshot.portScanError, snapshot.portScanResults.isEmpty {
3842 lines.append(" Port Scan Error: \(portScanError)")
3734 private static func exportNetworkLines(_ snapshot: LookupSnapshot) -> [String] {
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)")
38433744 }
3745 }
38443746
3845 lines.append(" Standard Ports:")
3846 let standardRows = portRows(from: snapshot, kind: .standard)
3847 if standardRows.isEmpty {
3848 lines.append(" No results")
3849 } else {
3850 for row in standardRows {
3851 lines.append(" \(row.portLabel) \(row.service): \(row.statusLabel)\(row.durationLabel.map { " \($0)" } ?? "")")
3852 if let banner = row.banner {
3853 lines.append(" Banner: \(banner)")
3854 }
3855 }
3747 if let ipGeolocationError = snapshot.ipGeolocationError, snapshot.ipGeolocation == nil {
3748 lines.append(" Location Error: \(ipGeolocationError)")
3749 } else if locationRows(from: snapshot).isEmpty {
3750 lines.append(" Location: No data")
3751 } else {
3752 lines.append(" Location:")
3753 for row in locationRows(from: snapshot) {
3754 lines.append(" \(row.label): \(row.value)")
38563755 }
3756 }
38573757
3858 lines.append(" Custom Ports:")
3859 let customRows = portRows(from: snapshot, kind: .custom)
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 }
3758 if let portScanError = snapshot.portScanError, snapshot.portScanResults.isEmpty {
3759 lines.append(" Port Scan Error: \(portScanError)")
38703760 }
38713761
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
38733767 }
38743768
38753769 private static func primaryIPAddress(from snapshot: LookupSnapshot) -> String? {
DomainDig/PortScanService.swift +26
@@ -74,6 +74,32 @@ struct PortScanService {
7474 .pipe { $0.isEmpty ? .empty("No custom port scan results") : .success($0) }
7575 }
7676
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
77103 static func grabBanner(host: String, port: UInt16, timeout: TimeInterval = 3.0) async -> String? {
78104 await withCheckedContinuation { continuation in
79105 guard let nwPort = NWEndpoint.Port(rawValue: port) else {
DomainDig/SSLCheckService.swift +42 −43
@@ -228,24 +228,15 @@ private enum DERCertificateParser {
228228 while pos < end {
229229 // Each SET in the issuer
230230 guard let setTL = readTagAndLength(bytes, offset: pos) else { break }
231 let setEnd = setTL.contentStart + setTL.length
231 pos = setTL.contentStart + setTL.length
232232
233233 // Inside the SET is a SEQUENCE with OID + value
234 if let seqTL = readTagAndLength(bytes, offset: setTL.contentStart) {
235 let seqEnd = seqTL.contentStart + seqTL.length
236 if let oidTL = readTagAndLength(bytes, offset: seqTL.contentStart) {
237 let oidBytes = Array(bytes[oidTL.contentStart..<oidTL.contentStart + oidTL.length])
238 if oidBytes == cnOID {
239 let valueStart = oidTL.contentStart + oidTL.length
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
234 guard let seqTL = readTagAndLength(bytes, offset: setTL.contentStart),
235 let oidTL = readTagAndLength(bytes, offset: seqTL.contentStart),
236 content(of: oidTL, in: bytes).elementsEqual(cnOID),
237 let valueTL = readTagAndLength(bytes, offset: oidTL.contentStart + oidTL.length)
238 else { continue }
239 return String(bytes: content(of: valueTL, in: bytes), encoding: .utf8)
249240 }
250241 return nil
251242 }
@@ -260,39 +251,41 @@ private enum DERCertificateParser {
260251 let extEnd = extSeq.contentStart + extSeq.length
261252
262253 // Each extension is SEQUENCE { OID, [critical], value }
263 if let oidTL = readTagAndLength(bytes, offset: extSeq.contentStart) {
264 let oidBytes = Array(bytes[oidTL.contentStart..<oidTL.contentStart + oidTL.length])
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 }
254 if let oidTL = readTagAndLength(bytes, offset: extSeq.contentStart), content(of: oidTL, in: bytes).elementsEqual(sanOID) {
255 sans += sanDNSNames(bytes, valueStart: oidTL.contentStart + oidTL.length, extensionEnd: extEnd)
290256 }
291257 pos = extEnd
292258 }
293259 return sans
294260 }
295261
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
296289 private static func extractValidity(_ bytes: [UInt8], sequenceStart: Int, length: Int) -> (Date?, Date?) {
297290 let end = sequenceStart + length
298291 var position = sequenceStart
@@ -362,8 +355,14 @@ private enum DERCertificateParser {
362355 length = len
363356 }
364357
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 }
365360 return TLV(contentStart: pos, length: length)
366361 }
362
363 private static func content(of tlv: TLV, in bytes: [UInt8]) -> ArraySlice<UInt8> {
364 bytes[tlv.contentStart..<tlv.contentStart + tlv.length]
365 }
367366}
368367
369368enum SSLError: LocalizedError {
DomainInspectionService.swift +1 −26
@@ -678,7 +678,7 @@ struct DomainInspectionService {
678678 private func mapPortScanResult(_ result: ServiceResult<[PortScanResult]>, domain: String) async -> (value: [PortScanResult], message: String?) {
679679 switch result {
680680 case let .success(results):
681 return (await enrichOpenPortBanners(in: results, domain: domain), nil)
681 return (await PortScanService.withBanners(results, host: domain), nil)
682682 case let .empty(message), let .error(message):
683683 return ([], message)
684684 }
@@ -716,29 +716,4 @@ struct DomainInspectionService {
716716 )
717717 }
718718 }
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 }
744719}
DomainReportBuilder.swift +47 −42
@@ -521,7 +521,8 @@ enum DomainIntelligenceService {
521521 }
522522
523523 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 }
525526 let dnsProviders = dnsValues(for: .NS, in: snapshot.dnsSections) + dnsValues(for: .CNAME, in: snapshot.dnsSections)
526527 let issuer = snapshot.sslInfo?.issuer.lowercased() ?? ""
527528 let org = snapshot.ipGeolocation?.org?.lowercased() ?? ""
@@ -626,59 +627,63 @@ enum DomainIntelligenceService {
626627 }
627628
628629 private static func buildSubdomainHistory(from snapshots: [LookupSnapshot]) -> [SubdomainHistoryEntry] {
629 struct WorkingState {
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] = [:]
630 var states: [String: SubdomainPresence] = [:]
638631 for snapshot in snapshots {
639632 let currentHosts = Set((snapshot.subdomains + snapshot.extendedSubdomains).map { $0.hostname.lowercased() })
640633 let knownHosts = Set(states.keys).union(currentHosts)
641634 for host in knownHosts {
642635 let isPresent = currentHosts.contains(host)
643 if var state = states[host] {
644 if isPresent {
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
636 if states[host] != nil {
637 states[host]?.observe(isPresent: isPresent, at: snapshot.timestamp)
653638 } else if isPresent {
654 states[host] = WorkingState(
655 firstSeen: snapshot.timestamp,
656 lastSeen: snapshot.timestamp,
657 recurrenceCount: 1,
658 statusChangeCount: 0,
659 lastSeenInPreviousSnapshot: true
660 )
639 states[host] = SubdomainPresence(firstSeen: snapshot.timestamp)
661640 }
662641 }
663642 }
664643
665 return states.map { host, state in
666 let isEphemeral = state.recurrenceCount <= 2 || state.statusChangeCount >= 2
667 return SubdomainHistoryEntry(
668 hostname: host,
669 firstSeen: state.firstSeen,
670 lastSeen: state.lastSeen,
671 recurrenceCount: state.recurrenceCount,
672 statusChangeCount: state.statusChangeCount,
673 lastKnownStatus: state.lastSeenInPreviousSnapshot ? "Active" : "Inactive",
674 isEphemeral: isEphemeral
675 )
644 return states.map { host, state in state.entry(hostname: host) }
645 .sorted { lhs, rhs in
646 if lhs.isEphemeral != rhs.isEphemeral {
647 return lhs.isEphemeral && !rhs.isEphemeral
648 }
649 return lhs.hostname < rhs.hostname
650 }
651 }
652
653 /// One subdomain's presence across a run of snapshots, from the first that saw it.
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
676664 }
677 .sorted { lhs, rhs in
678 if lhs.isEphemeral != rhs.isEphemeral {
679 return lhs.isEphemeral && !rhs.isEphemeral
665
666 mutating func observe(isPresent: Bool, at timestamp: Date) {
667 if isPresent {
668 lastSeen = timestamp
669 recurrenceCount += 1
680670 }
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 )
682687 }
683688 }
684689
DomainReportExporter.swift +266 −250
@@ -156,6 +156,25 @@ enum DomainReportExporter {
156156 }
157157
158158 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] {
159178 var lines = [
160179 "DomainDig Report",
161180 "Domain: \(report.domain)",
@@ -183,288 +202,285 @@ enum DomainReportExporter {
183202 if let workflowContext = report.workflowContext {
184203 lines.append("Workflow Context: \(workflowContext.workflowName ?? workflowContext.source)")
185204 }
205 return lines
206 }
186207
187 appendSection("Summary", to: &lines) {
188 [
189 "Primary IP: \(report.dns.primaryIP ?? "Unavailable")",
190 "Risk Score: \(report.riskAssessment.score) (\(report.riskAssessment.level.title))",
191 "TLS Status: \(report.web.tlsStatus)",
192 "HTTP: \(httpSummary(for: report))",
193 "Email: \(report.email.summary)",
194 "Subdomains: \(report.subdomains.count)",
195 "Extended Subdomains: \(report.extendedSubdomains.count)",
196 "External Price: \(report.domainPricing?.estimatedPrice ?? "Unavailable")",
197 "Reputation: \(report.reputation?.status.title ?? "Unavailable")"
198 ]
199 }
208 private static func summarySection(_ report: DomainReport) -> [String] {
209 [
210 "Primary IP: \(report.dns.primaryIP ?? "Unavailable")",
211 "Risk Score: \(report.riskAssessment.score) (\(report.riskAssessment.level.title))",
212 "TLS Status: \(report.web.tlsStatus)",
213 "HTTP: \(httpSummary(for: report))",
214 "Email: \(report.email.summary)",
215 "Subdomains: \(report.subdomains.count)",
216 "Extended Subdomains: \(report.extendedSubdomains.count)",
217 "External Price: \(report.domainPricing?.estimatedPrice ?? "Unavailable")",
218 "Reputation: \(report.reputation?.status.title ?? "Unavailable")"
219 ]
220 }
200221
201 appendSection("Risk", to: &lines) {
202 var values = [
203 "Score: \(report.riskAssessment.score)",
204 "Level: \(report.riskAssessment.level.title)"
205 ]
206 if report.riskAssessment.factors.isEmpty {
207 values.append("Factors: None")
208 } else {
209 values.append("Factors:")
210 for factor in report.riskAssessment.factors {
211 values.append(" [\(factor.impact.rawValue)] \(factor.description)")
212 }
222 private static func riskSection(_ report: DomainReport) -> [String] {
223 var values = [
224 "Score: \(report.riskAssessment.score)",
225 "Level: \(report.riskAssessment.level.title)"
226 ]
227 if report.riskAssessment.factors.isEmpty {
228 values.append("Factors: None")
229 } else {
230 values.append("Factors:")
231 for factor in report.riskAssessment.factors {
232 values.append(" [\(factor.impact.rawValue)] \(factor.description)")
213233 }
214 return values
215234 }
235 return values
236 }
216237
217 appendSection("Insights", to: &lines) {
218 report.insights.isEmpty ? ["No deterministic insights triggered"] : report.insights.map { "- \($0)" }
219 }
238 private static func insightsSection(_ report: DomainReport) -> [String] {
239 report.insights.isEmpty ? ["No deterministic insights triggered"] : report.insights.map { "- \($0)" }
240 }
220241
221 appendSection("Ownership", to: &lines) {
222 var ownershipLines = [
223 "Registrar: \(report.ownership?.registrar ?? "Unavailable")",
224 "Confidence: \(report.ownershipConfidence?.title ?? "N/A")",
225 "Created: \(ownershipDateLabel(report.ownership?.createdDate))",
226 "Expires: \(ownershipDateLabel(report.ownership?.expirationDate))",
227 "Registrant: \(report.ownership?.registrant ?? "Unavailable")",
228 "Nameservers: \(joined(report.ownership?.nameservers) ?? "Unavailable")",
229 "Status: \(joined(report.ownership?.status) ?? "Unavailable")",
230 "Abuse Contact: \(report.ownership?.abuseEmail ?? "Unavailable")"
231 ]
232 if let provenance = report.sectionProvenance[.ownership] {
233 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
242 private static func ownershipSection(_ report: DomainReport) -> [String] {
243 var ownershipLines = [
244 "Registrar: \(report.ownership?.registrar ?? "Unavailable")",
245 "Confidence: \(report.ownershipConfidence?.title ?? "N/A")",
246 "Created: \(ownershipDateLabel(report.ownership?.createdDate))",
247 "Expires: \(ownershipDateLabel(report.ownership?.expirationDate))",
248 "Registrant: \(report.ownership?.registrant ?? "Unavailable")",
249 "Nameservers: \(joined(report.ownership?.nameservers) ?? "Unavailable")",
250 "Status: \(joined(report.ownership?.status) ?? "Unavailable")",
251 "Abuse Contact: \(report.ownership?.abuseEmail ?? "Unavailable")"
252 ]
253 if let provenance = report.sectionProvenance[.ownership] {
254 ownershipLines.append("Provenance: \(provenanceLabel(provenance))")
241255 }
256 if let error = report.dns.error, report.ownership == nil {
257 ownershipLines.append("Error: \(error)")
258 }
259 return ownershipLines
260 }
242261
243 appendSection("Ownership History", to: &lines) {
244 guard !report.ownershipHistory.isEmpty else {
245 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 }
262 private static func ownershipHistorySection(_ report: DomainReport) -> [String] {
263 guard !report.ownershipHistory.isEmpty else {
264 return ["No ownership history available"]
255265 }
256266
257 appendSection("DNS", to: &lines) {
258 var dnsLines = [
259 "Lookup Duration: \(durationLabel(report.dns.lookupDurationMs))",
260 "Primary IP: \(report.dns.primaryIP ?? "Unavailable")",
261 "PTR: \(report.dns.ptrRecord ?? report.dns.ptrError ?? "Unavailable")",
262 "DNSSEC: \(dnssecLabel(report.dns.dnssecSigned))",
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
267 return report.ownershipHistory.map { event in
268 [
269 textDateFormatter.string(from: event.date),
270 event.summary,
271 "source=\(event.source)"
272 ].joined(separator: " | ")
285273 }
274 }
286275
287 appendSection("DNS History", to: &lines) {
288 guard !report.dnsHistory.isEmpty else {
289 return ["No DNS history available"]
290 }
276 private static func dnsSection(_ report: DomainReport) -> [String] {
277 var dnsLines = [
278 "Lookup Duration: \(durationLabel(report.dns.lookupDurationMs))",
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 }
291305
292 return report.dnsHistory.map { event in
293 [
294 textDateFormatter.string(from: event.date),
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 }
306 private static func dnsHistorySection(_ report: DomainReport) -> [String] {
307 guard !report.dnsHistory.isEmpty else {
308 return ["No DNS history available"]
301309 }
302310
303 appendSection("Web", to: &lines) {
304 var webLines = [
305 "TLS Status: \(report.web.tlsStatus)",
306 "TLS Grade: \(report.web.tlsGrade.rawValue)",
307 "TLS Highlights: \(report.web.tlsHighlights.joined(separator: " | "))",
308 "Certificate Warning: \(report.web.certificateWarningLevel.title)",
309 "Security Grade: \(report.web.securityGrade ?? "Unavailable")",
310 "HTTP Status: \(report.web.statusCode.map(String.init) ?? "Unavailable")",
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
311 return report.dnsHistory.map { event in
312 [
313 textDateFormatter.string(from: event.date),
314 event.summary,
315 "A=\(event.aRecords.joined(separator: " | ").nilIfEmpty ?? "-")",
316 "NS=\(event.nameservers.joined(separator: " | ").nilIfEmpty ?? "-")",
317 "source=\(event.source)"
318 ].joined(separator: " | ")
348319 }
320 }
349321
350 appendSection("Email", to: &lines) {
351 var emailLines = [report.email.summary]
352 if let grade = report.email.grade {
353 emailLines.append("Grade: \(grade.rawValue)")
354 }
355 if !report.email.reasons.isEmpty {
356 emailLines.append("Why: \(report.email.reasons.joined(separator: " | "))")
357 }
358 emailLines.append("Confidence: \(report.emailConfidence?.title ?? "N/A")")
359 if let provenance = report.sectionProvenance[.emailSecurity] {
360 emailLines.append("Provenance: \(provenanceLabel(provenance))")
361 }
362 if let records = report.email.records {
363 emailLines.append("SPF: \(recordLabel(records.spf))")
364 emailLines.append("DMARC: \(recordLabel(records.dmarc))")
365 emailLines.append("DKIM: \(recordLabel(records.dkim))")
366 emailLines.append("BIMI: \(recordLabel(records.bimi))")
367 emailLines.append("MTA-STS: \(records.mtaSts?.txtFound == true ? records.mtaSts?.policyMode ?? "found" : "Unavailable")")
322 private static func webSection(_ report: DomainReport) -> [String] {
323 var webLines = [
324 "TLS Status: \(report.web.tlsStatus)",
325 "TLS Grade: \(report.web.tlsGrade.rawValue)",
326 "TLS Highlights: \(report.web.tlsHighlights.joined(separator: " | "))",
327 "Certificate Warning: \(report.web.certificateWarningLevel.title)",
328 "Security Grade: \(report.web.securityGrade ?? "Unavailable")",
329 "HTTP Status: \(report.web.statusCode.map(String.init) ?? "Unavailable")",
330 "Protocol: \(report.web.httpProtocol ?? "Unavailable")",
331 "HTTP/3 Advertised: \(report.web.http3Advertised ? "Yes" : "No")",
332 "Final URL: \(report.web.finalURL ?? "Unavailable")",
333 "HSTS Preloaded: \(booleanLabel(report.web.hstsPreloaded))",
334 "Header Count: \(report.web.headerCount)"
335 ]
336 if let provenance = report.sectionProvenance[.ssl] {
337 webLines.append("TLS Provenance: \(provenanceLabel(provenance))")
338 }
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)")
368358 }
369 if let error = report.email.error {
370 emailLines.append("Error: \(error)")
359 }
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)" : "")")
371364 }
372 return emailLines
373365 }
366 return webLines
367 }
374368
375 appendSection("Network", to: &lines) {
376 var networkLines = [
377 "Reachability: \(report.network.reachabilitySummary)",
378 "Geolocation: \(report.network.geolocationSummary)",
379 "Geolocation Confidence: \(report.geolocationConfidence?.title ?? "N/A")",
380 "Open Ports: \(report.network.openPorts.map(String.init).joined(separator: ", ").nilIfEmpty ?? "None")"
381 ]
382 if let provenance = report.sectionProvenance[.ipGeolocation] {
383 networkLines.append("Geolocation Provenance: \(provenanceLabel(provenance))")
384 }
385 if let error = report.network.reachabilityError {
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
369 private static func emailSection(_ report: DomainReport) -> [String] {
370 var emailLines = [report.email.summary]
371 if let grade = report.email.grade {
372 emailLines.append("Grade: \(grade.rawValue)")
373 }
374 if !report.email.reasons.isEmpty {
375 emailLines.append("Why: \(report.email.reasons.joined(separator: " | "))")
376 }
377 emailLines.append("Confidence: \(report.emailConfidence?.title ?? "N/A")")
378 if let provenance = report.sectionProvenance[.emailSecurity] {
379 emailLines.append("Provenance: \(provenanceLabel(provenance))")
403380 }
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 }
404393
405 appendSection("Subdomains", to: &lines) {
406 var values = ["Confidence: \(report.subdomainConfidence?.title ?? "N/A")"]
407 if let provenance = report.sectionProvenance[.subdomains] {
408 values.append("Provenance: \(provenanceLabel(provenance))")
409 }
410 if report.subdomains.isEmpty {
411 values.append("None")
412 return values
413 }
414 if !report.subdomainGroups.isEmpty {
415 values.append("Groups: \(report.subdomainGroups.map { "\($0.label): \($0.subdomains.count)" }.joined(separator: " | "))")
416 }
417 values.append(contentsOf: report.subdomains.map { "- \($0)" })
418 if !report.extendedSubdomains.isEmpty {
419 values.append("Extended:")
420 values.append(contentsOf: report.extendedSubdomains.map { "- \($0)" })
394 private static func networkSection(_ report: DomainReport) -> [String] {
395 var networkLines = [
396 "Reachability: \(report.network.reachabilitySummary)",
397 "Geolocation: \(report.network.geolocationSummary)",
398 "Geolocation Confidence: \(report.geolocationConfidence?.title ?? "N/A")",
399 "Open Ports: \(report.network.openPorts.map(String.init).joined(separator: ", ").nilIfEmpty ?? "None")"
400 ]
401 if let provenance = report.sectionProvenance[.ipGeolocation] {
402 networkLines.append("Geolocation Provenance: \(provenanceLabel(provenance))")
403 }
404 if let error = report.network.reachabilityError {
405 networkLines.append("Reachability Error: \(error)")
406 }
407 if let error = report.network.geolocationError {
408 networkLines.append("Geolocation Error: \(error)")
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 )
421419 }
422 return values
423420 }
421 return networkLines
422 }
424423
425 appendSection("Pricing", to: &lines) {
426 guard let pricing = report.domainPricing else {
427 return ["External pricing unavailable"]
428 }
424 private static func subdomainsSection(_ report: DomainReport) -> [String] {
425 var values = ["Confidence: \(report.subdomainConfidence?.title ?? "N/A")"]
426 if let provenance = report.sectionProvenance[.subdomains] {
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 }
429443
430 return [
431 "Estimated Price: \(pricing.estimatedPrice ?? "Unavailable")",
432 "Premium: \(pricing.premiumIndicator == true ? "Yes" : "No")",
433 "Resale: \(pricing.resaleSignal ?? "Unavailable")",
434 "Auction: \(pricing.auctionSignal ?? "Unavailable")",
435 "Source: \(pricing.source)",
436 "Collected: \(textDateFormatter.string(from: pricing.collectedAt))"
437 ]
444 private static func pricingSection(_ report: DomainReport) -> [String] {
445 guard let pricing = report.domainPricing else {
446 return ["External pricing unavailable"]
438447 }
439448
440 appendSection("Changes", to: &lines) {
441 guard let changeSummary = report.changeSummary else {
442 return ["No comparison available"]
443 }
449 return [
450 "Estimated Price: \(pricing.estimatedPrice ?? "Unavailable")",
451 "Premium: \(pricing.premiumIndicator == true ? "Yes" : "No")",
452 "Resale: \(pricing.resaleSignal ?? "Unavailable")",
453 "Auction: \(pricing.auctionSignal ?? "Unavailable")",
454 "Source: \(pricing.source)",
455 "Collected: \(textDateFormatter.string(from: pricing.collectedAt))"
456 ]
457 }
444458
445 var values = [
446 "Has Changes: \(changeSummary.hasChanges ? "Yes" : "No")",
447 "Severity: \(changeSummary.severity.title)",
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
459 private static func changesSection(_ report: DomainReport) -> [String] {
460 guard let changeSummary = report.changeSummary else {
461 return ["No comparison available"]
465462 }
466463
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
468484 }
469485
470486 static func batchText(for reports: [DomainReport], title: String) -> String {
LookupSnapshot.swift +119
@@ -163,3 +163,122 @@ extension HistoryEntry {
163163 )
164164 }
165165}
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}