Qlty config and code cleanup !2

merged merged by cmc on 2026-10-24 03:19 UTC · krz/domain-dig:cleanup into main

29 files changed, +1711 −1968

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 +58
@@ -0,0 +1,58 @@
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 # DEBUG-only seed data for the accessibility audit tests.
15 "DomainDig/AuditFixtures.swift",
16]
17
18test_patterns = [
19 "**/test/**",
20 "**/tests/**",
21 "**/Tests/**",
22 "**/*_test.*",
23 "**/test_*.*",
24 "**/*.test.*",
25 "**/*Tests.swift",
26 "e2e/**",
27]
28
29[[source]]
30name = "default"
31default = true
32
33[[plugin]]
34name = "osv-scanner"
35
36[[plugin]]
37name = "trufflehog"
38
39# Early returns are guard clauses, which keep the happy path unindented.
40[smells.return_statements]
41enabled = false
42
43# Function and file complexity are left to review rather than counted.
44[smells.function_complexity]
45enabled = false
46
47[smells.file_complexity]
48enabled = false
49
50# Exhaustive switch-over-enum lookup tables share shape but not content.
51[language.swift.smells.duplication]
52# ownershipHistory and dnsHistory each pair a local history with an external one and merge
53# them; one generic version would take six closures.
54filter_patterns = [
55 "(import_declaration _)",
56 "(switch_statement _)",
57 "(function_declaration name: (simple_identifier) @_n (#match? @_n \"^(ownershipHistory|dnsHistory)$\"))",
58]
DomainDataPortabilityService.swift +36 −57
@@ -305,7 +305,8 @@ enum DataPortabilityCSV {
305 } 305 }
306 306
307 private nonisolated static func dictionary(for row: [String], header: [String]) -> [String: String] { 307 private nonisolated static func dictionary(for row: [String], header: [String]) -> [String: String] {
308 Dictionary(uniqueKeysWithValues: zip(header, row).map { ($0.0, $0.1) }) 308 // A repeated column keeps its first value rather than failing the import.
309 Dictionary(zip(header, row).map { ($0.0, $0.1) }) { first, _ in first }
309 } 310 }
310 311
311 private nonisolated static func csvLine(_ values: [String]) -> String { 312 private nonisolated static func csvLine(_ values: [String]) -> String {
@@ -903,76 +904,54 @@ enum DomainDataPortabilityService {
903 if backup.schemaVersion > DomainDigBackup.currentSchemaVersion { 904 if backup.schemaVersion > DomainDigBackup.currentSchemaVersion {
904 throw DataPortabilityError.unsupportedSchema(backup.schemaVersion) 905 throw DataPortabilityError.unsupportedSchema(backup.schemaVersion)
905 } 906 }
906 let report = DataValidationService.validate(backup: backup) 907 return .backup(backup, try passing(DataValidationService.validate(backup: backup)))
907 if !report.errors.isEmpty {
908 throw DataPortabilityError.validationFailed(report.errors)
909 }
910 return .backup(backup, report)
911 } 908 }
912
913 if let backup = try? decodeLegacyBackup(from: data) { 909 if let backup = try? decodeLegacyBackup(from: data) {
914 let report = DataValidationService.validate(backup: backup) 910 return .backup(backup, try passing(DataValidationService.validate(backup: backup)))
915 if !report.errors.isEmpty {
916 throw DataPortabilityError.validationFailed(report.errors)
917 }
918 return .backup(backup, report)
919 } 911 }
920
921 if let export = try? decoder.decode(TrackedDomainsExport.self, from: data) { 912 if let export = try? decoder.decode(TrackedDomainsExport.self, from: data) {
922 let report = DataValidationService.validate(trackedDomains: export.trackedDomains) 913 return try trackedDomainsPayload(export.trackedDomains)
923 if !report.errors.isEmpty {
924 throw DataPortabilityError.validationFailed(report.errors)
925 }
926 return .trackedDomains(export.trackedDomains, report)
927 } 914 }
928
929 if let export = try? decoder.decode(WorkflowsExport.self, from: data) { 915 if let export = try? decoder.decode(WorkflowsExport.self, from: data) {
930 let report = DataValidationService.validate(workflows: export.workflows) 916 return try workflowsPayload(export.workflows)
931 if !report.errors.isEmpty {
932 throw DataPortabilityError.validationFailed(report.errors)
933 }
934 return .workflows(export.workflows, report)
935 } 917 }
936
937 if let trackedDomains = try? decoder.decode([TrackedDomain].self, from: data) { 918 if let trackedDomains = try? decoder.decode([TrackedDomain].self, from: data) {
938 let report = DataValidationService.validate(trackedDomains: trackedDomains) 919 return try trackedDomainsPayload(trackedDomains)
939 if !report.errors.isEmpty {
940 throw DataPortabilityError.validationFailed(report.errors)
941 }
942 return .trackedDomains(trackedDomains, report)
943 } 920 }
944
945 if let workflows = try? decoder.decode([DomainWorkflow].self, from: data) { 921 if let workflows = try? decoder.decode([DomainWorkflow].self, from: data) {
946 let report = DataValidationService.validate(workflows: workflows) 922 return try workflowsPayload(workflows)
947 if !report.errors.isEmpty {
948 throw DataPortabilityError.validationFailed(report.errors)
949 }
950 return .workflows(workflows, report)
951 } 923 }
924 if fileName.lowercased().hasSuffix(".csv") {
925 return try decodeCSVPayload(from: data, fileName: fileName)
926 }
927 throw DataPortabilityError.unsupportedFormat
928 }
952 929
953 let lowercasedFileName = fileName.lowercased() 930 /// A CSV holds workflows when its name says so, and tracked domains otherwise.
954 if lowercasedFileName.hasSuffix(".csv") { 931 private static func decodeCSVPayload(from data: Data, fileName: String) throws -> ImportPayload {
955 guard let string = String(data: data, encoding: .utf8) else { 932 guard let string = String(data: data, encoding: .utf8) else {
956 throw DataPortabilityError.unreadableFile 933 throw DataPortabilityError.unreadableFile
957 } 934 }
958 if lowercasedFileName.contains("workflow") { 935 if fileName.lowercased().contains("workflow") {
959 let workflows = try DataPortabilityCSV.parseWorkflows(from: string) 936 return try workflowsPayload(DataPortabilityCSV.parseWorkflows(from: string))
960 let report = DataValidationService.validate(workflows: workflows)
961 if !report.errors.isEmpty {
962 throw DataPortabilityError.validationFailed(report.errors)
963 }
964 return .workflows(workflows, report)
965 }
966
967 let trackedDomains = try DataPortabilityCSV.parseTrackedDomains(from: string)
968 let report = DataValidationService.validate(trackedDomains: trackedDomains)
969 if !report.errors.isEmpty {
970 throw DataPortabilityError.validationFailed(report.errors)
971 }
972 return .trackedDomains(trackedDomains, report)
973 } 937 }
938 return try trackedDomainsPayload(DataPortabilityCSV.parseTrackedDomains(from: string))
939 }
974 940
975 throw DataPortabilityError.unsupportedFormat 941 private static func trackedDomainsPayload(_ trackedDomains: [TrackedDomain]) throws -> ImportPayload {
942 .trackedDomains(trackedDomains, try passing(DataValidationService.validate(trackedDomains: trackedDomains)))
943 }
944
945 private static func workflowsPayload(_ workflows: [DomainWorkflow]) throws -> ImportPayload {
946 .workflows(workflows, try passing(DataValidationService.validate(workflows: workflows)))
947 }
948
949 /// `report`, unless it found errors, which fail the import.
950 private static func passing(_ report: DataValidationReport) throws -> DataValidationReport {
951 guard report.errors.isEmpty else {
952 throw DataPortabilityError.validationFailed(report.errors)
953 }
954 return report
976 } 955 }
977 956
978 private static func decodeLegacyBackup(from data: Data) throws -> DomainDigBackup { 957 private static func decodeLegacyBackup(from data: Data) throws -> DomainDigBackup {
DomainDig/BatchSweepSummaryView.swift +37 −19
@@ -28,25 +28,12 @@ struct BatchSweepSummaryView: View {
28 Toggle("Show unchanged domains", isOn: $showUnchangedDomains) 28 Toggle("Show unchanged domains", isOn: $showUnchangedDomains)
29 } 29 }
30 30
31 Section(visibleResults.isEmpty ? "Changed Domains" : "Results") { 31 BatchResultsSection(
32 if visibleResults.isEmpty { 32 viewModel: viewModel,
33 Text("No domains with changes or warnings") 33 results: visibleResults,
34 .font(.system(.caption, design: .monospaced)) 34 emptyTitle: "Changed Domains",
35 .foregroundStyle(Color(.appTextSecondary)) 35 emptyText: "No domains with changes or warnings"
36 } else { 36 )
37 ForEach(visibleResults) { result in
38 if let entry = viewModel.historyEntry(for: result) {
39 NavigationLink {
40 HistoryDetailView(viewModel: viewModel, entry: entry)
41 } label: {
42 BatchResultRowView(result: result)
43 }
44 } else {
45 BatchResultRowView(result: result)
46 }
47 }
48 }
49 }
50 } 37 }
51 .navigationTitle(summary.source == .watchlistRefresh ? "Sweep Summary" : "Batch Summary") 38 .navigationTitle(summary.source == .watchlistRefresh ? "Sweep Summary" : "Batch Summary")
52 } 39 }
@@ -64,3 +51,34 @@ struct BatchSweepSummaryView: View {
64 } 51 }
65 } 52 }
66} 53}
54
55/// A batch's results, each opening its history entry where one was saved.
56/// Titled `emptyTitle`, with `emptyText` under it, when nothing is shown.
57struct BatchResultsSection: View {
58 @Bindable var viewModel: DomainViewModel
59 let results: [BatchLookupResult]
60 let emptyTitle: String
61 let emptyText: String
62
63 var body: some View {
64 Section(results.isEmpty ? emptyTitle : "Results") {
65 if results.isEmpty {
66 Text(emptyText)
67 .font(.system(.caption, design: .monospaced))
68 .foregroundStyle(Color(.appTextSecondary))
69 } else {
70 ForEach(results) { result in
71 if let entry = viewModel.historyEntry(for: result) {
72 NavigationLink {
73 HistoryDetailView(viewModel: viewModel, entry: entry)
74 } label: {
75 BatchResultRowView(result: result)
76 }
77 } else {
78 BatchResultRowView(result: result)
79 }
80 }
81 }
82 }
83 }
84}
DomainDig/CloudSyncService.swift +17 −17
@@ -782,34 +782,34 @@ final class CloudSyncService {
782 _ lhs: [String: SyncedDomainNote], 782 _ lhs: [String: SyncedDomainNote],
783 _ rhs: [String: SyncedDomainNote] 783 _ rhs: [String: SyncedDomainNote]
784 ) -> (notesByDomain: [String: SyncedDomainNote], hadConflict: Bool) { 784 ) -> (notesByDomain: [String: SyncedDomainNote], hadConflict: Bool) {
785 var merged = lhs 785 let result = mergeLatest(lhs, rhs, updatedAt: \.updatedAt)
786 var hadConflict = false 786 return (result.merged, result.hadConflict)
787
788 for (domain, remoteNote) in rhs {
789 if let localNote = merged[domain], localNote != remoteNote {
790 hadConflict = true
791 merged[domain] = localNote.updatedAt >= remoteNote.updatedAt ? localNote : remoteNote
792 } else {
793 merged[domain] = remoteNote
794 }
795 }
796
797 return (merged, hadConflict)
798 } 787 }
799 788
800 private func mergeHistoryMetadata( 789 private func mergeHistoryMetadata(
801 _ lhs: [String: SyncedHistoryMetadata], 790 _ lhs: [String: SyncedHistoryMetadata],
802 _ rhs: [String: SyncedHistoryMetadata] 791 _ rhs: [String: SyncedHistoryMetadata]
803 ) -> (historyMetadataByDomain: [String: SyncedHistoryMetadata], hadConflict: Bool) { 792 ) -> (historyMetadataByDomain: [String: SyncedHistoryMetadata], hadConflict: Bool) {
793 let result = mergeLatest(lhs, rhs, updatedAt: \.updatedAt)
794 return (result.merged, result.hadConflict)
795 }
796
797 /// `rhs` merged over `lhs` by domain; where both differ, the newer wins
798 /// (the local one on a tie) and the merge reports a conflict.
799 private func mergeLatest<Value: Equatable>(
800 _ lhs: [String: Value],
801 _ rhs: [String: Value],
802 updatedAt: KeyPath<Value, Date>
803 ) -> (merged: [String: Value], hadConflict: Bool) {
804 var merged = lhs 804 var merged = lhs
805 var hadConflict = false 805 var hadConflict = false
806 806
807 for (domain, remoteMetadata) in rhs { 807 for (domain, remote) in rhs {
808 if let localMetadata = merged[domain], localMetadata != remoteMetadata { 808 if let local = merged[domain], local != remote {
809 hadConflict = true 809 hadConflict = true
810 merged[domain] = localMetadata.updatedAt >= remoteMetadata.updatedAt ? localMetadata : remoteMetadata 810 merged[domain] = local[keyPath: updatedAt] >= remote[keyPath: updatedAt] ? local : remote
811 } else { 811 } else {
812 merged[domain] = remoteMetadata 812 merged[domain] = remote
813 } 813 }
814 } 814 }
815 815
DomainDig/ContentView.swift +2 −52
@@ -566,32 +566,7 @@ struct ContentView: View {
566 .accessibilityValue(viewModel.isCurrentDomainSaved ? "Saved" : "Not saved") 566 .accessibilityValue(viewModel.isCurrentDomainSaved ? "Saved" : "Not saved")
567 .accessibilityAddTraits(viewModel.isCurrentDomainSaved ? .isSelected : []) 567 .accessibilityAddTraits(viewModel.isCurrentDomainSaved ? .isSelected : [])
568 Menu { 568 Menu {
569 Button("Export TXT") { 569 ExportFormatButtons(share: shareSingleResults)
570 shareSingleResults(format: .text)
571 }
572 if FeatureAccessService.hasAccess(to: .advancedExports) {
573 Button("Export CSV") {
574 shareSingleResults(format: .csv)
575 }
576 Button("Export JSON") {
577 shareSingleResults(format: .json)
578 }
579 Button("Export Markdown") {
580 shareSingleResults(format: .markdown)
581 }
582 Button("Export PDF") {
583 shareSingleResults(format: .pdf)
584 }
585 } else {
586 Button("CSV Export • Available in Pro") { /* Inert: disabled Pro upsell affordance. */ }
587 .disabled(true)
588 Button("JSON Export • Available in Pro") { /* Inert: disabled Pro upsell affordance. */ }
589 .disabled(true)
590 Button("Markdown Export • Available in Pro") { /* Inert: disabled Pro upsell affordance. */ }
591 .disabled(true)
592 Button("PDF Export • Available in Pro") { /* Inert: disabled Pro upsell affordance. */ }
593 .disabled(true)
594 }
595 } label: { 570 } label: {
596 Image(systemName: "square.and.arrow.up") 571 Image(systemName: "square.and.arrow.up")
597 .font(appDensity.font(.body, design: .default)) 572 .font(appDensity.font(.body, design: .default))
@@ -619,32 +594,7 @@ struct ContentView: View {
619 showingBatchWorkflowSheet = true 594 showingBatchWorkflowSheet = true
620 } 595 }
621 Divider() 596 Divider()
622 Button("Export Batch TXT") { 597 ExportFormatButtons(share: shareBatchResults, batch: true)
623 shareBatchResults(format: .text)
624 }
625 if FeatureAccessService.hasAccess(to: .advancedExports) {
626 Button("Export Batch CSV") {
627 shareBatchResults(format: .csv)
628 }
629 Button("Export Batch JSON") {
630 shareBatchResults(format: .json)
631 }
632 Button("Export Batch Markdown") {
633 shareBatchResults(format: .markdown)
634 }
635 Button("Export Batch PDF") {
636 shareBatchResults(format: .pdf)
637 }
638 } else {
639 Button("Batch CSV • Available in Pro") { /* Inert: disabled Pro upsell affordance. */ }
640 .disabled(true)
641 Button("Batch JSON • Available in Pro") { /* Inert: disabled Pro upsell affordance. */ }
642 .disabled(true)
643 Button("Batch Markdown • Available in Pro") { /* Inert: disabled Pro upsell affordance. */ }
644 .disabled(true)
645 Button("Batch PDF • Available in Pro") { /* Inert: disabled Pro upsell affordance. */ }
646 .disabled(true)
647 }
648 } label: { 598 } label: {
649 Label("Export", systemImage: "square.and.arrow.up") 599 Label("Export", systemImage: "square.and.arrow.up")
650 .font(appDensity.font(.caption)) 600 .font(appDensity.font(.caption))
DomainDig/DashboardView.swift +17 −14
@@ -84,13 +84,8 @@ struct DashboardView: View {
84 dashboardEmptyRow("No recent portfolio changes") 84 dashboardEmptyRow("No recent portfolio changes")
85 } else { 85 } else {
86 ForEach(viewModel.filteredPortfolioRecentActivity.prefix(8)) { item in 86 ForEach(viewModel.filteredPortfolioRecentActivity.prefix(8)) { item in
87 if let trackedDomain = viewModel.trackedDomain(withID: item.trackedDomainID) { 87 trackedDomainLink(item.trackedDomainID) {
88 NavigationLink { 88 PortfolioActivityRow(item: item)
89 TrackedDomainDetailView(viewModel: viewModel, trackedDomain: trackedDomain)
90 } label: {
91 PortfolioActivityRow(item: item)
92 }
93 .buttonStyle(.plain)
94 } 89 }
95 } 90 }
96 } 91 }
@@ -102,13 +97,8 @@ struct DashboardView: View {
102 dashboardEmptyRow("Nothing urgent right now") 97 dashboardEmptyRow("Nothing urgent right now")
103 } else { 98 } else {
104 ForEach(viewModel.filteredPortfolioAttentionRequired.prefix(8)) { item in 99 ForEach(viewModel.filteredPortfolioAttentionRequired.prefix(8)) { item in
105 if let trackedDomain = viewModel.trackedDomain(withID: item.trackedDomainID) { 100 trackedDomainLink(item.trackedDomainID) {
106 NavigationLink { 101 PortfolioAttentionRow(item: item)
107 TrackedDomainDetailView(viewModel: viewModel, trackedDomain: trackedDomain)
108 } label: {
109 PortfolioAttentionRow(item: item)
110 }
111 .buttonStyle(.plain)
112 } 102 }
113 } 103 }
114 } 104 }
@@ -271,6 +261,19 @@ struct DashboardView: View {
271 return AnyShapeStyle(Color(.appSurfaceElevated)) 261 return AnyShapeStyle(Color(.appSurfaceElevated))
272 } 262 }
273 263
264 /// `label`, opening the tracked domain's detail; nothing for a domain no longer tracked.
265 @ViewBuilder
266 private func trackedDomainLink<Label: View>(_ id: UUID, @ViewBuilder label: () -> Label) -> some View {
267 if let trackedDomain = viewModel.trackedDomain(withID: id) {
268 NavigationLink {
269 TrackedDomainDetailView(viewModel: viewModel, trackedDomain: trackedDomain)
270 } label: {
271 label()
272 }
273 .buttonStyle(.plain)
274 }
275 }
276
274 private func dashboardEmptyRow(_ message: String) -> some View { 277 private func dashboardEmptyRow(_ message: String) -> some View {
275 Text(message) 278 Text(message)
276 .font(appDensity.font(.caption)) 279 .font(appDensity.font(.caption))
DomainDig/DataAccessService.swift +13 −11
@@ -2,17 +2,19 @@ import Foundation
2 2
3enum DataAccessService { 3enum DataAccessService {
4 static func hasAccess(to capability: DataCapability) -> Bool { 4 static func hasAccess(to capability: DataCapability) -> Bool {
5 switch capability { 5 FeatureAccessService.hasAccess(to: capability.feature)
6 case .ownershipHistory: 6 }
7 return FeatureAccessService.hasAccess(to: .ownershipHistory) 7}
8 case .dnsHistory: 8
9 return FeatureAccessService.hasAccess(to: .dnsHistory) 9extension DataCapability {
10 case .extendedSubdomains: 10 /// The plan feature that unlocks this data.
11 return FeatureAccessService.hasAccess(to: .extendedSubdomains) 11 var feature: FeatureCapability {
12 case .domainPricing: 12 switch self {
13 return FeatureAccessService.hasAccess(to: .domainPricing) 13 case .ownershipHistory: .ownershipHistory
14 case .reputation: 14 case .dnsHistory: .dnsHistory
15 return FeatureAccessService.hasAccess(to: .reputation) 15 case .extendedSubdomains: .extendedSubdomains
16 case .domainPricing: .domainPricing
17 case .reputation: .reputation
16 } 18 }
17 } 19 }
18} 20}
DomainDig/DiffService.swift +3 −2
@@ -329,8 +329,9 @@ enum DiffService {
329 } 329 }
330 330
331 private static func dnsSection(from oldReport: DomainReport, to newReport: DomainReport) -> DiffSection { 331 private static func dnsSection(from oldReport: DomainReport, to newReport: DomainReport) -> DiffSection {
332 let oldSections = Dictionary(uniqueKeysWithValues: oldReport.dns.recordSections.map { ($0.recordType, $0) }) 332 // Imported reports are not guaranteed one section per record type.
333 let newSections = Dictionary(uniqueKeysWithValues: newReport.dns.recordSections.map { ($0.recordType, $0) }) 333 let oldSections = Dictionary(oldReport.dns.recordSections.map { ($0.recordType, $0) }) { first, _ in first }
334 let newSections = Dictionary(newReport.dns.recordSections.map { ($0.recordType, $0) }) { first, _ in first }
334 let recordTypes = Set(oldSections.keys).union(newSections.keys).sorted { $0.rawValue < $1.rawValue } 335 let recordTypes = Set(oldSections.keys).union(newSections.keys).sorted { $0.rawValue < $1.rawValue }
335 336
336 var items: [DiffItem] = [ 337 var items: [DiffItem] = [
DomainDig/DomainDig/AuditExporter.swift +54 −68
@@ -48,7 +48,21 @@ enum AuditExporter {
48 lines.append("") 48 lines.append("")
49 } 49 }
50 50
51 lines.append("## Findings Summary") 51 lines += findingsSummaryLines(session)
52 lines += keyRiskLines(session)
53 lines.append("## Checklist")
54 for item in session.checklist {
55 lines.append("- [\(item.isComplete ? "x" : " ")] \(item.title): \(item.detail)")
56 }
57 lines.append("")
58 lines += findingLines(session)
59 lines += evidenceLines(session.evidence)
60
61 return lines.joined(separator: "\n")
62 }
63
64 private static func findingsSummaryLines(_ session: AuditSession) -> [String] {
65 var lines = ["## Findings Summary"]
52 if session.findings.isEmpty { 66 if session.findings.isEmpty {
53 lines.append("No findings recorded.") 67 lines.append("No findings recorded.")
54 } else { 68 } else {
@@ -57,8 +71,11 @@ enum AuditExporter {
57 } 71 }
58 } 72 }
59 lines.append("") 73 lines.append("")
74 return lines
75 }
60 76
61 lines.append("## Key Risks") 77 private static func keyRiskLines(_ session: AuditSession) -> [String] {
78 var lines = ["## Key Risks"]
62 if session.keyRisks.isEmpty { 79 if session.keyRisks.isEmpty {
63 lines.append("No medium or high-severity risks recorded.") 80 lines.append("No medium or high-severity risks recorded.")
64 } else { 81 } else {
@@ -67,46 +84,46 @@ enum AuditExporter {
67 } 84 }
68 } 85 }
69 lines.append("") 86 lines.append("")
87 return lines
88 }
70 89
71 lines.append("## Checklist") 90 private static func findingLines(_ session: AuditSession) -> [String] {
72 for item in session.checklist { 91 var lines = ["## Findings"]
73 lines.append("- [\(item.isComplete ? "x" : " ")] \(item.title): \(item.detail)")
74 }
75 lines.append("")
76
77 lines.append("## Findings")
78 if session.findings.isEmpty { 92 if session.findings.isEmpty {
79 lines.append("No findings recorded.") 93 lines.append("No findings recorded.")
80 } else { 94 }
81 for finding in session.findings { 95 for finding in session.findings {
82 lines.append("### \(finding.title)") 96 lines.append("### \(finding.title)")
83 lines.append("- Severity: \(finding.severity.title)") 97 lines.append("- Severity: \(finding.severity.title)")
84 lines.append("- Status: \(finding.status.title)") 98 lines.append("- Status: \(finding.status.title)")
85 if !finding.checklistAreas.isEmpty { 99 if !finding.checklistAreas.isEmpty {
86 lines.append("- Checklist Areas: \(finding.checklistAreas.map(\.title).joined(separator: ", "))") 100 lines.append("- Checklist Areas: \(finding.checklistAreas.map(\.title).joined(separator: ", "))")
87 }
88 lines.append("- Summary: \(finding.summary)")
89 if !finding.evidenceReferences.isEmpty {
90 lines.append("- Evidence: \(finding.evidenceReferences.joined(separator: " | "))")
91 }
92 if !finding.notes.isEmpty {
93 lines.append("- Notes: \(finding.notes)")
94 }
95 lines.append("")
96 } 101 }
102 lines.append("- Summary: \(finding.summary)")
103 if !finding.evidenceReferences.isEmpty {
104 lines.append("- Evidence: \(finding.evidenceReferences.joined(separator: " | "))")
105 }
106 if !finding.notes.isEmpty {
107 lines.append("- Notes: \(finding.notes)")
108 }
109 lines.append("")
97 } 110 }
111 return lines
112 }
98 113
99 lines.append("## Evidence Snapshot") 114 private static func evidenceLines(_ evidence: AuditEvidenceSnapshot) -> [String] {
100 lines.append("- Availability: \(availabilityTitle(session.evidence.report.availability))") 115 let report = evidence.report
101 lines.append("- Risk Score: \(session.evidence.report.riskAssessment.score) (\(session.evidence.report.riskAssessment.level.title))") 116 return [
102 lines.append("- TLS Status: \(session.evidence.report.web.tlsStatus)") 117 "## Evidence Snapshot",
103 lines.append("- Final URL: \(session.evidence.report.web.finalURL ?? "Unavailable")") 118 "- Availability: \(availabilityTitle(report.availability))",
104 lines.append("- Primary IP: \(session.evidence.report.dns.primaryIP ?? "Unavailable")") 119 "- Risk Score: \(report.riskAssessment.score) (\(report.riskAssessment.level.title))",
105 lines.append("- Reachability: \(session.evidence.report.network.reachabilitySummary)") 120 "- TLS Status: \(report.web.tlsStatus)",
106 lines.append("- Ownership: \(session.evidence.report.ownership?.registrar ?? "Unavailable")") 121 "- Final URL: \(report.web.finalURL ?? "Unavailable")",
107 lines.append("- Historical Context Snapshots: \(session.evidence.historicalContext.count)") 122 "- Primary IP: \(report.dns.primaryIP ?? "Unavailable")",
108 123 "- Reachability: \(report.network.reachabilitySummary)",
109 return lines.joined(separator: "\n") 124 "- Ownership: \(report.ownership?.registrar ?? "Unavailable")",
125 "- Historical Context Snapshots: \(evidence.historicalContext.count)",
126 ]
110 } 127 }
111 128
112 private static func availabilityTitle(_ status: DomainAvailabilityStatus) -> String { 129 private static func availabilityTitle(_ status: DomainAvailabilityStatus) -> String {
@@ -121,37 +138,6 @@ enum AuditExporter {
121 } 138 }
122 139
123 private static func pdfData(for session: AuditSession) throws -> Data { 140 private static func pdfData(for session: AuditSession) throws -> Data {
124 let markdown = markdown(for: session) 141 DomainReportExporter.pdfData(fromMarkdown: markdown(for: session))
125 #if canImport(UIKit)
126 let renderer = UIGraphicsPDFRenderer(bounds: CGRect(x: 0, y: 0, width: 612, height: 792))
127 return renderer.pdfData { context in
128 let lines = markdown.components(separatedBy: .newlines)
129 let paragraphStyle = NSMutableParagraphStyle()
130 paragraphStyle.lineBreakMode = .byWordWrapping
131 let attributes: [NSAttributedString.Key: Any] = [
132 .font: UIFont.monospacedSystemFont(ofSize: 11, weight: .regular),
133 .paragraphStyle: paragraphStyle
134 ]
135
136 var yOffset: CGFloat = 36
137 context.beginPage()
138
139 for line in lines {
140 if yOffset > 744 {
141 context.beginPage()
142 yOffset = 36
143 }
144
145 let renderedLine = NSString(string: line.isEmpty ? " " : line)
146 renderedLine.draw(
147 in: CGRect(x: 36, y: yOffset, width: 540, height: 22),
148 withAttributes: attributes
149 )
150 yOffset += 16
151 }
152 }
153 #else
154 return Data(markdown.utf8)
155 #endif
156 } 142 }
157} 143}
DomainDig/DomainInsightEngine.swift +117 −104
@@ -176,158 +176,171 @@ enum DomainInsightEngine {
176 tlsAssessment: TLSSummaryAssessment, 176 tlsAssessment: TLSSummaryAssessment,
177 subdomainGroups: [SubdomainGroup] 177 subdomainGroups: [SubdomainGroup]
178 ) -> DomainRiskAssessment { 178 ) -> DomainRiskAssessment {
179 var tally = RiskTally()
180 scoreAvailability(snapshot, into: &tally)
181 scoreDNS(snapshot, patterns: dnsPatterns, into: &tally)
182 scoreTLS(snapshot, assessment: tlsAssessment, into: &tally)
183 scoreRedirects(snapshot, into: &tally)
184 scoreEmail(snapshot, assessment: emailAssessment, into: &tally)
185 scorePorts(snapshot, into: &tally)
186 scoreSubdomains(snapshot, groups: subdomainGroups, into: &tally)
187 scoreGeolocation(snapshot, into: &tally)
188 // Compares against the score so far, so it runs after the snapshot's own factors.
189 if let previousSnapshot {
190 let delta = tally.score - analyze(snapshot: previousSnapshot).riskAssessment.score
191 if delta >= 15 {
192 tally.add(4, "Observed risk has increased materially since the previous snapshot", .negative)
193 }
194 }
195 scoreReputation(snapshot, into: &tally)
196
197 let clampedScore = min(max(tally.score, 0), 100)
198 let level: RiskLevel
199 switch clampedScore {
200 case 0..<35:
201 level = .low
202 case 35..<65:
203 level = .medium
204 default:
205 level = .high
206 }
207
208 return DomainRiskAssessment(score: clampedScore, level: level, factors: tally.factors)
209 }
210
211 /// A risk score in progress, from a baseline of 18, and the factors behind it.
212 private struct RiskTally {
179 var score = 18 213 var score = 18
180 var factors: [RiskFactor] = [] 214 var factors: [RiskFactor] = []
181 215
216 mutating func add(_ points: Int, _ description: String, _ impact: RiskImpact) {
217 score += points
218 factors.append(RiskFactor(description: description, impact: impact))
219 }
220 }
221
222 private static func scoreAvailability(_ snapshot: LookupSnapshot, into tally: inout RiskTally) {
182 switch snapshot.availabilityResult?.status ?? .unknown { 223 switch snapshot.availabilityResult?.status ?? .unknown {
183 case .available: 224 case .available:
184 score -= 12 225 tally.add(-12, "Domain appears available rather than actively deployed", .positive)
185 factors.append(.init(description: "Domain appears available rather than actively deployed", impact: .positive))
186 case .unknown: 226 case .unknown:
187 score += 8 227 tally.add(8, "Ownership and availability could not be confirmed", .negative)
188 factors.append(.init(description: "Ownership and availability could not be confirmed", impact: .negative))
189 case .registered: 228 case .registered:
190 if !snapshot.dnsSections.isEmpty || snapshot.sslInfo != nil || !snapshot.redirectChain.isEmpty { 229 if !snapshot.dnsSections.isEmpty || snapshot.sslInfo != nil || !snapshot.redirectChain.isEmpty {
191 score += 6 230 tally.add(6, "Registered domain exposes active infrastructure", .negative)
192 factors.append(.init(description: "Registered domain exposes active infrastructure", impact: .negative))
193 } else { 231 } else {
194 factors.append(.init(description: "Registered domain with limited active surface detected", impact: .neutral)) 232 tally.add(0, "Registered domain with limited active surface detected", .neutral)
195 } 233 }
196 } 234 }
235 }
197 236
237 private static func scoreDNS(_ snapshot: LookupSnapshot, patterns: DNSPatternSummary, into tally: inout RiskTally) {
198 let recordTypes = snapshot.dnsSections.filter { !$0.records.isEmpty || !$0.wildcardRecords.isEmpty }.count 238 let recordTypes = snapshot.dnsSections.filter { !$0.records.isEmpty || !$0.wildcardRecords.isEmpty }.count
199 if recordTypes >= 5 { 239 if recordTypes >= 5 {
200 score += 8 240 tally.add(8, "DNS configuration is broad across multiple record types", .negative)
201 factors.append(.init(description: "DNS configuration is broad across multiple record types", impact: .negative))
202 } 241 }
203 if dnsPatterns.wildcardDetected { 242 if patterns.wildcardDetected {
204 score += 12 243 tally.add(12, "Wildcard DNS is enabled", .negative)
205 factors.append(.init(description: "Wildcard DNS is enabled", impact: .negative))
206 } 244 }
207 if let firstPattern = dnsPatterns.patterns.first { 245 if let firstPattern = patterns.patterns.first {
208 factors.append(.init(description: firstPattern, impact: .neutral)) 246 tally.add(0, firstPattern, .neutral)
209 } 247 }
248 }
210 249
211 switch tlsAssessment.grade { 250 private static func scoreTLS(_ snapshot: LookupSnapshot, assessment: TLSSummaryAssessment, into tally: inout RiskTally) {
251 switch assessment.grade {
212 case .a: 252 case .a:
213 score -= 8 253 tally.add(-8, "TLS configuration looks current and stable", .positive)
214 factors.append(.init(description: "TLS configuration looks current and stable", impact: .positive))
215 case .b: 254 case .b:
216 score -= 3 255 tally.add(-3, "TLS is valid with minor concerns", .positive)
217 factors.append(.init(description: "TLS is valid with minor concerns", impact: .positive))
218 case .c: 256 case .c:
219 score += 10 257 tally.add(10, "TLS configuration has visible weaknesses", .negative)
220 factors.append(.init(description: "TLS configuration has visible weaknesses", impact: .negative))
221 case .f: 258 case .f:
222 score += 22 259 tally.add(22, "TLS is missing, invalid, or near failure", .negative)
223 factors.append(.init(description: "TLS is missing, invalid, or near failure", impact: .negative))
224 } 260 }
225
226 if let daysUntilExpiry = snapshot.sslInfo?.daysUntilExpiry, daysUntilExpiry <= 14 { 261 if let daysUntilExpiry = snapshot.sslInfo?.daysUntilExpiry, daysUntilExpiry <= 14 {
227 score += 10 262 tally.add(10, "Certificate expires within 14 days", .negative)
228 factors.append(.init(description: "Certificate expires within 14 days", impact: .negative))
229 } 263 }
264 }
230 265
266 private static func scoreRedirects(_ snapshot: LookupSnapshot, into tally: inout RiskTally) {
231 if snapshot.redirectChain.count >= 3 { 267 if snapshot.redirectChain.count >= 3 {
232 score += 8 268 tally.add(8, "Redirect chain is longer than expected", .negative)
233 factors.append(.init(description: "Redirect chain is longer than expected", impact: .negative))
234 } 269 }
235
236 if redirectLooksSensitive(snapshot.redirectChain.last?.url) { 270 if redirectLooksSensitive(snapshot.redirectChain.last?.url) {
237 score += 6 271 tally.add(6, "Redirect target looks like an auth or account gateway", .negative)
238 factors.append(.init(description: "Redirect target looks like an auth or account gateway", impact: .negative)) 272 }
239 } 273 }
240 274
241 if let emailAssessment { 275 private static func scoreEmail(
242 switch emailAssessment.grade { 276 _ snapshot: LookupSnapshot,
243 case .a: 277 assessment: EmailSecurityAssessment?,
244 score -= 10 278 into tally: inout RiskTally
245 factors.append(.init(description: "Email protections are strong and aligned", impact: .positive)) 279 ) {
246 case .b: 280 guard let assessment else {
247 score -= 4 281 if hasMXRecords(snapshot) {
248 factors.append(.init(description: "Email protections are present with minor gaps", impact: .positive)) 282 tally.add(14, "Mail is configured without enough email security evidence", .negative)
249 case .c:
250 score += 8
251 factors.append(.init(description: "Email protections are partial", impact: .negative))
252 case .f:
253 score += 18
254 factors.append(.init(description: "Email security protections are weak or absent", impact: .negative))
255 } 283 }
256 } else if hasMXRecords(snapshot) { 284 return
257 score += 14
258 factors.append(.init(description: "Mail is configured without enough email security evidence", impact: .negative))
259 } 285 }
286 switch assessment.grade {
287 case .a:
288 tally.add(-10, "Email protections are strong and aligned", .positive)
289 case .b:
290 tally.add(-4, "Email protections are present with minor gaps", .positive)
291 case .c:
292 tally.add(8, "Email protections are partial", .negative)
293 case .f:
294 tally.add(18, "Email security protections are weak or absent", .negative)
295 }
296 }
260 297
298 private static func scorePorts(_ snapshot: LookupSnapshot, into tally: inout RiskTally) {
261 let openPorts = snapshot.portScanResults.filter(\.open).map(\.port) 299 let openPorts = snapshot.portScanResults.filter(\.open).map(\.port)
262 let sensitivePorts: Set<UInt16> = [21, 22, 23, 25, 3389, 5900] 300 let sensitivePorts: Set<UInt16> = [21, 22, 23, 25, 3389, 5900]
263 let exposedSensitivePorts = openPorts.filter { sensitivePorts.contains($0) } 301 let exposedSensitivePorts = openPorts.filter { sensitivePorts.contains($0) }
264 if !exposedSensitivePorts.isEmpty { 302 if !exposedSensitivePorts.isEmpty {
265 score += min(18, exposedSensitivePorts.count * 6) 303 tally.add(min(18, exposedSensitivePorts.count * 6), "Sensitive management or mail ports are exposed", .negative)
266 factors.append(.init(description: "Sensitive management or mail ports are exposed", impact: .negative))
267 } else if Set(openPorts) == Set([80, 443]) { 304 } else if Set(openPorts) == Set([80, 443]) {
268 factors.append(.init(description: "Exposure is limited to standard web ports", impact: .positive)) 305 tally.add(0, "Exposure is limited to standard web ports", .positive)
269 } else if openPorts.count >= 3 { 306 } else if openPorts.count >= 3 {
270 score += 8 307 tally.add(8, "Multiple open services expand the attack surface", .negative)
271 factors.append(.init(description: "Multiple open services expand the attack surface", impact: .negative))
272 } 308 }
309 }
273 310
274 if !subdomainGroups.isEmpty { 311 private static func scoreSubdomains(_ snapshot: LookupSnapshot, groups: [SubdomainGroup], into tally: inout RiskTally) {
275 let labels = Set(subdomainGroups.map(\.label)) 312 guard !groups.isEmpty else { return }
276 if labels.contains("dev") || labels.contains("staging") { 313 let labels = Set(groups.map(\.label))
277 score += 8 314 if labels.contains("dev") || labels.contains("staging") {
278 factors.append(.init(description: "Development or staging subdomains are discoverable", impact: .negative)) 315 tally.add(8, "Development or staging subdomains are discoverable", .negative)
279 }
280 if labels.contains("admin") {
281 score += 10
282 factors.append(.init(description: "Administrative subdomains are discoverable", impact: .negative))
283 }
284 if snapshot.subdomains.count >= 8 {
285 score += 6
286 factors.append(.init(description: "Large passive subdomain footprint detected", impact: .negative))
287 }
288 } 316 }
317 if labels.contains("admin") {
318 tally.add(10, "Administrative subdomains are discoverable", .negative)
319 }
320 if snapshot.subdomains.count >= 8 {
321 tally.add(6, "Large passive subdomain footprint detected", .negative)
322 }
323 }
289 324
325 private static func scoreGeolocation(_ snapshot: LookupSnapshot, into tally: inout RiskTally) {
290 if snapshot.ipGeolocation == nil, 326 if snapshot.ipGeolocation == nil,
291 snapshot.availabilityResult?.status == .registered, 327 snapshot.availabilityResult?.status == .registered,
292 snapshot.dnsSections.contains(where: { $0.recordType == .A && !$0.records.isEmpty }) { 328 snapshot.dnsSections.contains(where: { $0.recordType == .A && !$0.records.isEmpty }) {
293 score += 4 329 tally.add(4, "Active host could not be geolocated", .neutral)
294 factors.append(.init(description: "Active host could not be geolocated", impact: .neutral))
295 }
296
297 if let previousSnapshot {
298 let previousAnalysis = analyze(snapshot: previousSnapshot)
299 let delta = score - previousAnalysis.riskAssessment.score
300 if delta >= 15 {
301 score += 4
302 factors.append(.init(description: "Observed risk has increased materially since the previous snapshot", impact: .negative))
303 }
304 }
305
306 if let reputation = snapshot.reputation {
307 switch reputation.status {
308 case .listed:
309 score += 25
310 let sourceList = reputation.listedSources.isEmpty ? "" : " (\(reputation.listedSources.joined(separator: ", ")))"
311 factors.append(.init(description: "Domain is flagged by a configured reputation source\(sourceList)", impact: .negative))
312 case .clean:
313 factors.append(.init(description: "Domain is clean against the configured reputation source", impact: .positive))
314 case .unknown:
315 break
316 }
317 } 330 }
331 }
318 332
319 let clampedScore = min(max(score, 0), 100) 333 private static func scoreReputation(_ snapshot: LookupSnapshot, into tally: inout RiskTally) {
320 let level: RiskLevel 334 guard let reputation = snapshot.reputation else { return }
321 switch clampedScore { 335 switch reputation.status {
322 case 0..<35: 336 case .listed:
323 level = .low 337 let sourceList = reputation.listedSources.isEmpty ? "" : " (\(reputation.listedSources.joined(separator: ", ")))"
324 case 35..<65: 338 tally.add(25, "Domain is flagged by a configured reputation source\(sourceList)", .negative)
325 level = .medium 339 case .clean:
326 default: 340 tally.add(0, "Domain is clean against the configured reputation source", .positive)
327 level = .high 341 case .unknown:
342 break
328 } 343 }
329
330 return DomainRiskAssessment(score: clampedScore, level: level, factors: factors)
331 } 344 }
332 345
333 private static func insights( 346 private static func insights(
DomainDig/DomainMonitoringService.swift +67 −157
@@ -187,16 +187,11 @@ final class DomainMonitoringScheduler {
187 private func handleAppRefresh(task: BGAppRefreshTask) { 187 private func handleAppRefresh(task: BGAppRefreshTask) {
188 _ = syncSchedule() 188 _ = syncSchedule()
189 189
190 let worker = Task { 190 task.run {
191 let outcome = await DomainMonitoringService.shared.performMonitoring( 191 await DomainMonitoringService.shared.performMonitoring(
192 trigger: .background, 192 trigger: .background,
193 requireEnabledSetting: true 193 requireEnabledSetting: true
194 ) 194 ).success
195 task.setTaskCompleted(success: outcome.success)
196 }
197
198 task.expirationHandler = {
199 worker.cancel()
200 } 195 }
201 } 196 }
202#endif 197#endif
@@ -290,11 +285,11 @@ final class DomainMonitoringService {
290 domain: trackedDomain.domain, 285 domain: trackedDomain.domain,
291 previousSnapshot: previousSnapshot 286 previousSnapshot: previousSnapshot
292 ) 287 )
293 let snapshot = Self.resolvedSnapshotAfterFallback(inspectedSnapshot, previousSnapshot: previousSnapshot) 288 let snapshot = inspectedSnapshot.resolvedAfterFallback(to: previousSnapshot)
294 // When the fallback fires, `snapshot` *is* `previousSnapshot`, so 289 // When the fallback fires, `snapshot` *is* `previousSnapshot`, so
295 // every comparison below is old-against-old and would otherwise 290 // every comparison below is old-against-old and would otherwise
296 // report "No meaningful changes" for a domain we never reached. 291 // report "No meaningful changes" for a domain we never reached.
297 let unreachableReason = (previousSnapshot != nil && Self.shouldFallbackToSnapshot(inspectedSnapshot)) 292 let unreachableReason = (previousSnapshot != nil && inspectedSnapshot.needsFallback)
298 ? Self.firstErrorMessage(in: inspectedSnapshot) 293 ? Self.firstErrorMessage(in: inspectedSnapshot)
299 : nil 294 : nil
300 let savedEntry: HistoryEntry? 295 let savedEntry: HistoryEntry?
@@ -602,38 +597,13 @@ final class DomainMonitoringService {
602 597
603 if settings.alertsEnabled, 598 if settings.alertsEnabled,
604 alertDescriptor.severity >= settings.alertFilter.minimumSeverity { 599 alertDescriptor.severity >= settings.alertFilter.minimumSeverity {
605 let pendingAlert = MonitoringPendingAlert( 600 alertsTriggered += await raiseAlert(
606 detectedAt: now, 601 alertDescriptor,
607 message: alertDescriptor.message, 602 for: &updated,
608 severity: alertDescriptor.severity, 603 state: &state,
609 changeHash: alertDescriptor.changeHash 604 deferred: isQuiet || !notificationsAuthorized,
605 now: now
610 ) 606 )
611
612 if isQuiet || !notificationsAuthorized {
613 updated.pendingMonitoringAlerts = deduplicatedPendingAlerts(
614 updated.pendingMonitoringAlerts + [pendingAlert]
615 )
616 } else {
617 let pendingAlerts = deduplicatedPendingAlerts(
618 updated.pendingMonitoringAlerts + [pendingAlert]
619 )
620 if pendingAlerts.count > 1 {
621 await LocalNotificationService.shared.notifyMonitoringSummary(
622 domain: trackedDomain.domain,
623 alerts: pendingAlerts
624 )
625 } else {
626 await LocalNotificationService.shared.notifyMonitoringAlert(
627 domain: trackedDomain.domain,
628 message: alertDescriptor.message,
629 severity: alertDescriptor.severity
630 )
631 }
632 alertsTriggered += 1
633 updated.pendingMonitoringAlerts = []
634 updated.lastAlertAt = now
635 state.lastAlertDate = now
636 }
637 } 607 }
638 } 608 }
639 } else { 609 } else {
@@ -668,6 +638,45 @@ final class DomainMonitoringService {
668 return (updated, alertsTriggered) 638 return (updated, alertsTriggered)
669 } 639 }
670 640
641 /// Queues the alert while notifications are deferred; otherwise notifies, folding in
642 /// any queued alerts, and returns the number of notifications sent.
643 private func raiseAlert(
644 _ alertDescriptor: MonitoringAlertDescriptor,
645 for updated: inout TrackedDomain,
646 state: inout MonitoringState,
647 deferred: Bool,
648 now: Date
649 ) async -> Int {
650 let pendingAlert = MonitoringPendingAlert(
651 detectedAt: now,
652 message: alertDescriptor.message,
653 severity: alertDescriptor.severity,
654 changeHash: alertDescriptor.changeHash
655 )
656 let pendingAlerts = deduplicatedPendingAlerts(updated.pendingMonitoringAlerts + [pendingAlert])
657 if deferred {
658 updated.pendingMonitoringAlerts = pendingAlerts
659 return 0
660 }
661
662 if pendingAlerts.count > 1 {
663 await LocalNotificationService.shared.notifyMonitoringSummary(
664 domain: updated.domain,
665 alerts: pendingAlerts
666 )
667 } else {
668 await LocalNotificationService.shared.notifyMonitoringAlert(
669 domain: updated.domain,
670 message: alertDescriptor.message,
671 severity: alertDescriptor.severity
672 )
673 }
674 updated.pendingMonitoringAlerts = []
675 updated.lastAlertAt = now
676 state.lastAlertDate = now
677 return 1
678 }
679
671 private func deduplicatedPendingAlerts(_ alerts: [MonitoringPendingAlert]) -> [MonitoringPendingAlert] { 680 private func deduplicatedPendingAlerts(_ alerts: [MonitoringPendingAlert]) -> [MonitoringPendingAlert] {
672 var uniqueByHash: [String: MonitoringPendingAlert] = [:] 681 var uniqueByHash: [String: MonitoringPendingAlert] = [:]
673 for alert in alerts { 682 for alert in alerts {
@@ -844,95 +853,8 @@ final class DomainMonitoringService {
844 } 853 }
845 } 854 }
846 855
847 private static func resolvedSnapshotAfterFallback(
848 _ snapshot: LookupSnapshot,
849 previousSnapshot: LookupSnapshot?
850 ) -> LookupSnapshot {
851 guard shouldFallbackToSnapshot(snapshot), let previousSnapshot else {
852 return snapshot
853 }
854
855 return LookupSnapshot(
856 historyEntryID: previousSnapshot.historyEntryID,
857 domain: previousSnapshot.domain,
858 timestamp: previousSnapshot.timestamp,
859 trackedDomainID: previousSnapshot.trackedDomainID,
860 note: previousSnapshot.note,
861 appVersion: previousSnapshot.appVersion,
862 resolverDisplayName: previousSnapshot.resolverDisplayName,
863 resolverURLString: previousSnapshot.resolverURLString,
864 dataSources: previousSnapshot.dataSources,
865 provenanceBySection: previousSnapshot.provenanceBySection,
866 availabilityConfidence: previousSnapshot.availabilityConfidence,
867 ownershipConfidence: previousSnapshot.ownershipConfidence,
868 subdomainConfidence: previousSnapshot.subdomainConfidence,
869 emailSecurityConfidence: previousSnapshot.emailSecurityConfidence,
870 geolocationConfidence: previousSnapshot.geolocationConfidence,
871 errorDetails: previousSnapshot.errorDetails,
872 isPartialSnapshot: previousSnapshot.isPartialSnapshot,
873 validationIssues: previousSnapshot.validationIssues,
874 totalLookupDurationMs: previousSnapshot.totalLookupDurationMs,
875 snapshotIndex: previousSnapshot.snapshotIndex,
876 previousSnapshotID: previousSnapshot.previousSnapshotID,
877 changeCount: previousSnapshot.changeCount,
878 severitySummary: previousSnapshot.severitySummary,
879 dnsSections: previousSnapshot.dnsSections,
880 dnsError: previousSnapshot.dnsError,
881 availabilityResult: previousSnapshot.availabilityResult,
882 suggestions: previousSnapshot.suggestions,
883 sslInfo: previousSnapshot.sslInfo,
884 sslError: previousSnapshot.sslError,
885 hstsPreloaded: previousSnapshot.hstsPreloaded,
886 httpHeaders: previousSnapshot.httpHeaders,
887 httpSecurityGrade: previousSnapshot.httpSecurityGrade,
888 httpStatusCode: previousSnapshot.httpStatusCode,
889 httpResponseTimeMs: previousSnapshot.httpResponseTimeMs,
890 httpProtocol: previousSnapshot.httpProtocol,
891 http3Advertised: previousSnapshot.http3Advertised,
892 httpHeadersError: previousSnapshot.httpHeadersError,
893 reachabilityResults: previousSnapshot.reachabilityResults,
894 reachabilityError: previousSnapshot.reachabilityError,
895 ipGeolocation: previousSnapshot.ipGeolocation,
896 ipGeolocationError: previousSnapshot.ipGeolocationError,
897 emailSecurity: previousSnapshot.emailSecurity,
898 emailSecurityError: previousSnapshot.emailSecurityError,
899 ownership: previousSnapshot.ownership,
900 ownershipError: previousSnapshot.ownershipError,
901 ownershipHistory: previousSnapshot.ownershipHistory,
902 ownershipHistoryError: previousSnapshot.ownershipHistoryError,
903 inferredProvider: previousSnapshot.inferredProvider,
904 priorProviders: previousSnapshot.priorProviders,
905 domainClassification: previousSnapshot.domainClassification,
906 ownershipTransitions: previousSnapshot.ownershipTransitions,
907 hostingTransitions: previousSnapshot.hostingTransitions,
908 subdomainHistory: previousSnapshot.subdomainHistory,
909 riskSignals: previousSnapshot.riskSignals,
910 intelligenceTimeline: previousSnapshot.intelligenceTimeline,
911 ptrRecord: previousSnapshot.ptrRecord,
912 ptrError: previousSnapshot.ptrError,
913 redirectChain: previousSnapshot.redirectChain,
914 redirectChainError: previousSnapshot.redirectChainError,
915 subdomains: previousSnapshot.subdomains,
916 subdomainsError: previousSnapshot.subdomainsError,
917 extendedSubdomains: previousSnapshot.extendedSubdomains,
918 extendedSubdomainsError: previousSnapshot.extendedSubdomainsError,
919 dnsHistory: previousSnapshot.dnsHistory,
920 dnsHistoryError: previousSnapshot.dnsHistoryError,
921 domainPricing: previousSnapshot.domainPricing,
922 domainPricingError: previousSnapshot.domainPricingError,
923 reputation: previousSnapshot.reputation,
924 reputationError: previousSnapshot.reputationError,
925 portScanResults: previousSnapshot.portScanResults,
926 portScanError: previousSnapshot.portScanError,
927 changeSummary: previousSnapshot.changeSummary,
928 resultSource: .snapshot,
929 cachedSections: [],
930 statusMessage: "Last known result • \(previousSnapshot.timestamp.formatted(date: .abbreviated, time: .shortened))"
931 )
932 }
933
934 /// First reported error on a snapshot, used to explain a fallback. Mirrors 856 /// First reported error on a snapshot, used to explain a fallback. Mirrors
935 /// the ordering `shouldFallbackToSnapshot` inspects. 857 /// the ordering `LookupSnapshot.needsFallback` inspects.
936 private static func firstErrorMessage(in snapshot: LookupSnapshot) -> String { 858 private static func firstErrorMessage(in snapshot: LookupSnapshot) -> String {
937 [ 859 [
938 snapshot.dnsError, 860 snapshot.dnsError,
@@ -947,34 +869,6 @@ final class DomainMonitoringService {
947 .first ?? "The lookup could not reach the domain." 869 .first ?? "The lookup could not reach the domain."
948 } 870 }
949 871
950 private static func shouldFallbackToSnapshot(_ snapshot: LookupSnapshot) -> Bool {
951 let candidateMessages = [
952 snapshot.dnsError,
953 snapshot.httpHeadersError,
954 snapshot.sslError,
955 snapshot.ownershipError,
956 snapshot.subdomainsError,
957 snapshot.redirectChainError,
958 snapshot.ipGeolocationError
959 ]
960 .compactMap { $0?.lowercased() }
961
962 guard !candidateMessages.isEmpty else { return false }
963 let connectivityFailure = candidateMessages.allSatisfy { message in
964 message.hasPrefix("network error:")
965 || message.hasPrefix("timeout:")
966 || message.hasPrefix("rate limit:")
967 }
968
969 let hasMaterialData = !snapshot.dnsSections.isEmpty
970 || !snapshot.httpHeaders.isEmpty
971 || snapshot.sslInfo != nil
972 || snapshot.ownership != nil
973 || !snapshot.subdomains.isEmpty
974
975 return connectivityFailure && !hasMaterialData
976 }
977
978 private static func primaryIPAddress(from snapshot: LookupSnapshot) -> String? { 872 private static func primaryIPAddress(from snapshot: LookupSnapshot) -> String? {
979 snapshot.dnsSections.first(where: { $0.recordType == .A })?.records.first?.value 873 snapshot.dnsSections.first(where: { $0.recordType == .A })?.records.first?.value
980 } 874 }
@@ -1004,3 +898,19 @@ final class DomainMonitoringService {
1004 return snapshot.emailSecurityError 898 return snapshot.emailSecurityError
1005 } 899 }
1006} 900}
901
902#if canImport(BackgroundTasks)
903extension BGAppRefreshTask {
904 /// Runs `work` for this refresh, completing the task with whether it succeeded, and cancels it
905 /// when the system ends the task early.
906 @MainActor
907 func run(_ work: @escaping @MainActor () async -> Bool) {
908 let worker = Task {
909 setTaskCompleted(success: await work())
910 }
911 expirationHandler = {
912 worker.cancel()
913 }
914 }
915}
916#endif
DomainDig/DomainViewModel.swift +326 −460
@@ -1282,101 +1282,73 @@ final class DomainViewModel {
1282 } 1282 }
1283 1283
1284 func loadOwnershipHistory() async { 1284 func loadOwnershipHistory() async {
1285 guard !searchedDomain.isEmpty else { return } 1285 await loadLookup(.ownershipHistory, into: \.ownershipHistory, loading: \.ownershipHistoryLoading, error: \.ownershipHistoryError,
1286 guard DataAccessService.hasAccess(to: .ownershipHistory) else { 1286 fallback: "Ownership history unavailable") {
1287 upgradePrompt = FeatureAccessService.upgradePrompt(for: .ownershipHistory) 1287 await ExternalDataService.shared.ownershipHistory(
1288 return 1288 domain: searchedDomain,
1289 currentOwnership: ownershipResult,
1290 historyEntries: history
1291 ).value
1289 } 1292 }
1290 guard ownershipHistory.isEmpty else { return }
1291
1292 ownershipHistoryLoading = true
1293 ownershipHistoryError = nil
1294
1295 let outcome = await ExternalDataService.shared.ownershipHistory(
1296 domain: searchedDomain,
1297 currentOwnership: ownershipResult,
1298 historyEntries: history
1299 )
1300
1301 switch outcome.value {
1302 case let .success(events):
1303 ownershipHistory = events
1304 ownershipHistoryError = nil
1305 case let .empty(message):
1306 ownershipHistory = []
1307 ownershipHistoryError = message
1308 case let .error(message):
1309 ownershipHistory = []
1310 ownershipHistoryError = conciseExternalMessage(message, fallback: "Ownership history unavailable")
1311 }
1312
1313 ownershipHistoryLoading = false
1314 _ = saveHistoryEntry(replaceLatest: true)
1315 } 1293 }
1316 1294
1317 func loadDNSHistory() async { 1295 func loadDNSHistory() async {
1318 guard !searchedDomain.isEmpty else { return } 1296 await loadLookup(.dnsHistory, into: \.dnsHistory, loading: \.dnsHistoryLoading, error: \.dnsHistoryError,
1319 guard DataAccessService.hasAccess(to: .dnsHistory) else { 1297 fallback: "DNS history unavailable") {
1320 upgradePrompt = FeatureAccessService.upgradePrompt(for: .dnsHistory) 1298 await ExternalDataService.shared.dnsHistory(
1321 return 1299 domain: searchedDomain,
1322 } 1300 dnsSections: dnsSections,
1323 guard dnsHistory.isEmpty else { return } 1301 historyEntries: history
1324 1302 ).value
1325 dnsHistoryLoading = true
1326 dnsHistoryError = nil
1327
1328 let outcome = await ExternalDataService.shared.dnsHistory(
1329 domain: searchedDomain,
1330 dnsSections: dnsSections,
1331 historyEntries: history
1332 )
1333
1334 switch outcome.value {
1335 case let .success(events):
1336 dnsHistory = events
1337 dnsHistoryError = nil
1338 case let .empty(message):
1339 dnsHistory = []
1340 dnsHistoryError = message
1341 case let .error(message):
1342 dnsHistory = []
1343 dnsHistoryError = conciseExternalMessage(message, fallback: "DNS history unavailable")
1344 } 1303 }
1345
1346 dnsHistoryLoading = false
1347 _ = saveHistoryEntry(replaceLatest: true)
1348 } 1304 }
1349 1305
1350 func loadExtendedSubdomains() async { 1306 func loadExtendedSubdomains() async {
1307 await loadLookup(.extendedSubdomains, into: \.extendedSubdomains, loading: \.extendedSubdomainsLoading, error: \.extendedSubdomainsError,
1308 fallback: "Extended subdomains unavailable") {
1309 await ExternalDataService.shared.extendedSubdomains(
1310 domain: searchedDomain,
1311 existing: subdomains
1312 ).value
1313 }
1314 }
1315
1316 /// Loads `capability`'s lookup for the searched domain into `items`, unless it is loaded
1317 /// already, or shows the upgrade prompt when the plan doesn't include it.
1318 private func loadLookup<Item>(
1319 _ capability: DataCapability,
1320 into items: ReferenceWritableKeyPath<DomainViewModel, [Item]>,
1321 loading: ReferenceWritableKeyPath<DomainViewModel, Bool>,
1322 error: ReferenceWritableKeyPath<DomainViewModel, String?>,
1323 fallback: String,
1324 fetch: () async -> ServiceResult<[Item]>
1325 ) async {
1351 guard !searchedDomain.isEmpty else { return } 1326 guard !searchedDomain.isEmpty else { return }
1352 guard DataAccessService.hasAccess(to: .extendedSubdomains) else { 1327 guard DataAccessService.hasAccess(to: capability) else {
1353 upgradePrompt = FeatureAccessService.upgradePrompt(for: .extendedSubdomains) 1328 upgradePrompt = FeatureAccessService.upgradePrompt(for: capability.feature)
1354 return 1329 return
1355 } 1330 }
1356 guard extendedSubdomains.isEmpty else { return } 1331 guard self[keyPath: items].isEmpty else { return }
1357 1332
1358 extendedSubdomainsLoading = true 1333 self[keyPath: loading] = true
1359 extendedSubdomainsError = nil 1334 self[keyPath: error] = nil
1360 1335
1361 let outcome = await ExternalDataService.shared.extendedSubdomains( 1336 (self[keyPath: items], self[keyPath: error]) = found(await fetch(), fallback: fallback)
1362 domain: searchedDomain,
1363 existing: subdomains
1364 )
1365 1337
1366 switch outcome.value { 1338 self[keyPath: loading] = false
1367 case let .success(results): 1339 _ = saveHistoryEntry(replaceLatest: true)
1368 extendedSubdomains = results 1340 }
1369 extendedSubdomainsError = nil 1341
1342 /// What a lookup found, and the message to show when it found nothing or failed.
1343 private func found<Item>(_ result: ServiceResult<[Item]>, fallback: String) -> ([Item], String?) {
1344 switch result {
1345 case let .success(items):
1346 return (items, nil)
1370 case let .empty(message): 1347 case let .empty(message):
1371 extendedSubdomains = [] 1348 return ([], message)
1372 extendedSubdomainsError = message
1373 case let .error(message): 1349 case let .error(message):
1374 extendedSubdomains = [] 1350 return ([], conciseExternalMessage(message, fallback: fallback))
1375 extendedSubdomainsError = conciseExternalMessage(message, fallback: "Extended subdomains unavailable")
1376 } 1351 }
1377
1378 extendedSubdomainsLoading = false
1379 _ = saveHistoryEntry(replaceLatest: true)
1380 } 1352 }
1381 1353
1382 func refreshUsageCredits() async { 1354 func refreshUsageCredits() async {
@@ -1395,7 +1367,7 @@ final class DomainViewModel {
1395 DomainDebugLog.debug("DomainViewModel.performLookup inspectionReturned domain=\(domain)") 1367 DomainDebugLog.debug("DomainViewModel.performLookup inspectionReturned domain=\(domain)")
1396 guard !Task.isCancelled, isCurrentLookup(lookupID) else { return nil } 1368 guard !Task.isCancelled, isCurrentLookup(lookupID) else { return nil }
1397 1369
1398 let snapshot = Self.resolvedSnapshotAfterFallback(inspectedSnapshot, previousSnapshot: previous) 1370 let snapshot = inspectedSnapshot.resolvedAfterFallback(to: previous)
1399 let applyStartedAt = DomainDebugLog.signpostStart("DomainViewModel.applySnapshot", domain: domain) 1371 let applyStartedAt = DomainDebugLog.signpostStart("DomainViewModel.applySnapshot", domain: domain)
1400 applySnapshot(snapshot) 1372 applySnapshot(snapshot)
1401 DomainDebugLog.signpostEnd("DomainViewModel.applySnapshot", start: applyStartedAt, domain: domain) 1373 DomainDebugLog.signpostEnd("DomainViewModel.applySnapshot", start: applyStartedAt, domain: domain)
@@ -1506,119 +1478,6 @@ final class DomainViewModel {
1506 customPortScanLoading = false 1478 customPortScanLoading = false
1507 } 1479 }
1508 1480
1509 private static func resolvedSnapshotAfterFallback(
1510 _ snapshot: LookupSnapshot,
1511 previousSnapshot: LookupSnapshot?
1512 ) -> LookupSnapshot {
1513 guard shouldFallbackToSnapshot(snapshot), let previousSnapshot else {
1514 return snapshot
1515 }
1516
1517 return LookupSnapshot(
1518 historyEntryID: previousSnapshot.historyEntryID,
1519 domain: previousSnapshot.domain,
1520 timestamp: previousSnapshot.timestamp,
1521 trackedDomainID: previousSnapshot.trackedDomainID,
1522 note: previousSnapshot.note,
1523 appVersion: previousSnapshot.appVersion,
1524 resolverDisplayName: previousSnapshot.resolverDisplayName,
1525 resolverURLString: previousSnapshot.resolverURLString,
1526 dataSources: previousSnapshot.dataSources,
1527 provenanceBySection: previousSnapshot.provenanceBySection,
1528 availabilityConfidence: previousSnapshot.availabilityConfidence,
1529 ownershipConfidence: previousSnapshot.ownershipConfidence,
1530 subdomainConfidence: previousSnapshot.subdomainConfidence,
1531 emailSecurityConfidence: previousSnapshot.emailSecurityConfidence,
1532 geolocationConfidence: previousSnapshot.geolocationConfidence,
1533 errorDetails: previousSnapshot.errorDetails,
1534 isPartialSnapshot: previousSnapshot.isPartialSnapshot,
1535 validationIssues: previousSnapshot.validationIssues,
1536 totalLookupDurationMs: previousSnapshot.totalLookupDurationMs,
1537 snapshotIndex: previousSnapshot.snapshotIndex,
1538 previousSnapshotID: previousSnapshot.previousSnapshotID,
1539 changeCount: previousSnapshot.changeCount,
1540 severitySummary: previousSnapshot.severitySummary,
1541 dnsSections: previousSnapshot.dnsSections,
1542 dnsError: previousSnapshot.dnsError,
1543 availabilityResult: previousSnapshot.availabilityResult,
1544 suggestions: previousSnapshot.suggestions,
1545 sslInfo: previousSnapshot.sslInfo,
1546 sslError: previousSnapshot.sslError,
1547 hstsPreloaded: previousSnapshot.hstsPreloaded,
1548 httpHeaders: previousSnapshot.httpHeaders,
1549 httpSecurityGrade: previousSnapshot.httpSecurityGrade,
1550 httpStatusCode: previousSnapshot.httpStatusCode,
1551 httpResponseTimeMs: previousSnapshot.httpResponseTimeMs,
1552 httpProtocol: previousSnapshot.httpProtocol,
1553 http3Advertised: previousSnapshot.http3Advertised,
1554 httpHeadersError: previousSnapshot.httpHeadersError,
1555 reachabilityResults: previousSnapshot.reachabilityResults,
1556 reachabilityError: previousSnapshot.reachabilityError,
1557 ipGeolocation: previousSnapshot.ipGeolocation,
1558 ipGeolocationError: previousSnapshot.ipGeolocationError,
1559 emailSecurity: previousSnapshot.emailSecurity,
1560 emailSecurityError: previousSnapshot.emailSecurityError,
1561 ownership: previousSnapshot.ownership,
1562 ownershipError: previousSnapshot.ownershipError,
1563 ownershipHistory: previousSnapshot.ownershipHistory,
1564 ownershipHistoryError: previousSnapshot.ownershipHistoryError,
1565 inferredProvider: previousSnapshot.inferredProvider,
1566 priorProviders: previousSnapshot.priorProviders,
1567 domainClassification: previousSnapshot.domainClassification,
1568 ownershipTransitions: previousSnapshot.ownershipTransitions,
1569 hostingTransitions: previousSnapshot.hostingTransitions,
1570 subdomainHistory: previousSnapshot.subdomainHistory,
1571 riskSignals: previousSnapshot.riskSignals,
1572 intelligenceTimeline: previousSnapshot.intelligenceTimeline,
1573 ptrRecord: previousSnapshot.ptrRecord,
1574 ptrError: previousSnapshot.ptrError,
1575 redirectChain: previousSnapshot.redirectChain,
1576 redirectChainError: previousSnapshot.redirectChainError,
1577 subdomains: previousSnapshot.subdomains,
1578 subdomainsError: previousSnapshot.subdomainsError,
1579 extendedSubdomains: previousSnapshot.extendedSubdomains,
1580 extendedSubdomainsError: previousSnapshot.extendedSubdomainsError,
1581 dnsHistory: previousSnapshot.dnsHistory,
1582 dnsHistoryError: previousSnapshot.dnsHistoryError,
1583 domainPricing: previousSnapshot.domainPricing,
1584 domainPricingError: previousSnapshot.domainPricingError,
1585 reputation: previousSnapshot.reputation,
1586 reputationError: previousSnapshot.reputationError,
1587 portScanResults: previousSnapshot.portScanResults,
1588 portScanError: previousSnapshot.portScanError,
1589 changeSummary: previousSnapshot.changeSummary,
1590 resultSource: .snapshot,
1591 cachedSections: [],
1592 statusMessage: "Last known result • \(previousSnapshot.timestamp.formatted(date: .abbreviated, time: .shortened))"
1593 )
1594 }
1595
1596 private static func shouldFallbackToSnapshot(_ snapshot: LookupSnapshot) -> Bool {
1597 let candidateMessages = [
1598 snapshot.dnsError,
1599 snapshot.httpHeadersError,
1600 snapshot.sslError,
1601 snapshot.ownershipError,
1602 snapshot.subdomainsError,
1603 snapshot.redirectChainError,
1604 snapshot.ipGeolocationError
1605 ]
1606 .compactMap { $0?.lowercased() }
1607
1608 guard !candidateMessages.isEmpty else { return false }
1609 let failedDueToConnectivity = candidateMessages.allSatisfy { message in
1610 message.hasPrefix("network error:") || message.hasPrefix("timeout:") || message.hasPrefix("rate limit:")
1611 }
1612
1613 let hasMaterialData = !snapshot.dnsSections.isEmpty
1614 || !snapshot.httpHeaders.isEmpty
1615 || snapshot.sslInfo != nil
1616 || snapshot.ownership != nil
1617 || !snapshot.subdomains.isEmpty
1618
1619 return failedDueToConnectivity && !hasMaterialData
1620 }
1621
1622 private func runDNS(domain: String, lookupID: UUID) async { 1481 private func runDNS(domain: String, lookupID: UUID) async {
1623 let result = await DNSLookupService.lookupAll(domain: domain) 1482 let result = await DNSLookupService.lookupAll(domain: domain)
1624 guard !Task.isCancelled, isCurrentLookup(lookupID) else { return } 1483 guard !Task.isCancelled, isCurrentLookup(lookupID) else { return }
@@ -1774,7 +1633,7 @@ final class DomainViewModel {
1774 let result = await PortScanService.scanAll(domain: domain) 1633 let result = await PortScanService.scanAll(domain: domain)
1775 switch result { 1634 switch result {
1776 case let .success(results): 1635 case let .success(results):
1777 let enrichedResults = await enrichOpenPortBanners(in: results, domain: domain) 1636 let enrichedResults = await PortScanService.withBanners(results, host: domain)
1778 guard !Task.isCancelled, isCurrentLookup(lookupID) else { return } 1637 guard !Task.isCancelled, isCurrentLookup(lookupID) else { return }
1779 portScanResults = enrichedResults 1638 portScanResults = enrichedResults
1780 portScanError = nil 1639 portScanError = nil
@@ -1833,36 +1692,7 @@ final class DomainViewModel {
1833 let inspectionService = DomainInspectionService() 1692 let inspectionService = DomainInspectionService()
1834 let snapshot = await inspectionService.inspectSnapshot(domain: domain, previousSnapshot: previousSnapshot) 1693 let snapshot = await inspectionService.inspectSnapshot(domain: domain, previousSnapshot: previousSnapshot)
1835 guard !Task.isCancelled else { return nil } 1694 guard !Task.isCancelled else { return nil }
1836 return BatchLookupPayload(snapshot: resolvedSnapshotAfterFallback(snapshot, previousSnapshot: previousSnapshot)) 1695 return BatchLookupPayload(snapshot: snapshot.resolvedAfterFallback(to: previousSnapshot))
1837 }
1838
1839 private static func enrichOpenPortBanners(_ results: [PortScanResult], domain: String) async -> [PortScanResult] {
1840 let banners = await withTaskGroup(of: (UInt16, String?).self, returning: [UInt16: String].self) { group in
1841 for result in results where result.open {
1842 group.addTask {
1843 let banner = await PortScanService.grabBanner(host: domain, port: result.port)
1844 return (result.port, banner)
1845 }
1846 }
1847
1848 var collected: [UInt16: String] = [:]
1849 for await (port, banner) in group {
1850 if let banner {
1851 collected[port] = banner
1852 }
1853 }
1854 return collected
1855 }
1856
1857 return results.map { result in
1858 var updated = result
1859 updated.banner = banners[result.port]
1860 return updated
1861 }
1862 }
1863
1864 private func enrichOpenPortBanners(in results: [PortScanResult], domain: String) async -> [PortScanResult] {
1865 await Self.enrichOpenPortBanners(results, domain: domain)
1866 } 1696 }
1867 1697
1868 @discardableResult 1698 @discardableResult
@@ -2840,32 +2670,7 @@ final class DomainViewModel {
2840 private func buildAttentionQueue(from domainStates: [PortfolioDomainStatus]) -> [PortfolioAttentionItem] { 2670 private func buildAttentionQueue(from domainStates: [PortfolioDomainStatus]) -> [PortfolioAttentionItem] {
2841 domainStates.compactMap { state in 2671 domainStates.compactMap { state in
2842 guard state.health != .healthy else { return nil } 2672 guard state.health != .healthy else { return nil }
2843 let reason: String 2673 let (reason, timestamp) = Self.attentionReason(for: state)
2844 let timestamp: Date
2845
2846 if state.isUnreachable {
2847 reason = "Endpoint is unreachable"
2848 timestamp = state.lastMonitoringFailure ?? state.trackedDomain.updatedAt
2849 } else if state.certificateExpiryState == .critical {
2850 reason = "Certificate is expiring in under 14 days"
2851 timestamp = state.lastChangeDate ?? state.trackedDomain.updatedAt
2852 } else if state.certificateExpiryState == .warning {
2853 reason = "Certificate expires within 30 days"
2854 timestamp = state.lastChangeDate ?? state.trackedDomain.updatedAt
2855 } else if state.recentFailureCount >= 2 || state.instabilityScore >= 70 {
2856 reason = "Repeated instability detected"
2857 timestamp = state.lastMonitoringFailure ?? state.trackedDomain.updatedAt
2858 } else if state.recentDNSChange {
2859 reason = "DNS changed recently"
2860 timestamp = state.lastChangeDate ?? state.trackedDomain.updatedAt
2861 } else if state.recentCriticalChange {
2862 reason = "Recent critical change detected"
2863 timestamp = state.lastChangeDate ?? state.trackedDomain.updatedAt
2864 } else {
2865 reason = "Needs attention"
2866 timestamp = state.trackedDomain.updatedAt
2867 }
2868
2869 return PortfolioAttentionItem( 2674 return PortfolioAttentionItem(
2870 id: "\(state.trackedDomain.id.uuidString)|\(reason)", 2675 id: "\(state.trackedDomain.id.uuidString)|\(reason)",
2871 trackedDomainID: state.trackedDomain.id, 2676 trackedDomainID: state.trackedDomain.id,
@@ -2883,6 +2688,32 @@ final class DomainViewModel {
2883 } 2688 }
2884 } 2689 }
2885 2690
2691 /// Why an unhealthy domain needs attention, most urgent cause first, and
2692 /// when that cause was last seen.
2693 private static func attentionReason(for state: PortfolioDomainStatus) -> (reason: String, timestamp: Date) {
2694 let changedAt = state.lastChangeDate ?? state.trackedDomain.updatedAt
2695 let failedAt = state.lastMonitoringFailure ?? state.trackedDomain.updatedAt
2696 if state.isUnreachable {
2697 return ("Endpoint is unreachable", failedAt)
2698 }
2699 if state.certificateExpiryState == .critical {
2700 return ("Certificate is expiring in under 14 days", changedAt)
2701 }
2702 if state.certificateExpiryState == .warning {
2703 return ("Certificate expires within 30 days", changedAt)
2704 }
2705 if state.recentFailureCount >= 2 || state.instabilityScore >= 70 {
2706 return ("Repeated instability detected", failedAt)
2707 }
2708 if state.recentDNSChange {
2709 return ("DNS changed recently", changedAt)
2710 }
2711 if state.recentCriticalChange {
2712 return ("Recent critical change detected", changedAt)
2713 }
2714 return ("Needs attention", state.trackedDomain.updatedAt)
2715 }
2716
2886 private func buildPortfolioGroups(from domainStates: [PortfolioDomainStatus]) -> [PortfolioGroup] { 2717 private func buildPortfolioGroups(from domainStates: [PortfolioDomainStatus]) -> [PortfolioGroup] {
2887 Dictionary(grouping: domainStates, by: \.apexDomain) 2718 Dictionary(grouping: domainStates, by: \.apexDomain)
2888 .map { apexDomain, domains in 2719 .map { apexDomain, domains in
@@ -3329,40 +3160,10 @@ final class DomainViewModel {
3329 ) 3160 )
3330 } 3161 }
3331 if let pricing = snapshot.domainPricing { 3162 if let pricing = snapshot.domainPricing {
3332 rows.append( 3163 rows += pricingRows(pricing)
3333 InfoRowViewData(
3334 label: "External Price",
3335 value: pricing.estimatedPrice ?? "Unavailable",
3336 tone: .secondary
3337 )
3338 )
3339 if let premiumIndicator = pricing.premiumIndicator {
3340 rows.append(
3341 InfoRowViewData(
3342 label: "Premium",
3343 value: premiumIndicator ? "Yes" : "No",
3344 tone: premiumIndicator ? .warning : .secondary
3345 )
3346 )
3347 }
3348 if let resaleSignal = pricing.resaleSignal {
3349 rows.append(InfoRowViewData(label: "Resale", value: resaleSignal, tone: .secondary))
3350 }
3351 if let auctionSignal = pricing.auctionSignal {
3352 rows.append(InfoRowViewData(label: "Auction", value: auctionSignal, tone: .secondary))
3353 }
3354 } 3164 }
3355 if let reputation = snapshot.reputation { 3165 if let reputation = snapshot.reputation {
3356 let tone: ResultTone 3166 rows.append(reputationRow(reputation))
3357 switch reputation.status {
3358 case .clean: tone = .success
3359 case .listed: tone = .failure
3360 case .unknown: tone = .secondary
3361 }
3362 let value = reputation.status == .listed && !reputation.listedSources.isEmpty
3363 ? "\(reputation.status.title) (\(reputation.listedSources.joined(separator: ", ")))"
3364 : reputation.status.title
3365 rows.append(InfoRowViewData(label: "Reputation", value: value, tone: tone))
3366 } 3167 }
3367 if let certificateStatus = certificateBadgeLabel(from: snapshot) { 3168 if let certificateStatus = certificateBadgeLabel(from: snapshot) {
3368 rows.insert( 3169 rows.insert(
@@ -3377,6 +3178,39 @@ final class DomainViewModel {
3377 return rows 3178 return rows
3378 } 3179 }
3379 3180
3181 private static func pricingRows(_ pricing: DomainPricingInsight) -> [InfoRowViewData] {
3182 var rows = [InfoRowViewData(label: "External Price", value: pricing.estimatedPrice ?? "Unavailable", tone: .secondary)]
3183 if let premiumIndicator = pricing.premiumIndicator {
3184 rows.append(
3185 InfoRowViewData(
3186 label: "Premium",
3187 value: premiumIndicator ? "Yes" : "No",
3188 tone: premiumIndicator ? .warning : .secondary
3189 )
3190 )
3191 }
3192 if let resaleSignal = pricing.resaleSignal {
3193 rows.append(InfoRowViewData(label: "Resale", value: resaleSignal, tone: .secondary))
3194 }
3195 if let auctionSignal = pricing.auctionSignal {
3196 rows.append(InfoRowViewData(label: "Auction", value: auctionSignal, tone: .secondary))
3197 }
3198 return rows
3199 }
3200
3201 private static func reputationRow(_ reputation: DomainReputationResult) -> InfoRowViewData {
3202 let tone: ResultTone
3203 switch reputation.status {
3204 case .clean: tone = .success
3205 case .listed: tone = .failure
3206 case .unknown: tone = .secondary
3207 }
3208 let value = reputation.status == .listed && !reputation.listedSources.isEmpty
3209 ? "\(reputation.status.title) (\(reputation.listedSources.joined(separator: ", ")))"
3210 : reputation.status.title
3211 return InfoRowViewData(label: "Reputation", value: value, tone: tone)
3212 }
3213
3380 static func suggestionRows(from snapshot: LookupSnapshot) -> [DomainSuggestionViewData] { 3214 static func suggestionRows(from snapshot: LookupSnapshot) -> [DomainSuggestionViewData] {
3381 snapshot.suggestions.map { 3215 snapshot.suggestions.map {
3382 DomainSuggestionViewData( 3216 DomainSuggestionViewData(
@@ -3647,229 +3481,261 @@ final class DomainViewModel {
3647 lines.append("Tracking Note: \(note)") 3481 lines.append("Tracking Note: \(note)")
3648 } 3482 }
3649 3483
3650 func appendSection(_ title: String, body: () -> Void) { 3484 func appendSection(_ title: String, _ body: [String]) {
3651 lines.append("") 3485 lines.append("")
3652 lines.append(title) 3486 lines.append(title)
3653 lines.append(String(repeating: "-", count: title.count)) 3487 lines.append(String(repeating: "-", count: title.count))
3654 body() 3488 lines += body
3655 } 3489 }
3656 3490
3657 appendSection("Summary") { 3491 appendSection("Summary", exportSummaryLines(snapshot, changeSummary: changeSummary, exportDateFormatter: exportDateFormatter))
3658 for item in summaryFields(from: snapshot) { 3492 appendSection("Tracking", exportTrackingLines(trackedDomain, exportDateFormatter: exportDateFormatter))
3659 lines.append(" \(item.label): \(item.value)") 3493 appendSection("Diff Summary", exportDiffSummaryLines(diffSections))
3660 } 3494 appendSection("Domain", exportDomainLines(snapshot))
3661 if let changeSummary { 3495 appendSection("Ownership", exportOwnershipLines(snapshot))
3662 lines.append(" Change Summary: \(changeSummary.message)") 3496 appendSection("Subdomains", exportSubdomainsLines(snapshot))
3663 lines.append(" Severity: \(changeSummary.severity.title)") 3497 appendSection("DNS", exportDnsLines(snapshot))
3664 lines.append(" Changed Sections: \(changeSummary.changedSections.isEmpty ? "None" : changeSummary.changedSections.joined(separator: ", "))") 3498 appendSection("Web", exportWebLines(snapshot))
3665 lines.append(" Compared At: \(exportDateFormatter.string(from: changeSummary.generatedAt))") 3499 appendSection("Email", exportEmailLines(snapshot))
3666 } 3500 appendSection("Network", exportNetworkLines(snapshot))
3667 }
3668 3501
3669 appendSection("Tracking") { 3502 return lines.joined(separator: "\n")
3670 if let trackedDomain { 3503 }
3671 lines.append(" Pinned: \(trackedDomain.isPinned ? "Yes" : "No")") 3504
3672 lines.append(" Last Refresh: \(exportDateFormatter.string(from: trackedDomain.updatedAt))") 3505 private static func exportSummaryLines(
3673 lines.append(" Last Known Availability: \(availabilityLabel(trackedDomain.lastKnownAvailability))") 3506 _ snapshot: LookupSnapshot,
3674 if let note = trackedDomain.note?.nilIfEmpty { 3507 changeSummary: DomainChangeSummary?,
3675 lines.append(" Note: \(note)") 3508 exportDateFormatter: DateFormatter
3676 } 3509 ) -> [String] {
3677 } else { 3510 var lines: [String] = []
3678 lines.append(" This domain is not currently tracked.") 3511 for item in summaryFields(from: snapshot) {
3512 lines.append(" \(item.label): \(item.value)")
3513 }
3514 if let changeSummary {
3515 lines.append(" Change Summary: \(changeSummary.message)")
3516 lines.append(" Severity: \(changeSummary.severity.title)")
3517 lines.append(" Changed Sections: \(changeSummary.changedSections.isEmpty ? "None" : changeSummary.changedSections.joined(separator: ", "))")
3518 lines.append(" Compared At: \(exportDateFormatter.string(from: changeSummary.generatedAt))")
3519 }
3520 return lines
3521 }
3522
3523 private static func exportTrackingLines(_ trackedDomain: TrackedDomain?, exportDateFormatter: DateFormatter) -> [String] {
3524 var lines: [String] = []
3525 if let trackedDomain {
3526 lines.append(" Pinned: \(trackedDomain.isPinned ? "Yes" : "No")")
3527 lines.append(" Last Refresh: \(exportDateFormatter.string(from: trackedDomain.updatedAt))")
3528 lines.append(" Last Known Availability: \(availabilityLabel(trackedDomain.lastKnownAvailability))")
3529 if let note = trackedDomain.note?.nilIfEmpty {
3530 lines.append(" Note: \(note)")
3679 } 3531 }
3532 } else {
3533 lines.append(" This domain is not currently tracked.")
3680 } 3534 }
3535 return lines
3536 }
3681 3537
3682 appendSection("Diff Summary") { 3538 private static func exportDiffSummaryLines(_ diffSections: [DomainDiffSection]) -> [String] {
3683 if diffSections.isEmpty { 3539 var lines: [String] = []
3684 lines.append(" No comparison available") 3540 if diffSections.isEmpty {
3685 } else { 3541 lines.append(" No comparison available")
3686 for section in diffSections where section.items.contains(where: { $0.changeType != .unchanged }) { 3542 } else {
3687 lines.append(" \(section.title)") 3543 for section in diffSections where section.items.contains(where: { $0.changeType != .unchanged }) {
3688 for item in section.items where item.changeType != .unchanged { 3544 lines.append(" \(section.title)")
3689 lines.append(" [\(item.changeType.rawValue.capitalized)] \(item.label): \(item.oldValue ?? "None") -> \(item.newValue ?? "None")") 3545 for item in section.items where item.changeType != .unchanged {
3690 } 3546 lines.append(" [\(item.changeType.rawValue.capitalized)] \(item.label): \(item.oldValue ?? "None") -> \(item.newValue ?? "None")")
3691 } 3547 }
3692 } 3548 }
3693 } 3549 }
3550 return lines
3551 }
3694 3552
3695 appendSection("Domain") { 3553 private static func exportDomainLines(_ snapshot: LookupSnapshot) -> [String] {
3696 for row in domainRows(from: snapshot) { 3554 var lines: [String] = []
3697 lines.append(" \(row.label): \(row.value)") 3555 for row in domainRows(from: snapshot) {
3698 } 3556 lines.append(" \(row.label): \(row.value)")
3699 if snapshot.suggestions.isEmpty { 3557 }
3700 lines.append(" Suggestions: None") 3558 if snapshot.suggestions.isEmpty {
3701 } else { 3559 lines.append(" Suggestions: None")
3702 lines.append(" Suggestions:") 3560 } else {
3703 for suggestion in snapshot.suggestions { 3561 lines.append(" Suggestions:")
3704 lines.append(" \(suggestion.domain): \(availabilityLabel(suggestion.status))") 3562 for suggestion in snapshot.suggestions {
3705 } 3563 lines.append(" \(suggestion.domain): \(availabilityLabel(suggestion.status))")
3706 } 3564 }
3707 } 3565 }
3566 return lines
3567 }
3708 3568
3709 appendSection("Ownership") { 3569 private static func exportOwnershipLines(_ snapshot: LookupSnapshot) -> [String] {
3710 for row in ownershipRows(from: snapshot) { 3570 var lines: [String] = []
3711 lines.append(" \(row.label): \(row.value)") 3571 for row in ownershipRows(from: snapshot) {
3712 } 3572 lines.append(" \(row.label): \(row.value)")
3713 if let ownershipError = snapshot.ownershipError, snapshot.ownership == nil {
3714 lines.append(" Source: \(ownershipError)")
3715 }
3716 if !DataAccessService.hasAccess(to: .ownershipHistory) {
3717 lines.append(" Ownership history (coming soon)")
3718 }
3719 } 3573 }
3574 if let ownershipError = snapshot.ownershipError, snapshot.ownership == nil {
3575 lines.append(" Source: \(ownershipError)")
3576 }
3577 if !DataAccessService.hasAccess(to: .ownershipHistory) {
3578 lines.append(" Ownership history (coming soon)")
3579 }
3580 return lines
3581 }
3720 3582
3721 appendSection("Subdomains") { 3583 private static func exportSubdomainsLines(_ snapshot: LookupSnapshot) -> [String] {
3722 lines.append(" Count: \(snapshot.subdomains.count)") 3584 var lines: [String] = []
3723 if snapshot.subdomains.isEmpty { 3585 lines.append(" Count: \(snapshot.subdomains.count)")
3724 lines.append(" \(snapshot.subdomainsError ?? "No passive subdomains found")") 3586 if snapshot.subdomains.isEmpty {
3725 } else { 3587 lines.append(" \(snapshot.subdomainsError ?? "No passive subdomains found")")
3726 for subdomain in subdomainRows(from: snapshot) { 3588 } else {
3727 let marker = subdomain.isInteresting ? " [interesting]" : "" 3589 for subdomain in subdomainRows(from: snapshot) {
3728 lines.append(" \(subdomain.hostname)\(marker)") 3590 let marker = subdomain.isInteresting ? " [interesting]" : ""
3729 } 3591 lines.append(" \(subdomain.hostname)\(marker)")
3730 }
3731 if !DataAccessService.hasAccess(to: .extendedSubdomains) {
3732 lines.append(" Extended subdomain discovery (Pro+)")
3733 } 3592 }
3734 } 3593 }
3594 if !DataAccessService.hasAccess(to: .extendedSubdomains) {
3595 lines.append(" Extended subdomain discovery (Pro+)")
3596 }
3597 return lines
3598 }
3735 3599
3736 appendSection("DNS") { 3600 private static func exportDnsLines(_ snapshot: LookupSnapshot) -> [String] {
3737 if let dnsError = snapshot.dnsError { 3601 var lines: [String] = []
3738 lines.append(" Error: \(dnsError)") 3602 if let dnsError = snapshot.dnsError {
3739 } 3603 lines.append(" Error: \(dnsError)")
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 }
3763 } 3604 }
3605 if let dnssecLabel = dnssecLabel(from: snapshot) {
3606 lines.append(" \(dnssecLabel)")
3607 }
3608 for section in dnsRows(from: snapshot) {
3609 lines += exportDNSSectionLines(section)
3610 }
3611 if let ptrRecord = snapshot.ptrRecord {
3612 lines.append(" PTR: \(ptrRecord)")
3613 } else if let ptrError = snapshot.ptrError {
3614 lines.append(" PTR Error: \(ptrError)")
3615 }
3616 return lines
3617 }
3764 3618
3765 appendSection("Web") { 3619 private static func exportDNSSectionLines(_ section: DNSRecordSectionViewData) -> [String] {
3766 if let sslError = snapshot.sslError { 3620 var lines = [" \(section.title)"]
3767 lines.append(" TLS Error: \(sslError)") 3621 if let message = section.message {
3768 } else { 3622 lines.append(" \(message.isError ? "Error" : "Info"): \(message.text)")
3769 for row in webCertificateRows(from: snapshot) { 3623 }
3770 lines.append(" \(row.label): \(row.value)") 3624 for row in section.rows {
3771 } 3625 lines.append(" \(row.value) (\(row.label))")
3626 }
3627 if let wildcardTitle = section.wildcardTitle {
3628 lines.append(" \(wildcardTitle)")
3629 for row in section.wildcardRows {
3630 lines.append(" \(row.value) (\(row.label))")
3772 } 3631 }
3632 }
3633 return lines
3634 }
3773 3635
3774 if let httpHeadersError = snapshot.httpHeadersError { 3636 private static func exportResponseLines(_ snapshot: LookupSnapshot) -> [String] {
3775 lines.append(" Headers Error: \(httpHeadersError)") 3637 if let httpHeadersError = snapshot.httpHeadersError {
3776 } else { 3638 return [" Headers Error: \(httpHeadersError)"]
3777 for row in webResponseRows(from: snapshot) { 3639 }
3778 lines.append(" \(row.label): \(row.value)") 3640 var lines = webResponseRows(from: snapshot).map { " \($0.label): \($0.value)" }
3779 } 3641 if snapshot.httpHeaders.isEmpty {
3780 if snapshot.httpHeaders.isEmpty { 3642 lines.append(" Headers: No headers returned")
3781 lines.append(" Headers: No headers returned") 3643 } else {
3782 } else { 3644 lines.append(" Headers:")
3783 lines.append(" Headers:") 3645 for header in snapshot.httpHeaders {
3784 for header in snapshot.httpHeaders { 3646 lines.append(" \(header.name): \(header.value)")
3785 lines.append(" \(header.name): \(header.value)")
3786 }
3787 }
3788 } 3647 }
3648 }
3649 return lines
3650 }
3789 3651
3790 if let redirectChainError = snapshot.redirectChainError { 3652 private static func exportWebLines(_ snapshot: LookupSnapshot) -> [String] {
3791 lines.append(" Redirect Error: \(redirectChainError)") 3653 var lines: [String] = []
3792 } else if snapshot.redirectChain.isEmpty { 3654 if let sslError = snapshot.sslError {
3793 lines.append(" Redirects: No redirect data available") 3655 lines.append(" TLS Error: \(sslError)")
3794 } else { 3656 } else {
3795 lines.append(" Redirects:") 3657 for row in webCertificateRows(from: snapshot) {
3796 for hop in redirectRows(from: snapshot) { 3658 lines.append(" \(row.label): \(row.value)")
3797 lines.append(" \(hop.stepLabel). \(hop.statusCode) \(hop.url)\(hop.isFinal ? " (final)" : "")")
3798 }
3799 } 3659 }
3800 } 3660 }
3661 lines += exportResponseLines(snapshot)
3801 3662
3802 appendSection("Email") { 3663 if let redirectChainError = snapshot.redirectChainError {
3803 if let emailSecurityError = snapshot.emailSecurityError { 3664 lines.append(" Redirect Error: \(redirectChainError)")
3804 lines.append(" Error: \(emailSecurityError)") 3665 } else if snapshot.redirectChain.isEmpty {
3805 } else if emailRows(from: snapshot).isEmpty { 3666 lines.append(" Redirects: No redirect data available")
3806 lines.append(" No email security records found") 3667 } else {
3807 } else { 3668 lines.append(" Redirects:")
3808 for row in emailRows(from: snapshot) { 3669 for hop in redirectRows(from: snapshot) {
3809 lines.append(" \(row.label): \(row.status)") 3670 lines.append(" \(hop.stepLabel). \(hop.statusCode) \(hop.url)\(hop.isFinal ? " (final)" : "")")
3810 lines.append(" \(row.detail)")
3811 if let auxiliaryDetail = row.auxiliaryDetail {
3812 lines.append(" \(auxiliaryDetail)")
3813 }
3814 }
3815 } 3671 }
3816 } 3672 }
3673 return lines
3674 }
3817 3675
3818 appendSection("Network") { 3676 private static func exportEmailLines(_ snapshot: LookupSnapshot) -> [String] {
3819 if let reachabilityError = snapshot.reachabilityError { 3677 var lines: [String] = []
3820 lines.append(" Reachability Error: \(reachabilityError)") 3678 if let emailSecurityError = snapshot.emailSecurityError {
3821 } else if reachabilityRows(from: snapshot).isEmpty { 3679 lines.append(" Error: \(emailSecurityError)")
3822 lines.append(" Reachability: No results") 3680 } else if emailRows(from: snapshot).isEmpty {
3823 } else { 3681 lines.append(" No email security records found")
3824 lines.append(" Reachability:") 3682 } else {
3825 for row in reachabilityRows(from: snapshot) { 3683 for row in emailRows(from: snapshot) {
3826 lines.append(" \(row.portLabel): \(row.statusLabel) \(row.latencyLabel)") 3684 lines.append(" \(row.label): \(row.status)")
3685 lines.append(" \(row.detail)")
3686 if let auxiliaryDetail = row.auxiliaryDetail {
3687 lines.append(" \(auxiliaryDetail)")
3827 } 3688 }
3828 } 3689 }
3690 }
3691 return lines
3692 }
3829 3693
3830 if let ipGeolocationError = snapshot.ipGeolocationError, snapshot.ipGeolocation == nil { 3694 private static func exportPortLines(_ rows: [PortScanRowViewData]) -> [String] {
3831 lines.append(" Location Error: \(ipGeolocationError)") 3695 guard !rows.isEmpty else { return [" No results"] }
3832 } else if locationRows(from: snapshot).isEmpty { 3696 var lines: [String] = []
3833 lines.append(" Location: No data") 3697 for row in rows {
3834 } else { 3698 lines.append(" \(row.portLabel) \(row.service): \(row.statusLabel)\(row.durationLabel.map { " \($0)" } ?? "")")
3835 lines.append(" Location:") 3699 if let banner = row.banner {
3836 for row in locationRows(from: snapshot) { 3700 lines.append(" Banner: \(banner)")
3837 lines.append(" \(row.label): \(row.value)")
3838 }
3839 } 3701 }
3702 }
3703 return lines
3704 }
3840 3705
3841 if let portScanError = snapshot.portScanError, snapshot.portScanResults.isEmpty { 3706 private static func exportNetworkLines(_ snapshot: LookupSnapshot) -> [String] {
3842 lines.append(" Port Scan Error: \(portScanError)") 3707 var lines: [String] = []
3708 if let reachabilityError = snapshot.reachabilityError {
3709 lines.append(" Reachability Error: \(reachabilityError)")
3710 } else if reachabilityRows(from: snapshot).isEmpty {
3711 lines.append(" Reachability: No results")
3712 } else {
3713 lines.append(" Reachability:")
3714 for row in reachabilityRows(from: snapshot) {
3715 lines.append(" \(row.portLabel): \(row.statusLabel) \(row.latencyLabel)")
3843 } 3716 }
3717 }
3844 3718
3845 lines.append(" Standard Ports:") 3719 if let ipGeolocationError = snapshot.ipGeolocationError, snapshot.ipGeolocation == nil {
3846 let standardRows = portRows(from: snapshot, kind: .standard) 3720 lines.append(" Location Error: \(ipGeolocationError)")
3847 if standardRows.isEmpty { 3721 } else if locationRows(from: snapshot).isEmpty {
3848 lines.append(" No results") 3722 lines.append(" Location: No data")
3849 } else { 3723 } else {
3850 for row in standardRows { 3724 lines.append(" Location:")
3851 lines.append(" \(row.portLabel) \(row.service): \(row.statusLabel)\(row.durationLabel.map { " \($0)" } ?? "")") 3725 for row in locationRows(from: snapshot) {
3852 if let banner = row.banner { 3726 lines.append(" \(row.label): \(row.value)")
3853 lines.append(" Banner: \(banner)")
3854 }
3855 }
3856 } 3727 }
3728 }
3857 3729
3858 lines.append(" Custom Ports:") 3730 if let portScanError = snapshot.portScanError, snapshot.portScanResults.isEmpty {
3859 let customRows = portRows(from: snapshot, kind: .custom) 3731 lines.append(" Port Scan Error: \(portScanError)")
3860 if customRows.isEmpty {
3861 lines.append(" No results")
3862 } else {
3863 for row in customRows {
3864 lines.append(" \(row.portLabel) \(row.service): \(row.statusLabel)\(row.durationLabel.map { " \($0)" } ?? "")")
3865 if let banner = row.banner {
3866 lines.append(" Banner: \(banner)")
3867 }
3868 }
3869 }
3870 } 3732 }
3871 3733
3872 return lines.joined(separator: "\n") 3734 lines.append(" Standard Ports:")
3735 lines += exportPortLines(portRows(from: snapshot, kind: .standard))
3736 lines.append(" Custom Ports:")
3737 lines += exportPortLines(portRows(from: snapshot, kind: .custom))
3738 return lines
3873 } 3739 }
3874 3740
3875 private static func primaryIPAddress(from snapshot: LookupSnapshot) -> String? { 3741 private static func primaryIPAddress(from snapshot: LookupSnapshot) -> String? {
DomainDig/ExportPresenter.swift +32
@@ -30,3 +30,35 @@ enum ExportPresenter {
30 presenter.present(activityController, animated: true) 30 presenter.present(activityController, animated: true)
31 } 31 }
32} 32}
33
34/// The export menu's entries: text for everyone, the other formats with
35/// advanced exports, and otherwise disabled Pro upsells in their place.
36struct ExportFormatButtons: View {
37 let share: (DomainExportFormat) -> Void
38 /// Labels the entries as exporting a batch.
39 var batch = false
40
41 var body: some View {
42 let noun = batch ? " Batch" : ""
43 Button("Export\(noun) TXT") {
44 share(.text)
45 }
46 if FeatureAccessService.hasAccess(to: .advancedExports) {
47 ForEach(Self.advancedFormats, id: \.label) { format in
48 Button("Export\(noun) \(format.label)") {
49 share(format.format)
50 }
51 }
52 } else {
53 ForEach(Self.advancedFormats, id: \.label) { format in
54 // Inert: disabled Pro upsell affordance.
55 Button(batch ? "Batch \(format.label) • Available in Pro" : "\(format.label) Export • Available in Pro") {}
56 .disabled(true)
57 }
58 }
59 }
60
61 private static let advancedFormats: [(label: String, format: DomainExportFormat)] = [
62 ("CSV", .csv), ("JSON", .json), ("Markdown", .markdown), ("PDF", .pdf),
63 ]
64}
DomainDig/GenericPasswordKeychain.swift added +41
@@ -0,0 +1,41 @@
1import Foundation
2import Security
3
4/// Secrets kept as generic-password keychain items, keyed by account and
5/// readable after first unlock.
6enum GenericPasswordKeychain {
7 /// Replaces any item under `reference`. False when the keychain refuses.
8 static func save(_ secret: String, reference: String) -> Bool {
9 delete(reference: reference)
10 let query: [String: Any] = [
11 kSecClass as String: kSecClassGenericPassword,
12 kSecAttrAccount as String: reference,
13 kSecValueData as String: Data(secret.utf8),
14 kSecAttrAccessible as String: kSecAttrAccessibleAfterFirstUnlock
15 ]
16 return SecItemAdd(query as CFDictionary, nil) == errSecSuccess
17 }
18
19 static func secret(reference: String) -> String? {
20 let query: [String: Any] = [
21 kSecClass as String: kSecClassGenericPassword,
22 kSecAttrAccount as String: reference,
23 kSecReturnData as String: true,
24 kSecMatchLimit as String: kSecMatchLimitOne
25 ]
26 var result: CFTypeRef?
27 guard SecItemCopyMatching(query as CFDictionary, &result) == errSecSuccess,
28 let data = result as? Data else {
29 return nil
30 }
31 return String(data: data, encoding: .utf8)
32 }
33
34 static func delete(reference: String) {
35 let query: [String: Any] = [
36 kSecClass as String: kSecClassGenericPassword,
37 kSecAttrAccount as String: reference
38 ]
39 SecItemDelete(query as CFDictionary)
40 }
41}
DomainDig/IntegrationService.swift +23 −46
@@ -646,47 +646,20 @@ private enum HTTPIntegrationClient {
646 646
647private enum IntegrationSecretStore { 647private enum IntegrationSecretStore {
648 static func save(secret: String, reference: String) throws { 648 static func save(secret: String, reference: String) throws {
649 let data = Data(secret.utf8) 649 guard GenericPasswordKeychain.save(secret, reference: reference) else {
650 try? delete(reference: reference)
651
652 let query: [String: Any] = [
653 kSecClass as String: kSecClassGenericPassword,
654 kSecAttrAccount as String: reference,
655 kSecValueData as String: data,
656 kSecAttrAccessible as String: kSecAttrAccessibleAfterFirstUnlock
657 ]
658
659 let status = SecItemAdd(query as CFDictionary, nil)
660 guard status == errSecSuccess else {
661 throw IntegrationError.smtp("Could not save integration secret.") 650 throw IntegrationError.smtp("Could not save integration secret.")
662 } 651 }
663 } 652 }
664 653
665 static func secret(reference: String) throws -> String { 654 static func secret(reference: String) throws -> String {
666 let query: [String: Any] = [ 655 guard let secret = GenericPasswordKeychain.secret(reference: reference) else {
667 kSecClass as String: kSecClassGenericPassword,
668 kSecAttrAccount as String: reference,
669 kSecReturnData as String: true,
670 kSecMatchLimit as String: kSecMatchLimitOne
671 ]
672
673 var result: CFTypeRef?
674 let status = SecItemCopyMatching(query as CFDictionary, &result)
675 guard status == errSecSuccess,
676 let data = result as? Data,
677 let secret = String(data: data, encoding: .utf8) else {
678 throw IntegrationError.missingSecret 656 throw IntegrationError.missingSecret
679 } 657 }
680
681 return secret 658 return secret
682 } 659 }
683 660
684 static func delete(reference: String) throws { 661 static func delete(reference: String) throws {
685 let query: [String: Any] = [ 662 GenericPasswordKeychain.delete(reference: reference)
686 kSecClass as String: kSecClassGenericPassword,
687 kSecAttrAccount as String: reference
688 ]
689 SecItemDelete(query as CFDictionary)
690 } 663 }
691} 664}
692 665
@@ -778,23 +751,12 @@ private actor SMTPChannel {
778 // from the connection's queue. 751 // from the connection's queue.
779 let hasResumed = OSAllocatedUnfairLock(initialState: false) 752 let hasResumed = OSAllocatedUnfairLock(initialState: false)
780 connection.stateUpdateHandler = { state in 753 connection.stateUpdateHandler = { state in
781 let isFirst: () -> Bool = { 754 guard let outcome = Self.startOutcome(for: state) else { return }
782 hasResumed.withLock { resumed in 755 let isFirst = hasResumed.withLock { resumed in
783 if resumed { return false } 756 defer { resumed = true }
784 resumed = true 757 return !resumed
785 return true
786 }
787 }
788 switch state {
789 case .ready:
790 if isFirst() { continuation.resume() }
791 case .failed(let error):
792 if isFirst() { continuation.resume(throwing: error) }
793 case .cancelled:
794 if isFirst() { continuation.resume(throwing: IntegrationError.streamClosed) }
795 default:
796 break
797 } 758 }
759 if isFirst { continuation.resume(with: outcome) }
798 } 760 }
799 connection.start(queue: .global(qos: .utility)) 761 connection.start(queue: .global(qos: .utility))
800 } 762 }
@@ -803,6 +765,21 @@ private actor SMTPChannel {
803 startReceiveLoop() 765 startReceiveLoop()
804 } 766 }
805 767
768 /// How a connection state settles `start()`: ready succeeds, failure or
769 /// cancellation throws, and anything else is still in progress.
770 private static func startOutcome(for state: NWConnection.State) -> Result<Void, Error>? {
771 switch state {
772 case .ready:
773 return .success(())
774 case .failed(let error):
775 return .failure(error)
776 case .cancelled:
777 return .failure(IntegrationError.streamClosed)
778 default:
779 return nil
780 }
781 }
782
806 func cancel() { 783 func cancel() {
807 connection.cancel() 784 connection.cancel()
808 } 785 }
DomainDig/Models.swift +1 −15
@@ -1246,25 +1246,11 @@ struct MonitoringState: Codable, Equatable, Sendable {
1246} 1246}
1247 1247
1248struct MonitoringPendingAlert: Codable, Identifiable, Equatable, Sendable { 1248struct MonitoringPendingAlert: Codable, Identifiable, Equatable, Sendable {
1249 let id: UUID 1249 var id = UUID()
1250 var detectedAt: Date 1250 var detectedAt: Date
1251 var message: String 1251 var message: String
1252 var severity: MonitoringAlertSeverity 1252 var severity: MonitoringAlertSeverity
1253 var changeHash: String 1253 var changeHash: String
1254
1255 init(
1256 id: UUID = UUID(),
1257 detectedAt: Date,
1258 message: String,
1259 severity: MonitoringAlertSeverity,
1260 changeHash: String
1261 ) {
1262 self.id = id
1263 self.detectedAt = detectedAt
1264 self.message = message
1265 self.severity = severity
1266 self.changeHash = changeHash
1267 }
1268} 1254}
1269 1255
1270 1256
DomainDig/PortScanService.swift +26
@@ -74,6 +74,32 @@ struct PortScanService {
74 .pipe { $0.isEmpty ? .empty("No custom port scan results") : .success($0) } 74 .pipe { $0.isEmpty ? .empty("No custom port scan results") : .success($0) }
75 } 75 }
76 76
77 /// `results` with each open port's banner, grabbed concurrently.
78 static func withBanners(_ results: [PortScanResult], host: String) async -> [PortScanResult] {
79 let banners = await withTaskGroup(of: (UInt16, String?).self, returning: [UInt16: String].self) { group in
80 for result in results where result.open {
81 group.addTask {
82 let banner = await grabBanner(host: host, port: result.port)
83 return (result.port, banner)
84 }
85 }
86
87 var collected: [UInt16: String] = [:]
88 for await (port, banner) in group {
89 if let banner {
90 collected[port] = banner
91 }
92 }
93 return collected
94 }
95
96 return results.map { result in
97 var updated = result
98 updated.banner = banners[result.port]
99 return updated
100 }
101 }
102
77 static func grabBanner(host: String, port: UInt16, timeout: TimeInterval = 3.0) async -> String? { 103 static func grabBanner(host: String, port: UInt16, timeout: TimeInterval = 3.0) async -> String? {
78 await withCheckedContinuation { continuation in 104 await withCheckedContinuation { continuation in
79 guard let nwPort = NWEndpoint.Port(rawValue: port) else { 105 guard let nwPort = NWEndpoint.Port(rawValue: port) else {
DomainDig/ResultSectionViews.swift +154 −124
@@ -234,43 +234,48 @@ struct OwnershipSectionView: View {
234 MessageRowView(text: error, isError: error != "Unavailable") 234 MessageRowView(text: error, isError: error != "Unavailable")
235 .padding(.top, 4) 235 .padding(.top, 4)
236 } 236 }
237 VStack(alignment: .leading, spacing: 8) { 237 historyBlock
238 HStack { 238 }
239 Text("History") 239 }
240 .font(appDensity.font(.caption)) 240 }
241 .foregroundStyle(Color(.appTextSecondary)) 241 }
242 Spacer() 242
243 if let onLoadHistory, history.isEmpty, !historyLoading, !showsHistoryPlaceholder { 243 @ViewBuilder
244 Button("Load") { 244 private var historyBlock: some View {
245 onLoadHistory() 245 VStack(alignment: .leading, spacing: 8) {
246 } 246 HStack {
247 .buttonStyle(.bordered) 247 Text("History")
248 .font(appDensity.font(.caption2)) 248 .font(appDensity.font(.caption))
249 } 249 .foregroundStyle(Color(.appTextSecondary))
250 } 250 Spacer()
251 if historyLoading { 251 if let onLoadHistory, history.isEmpty, !historyLoading, !showsHistoryPlaceholder {
252 ProgressView("Loading history…") 252 Button("Load") {
253 .appLoadingStyle() 253 onLoadHistory()
254 } else if !history.isEmpty { 254 }
255 ForEach(history) { event in 255 .buttonStyle(.bordered)
256 VStack(alignment: .leading, spacing: 3) { 256 .font(appDensity.font(.caption2))
257 Text(event.date.formatted(date: .abbreviated, time: .omitted)) 257 }
258 .font(appDensity.font(.caption2)) 258 }
259 .foregroundStyle(Color(.appTextSecondary)) 259 if historyLoading {
260 Text(event.summary) 260 ProgressView("Loading history…")
261 .font(appDensity.font(.caption)) 261 .appLoadingStyle()
262 Text(event.source) 262 } else if !history.isEmpty {
263 .font(appDensity.font(.caption2)) 263 ForEach(history) { event in
264 .foregroundStyle(Color(.appTextSecondary)) 264 VStack(alignment: .leading, spacing: 3) {
265 } 265 Text(event.date.formatted(date: .abbreviated, time: .omitted))
266 } 266 .font(appDensity.font(.caption2))
267 } else if let historyError { 267 .foregroundStyle(Color(.appTextSecondary))
268 MessageRowView(text: historyError, isError: false) 268 Text(event.summary)
269 } else if showsHistoryPlaceholder { 269 .font(appDensity.font(.caption))
270 MessageRowView(text: "Ownership history available in Pro+", isError: false) 270 Text(event.source)
271 } 271 .font(appDensity.font(.caption2))
272 .foregroundStyle(Color(.appTextSecondary))
272 } 273 }
273 } 274 }
275 } else if let historyError {
276 MessageRowView(text: historyError, isError: false)
277 } else if showsHistoryPlaceholder {
278 MessageRowView(text: "Ownership history available in Pro+", isError: false)
274 } 279 }
275 } 280 }
276 } 281 }
@@ -463,54 +468,69 @@ struct SubdomainsSectionView: View {
463 .buttonStyle(.bordered) 468 .buttonStyle(.bordered)
464 .font(appDensity.font(.caption2)) 469 .font(appDensity.font(.caption2))
465 } 470 }
466 if !groups.isEmpty { 471 groupList
467 Text("Groups") 472 subdomainRows
468 .font(appDensity.font(.caption2)) 473 extendedStatus
469 .foregroundStyle(Color(.appTextSecondary)) 474 }
470 ForEach(groups) { group in 475 }
471 HStack { 476 }
472 Text("\(group.label).*") 477 }
473 .font(appDensity.font(.caption)) 478
474 .foregroundStyle(Color(.statusInfo)) 479 @ViewBuilder
475 Spacer() 480 private var extendedStatus: some View {
476 Text("\(group.subdomains.count)") 481 if extendedLoading {
477 .font(appDensity.font(.caption2)) 482 ProgressView("Loading extended subdomains…")
478 .foregroundStyle(Color(.appTextSecondary)) 483 .appLoadingStyle()
479 } 484 .padding(.top, 4)
480 } 485 } else if extendedCount > 0 {
481 } 486 MessageRowView(text: "\(extendedCount) extended results included", isError: false)
482 ForEach(rows) { row in 487 .padding(.top, 4)
483 HStack(spacing: 8) { 488 } else if let extendedError {
484 Text(row.hostname) 489 MessageRowView(text: extendedError, isError: false)
485 .font(appDensity.font(.caption)) 490 .padding(.top, 4)
486 .foregroundStyle(.primary) 491 } else if showsExtendedPlaceholder {
487 .textSelection(.enabled) 492 MessageRowView(text: "Extended subdomain discovery available in Pro+", isError: false)
488 Spacer() 493 .padding(.top, 4)
489 if row.isInteresting { 494 }
490 Text("Interesting") 495 }
491 .font(.system(.caption2, design: .monospaced)) 496
492 .foregroundStyle(Color(.statusWarning)) 497 @ViewBuilder
493 .padding(.horizontal, 8) 498 private var groupList: some View {
494 .padding(.vertical, 4) 499 if !groups.isEmpty {
495 .background(Color(.statusWarningSurface)) 500 Text("Groups")
496 .clipShape(Capsule()) 501 .font(appDensity.font(.caption2))
497 } 502 .foregroundStyle(Color(.appTextSecondary))
498 } 503 ForEach(groups) { group in
499 } 504 HStack {
500 if extendedLoading { 505 Text("\(group.label).*")
501 ProgressView("Loading extended subdomains…") 506 .font(appDensity.font(.caption))
502 .appLoadingStyle() 507 .foregroundStyle(Color(.statusInfo))
503 .padding(.top, 4) 508 Spacer()
504 } else if extendedCount > 0 { 509 Text("\(group.subdomains.count)")
505 MessageRowView(text: "\(extendedCount) extended results included", isError: false) 510 .font(appDensity.font(.caption2))
506 .padding(.top, 4) 511 .foregroundStyle(Color(.appTextSecondary))
507 } else if let extendedError { 512 }
508 MessageRowView(text: extendedError, isError: false) 513 }
509 .padding(.top, 4) 514 }
510 } else if showsExtendedPlaceholder { 515 }
511 MessageRowView(text: "Extended subdomain discovery available in Pro+", isError: false) 516
512 .padding(.top, 4) 517 @ViewBuilder
513 } 518 private var subdomainRows: some View {
519 ForEach(rows) { row in
520 HStack(spacing: 8) {
521 Text(row.hostname)
522 .font(appDensity.font(.caption))
523 .foregroundStyle(.primary)
524 .textSelection(.enabled)
525 Spacer()
526 if row.isInteresting {
527 Text("Interesting")
528 .font(.system(.caption2, design: .monospaced))
529 .foregroundStyle(Color(.statusWarning))
530 .padding(.horizontal, 8)
531 .padding(.vertical, 4)
532 .background(Color(.statusWarningSurface))
533 .clipShape(Capsule())
514 } 534 }
515 } 535 }
516 } 536 }
@@ -576,21 +596,7 @@ struct DNSSectionView: View {
576 } else if let sectionError, sections.isEmpty { 596 } else if let sectionError, sections.isEmpty {
577 MessageCardView(text: sectionError, isError: true) 597 MessageCardView(text: sectionError, isError: true)
578 } else { 598 } else {
579 if dnsProvenance != nil { 599 provenanceCard
580 CardView(allowsHorizontalScroll: false) {
581 SectionTrustMetadataView(provenance: dnsProvenance, confidence: nil)
582 if let patternSummary {
583 if !patternSummary.providers.isEmpty {
584 MessageRowView(text: "Providers: \(patternSummary.providers.joined(separator: ", "))", isError: false)
585 }
586 if !patternSummary.patterns.isEmpty {
587 ForEach(Array(patternSummary.patterns.enumerated()), id: \.offset) { _, pattern in
588 MessageRowView(text: pattern, isError: false)
589 }
590 }
591 }
592 }
593 }
594 ForEach(sections) { section in 600 ForEach(sections) { section in
595 CardView { 601 CardView {
596 Text(section.title) 602 Text(section.title)
@@ -643,33 +649,57 @@ struct DNSSectionView: View {
643 .font(appDensity.font(.caption2)) 649 .font(appDensity.font(.caption2))
644 } 650 }
645 } 651 }
646 if historyLoading { 652 historyContent
647 ProgressView("Loading DNS history…") 653 }
648 .appLoadingStyle() 654 }
649 } else if !history.isEmpty { 655 }
650 ForEach(history) { event in 656 }
651 VStack(alignment: .leading, spacing: 3) { 657
652 Text(event.date.formatted(date: .abbreviated, time: .omitted)) 658 @ViewBuilder
653 .font(appDensity.font(.caption2)) 659 private var historyContent: some View {
654 .foregroundStyle(Color(.appTextSecondary)) 660 if historyLoading {
655 Text(event.summary) 661 ProgressView("Loading DNS history…")
656 .font(appDensity.font(.caption)) 662 .appLoadingStyle()
657 if !event.aRecords.isEmpty { 663 } else if !history.isEmpty {
658 Text("A: \(event.aRecords.joined(separator: ", "))") 664 ForEach(history) { event in
659 .font(appDensity.font(.caption2)) 665 VStack(alignment: .leading, spacing: 3) {
660 .foregroundStyle(Color(.appTextSecondary)) 666 Text(event.date.formatted(date: .abbreviated, time: .omitted))
661 } 667 .font(appDensity.font(.caption2))
662 if !event.nameservers.isEmpty { 668 .foregroundStyle(Color(.appTextSecondary))
663 Text("NS: \(event.nameservers.joined(separator: ", "))") 669 Text(event.summary)
664 .font(appDensity.font(.caption2)) 670 .font(appDensity.font(.caption))
665 .foregroundStyle(Color(.appTextSecondary)) 671 if !event.aRecords.isEmpty {
666 } 672 Text("A: \(event.aRecords.joined(separator: ", "))")
667 } 673 .font(appDensity.font(.caption2))
674 .foregroundStyle(Color(.appTextSecondary))
675 }
676 if !event.nameservers.isEmpty {
677 Text("NS: \(event.nameservers.joined(separator: ", "))")
678 .font(appDensity.font(.caption2))
679 .foregroundStyle(Color(.appTextSecondary))
680 }
681 }
682 }
683 } else if let historyError {
684 MessageRowView(text: historyError, isError: false)
685 } else if showsHistoryPlaceholder {
686 MessageRowView(text: "DNS history available in Pro+", isError: false)
687 }
688 }
689
690 @ViewBuilder
691 private var provenanceCard: some View {
692 if dnsProvenance != nil {
693 CardView(allowsHorizontalScroll: false) {
694 SectionTrustMetadataView(provenance: dnsProvenance, confidence: nil)
695 if let patternSummary {
696 if !patternSummary.providers.isEmpty {
697 MessageRowView(text: "Providers: \(patternSummary.providers.joined(separator: ", "))", isError: false)
698 }
699 if !patternSummary.patterns.isEmpty {
700 ForEach(Array(patternSummary.patterns.enumerated()), id: \.offset) { _, pattern in
701 MessageRowView(text: pattern, isError: false)
668 } 702 }
669 } else if let historyError {
670 MessageRowView(text: historyError, isError: false)
671 } else if showsHistoryPlaceholder {
672 MessageRowView(text: "DNS history available in Pro+", isError: false)
673 } 703 }
674 } 704 }
675 } 705 }
DomainDig/SSLCheckService.swift +42 −43
@@ -228,24 +228,15 @@ private enum DERCertificateParser {
228 while pos < end { 228 while pos < end {
229 // Each SET in the issuer 229 // Each SET in the issuer
230 guard let setTL = readTagAndLength(bytes, offset: pos) else { break } 230 guard let setTL = readTagAndLength(bytes, offset: pos) else { break }
231 let setEnd = setTL.contentStart + setTL.length 231 pos = setTL.contentStart + setTL.length
232 232
233 // Inside the SET is a SEQUENCE with OID + value 233 // Inside the SET is a SEQUENCE with OID + value
234 if let seqTL = readTagAndLength(bytes, offset: setTL.contentStart) { 234 guard let seqTL = readTagAndLength(bytes, offset: setTL.contentStart),
235 let seqEnd = seqTL.contentStart + seqTL.length 235 let oidTL = readTagAndLength(bytes, offset: seqTL.contentStart),
236 if let oidTL = readTagAndLength(bytes, offset: seqTL.contentStart) { 236 content(of: oidTL, in: bytes).elementsEqual(cnOID),
237 let oidBytes = Array(bytes[oidTL.contentStart..<oidTL.contentStart + oidTL.length]) 237 let valueTL = readTagAndLength(bytes, offset: oidTL.contentStart + oidTL.length)
238 if oidBytes == cnOID { 238 else { continue }
239 let valueStart = oidTL.contentStart + oidTL.length 239 return String(bytes: content(of: valueTL, in: bytes), encoding: .utf8)
240 if let valueTL = readTagAndLength(bytes, offset: valueStart) {
241 let strBytes = bytes[valueTL.contentStart..<valueTL.contentStart + valueTL.length]
242 return String(bytes: strBytes, encoding: .utf8)
243 }
244 }
245 _ = seqEnd // suppress unused warning
246 }
247 }
248 pos = setEnd
249 } 240 }
250 return nil 241 return nil
251 } 242 }
@@ -260,39 +251,41 @@ private enum DERCertificateParser {
260 let extEnd = extSeq.contentStart + extSeq.length 251 let extEnd = extSeq.contentStart + extSeq.length
261 252
262 // Each extension is SEQUENCE { OID, [critical], value } 253 // Each extension is SEQUENCE { OID, [critical], value }
263 if let oidTL = readTagAndLength(bytes, offset: extSeq.contentStart) { 254 if let oidTL = readTagAndLength(bytes, offset: extSeq.contentStart), content(of: oidTL, in: bytes).elementsEqual(sanOID) {
264 let oidBytes = Array(bytes[oidTL.contentStart..<oidTL.contentStart + oidTL.length]) 255 sans += sanDNSNames(bytes, valueStart: oidTL.contentStart + oidTL.length, extensionEnd: extEnd)
265 if oidBytes == sanOID {
266 var valuePos = oidTL.contentStart + oidTL.length
267 // Skip optional critical BOOLEAN
268 if valuePos < extEnd, bytes[valuePos] == 0x01,
269 let boolTL = readTagAndLength(bytes, offset: valuePos) {
270 valuePos = boolTL.contentStart + boolTL.length
271 }
272 // The value is an OCTET STRING wrapping a SEQUENCE of GeneralNames
273 if let octetTL = readTagAndLength(bytes, offset: valuePos),
274 let sanSeq = readTagAndLength(bytes, offset: octetTL.contentStart) {
275 let sanEnd = sanSeq.contentStart + sanSeq.length
276 var sanPos = sanSeq.contentStart
277 while sanPos < sanEnd {
278 guard let nameTL = readTagAndLength(bytes, offset: sanPos) else { break }
279 // Context tag [2] = dNSName (IA5String)
280 if (bytes[sanPos] & 0x1F) == 2 {
281 let nameBytes = bytes[nameTL.contentStart..<nameTL.contentStart + nameTL.length]
282 if let name = String(bytes: nameBytes, encoding: .ascii) {
283 sans.append(name)
284 }
285 }
286 sanPos = nameTL.contentStart + nameTL.length
287 }
288 }
289 }
290 } 256 }
291 pos = extEnd 257 pos = extEnd
292 } 258 }
293 return sans 259 return sans
294 } 260 }
295 261
262 /// The dNSName entries of a subjectAltName extension whose value starts at `valueStart`.
263 private static func sanDNSNames(_ bytes: [UInt8], valueStart: Int, extensionEnd: Int) -> [String] {
264 var valuePos = valueStart
265 // Skip optional critical BOOLEAN
266 if valuePos < extensionEnd, bytes[valuePos] == 0x01,
267 let boolTL = readTagAndLength(bytes, offset: valuePos) {
268 valuePos = boolTL.contentStart + boolTL.length
269 }
270 // The value is an OCTET STRING wrapping a SEQUENCE of GeneralNames
271 guard let octetTL = readTagAndLength(bytes, offset: valuePos),
272 let sanSeq = readTagAndLength(bytes, offset: octetTL.contentStart)
273 else { return [] }
274
275 let sanEnd = sanSeq.contentStart + sanSeq.length
276 var sanPos = sanSeq.contentStart
277 var names: [String] = []
278 while sanPos < sanEnd {
279 guard let nameTL = readTagAndLength(bytes, offset: sanPos) else { break }
280 // Context tag [2] = dNSName (IA5String)
281 if (bytes[sanPos] & 0x1F) == 2, let name = String(bytes: content(of: nameTL, in: bytes), encoding: .ascii) {
282 names.append(name)
283 }
284 sanPos = nameTL.contentStart + nameTL.length
285 }
286 return names
287 }
288
296 private static func extractValidity(_ bytes: [UInt8], sequenceStart: Int, length: Int) -> (Date?, Date?) { 289 private static func extractValidity(_ bytes: [UInt8], sequenceStart: Int, length: Int) -> (Date?, Date?) {
297 let end = sequenceStart + length 290 let end = sequenceStart + length
298 var position = sequenceStart 291 var position = sequenceStart
@@ -362,8 +355,14 @@ private enum DERCertificateParser {
362 length = len 355 length = len
363 } 356 }
364 357
358 // A length past the end of the data is malformed, and slicing to it would trap.
359 guard length <= bytes.count - pos else { return nil }
365 return TLV(contentStart: pos, length: length) 360 return TLV(contentStart: pos, length: length)
366 } 361 }
362
363 private static func content(of tlv: TLV, in bytes: [UInt8]) -> ArraySlice<UInt8> {
364 bytes[tlv.contentStart..<tlv.contentStart + tlv.length]
365 }
367} 366}
368 367
369enum SSLError: LocalizedError { 368enum SSLError: LocalizedError {
DomainDig/ScheduledReportService.swift +3 −22
@@ -31,25 +31,11 @@ struct ScheduledReportSettings: Codable, Equatable {
31} 31}
32 32
33struct ScheduledReportLog: Codable, Identifiable, Equatable { 33struct ScheduledReportLog: Codable, Identifiable, Equatable {
34 let id: UUID 34 var id = UUID()
35 let generatedAt: Date 35 let generatedAt: Date
36 let domainCount: Int 36 let domainCount: Int
37 let format: DomainExportFormat 37 let format: DomainExportFormat
38 let fileName: String 38 let fileName: String
39
40 init(
41 id: UUID = UUID(),
42 generatedAt: Date,
43 domainCount: Int,
44 format: DomainExportFormat,
45 fileName: String
46 ) {
47 self.id = id
48 self.generatedAt = generatedAt
49 self.domainCount = domainCount
50 self.format = format
51 self.fileName = fileName
52 }
53} 39}
54 40
55/// Local, UserDefaults-backed persistence for scheduled-report settings and 41/// Local, UserDefaults-backed persistence for scheduled-report settings and
@@ -245,13 +231,8 @@ final class ScheduledReportScheduler {
245 private func handleAppRefresh(task: BGAppRefreshTask) { 231 private func handleAppRefresh(task: BGAppRefreshTask) {
246 _ = syncSchedule() 232 _ = syncSchedule()
247 233
248 let worker = Task { 234 task.run {
249 let outcome = await ScheduledReportService.shared.generateReport(trigger: .background, requireEnabledSetting: true) 235 await ScheduledReportService.shared.generateReport(trigger: .background, requireEnabledSetting: true).success
250 task.setTaskCompleted(success: outcome.success)
251 }
252
253 task.expirationHandler = {
254 worker.cancel()
255 } 236 }
256 } 237 }
257 #endif 238 #endif
DomainDig/SettingsViews.swift +16 −35
@@ -483,41 +483,14 @@ private struct MonitoringSettingsView: View {
483 ) 483 )
484 484
485 if viewModel.monitoringSettings.quietHours != nil { 485 if viewModel.monitoringSettings.quietHours != nil {
486 Picker( 486 hourPicker("Quiet Starts", selection: Binding(
487 "Quiet Starts", 487 get: { quietHoursStart },
488 selection: Binding( 488 set: { viewModel.setMonitoringQuietHours(startHour: $0, endHour: quietHoursEnd, isEnabled: true) }
489 get: { quietHoursStart }, 489 ))
490 set: { startHour in 490 hourPicker("Quiet Ends", selection: Binding(
491 viewModel.setMonitoringQuietHours( 491 get: { quietHoursEnd },
492 startHour: startHour, 492 set: { viewModel.setMonitoringQuietHours(startHour: quietHoursStart, endHour: $0, isEnabled: true) }
493 endHour: quietHoursEnd, 493 ))
494 isEnabled: true
495 )
496 }
497 )
498 ) {
499 ForEach(0..<24, id: \.self) { hour in
500 Text(Self.monitoringHourLabel(for: hour)).tag(hour)
501 }
502 }
503
504 Picker(
505 "Quiet Ends",
506 selection: Binding(
507 get: { quietHoursEnd },
508 set: { endHour in
509 viewModel.setMonitoringQuietHours(
510 startHour: quietHoursStart,
511 endHour: endHour,
512 isEnabled: true
513 )
514 }
515 )
516 ) {
517 ForEach(0..<24, id: \.self) { hour in
518 Text(Self.monitoringHourLabel(for: hour)).tag(hour)
519 }
520 }
521 } 494 }
522 495
523 Picker( 496 Picker(
@@ -597,6 +570,14 @@ private struct MonitoringSettingsView: View {
597 } 570 }
598 } 571 }
599 572
573 private func hourPicker(_ title: String, selection: Binding<Int>) -> some View {
574 Picker(title, selection: selection) {
575 ForEach(0..<24, id: \.self) { hour in
576 Text(Self.monitoringHourLabel(for: hour)).tag(hour)
577 }
578 }
579 }
580
600 private static func monitoringHourLabel(for hour: Int) -> String { 581 private static func monitoringHourLabel(for hour: Int) -> String {
601 let formatter = DateFormatter() 582 let formatter = DateFormatter()
602 formatter.dateFormat = "h a" 583 formatter.dateFormat = "h a"
DomainDig/WatchlistView.swift +56 −89
@@ -150,36 +150,7 @@ struct WatchlistView: View {
150 } 150 }
151 } 151 }
152 152
153 Button("Export TXT") { 153 ExportFormatButtons(share: shareTrackedDomains)
154 shareTrackedDomains(format: .text)
155 }
156
157 if FeatureAccessService.hasAccess(to: .advancedExports) {
158 Button("Export CSV") {
159 shareTrackedDomains(format: .csv)
160 }
161
162 Button("Export JSON") {
163 shareTrackedDomains(format: .json)
164 }
165
166 Button("Export Markdown") {
167 shareTrackedDomains(format: .markdown)
168 }
169
170 Button("Export PDF") {
171 shareTrackedDomains(format: .pdf)
172 }
173 } else {
174 Button("CSV Export • Available in Pro") { /* Inert: disabled Pro upsell affordance. */ }
175 .disabled(true)
176 Button("JSON Export • Available in Pro") { /* Inert: disabled Pro upsell affordance. */ }
177 .disabled(true)
178 Button("Markdown Export • Available in Pro") { /* Inert: disabled Pro upsell affordance. */ }
179 .disabled(true)
180 Button("PDF Export • Available in Pro") { /* Inert: disabled Pro upsell affordance. */ }
181 .disabled(true)
182 }
183 } label: { 154 } label: {
184 Image(systemName: "line.3.horizontal.decrease.circle") 155 Image(systemName: "line.3.horizontal.decrease.circle")
185 } 156 }
@@ -313,76 +284,72 @@ struct WatchlistView: View {
313 } 284 }
314 .buttonStyle(.plain) 285 .buttonStyle(.plain)
315 .swipeActions(edge: .leading, allowsFullSwipe: false) { 286 .swipeActions(edge: .leading, allowsFullSwipe: false) {
316 Button { 287 refreshButton(trackedDomain)
317 AppHaptics.refresh() 288 .tint(Color(.statusInfo))
318 viewModel.refreshTrackedDomain(trackedDomain) 289 pinButton(trackedDomain)
319 } label: { 290 .tint(Color(.statusWarning))
320 Label("Refresh", systemImage: "arrow.clockwise")
321 }
322 .tint(Color(.statusInfo))
323
324 Button {
325 viewModel.togglePinned(for: trackedDomain)
326 } label: {
327 Label(trackedDomain.isPinned ? "Unpin" : "Pin", systemImage: trackedDomain.isPinned ? "pin.slash" : "pin")
328 }
329 .tint(Color(.statusWarning))
330 } 291 }
331 .swipeActions(edge: .trailing, allowsFullSwipe: false) { 292 .swipeActions(edge: .trailing, allowsFullSwipe: false) {
332 Button { 293 refreshButton(trackedDomain)
333 AppHaptics.refresh() 294 .tint(Color(.statusInfo))
334 viewModel.refreshTrackedDomain(trackedDomain) 295 deleteButton(trackedDomain)
335 } label: {
336 Label("Refresh", systemImage: "arrow.clockwise")
337 }
338 .tint(Color(.statusInfo))
339
340 if viewModel.canDelete(trackedDomain) {
341 Button(role: .destructive) {
342 viewModel.deleteTrackedDomain(trackedDomain)
343 } label: {
344 Label("Delete", systemImage: "trash")
345 }
346 }
347 } 296 }
348 .contextMenu { 297 .contextMenu {
349 Button { 298 rowMenu(trackedDomain)
350 AppHaptics.refresh() 299 }
351 viewModel.refreshTrackedDomain(trackedDomain) 300 .listRowBackground(Color(.appSurface))
352 } label: { 301 }
353 Label("Refresh", systemImage: "arrow.clockwise")
354 }
355 302
356 Button { 303 @ViewBuilder
357 dismiss() 304 private func rowMenu(_ trackedDomain: TrackedDomain) -> some View {
358 viewModel.rerunInspection(for: trackedDomain) 305 refreshButton(trackedDomain)
359 } label: {
360 Label("Open Inspection", systemImage: "magnifyingglass")
361 }
362 306
363 Button { 307 Button {
364 viewModel.togglePinned(for: trackedDomain) 308 dismiss()
365 } label: { 309 viewModel.rerunInspection(for: trackedDomain)
366 Label(trackedDomain.isPinned ? "Unpin" : "Pin", systemImage: trackedDomain.isPinned ? "pin.slash" : "pin") 310 } label: {
367 } 311 Label("Open Inspection", systemImage: "magnifyingglass")
312 }
313
314 pinButton(trackedDomain)
368 .disabled(!viewModel.canEdit(trackedDomain)) 315 .disabled(!viewModel.canEdit(trackedDomain))
369 316
370 Button { 317 Button {
371 // The system sharing UI manages participants and permissions. 318 // The system sharing UI manages participants and permissions.
372 } label: { 319 } label: {
373 Label(trackedDomain.collaboration?.isShared == true ? "Shared" : "Private", systemImage: "person.2") 320 Label(trackedDomain.collaboration?.isShared == true ? "Shared" : "Private", systemImage: "person.2")
374 } 321 }
375 .disabled(true) 322 .disabled(true)
376 323
377 if viewModel.canDelete(trackedDomain) { 324 deleteButton(trackedDomain)
378 Button(role: .destructive) { 325 }
379 viewModel.deleteTrackedDomain(trackedDomain) 326
380 } label: { 327 private func refreshButton(_ trackedDomain: TrackedDomain) -> some View {
381 Label("Delete", systemImage: "trash") 328 Button {
382 } 329 AppHaptics.refresh()
330 viewModel.refreshTrackedDomain(trackedDomain)
331 } label: {
332 Label("Refresh", systemImage: "arrow.clockwise")
333 }
334 }
335
336 private func pinButton(_ trackedDomain: TrackedDomain) -> some View {
337 Button {
338 viewModel.togglePinned(for: trackedDomain)
339 } label: {
340 Label(trackedDomain.isPinned ? "Unpin" : "Pin", systemImage: trackedDomain.isPinned ? "pin.slash" : "pin")
341 }
342 }
343
344 @ViewBuilder
345 private func deleteButton(_ trackedDomain: TrackedDomain) -> some View {
346 if viewModel.canDelete(trackedDomain) {
347 Button(role: .destructive) {
348 viewModel.deleteTrackedDomain(trackedDomain)
349 } label: {
350 Label("Delete", systemImage: "trash")
383 } 351 }
384 } 352 }
385 .listRowBackground(Color(.appSurface))
386 } 353 }
387 354
388 private var batchSummaryBinding: Binding<BatchSweepSummary?> { 355 private var batchSummaryBinding: Binding<BatchSweepSummary?> {
DomainDig/WorkflowsView.swift +8 −71
@@ -237,32 +237,7 @@ struct WorkflowDetailView: View {
237 if latestSummary != nil { 237 if latestSummary != nil {
238 Toggle("Export all domains", isOn: $includeAllExports) 238 Toggle("Export all domains", isOn: $includeAllExports)
239 Menu { 239 Menu {
240 Button("Export TXT") { 240 ExportFormatButtons(share: shareWorkflowResults)
241 shareWorkflowResults(format: .text)
242 }
243 if FeatureAccessService.hasAccess(to: .advancedExports) {
244 Button("Export CSV") {
245 shareWorkflowResults(format: .csv)
246 }
247 Button("Export JSON") {
248 shareWorkflowResults(format: .json)
249 }
250 Button("Export Markdown") {
251 shareWorkflowResults(format: .markdown)
252 }
253 Button("Export PDF") {
254 shareWorkflowResults(format: .pdf)
255 }
256 } else {
257 Button("CSV Export • Available in Pro") { /* Inert: disabled Pro upsell affordance. */ }
258 .disabled(true)
259 Button("JSON Export • Available in Pro") { /* Inert: disabled Pro upsell affordance. */ }
260 .disabled(true)
261 Button("Markdown Export • Available in Pro") { /* Inert: disabled Pro upsell affordance. */ }
262 .disabled(true)
263 Button("PDF Export • Available in Pro") { /* Inert: disabled Pro upsell affordance. */ }
264 .disabled(true)
265 }
266 } label: { 241 } label: {
267 Label("Export Results", systemImage: "square.and.arrow.up") 242 Label("Export Results", systemImage: "square.and.arrow.up")
268 } 243 }
@@ -512,56 +487,18 @@ struct WorkflowRunSummaryView: View {
512 } 487 }
513 } 488 }
514 489
515 Section(visibleResults.isEmpty ? "Meaningful Changes" : "Results") { 490 BatchResultsSection(
516 if visibleResults.isEmpty { 491 viewModel: viewModel,
517 Text("No domains with meaningful changes or warnings") 492 results: visibleResults,
518 .font(.system(.caption, design: .monospaced)) 493 emptyTitle: "Meaningful Changes",
519 .foregroundStyle(Color(.appTextSecondary)) 494 emptyText: "No domains with meaningful changes or warnings"
520 } else { 495 )
521 ForEach(visibleResults) { result in
522 if let entry = viewModel.historyEntry(for: result) {
523 NavigationLink {
524 HistoryDetailView(viewModel: viewModel, entry: entry)
525 } label: {
526 BatchResultRowView(result: result)
527 }
528 } else {
529 BatchResultRowView(result: result)
530 }
531 }
532 }
533 }
534 } 496 }
535 .navigationTitle("Workflow Summary") 497 .navigationTitle("Workflow Summary")
536 .toolbar { 498 .toolbar {
537 ToolbarItemGroup(placement: .topBarTrailing) { 499 ToolbarItemGroup(placement: .topBarTrailing) {
538 Menu { 500 Menu {
539 Button("Export TXT") { 501 ExportFormatButtons(share: share)
540 share(format: .text)
541 }
542 if FeatureAccessService.hasAccess(to: .advancedExports) {
543 Button("Export CSV") {
544 share(format: .csv)
545 }
546 Button("Export JSON") {
547 share(format: .json)
548 }
549 Button("Export Markdown") {
550 share(format: .markdown)
551 }
552 Button("Export PDF") {
553 share(format: .pdf)
554 }
555 } else {
556 Button("CSV Export • Available in Pro") { /* Inert: disabled Pro upsell affordance. */ }
557 .disabled(true)
558 Button("JSON Export • Available in Pro") { /* Inert: disabled Pro upsell affordance. */ }
559 .disabled(true)
560 Button("Markdown Export • Available in Pro") { /* Inert: disabled Pro upsell affordance. */ }
561 .disabled(true)
562 Button("PDF Export • Available in Pro") { /* Inert: disabled Pro upsell affordance. */ }
563 .disabled(true)
564 }
565 } label: { 502 } label: {
566 Image(systemName: "square.and.arrow.up") 503 Image(systemName: "square.and.arrow.up")
567 } 504 }
DomainInspectionService.swift +120 −240
@@ -19,11 +19,7 @@ struct DomainInspectionService {
19 let startedAt = Date() 19 let startedAt = Date()
20 let resolverDisplayName = DNSLookupService.currentResolverDisplayName() 20 let resolverDisplayName = DNSLookupService.currentResolverDisplayName()
21 let resolverURLString = DNSLookupService.currentResolverURLString() 21 let resolverURLString = DNSLookupService.currentResolverURLString()
22 var cachedSections = Set<LookupSectionKind>() 22 var ledger = InspectionLedger(resolverDisplayName: resolverDisplayName)
23 var sectionSources: [LookupResultSource] = []
24 var provenanceBySection: [LookupSectionKind: SectionProvenance] = [:]
25 var dataSources = Set<String>()
26 var errorDetails: [LookupSectionKind: InspectionFailure] = [:]
27 23
28 async let dnsFetch = runtime.dns(domain: normalizedDomain) 24 async let dnsFetch = runtime.dns(domain: normalizedDomain)
29 async let availabilityFetch = runtime.availability(domain: normalizedDomain) 25 async let availabilityFetch = runtime.availability(domain: normalizedDomain)
@@ -37,110 +33,46 @@ struct DomainInspectionService {
37 let resolvedDNS = await dnsFetch 33 let resolvedDNS = await dnsFetch
38 DomainDebugLog.debug("Inspection.sectionComplete domain=\(normalizedDomain) section=dns source=\(resolvedDNS.source.rawValue)") 34 DomainDebugLog.debug("Inspection.sectionComplete domain=\(normalizedDomain) section=dns source=\(resolvedDNS.source.rawValue)")
39 let dnsResult = normalizeErrors(in: resolvedDNS.value) 35 let dnsResult = normalizeErrors(in: resolvedDNS.value)
40 track( 36 ledger.track(.dns, source: resolvedDNS.source)
41 .dns, 37 ledger.captureFailure(for: .dns, result: dnsResult)
42 source: resolvedDNS.source,
43 provenance: provenance(for: .dns, source: resolvedDNS.source, collectedAt: Date(), resolverDisplayName: resolverDisplayName),
44 cachedSections: &cachedSections,
45 sectionSources: &sectionSources,
46 provenanceBySection: &provenanceBySection,
47 dataSources: &dataSources
48 )
49 captureFailure(for: .dns, result: dnsResult, into: &errorDetails)
50 38
51 let availability = await availabilityFetch 39 let availability = await availabilityFetch
52 DomainDebugLog.debug("Inspection.sectionComplete domain=\(normalizedDomain) section=availability source=\(availability.source.rawValue)") 40 DomainDebugLog.debug("Inspection.sectionComplete domain=\(normalizedDomain) section=availability source=\(availability.source.rawValue)")
53 track( 41 ledger.track(.availability, source: availability.source)
54 .availability,
55 source: availability.source,
56 provenance: provenance(for: .availability, source: availability.source, collectedAt: Date(), resolverDisplayName: resolverDisplayName),
57 cachedSections: &cachedSections,
58 sectionSources: &sectionSources,
59 provenanceBySection: &provenanceBySection,
60 dataSources: &dataSources
61 )
62 42
63 let resolvedSSL = await sslFetch 43 let resolvedSSL = await sslFetch
64 DomainDebugLog.debug("Inspection.sectionComplete domain=\(normalizedDomain) section=ssl source=\(resolvedSSL.source.rawValue)") 44 DomainDebugLog.debug("Inspection.sectionComplete domain=\(normalizedDomain) section=ssl source=\(resolvedSSL.source.rawValue)")
65 let sslResult = normalizeErrors(in: resolvedSSL.value) 45 let sslResult = normalizeErrors(in: resolvedSSL.value)
66 track( 46 ledger.track(.ssl, source: resolvedSSL.source)
67 .ssl, 47 ledger.captureFailure(for: .ssl, result: sslResult)
68 source: resolvedSSL.source,
69 provenance: provenance(for: .ssl, source: resolvedSSL.source, collectedAt: Date(), resolverDisplayName: resolverDisplayName),
70 cachedSections: &cachedSections,
71 sectionSources: &sectionSources,
72 provenanceBySection: &provenanceBySection,
73 dataSources: &dataSources
74 )
75 captureFailure(for: .ssl, result: sslResult, into: &errorDetails)
76 48
77 let hsts = await hstsFetch 49 let hsts = await hstsFetch
78 DomainDebugLog.debug("Inspection.sectionComplete domain=\(normalizedDomain) section=hsts source=\(hsts.source.rawValue)") 50 DomainDebugLog.debug("Inspection.sectionComplete domain=\(normalizedDomain) section=hsts source=\(hsts.source.rawValue)")
79 track( 51 ledger.track(.hsts, source: hsts.source)
80 .hsts,
81 source: hsts.source,
82 provenance: provenance(for: .hsts, source: hsts.source, collectedAt: Date(), resolverDisplayName: resolverDisplayName),
83 cachedSections: &cachedSections,
84 sectionSources: &sectionSources,
85 provenanceBySection: &provenanceBySection,
86 dataSources: &dataSources
87 )
88 52
89 let http = await httpFetch 53 let http = await httpFetch
90 DomainDebugLog.debug("Inspection.sectionComplete domain=\(normalizedDomain) section=http source=\(http.source.rawValue)") 54 DomainDebugLog.debug("Inspection.sectionComplete domain=\(normalizedDomain) section=http source=\(http.source.rawValue)")
91 let httpResult = normalizeErrors(in: http.value) 55 let httpResult = normalizeErrors(in: http.value)
92 track( 56 ledger.track(.httpHeaders, source: http.source)
93 .httpHeaders, 57 ledger.captureFailure(for: .httpHeaders, result: httpResult)
94 source: http.source,
95 provenance: provenance(for: .httpHeaders, source: http.source, collectedAt: Date(), resolverDisplayName: resolverDisplayName),
96 cachedSections: &cachedSections,
97 sectionSources: &sectionSources,
98 provenanceBySection: &provenanceBySection,
99 dataSources: &dataSources
100 )
101 captureFailure(for: .httpHeaders, result: httpResult, into: &errorDetails)
102 58
103 let resolvedOwnership = await ownershipFetch 59 let resolvedOwnership = await ownershipFetch
104 DomainDebugLog.debug("Inspection.sectionComplete domain=\(normalizedDomain) section=ownership source=\(resolvedOwnership.source.rawValue)") 60 DomainDebugLog.debug("Inspection.sectionComplete domain=\(normalizedDomain) section=ownership source=\(resolvedOwnership.source.rawValue)")
105 let ownershipResult = normalizeErrors(in: resolvedOwnership.value) 61 let ownershipResult = normalizeErrors(in: resolvedOwnership.value)
106 track( 62 ledger.track(.ownership, source: resolvedOwnership.source)
107 .ownership, 63 ledger.captureFailure(for: .ownership, result: ownershipResult)
108 source: resolvedOwnership.source,
109 provenance: provenance(for: .ownership, source: resolvedOwnership.source, collectedAt: Date(), resolverDisplayName: resolverDisplayName),
110 cachedSections: &cachedSections,
111 sectionSources: &sectionSources,
112 provenanceBySection: &provenanceBySection,
113 dataSources: &dataSources
114 )
115 captureFailure(for: .ownership, result: ownershipResult, into: &errorDetails)
116 64
117 let redirects = await redirectFetch 65 let redirects = await redirectFetch
118 DomainDebugLog.debug("Inspection.sectionComplete domain=\(normalizedDomain) section=redirect source=\(redirects.source.rawValue)") 66 DomainDebugLog.debug("Inspection.sectionComplete domain=\(normalizedDomain) section=redirect source=\(redirects.source.rawValue)")
119 let redirectResult = normalizeErrors(in: redirects.value) 67 let redirectResult = normalizeErrors(in: redirects.value)
120 track( 68 ledger.track(.redirectChain, source: redirects.source)
121 .redirectChain, 69 ledger.captureFailure(for: .redirectChain, result: redirectResult)
122 source: redirects.source,
123 provenance: provenance(for: .redirectChain, source: redirects.source, collectedAt: Date(), resolverDisplayName: resolverDisplayName),
124 cachedSections: &cachedSections,
125 sectionSources: &sectionSources,
126 provenanceBySection: &provenanceBySection,
127 dataSources: &dataSources
128 )
129 captureFailure(for: .redirectChain, result: redirectResult, into: &errorDetails)
130 70
131 let resolvedSubdomains = await subdomainFetch 71 let resolvedSubdomains = await subdomainFetch
132 DomainDebugLog.debug("Inspection.sectionComplete domain=\(normalizedDomain) section=subdomains source=\(resolvedSubdomains.source.rawValue)") 72 DomainDebugLog.debug("Inspection.sectionComplete domain=\(normalizedDomain) section=subdomains source=\(resolvedSubdomains.source.rawValue)")
133 let subdomainResult = normalizeErrors(in: resolvedSubdomains.value) 73 let subdomainResult = normalizeErrors(in: resolvedSubdomains.value)
134 track( 74 ledger.track(.subdomains, source: resolvedSubdomains.source)
135 .subdomains, 75 ledger.captureFailure(for: .subdomains, result: subdomainResult)
136 source: resolvedSubdomains.source,
137 provenance: provenance(for: .subdomains, source: resolvedSubdomains.source, collectedAt: Date(), resolverDisplayName: resolverDisplayName),
138 cachedSections: &cachedSections,
139 sectionSources: &sectionSources,
140 provenanceBySection: &provenanceBySection,
141 dataSources: &dataSources
142 )
143 captureFailure(for: .subdomains, result: subdomainResult, into: &errorDetails)
144 76
145 let dnsSections = mapServiceResult(dnsResult, emptyValue: []) 77 let dnsSections = mapServiceResult(dnsResult, emptyValue: [])
146 let sslInfo = mapOptionalValueServiceResult(sslResult) 78 let sslInfo = mapOptionalValueServiceResult(sslResult)
@@ -158,85 +90,46 @@ struct DomainInspectionService {
158 let canReuseDNSDependents = canReuseDependentSections(from: previousSnapshot, dnsSections: dnsSections.value) 90 let canReuseDNSDependents = canReuseDependentSections(from: previousSnapshot, dnsSections: dnsSections.value)
159 let canReuseIPDependents = canReuseIPBasedSections(from: previousSnapshot, primaryIP: primaryIP) 91 let canReuseIPDependents = canReuseIPBasedSections(from: previousSnapshot, primaryIP: primaryIP)
160 92
161 let reachabilityOutcome: CachedLookupResult<ServiceResult<[PortReachability]>> 93 let reachabilityOutcome = await whenRoutable(hasNetworkTarget) {
162 if hasNetworkTarget { 94 await runtime.reachability(domain: normalizedDomain)
163 reachabilityOutcome = await runtime.reachability(domain: normalizedDomain)
164 } else {
165 reachabilityOutcome = CachedLookupResult(value: .empty("No routable address available"), source: .live)
166 } 95 }
167 let reachabilityResult = normalizeErrors(in: reachabilityOutcome.value) 96 let reachabilityResult = normalizeErrors(in: reachabilityOutcome.value)
168 DomainDebugLog.debug("Inspection.sectionComplete domain=\(normalizedDomain) section=reachability hasNetworkTarget=\(hasNetworkTarget) source=\(reachabilityOutcome.source.rawValue)") 97 DomainDebugLog.debug("Inspection.sectionComplete domain=\(normalizedDomain) section=reachability hasNetworkTarget=\(hasNetworkTarget) source=\(reachabilityOutcome.source.rawValue)")
169 track( 98 ledger.track(.reachability, source: reachabilityOutcome.source)
170 .reachability,
171 source: reachabilityOutcome.source,
172 provenance: provenance(for: .reachability, source: reachabilityOutcome.source, collectedAt: Date(), resolverDisplayName: resolverDisplayName),
173 cachedSections: &cachedSections,
174 sectionSources: &sectionSources,
175 provenanceBySection: &provenanceBySection,
176 dataSources: &dataSources
177 )
178 if hasNetworkTarget { 99 if hasNetworkTarget {
179 captureFailure(for: .reachability, result: reachabilityResult, into: &errorDetails) 100 ledger.captureFailure(for: .reachability, result: reachabilityResult)
180 } 101 }
181 let reachabilityResultValue = mapServiceResult(reachabilityResult, emptyValue: []) 102 let reachabilityResultValue = mapServiceResult(reachabilityResult, emptyValue: [])
182 103
183 let portScanOutcome: CachedLookupResult<ServiceResult<[PortScanResult]>> 104 let portScanOutcome = await whenRoutable(hasNetworkTarget) {
184 if hasNetworkTarget { 105 await runtime.portScan(domain: normalizedDomain)
185 portScanOutcome = await runtime.portScan(domain: normalizedDomain)
186 } else {
187 portScanOutcome = CachedLookupResult(value: .empty("No routable address available"), source: .live)
188 } 106 }
189 let portScanResult = normalizeErrors(in: portScanOutcome.value) 107 let portScanResult = normalizeErrors(in: portScanOutcome.value)
190 DomainDebugLog.debug("Inspection.sectionComplete domain=\(normalizedDomain) section=portScan hasNetworkTarget=\(hasNetworkTarget) source=\(portScanOutcome.source.rawValue)") 108 DomainDebugLog.debug("Inspection.sectionComplete domain=\(normalizedDomain) section=portScan hasNetworkTarget=\(hasNetworkTarget) source=\(portScanOutcome.source.rawValue)")
191 track( 109 ledger.track(.portScan, source: portScanOutcome.source)
192 .portScan,
193 source: portScanOutcome.source,
194 provenance: provenance(for: .portScan, source: portScanOutcome.source, collectedAt: Date(), resolverDisplayName: resolverDisplayName),
195 cachedSections: &cachedSections,
196 sectionSources: &sectionSources,
197 provenanceBySection: &provenanceBySection,
198 dataSources: &dataSources
199 )
200 if hasNetworkTarget { 110 if hasNetworkTarget {
201 captureFailure(for: .portScan, result: portScanResult, into: &errorDetails) 111 ledger.captureFailure(for: .portScan, result: portScanResult)
202 } 112 }
203 let portScanResults = hasNetworkTarget 113 let portScanResults = hasNetworkTarget
204 ? await mapPortScanResult(portScanResult, domain: normalizedDomain) 114 ? await mapPortScanResult(portScanResult, domain: normalizedDomain)
205 : (value: [], message: nil) 115 : (value: [], message: nil)
206 116
207 let emailOutcome: CachedLookupResult<ServiceResult<EmailSecurityResult>> 117 let emailOutcome = await reusingPrevious(
208 if canReuseDNSDependents, let previousSnapshot, let emailSecurity = previousSnapshot.emailSecurity { 118 previousSnapshot?.emailSecurity,
209 emailOutcome = CachedLookupResult(value: .success(emailSecurity), source: .cached) 119 error: previousSnapshot?.emailSecurityError,
210 } else if canReuseDNSDependents, let previousSnapshot, let error = previousSnapshot.emailSecurityError { 120 when: canReuseDNSDependents
211 emailOutcome = CachedLookupResult(value: .error(error), source: .cached) 121 ) {
212 } else { 122 await runtime.email(domain: normalizedDomain, txtRecords: txtRecords)
213 emailOutcome = await runtime.email(domain: normalizedDomain, txtRecords: txtRecords)
214 } 123 }
215 let normalizedEmailResult = normalizeErrors(in: emailOutcome.value) 124 let normalizedEmailResult = normalizeErrors(in: emailOutcome.value)
216 DomainDebugLog.debug("Inspection.sectionComplete domain=\(normalizedDomain) section=email source=\(emailOutcome.source.rawValue)") 125 DomainDebugLog.debug("Inspection.sectionComplete domain=\(normalizedDomain) section=email source=\(emailOutcome.source.rawValue)")
217 track( 126 ledger.track(.emailSecurity, source: emailOutcome.source)
218 .emailSecurity, 127 ledger.captureFailure(for: .emailSecurity, result: normalizedEmailResult)
219 source: emailOutcome.source,
220 provenance: provenance(for: .emailSecurity, source: emailOutcome.source, collectedAt: Date(), resolverDisplayName: resolverDisplayName),
221 cachedSections: &cachedSections,
222 sectionSources: &sectionSources,
223 provenanceBySection: &provenanceBySection,
224 dataSources: &dataSources
225 )
226 captureFailure(for: .emailSecurity, result: normalizedEmailResult, into: &errorDetails)
227 128
228 let suggestionsOutcome: CachedLookupResult<[DomainSuggestionResult]> 129 let suggestionsOutcome: CachedLookupResult<[DomainSuggestionResult]>
229 if availability.value.status == .registered { 130 if availability.value.status == .registered {
230 suggestionsOutcome = await runtime.suggestions(domain: normalizedDomain) 131 suggestionsOutcome = await runtime.suggestions(domain: normalizedDomain)
231 track( 132 ledger.track(.suggestions, source: suggestionsOutcome.source)
232 .suggestions,
233 source: suggestionsOutcome.source,
234 provenance: provenance(for: .suggestions, source: suggestionsOutcome.source, collectedAt: Date(), resolverDisplayName: resolverDisplayName),
235 cachedSections: &cachedSections,
236 sectionSources: &sectionSources,
237 provenanceBySection: &provenanceBySection,
238 dataSources: &dataSources
239 )
240 } else { 133 } else {
241 suggestionsOutcome = CachedLookupResult(value: [], source: .live) 134 suggestionsOutcome = CachedLookupResult(value: [], source: .live)
242 } 135 }
@@ -244,48 +137,26 @@ struct DomainInspectionService {
244 let ptrOutcome: CachedLookupResult<ServiceResult<String>>? 137 let ptrOutcome: CachedLookupResult<ServiceResult<String>>?
245 let geoOutcome: CachedLookupResult<ServiceResult<IPGeolocation>>? 138 let geoOutcome: CachedLookupResult<ServiceResult<IPGeolocation>>?
246 if let primaryIP { 139 if let primaryIP {
247 if canReuseIPDependents, let previousSnapshot, let ptrRecord = previousSnapshot.ptrRecord { 140 let ptr = await reusingPrevious(
248 ptrOutcome = CachedLookupResult(value: .success(ptrRecord), source: .cached) 141 previousSnapshot?.ptrRecord,
249 } else if canReuseIPDependents, let previousSnapshot, let ptrError = previousSnapshot.ptrError { 142 error: previousSnapshot?.ptrError,
250 ptrOutcome = CachedLookupResult(value: .error(ptrError), source: .cached) 143 when: canReuseIPDependents
251 } else { 144 ) {
252 ptrOutcome = await runtime.ptr(ip: primaryIP, resolverURLString: resolverURLString) 145 await runtime.ptr(ip: primaryIP, resolverURLString: resolverURLString)
253 }
254
255 if canReuseIPDependents, let previousSnapshot, let ipGeolocation = previousSnapshot.ipGeolocation {
256 geoOutcome = CachedLookupResult(value: .success(ipGeolocation), source: .cached)
257 } else if canReuseIPDependents, let previousSnapshot, let ipGeolocationError = previousSnapshot.ipGeolocationError {
258 geoOutcome = CachedLookupResult(value: .error(ipGeolocationError), source: .cached)
259 } else {
260 geoOutcome = await runtime.ipGeolocation(ip: primaryIP)
261 }
262
263 if let ptrOutcome {
264 let normalizedPTRResult = normalizeErrors(in: ptrOutcome.value)
265 track(
266 .ptr,
267 source: ptrOutcome.source,
268 provenance: provenance(for: .ptr, source: ptrOutcome.source, collectedAt: Date(), resolverDisplayName: resolverDisplayName),
269 cachedSections: &cachedSections,
270 sectionSources: &sectionSources,
271 provenanceBySection: &provenanceBySection,
272 dataSources: &dataSources
273 )
274 captureFailure(for: .ptr, result: normalizedPTRResult, into: &errorDetails)
275 } 146 }
276 if let geoOutcome { 147 let geo = await reusingPrevious(
277 let normalizedGeoResult = normalizeErrors(in: geoOutcome.value) 148 previousSnapshot?.ipGeolocation,
278 track( 149 error: previousSnapshot?.ipGeolocationError,
279 .ipGeolocation, 150 when: canReuseIPDependents
280 source: geoOutcome.source, 151 ) {
281 provenance: provenance(for: .ipGeolocation, source: geoOutcome.source, collectedAt: Date(), resolverDisplayName: resolverDisplayName), 152 await runtime.ipGeolocation(ip: primaryIP)
282 cachedSections: &cachedSections,
283 sectionSources: &sectionSources,
284 provenanceBySection: &provenanceBySection,
285 dataSources: &dataSources
286 )
287 captureFailure(for: .ipGeolocation, result: normalizedGeoResult, into: &errorDetails)
288 } 153 }
154 ledger.track(.ptr, source: ptr.source)
155 ledger.captureFailure(for: .ptr, result: normalizeErrors(in: ptr.value))
156 ledger.track(.ipGeolocation, source: geo.source)
157 ledger.captureFailure(for: .ipGeolocation, result: normalizeErrors(in: geo.value))
158 ptrOutcome = ptr
159 geoOutcome = geo
289 } else { 160 } else {
290 ptrOutcome = nil 161 ptrOutcome = nil
291 geoOutcome = nil 162 geoOutcome = nil
@@ -294,12 +165,12 @@ struct DomainInspectionService {
294 let emailSecurity = mapOptionalValueServiceResult(normalizedEmailResult) 165 let emailSecurity = mapOptionalValueServiceResult(normalizedEmailResult)
295 let ptrRecord = mapOptionalServiceResult(ptrOutcome.map { normalizeErrors(in: $0.value) }, missingMessage: "No A record available") 166 let ptrRecord = mapOptionalServiceResult(ptrOutcome.map { normalizeErrors(in: $0.value) }, missingMessage: "No A record available")
296 let geolocation = mapOptionalServiceResult(geoOutcome.map { normalizeErrors(in: $0.value) }, missingMessage: "No A record available") 167 let geolocation = mapOptionalServiceResult(geoOutcome.map { normalizeErrors(in: $0.value) }, missingMessage: "No A record available")
297 let availabilityConfidence = confidenceForAvailability(result: availability.value, provenance: provenanceBySection[.availability]) 168 let availabilityConfidence = confidenceForAvailability(result: availability.value, provenance: ledger.provenanceBySection[.availability])
298 let ownershipConfidence = confidenceForOwnership(result: ownership.value) 169 let ownershipConfidence = confidenceForOwnership(result: ownership.value)
299 let subdomainConfidence = confidenceForSubdomains(results: subdomains.value) 170 let subdomainConfidence = confidenceForSubdomains(results: subdomains.value)
300 let emailConfidence = confidenceForEmail(result: emailSecurity.value) 171 let emailConfidence = confidenceForEmail(result: emailSecurity.value)
301 let geolocationConfidence = confidenceForGeolocation(result: geolocation.value) 172 let geolocationConfidence = confidenceForGeolocation(result: geolocation.value)
302 let validationIssues = validationIssues(for: normalizedDomain, snapshotTimestamp: startedAt, availability: availability.value, dnsSections: dnsSections.value, provenanceBySection: provenanceBySection) 173 let validationIssues = validationIssues(for: normalizedDomain, snapshotTimestamp: startedAt, availability: availability.value, dnsSections: dnsSections.value, provenanceBySection: ledger.provenanceBySection)
303 174
304 let snapshot = LookupSnapshot( 175 let snapshot = LookupSnapshot(
305 historyEntryID: nil, 176 historyEntryID: nil,
@@ -310,14 +181,14 @@ struct DomainInspectionService {
310 appVersion: AppVersion.current, 181 appVersion: AppVersion.current,
311 resolverDisplayName: resolverDisplayName, 182 resolverDisplayName: resolverDisplayName,
312 resolverURLString: resolverURLString, 183 resolverURLString: resolverURLString,
313 dataSources: Array(dataSources).sorted(), 184 dataSources: Array(ledger.dataSources).sorted(),
314 provenanceBySection: provenanceBySection, 185 provenanceBySection: ledger.provenanceBySection,
315 availabilityConfidence: availabilityConfidence, 186 availabilityConfidence: availabilityConfidence,
316 ownershipConfidence: ownershipConfidence, 187 ownershipConfidence: ownershipConfidence,
317 subdomainConfidence: subdomainConfidence, 188 subdomainConfidence: subdomainConfidence,
318 emailSecurityConfidence: emailConfidence, 189 emailSecurityConfidence: emailConfidence,
319 geolocationConfidence: geolocationConfidence, 190 geolocationConfidence: geolocationConfidence,
320 errorDetails: errorDetails, 191 errorDetails: ledger.errorDetails,
321 isPartialSnapshot: !validationIssues.isEmpty, 192 isPartialSnapshot: !validationIssues.isEmpty,
322 validationIssues: validationIssues, 193 validationIssues: validationIssues,
323 totalLookupDurationMs: Int(Date().timeIntervalSince(startedAt) * 1000), 194 totalLookupDurationMs: Int(Date().timeIntervalSince(startedAt) * 1000),
@@ -374,8 +245,8 @@ struct DomainInspectionService {
374 portScanResults: portScanResults.value, 245 portScanResults: portScanResults.value,
375 portScanError: portScanResults.message, 246 portScanError: portScanResults.message,
376 changeSummary: nil, 247 changeSummary: nil,
377 resultSource: aggregateSource(sectionSources), 248 resultSource: aggregateSource(ledger.sectionSources),
378 cachedSections: Array(cachedSections).sorted { $0.rawValue < $1.rawValue }, 249 cachedSections: Array(ledger.cachedSections).sorted { $0.rawValue < $1.rawValue },
379 statusMessage: nil 250 statusMessage: nil
380 ) 251 )
381 DomainDebugLog.signpostEnd( 252 DomainDebugLog.signpostEnd(
@@ -396,24 +267,36 @@ struct DomainInspectionService {
396 .lowercased() ?? domain.lowercased() 267 .lowercased() ?? domain.lowercased()
397 } 268 }
398 269
399 private func track( 270 /// A lookup that needs an address to reach, or an empty result when the
400 _ section: LookupSectionKind, 271 /// domain has none.
401 source: LookupResultSource, 272 private func whenRoutable<Value>(
402 provenance: SectionProvenance, 273 _ hasNetworkTarget: Bool,
403 cachedSections: inout Set<LookupSectionKind>, 274 fetch: () async -> CachedLookupResult<ServiceResult<Value>>
404 sectionSources: inout [LookupResultSource], 275 ) async -> CachedLookupResult<ServiceResult<Value>> {
405 provenanceBySection: inout [LookupSectionKind: SectionProvenance], 276 guard hasNetworkTarget else {
406 dataSources: inout Set<String> 277 return CachedLookupResult(value: .empty("No routable address available"), source: .live)
407 ) {
408 sectionSources.append(source)
409 provenanceBySection[section] = provenance
410 dataSources.insert(provenance.provider ?? provenance.source)
411 if source != .live {
412 cachedSections.insert(section)
413 } 278 }
279 return await fetch()
414 } 280 }
415 281
416 private func provenance( 282 /// The previous snapshot's value, or its error, when its section can be
283 /// reused; otherwise a fresh lookup.
284 private func reusingPrevious<Value>(
285 _ value: Value?,
286 error: String?,
287 when reusable: Bool,
288 otherwise fetch: () async -> CachedLookupResult<ServiceResult<Value>>
289 ) async -> CachedLookupResult<ServiceResult<Value>> {
290 if reusable, let value {
291 return CachedLookupResult(value: .success(value), source: .cached)
292 }
293 if reusable, let error {
294 return CachedLookupResult(value: .error(error), source: .cached)
295 }
296 return await fetch()
297 }
298
299 fileprivate static func provenance(
417 for section: LookupSectionKind, 300 for section: LookupSectionKind,
418 source: LookupResultSource, 301 source: LookupResultSource,
419 collectedAt: Date, 302 collectedAt: Date,
@@ -514,13 +397,13 @@ struct DomainInspectionService {
514 case let .success(value): 397 case let .success(value):
515 return .success(value) 398 return .success(value)
516 case let .empty(message): 399 case let .empty(message):
517 return .empty(classifyFailure(from: message, defaultKind: .unavailable).message) 400 return .empty(Self.classifyFailure(from: message, defaultKind: .unavailable).message)
518 case let .error(message): 401 case let .error(message):
519 return .error(classifyFailure(from: message).message) 402 return .error(Self.classifyFailure(from: message).message)
520 } 403 }
521 } 404 }
522 405
523 private func classifyFailure(from message: String, defaultKind: InspectionErrorKind = .unknown) -> InspectionFailure { 406 fileprivate static func classifyFailure(from message: String, defaultKind: InspectionErrorKind = .unknown) -> InspectionFailure {
524 let normalizedMessage = message.trimmingCharacters(in: .whitespacesAndNewlines) 407 let normalizedMessage = message.trimmingCharacters(in: .whitespacesAndNewlines)
525 let lowercasedMessage = normalizedMessage.lowercased() 408 let lowercasedMessage = normalizedMessage.lowercased()
526 if lowercasedMessage.contains("timed out") { 409 if lowercasedMessage.contains("timed out") {
@@ -554,21 +437,6 @@ struct DomainInspectionService {
554 return InspectionFailure(kind: .unknown, message: normalizedMessage.isEmpty ? defaultKind.title : normalizedMessage, details: normalizedMessage) 437 return InspectionFailure(kind: .unknown, message: normalizedMessage.isEmpty ? defaultKind.title : normalizedMessage, details: normalizedMessage)
555 } 438 }
556 439
557 private func captureFailure<Value>(
558 for section: LookupSectionKind,
559 result: ServiceResult<Value>,
560 into errorDetails: inout [LookupSectionKind: InspectionFailure]
561 ) {
562 switch result {
563 case .success:
564 return
565 case let .empty(message):
566 errorDetails[section] = classifyFailure(from: message, defaultKind: .unavailable)
567 case let .error(message):
568 errorDetails[section] = classifyFailure(from: message)
569 }
570 }
571
572 private func confidenceForAvailability(result: DomainAvailabilityResult, provenance: SectionProvenance?) -> ConfidenceLevel { 440 private func confidenceForAvailability(result: DomainAvailabilityResult, provenance: SectionProvenance?) -> ConfidenceLevel {
573 guard result.status != .unknown else { return .low } 441 guard result.status != .unknown else { return .low }
574 if provenance?.provider?.localizedCaseInsensitiveContains("rdap.org") == true, result.status == .registered { 442 if provenance?.provider?.localizedCaseInsensitiveContains("rdap.org") == true, result.status == .registered {
@@ -678,7 +546,7 @@ struct DomainInspectionService {
678 private func mapPortScanResult(_ result: ServiceResult<[PortScanResult]>, domain: String) async -> (value: [PortScanResult], message: String?) { 546 private func mapPortScanResult(_ result: ServiceResult<[PortScanResult]>, domain: String) async -> (value: [PortScanResult], message: String?) {
679 switch result { 547 switch result {
680 case let .success(results): 548 case let .success(results):
681 return (await enrichOpenPortBanners(in: results, domain: domain), nil) 549 return (await PortScanService.withBanners(results, host: domain), nil)
682 case let .empty(message), let .error(message): 550 case let .empty(message), let .error(message):
683 return ([], message) 551 return ([], message)
684 } 552 }
@@ -716,29 +584,41 @@ struct DomainInspectionService {
716 ) 584 )
717 } 585 }
718 } 586 }
587}
719 588
720 private func enrichOpenPortBanners(in results: [PortScanResult], domain: String) async -> [PortScanResult] { 589/// What an inspection has learned about its sections so far: where each came
721 let banners = await withTaskGroup(of: (UInt16, String?).self, returning: [UInt16: String].self) { group in 590/// from, which were served from cache, and which failed.
722 for result in results where result.open { 591private struct InspectionLedger {
723 group.addTask { 592 let resolverDisplayName: String
724 let banner = await PortScanService.grabBanner(host: domain, port: result.port) 593 var cachedSections = Set<LookupSectionKind>()
725 return (result.port, banner) 594 var sectionSources: [LookupResultSource] = []
726 } 595 var provenanceBySection: [LookupSectionKind: SectionProvenance] = [:]
727 } 596 var dataSources = Set<String>()
728 597 var errorDetails: [LookupSectionKind: InspectionFailure] = [:]
729 var collected: [UInt16: String] = [:] 598
730 for await (port, banner) in group { 599 mutating func track(_ section: LookupSectionKind, source: LookupResultSource) {
731 if let banner { 600 let provenance = DomainInspectionService.provenance(
732 collected[port] = banner 601 for: section,
733 } 602 source: source,
734 } 603 collectedAt: Date(),
735 return collected 604 resolverDisplayName: resolverDisplayName
605 )
606 sectionSources.append(source)
607 provenanceBySection[section] = provenance
608 dataSources.insert(provenance.provider ?? provenance.source)
609 if source != .live {
610 cachedSections.insert(section)
736 } 611 }
612 }
737 613
738 return results.map { result in 614 mutating func captureFailure<Value>(for section: LookupSectionKind, result: ServiceResult<Value>) {
739 var updated = result 615 switch result {
740 updated.banner = banners[result.port] 616 case .success:
741 return updated 617 return
618 case let .empty(message):
619 errorDetails[section] = DomainInspectionService.classifyFailure(from: message, defaultKind: .unavailable)
620 case let .error(message):
621 errorDetails[section] = DomainInspectionService.classifyFailure(from: message)
742 } 622 }
743 } 623 }
744} 624}
DomainReportBuilder.swift +47 −42
@@ -521,7 +521,8 @@ enum DomainIntelligenceService {
521 } 521 }
522 522
523 private static func inferProvider(from snapshot: LookupSnapshot) -> InferredProviderFingerprint? { 523 private static func inferProvider(from snapshot: LookupSnapshot) -> InferredProviderFingerprint? {
524 let headerMap = Dictionary(uniqueKeysWithValues: snapshot.httpHeaders.map { ($0.name.lowercased(), $0.value.lowercased()) }) 524 // A stored or imported snapshot can repeat a header name in another case.
525 let headerMap = Dictionary(snapshot.httpHeaders.map { ($0.name.lowercased(), $0.value.lowercased()) }) { first, _ in first }
525 let dnsProviders = dnsValues(for: .NS, in: snapshot.dnsSections) + dnsValues(for: .CNAME, in: snapshot.dnsSections) 526 let dnsProviders = dnsValues(for: .NS, in: snapshot.dnsSections) + dnsValues(for: .CNAME, in: snapshot.dnsSections)
526 let issuer = snapshot.sslInfo?.issuer.lowercased() ?? "" 527 let issuer = snapshot.sslInfo?.issuer.lowercased() ?? ""
527 let org = snapshot.ipGeolocation?.org?.lowercased() ?? "" 528 let org = snapshot.ipGeolocation?.org?.lowercased() ?? ""
@@ -626,59 +627,63 @@ enum DomainIntelligenceService {
626 } 627 }
627 628
628 private static func buildSubdomainHistory(from snapshots: [LookupSnapshot]) -> [SubdomainHistoryEntry] { 629 private static func buildSubdomainHistory(from snapshots: [LookupSnapshot]) -> [SubdomainHistoryEntry] {
629 struct WorkingState { 630 var states: [String: SubdomainPresence] = [:]
630 var firstSeen: Date
631 var lastSeen: Date
632 var recurrenceCount: Int
633 var statusChangeCount: Int
634 var lastSeenInPreviousSnapshot: Bool
635 }
636
637 var states: [String: WorkingState] = [:]
638 for snapshot in snapshots { 631 for snapshot in snapshots {
639 let currentHosts = Set((snapshot.subdomains + snapshot.extendedSubdomains).map { $0.hostname.lowercased() }) 632 let currentHosts = Set((snapshot.subdomains + snapshot.extendedSubdomains).map { $0.hostname.lowercased() })
640 let knownHosts = Set(states.keys).union(currentHosts) 633 let knownHosts = Set(states.keys).union(currentHosts)
641 for host in knownHosts { 634 for host in knownHosts {
642 let isPresent = currentHosts.contains(host) 635 let isPresent = currentHosts.contains(host)
643 if var state = states[host] { 636 if states[host] != nil {
644 if isPresent { 637 states[host]?.observe(isPresent: isPresent, at: snapshot.timestamp)
645 state.lastSeen = snapshot.timestamp
646 state.recurrenceCount += 1
647 }
648 if state.lastSeenInPreviousSnapshot != isPresent {
649 state.statusChangeCount += 1
650 }
651 state.lastSeenInPreviousSnapshot = isPresent
652 states[host] = state
653 } else if isPresent { 638 } else if isPresent {
654 states[host] = WorkingState( 639 states[host] = SubdomainPresence(firstSeen: snapshot.timestamp)
655 firstSeen: snapshot.timestamp,
656 lastSeen: snapshot.timestamp,
657 recurrenceCount: 1,
658 statusChangeCount: 0,
659 lastSeenInPreviousSnapshot: true
660 )
661 } 640 }
662 } 641 }
663 } 642 }
664 643
665 return states.map { host, state in 644 return states.map { host, state in state.entry(hostname: host) }
666 let isEphemeral = state.recurrenceCount <= 2 || state.statusChangeCount >= 2 645 .sorted { lhs, rhs in
667 return SubdomainHistoryEntry( 646 if lhs.isEphemeral != rhs.isEphemeral {
668 hostname: host, 647 return lhs.isEphemeral && !rhs.isEphemeral
669 firstSeen: state.firstSeen, 648 }
670 lastSeen: state.lastSeen, 649 return lhs.hostname < rhs.hostname
671 recurrenceCount: state.recurrenceCount, 650 }
672 statusChangeCount: state.statusChangeCount, 651 }
673 lastKnownStatus: state.lastSeenInPreviousSnapshot ? "Active" : "Inactive", 652
674 isEphemeral: isEphemeral 653 /// One subdomain's presence across a run of snapshots, from the first that saw it.
675 ) 654 private struct SubdomainPresence {
655 var firstSeen: Date
656 var lastSeen: Date
657 var recurrenceCount = 1
658 var statusChangeCount = 0
659 var lastSeenInPreviousSnapshot = true
660
661 init(firstSeen: Date) {
662 self.firstSeen = firstSeen
663 lastSeen = firstSeen
676 } 664 }
677 .sorted { lhs, rhs in 665
678 if lhs.isEphemeral != rhs.isEphemeral { 666 mutating func observe(isPresent: Bool, at timestamp: Date) {
679 return lhs.isEphemeral && !rhs.isEphemeral 667 if isPresent {
668 lastSeen = timestamp
669 recurrenceCount += 1
680 } 670 }
681 return lhs.hostname < rhs.hostname 671 if lastSeenInPreviousSnapshot != isPresent {
672 statusChangeCount += 1
673 }
674 lastSeenInPreviousSnapshot = isPresent
675 }
676
677 func entry(hostname: String) -> SubdomainHistoryEntry {
678 SubdomainHistoryEntry(
679 hostname: hostname,
680 firstSeen: firstSeen,
681 lastSeen: lastSeen,
682 recurrenceCount: recurrenceCount,
683 statusChangeCount: statusChangeCount,
684 lastKnownStatus: lastSeenInPreviousSnapshot ? "Active" : "Inactive",
685 isEphemeral: recurrenceCount <= 2 || statusChangeCount >= 2
686 )
682 } 687 }
683 } 688 }
684 689
DomainReportExporter.swift +266 −250
@@ -156,6 +156,25 @@ enum DomainReportExporter {
156 } 156 }
157 157
158 static func text(for report: DomainReport) -> String { 158 static func text(for report: DomainReport) -> String {
159 var lines = headerLines(report)
160 appendSection("Summary", to: &lines) { summarySection(report) }
161 appendSection("Risk", to: &lines) { riskSection(report) }
162 appendSection("Insights", to: &lines) { insightsSection(report) }
163 appendSection("Ownership", to: &lines) { ownershipSection(report) }
164 appendSection("Ownership History", to: &lines) { ownershipHistorySection(report) }
165 appendSection("DNS", to: &lines) { dnsSection(report) }
166 appendSection("DNS History", to: &lines) { dnsHistorySection(report) }
167 appendSection("Web", to: &lines) { webSection(report) }
168 appendSection("Email", to: &lines) { emailSection(report) }
169 appendSection("Network", to: &lines) { networkSection(report) }
170 appendSection("Subdomains", to: &lines) { subdomainsSection(report) }
171 appendSection("Pricing", to: &lines) { pricingSection(report) }
172 appendSection("Changes", to: &lines) { changesSection(report) }
173 return lines.joined(separator: "\n")
174 }
175
176 /// The report's title block: what was looked up, when, how, and with what caveats.
177 private static func headerLines(_ report: DomainReport) -> [String] {
159 var lines = [ 178 var lines = [
160 "DomainDig Report", 179 "DomainDig Report",
161 "Domain: \(report.domain)", 180 "Domain: \(report.domain)",
@@ -183,288 +202,285 @@ enum DomainReportExporter {
183 if let workflowContext = report.workflowContext { 202 if let workflowContext = report.workflowContext {
184 lines.append("Workflow Context: \(workflowContext.workflowName ?? workflowContext.source)") 203 lines.append("Workflow Context: \(workflowContext.workflowName ?? workflowContext.source)")
185 } 204 }
205 return lines
206 }
186 207
187 appendSection("Summary", to: &lines) { 208 private static func summarySection(_ report: DomainReport) -> [String] {
188 [ 209 [
189 "Primary IP: \(report.dns.primaryIP ?? "Unavailable")", 210 "Primary IP: \(report.dns.primaryIP ?? "Unavailable")",
190 "Risk Score: \(report.riskAssessment.score) (\(report.riskAssessment.level.title))", 211 "Risk Score: \(report.riskAssessment.score) (\(report.riskAssessment.level.title))",
191 "TLS Status: \(report.web.tlsStatus)", 212 "TLS Status: \(report.web.tlsStatus)",
192 "HTTP: \(httpSummary(for: report))", 213 "HTTP: \(httpSummary(for: report))",
193 "Email: \(report.email.summary)", 214 "Email: \(report.email.summary)",
194 "Subdomains: \(report.subdomains.count)", 215 "Subdomains: \(report.subdomains.count)",
195 "Extended Subdomains: \(report.extendedSubdomains.count)", 216 "Extended Subdomains: \(report.extendedSubdomains.count)",
196 "External Price: \(report.domainPricing?.estimatedPrice ?? "Unavailable")", 217 "External Price: \(report.domainPricing?.estimatedPrice ?? "Unavailable")",
197 "Reputation: \(report.reputation?.status.title ?? "Unavailable")" 218 "Reputation: \(report.reputation?.status.title ?? "Unavailable")"
198 ] 219 ]
199 } 220 }
200 221
201 appendSection("Risk", to: &lines) { 222 private static func riskSection(_ report: DomainReport) -> [String] {
202 var values = [ 223 var values = [
203 "Score: \(report.riskAssessment.score)", 224 "Score: \(report.riskAssessment.score)",
204 "Level: \(report.riskAssessment.level.title)" 225 "Level: \(report.riskAssessment.level.title)"
205 ] 226 ]
206 if report.riskAssessment.factors.isEmpty { 227 if report.riskAssessment.factors.isEmpty {
207 values.append("Factors: None") 228 values.append("Factors: None")
208 } else { 229 } else {
209 values.append("Factors:") 230 values.append("Factors:")
210 for factor in report.riskAssessment.factors { 231 for factor in report.riskAssessment.factors {
211 values.append(" [\(factor.impact.rawValue)] \(factor.description)") 232 values.append(" [\(factor.impact.rawValue)] \(factor.description)")
212 }
213 } 233 }
214 return values
215 } 234 }
235 return values
236 }
216 237
217 appendSection("Insights", to: &lines) { 238 private static func insightsSection(_ report: DomainReport) -> [String] {
218 report.insights.isEmpty ? ["No deterministic insights triggered"] : report.insights.map { "- \($0)" } 239 report.insights.isEmpty ? ["No deterministic insights triggered"] : report.insights.map { "- \($0)" }
219 } 240 }
220 241
221 appendSection("Ownership", to: &lines) { 242 private static func ownershipSection(_ report: DomainReport) -> [String] {
222 var ownershipLines = [ 243 var ownershipLines = [
223 "Registrar: \(report.ownership?.registrar ?? "Unavailable")", 244 "Registrar: \(report.ownership?.registrar ?? "Unavailable")",
224 "Confidence: \(report.ownershipConfidence?.title ?? "N/A")", 245 "Confidence: \(report.ownershipConfidence?.title ?? "N/A")",
225 "Created: \(ownershipDateLabel(report.ownership?.createdDate))", 246 "Created: \(ownershipDateLabel(report.ownership?.createdDate))",
226 "Expires: \(ownershipDateLabel(report.ownership?.expirationDate))", 247 "Expires: \(ownershipDateLabel(report.ownership?.expirationDate))",
227 "Registrant: \(report.ownership?.registrant ?? "Unavailable")", 248 "Registrant: \(report.ownership?.registrant ?? "Unavailable")",
228 "Nameservers: \(joined(report.ownership?.nameservers) ?? "Unavailable")", 249 "Nameservers: \(joined(report.ownership?.nameservers) ?? "Unavailable")",
229 "Status: \(joined(report.ownership?.status) ?? "Unavailable")", 250 "Status: \(joined(report.ownership?.status) ?? "Unavailable")",
230 "Abuse Contact: \(report.ownership?.abuseEmail ?? "Unavailable")" 251 "Abuse Contact: \(report.ownership?.abuseEmail ?? "Unavailable")"
231 ] 252 ]
232 if let provenance = report.sectionProvenance[.ownership] { 253 if let provenance = report.sectionProvenance[.ownership] {
233 ownershipLines.append("Provenance: \(provenanceLabel(provenance))") 254 ownershipLines.append("Provenance: \(provenanceLabel(provenance))")
234 }
235 if let error = report.dns.error, report.ownership == nil {
236 ownershipLines.append("Error: \(error)")
237 } else if let error = report.changeSummary?.message, report.ownership == nil, report.ownership == nil {
238 _ = error
239 }
240 return ownershipLines
241 } 255 }
256 if let error = report.dns.error, report.ownership == nil {
257 ownershipLines.append("Error: \(error)")
258 }
259 return ownershipLines
260 }
242 261
243 appendSection("Ownership History", to: &lines) { 262 private static func ownershipHistorySection(_ report: DomainReport) -> [String] {
244 guard !report.ownershipHistory.isEmpty else { 263 guard !report.ownershipHistory.isEmpty else {
245 return ["No ownership history available"] 264 return ["No ownership history available"]
246 }
247
248 return report.ownershipHistory.map { event in
249 [
250 textDateFormatter.string(from: event.date),
251 event.summary,
252 "source=\(event.source)"
253 ].joined(separator: " | ")
254 }
255 } 265 }
256 266
257 appendSection("DNS", to: &lines) { 267 return report.ownershipHistory.map { event in
258 var dnsLines = [ 268 [
259 "Lookup Duration: \(durationLabel(report.dns.lookupDurationMs))", 269 textDateFormatter.string(from: event.date),
260 "Primary IP: \(report.dns.primaryIP ?? "Unavailable")", 270 event.summary,
261 "PTR: \(report.dns.ptrRecord ?? report.dns.ptrError ?? "Unavailable")", 271 "source=\(event.source)"
262 "DNSSEC: \(dnssecLabel(report.dns.dnssecSigned))", 272 ].joined(separator: " | ")
263 "Patterns: \(report.dns.patternSummary.patterns.joined(separator: " | ").nilIfEmpty ?? "None")"
264 ]
265 if let provenance = report.sectionProvenance[.dns] {
266 dnsLines.append("Provenance: \(provenanceLabel(provenance))")
267 }
268 if let error = report.dns.error {
269 dnsLines.append("Error: \(error)")
270 }
271 if report.dns.recordSections.isEmpty {
272 dnsLines.append("Records: None")
273 } else {
274 dnsLines.append("Records:")
275 for section in report.dns.recordSections {
276 var seen: Set<String> = []
277 let values = (section.records + section.wildcardRecords)
278 .map(\.value)
279 .filter { seen.insert($0).inserted }
280 let renderedValues = values.isEmpty ? "None" : values.joined(separator: " | ")
281 dnsLines.append(" \(section.recordType.rawValue): \(renderedValues)")
282 }
283 }
284 return dnsLines
285 } 273 }
274 }
286 275
287 appendSection("DNS History", to: &lines) { 276 private static func dnsSection(_ report: DomainReport) -> [String] {
288 guard !report.dnsHistory.isEmpty else { 277 var dnsLines = [
289 return ["No DNS history available"] 278 "Lookup Duration: \(durationLabel(report.dns.lookupDurationMs))",
290 } 279 "Primary IP: \(report.dns.primaryIP ?? "Unavailable")",
280 "PTR: \(report.dns.ptrRecord ?? report.dns.ptrError ?? "Unavailable")",
281 "DNSSEC: \(dnssecLabel(report.dns.dnssecSigned))",
282 "Patterns: \(report.dns.patternSummary.patterns.joined(separator: " | ").nilIfEmpty ?? "None")"
283 ]
284 if let provenance = report.sectionProvenance[.dns] {
285 dnsLines.append("Provenance: \(provenanceLabel(provenance))")
286 }
287 if let error = report.dns.error {
288 dnsLines.append("Error: \(error)")
289 }
290 if report.dns.recordSections.isEmpty {
291 dnsLines.append("Records: None")
292 } else {
293 dnsLines.append("Records:")
294 for section in report.dns.recordSections {
295 var seen: Set<String> = []
296 let values = (section.records + section.wildcardRecords)
297 .map(\.value)
298 .filter { seen.insert($0).inserted }
299 let renderedValues = values.isEmpty ? "None" : values.joined(separator: " | ")
300 dnsLines.append(" \(section.recordType.rawValue): \(renderedValues)")
301 }
302 }
303 return dnsLines
304 }
291 305
292 return report.dnsHistory.map { event in 306 private static func dnsHistorySection(_ report: DomainReport) -> [String] {
293 [ 307 guard !report.dnsHistory.isEmpty else {
294 textDateFormatter.string(from: event.date), 308 return ["No DNS history available"]
295 event.summary,
296 "A=\(event.aRecords.joined(separator: " | ").nilIfEmpty ?? "-")",
297 "NS=\(event.nameservers.joined(separator: " | ").nilIfEmpty ?? "-")",
298 "source=\(event.source)"
299 ].joined(separator: " | ")
300 }
301 } 309 }
302 310
303 appendSection("Web", to: &lines) { 311 return report.dnsHistory.map { event in
304 var webLines = [ 312 [
305 "TLS Status: \(report.web.tlsStatus)", 313 textDateFormatter.string(from: event.date),
306 "TLS Grade: \(report.web.tlsGrade.rawValue)", 314 event.summary,
307 "TLS Highlights: \(report.web.tlsHighlights.joined(separator: " | "))", 315 "A=\(event.aRecords.joined(separator: " | ").nilIfEmpty ?? "-")",
308 "Certificate Warning: \(report.web.certificateWarningLevel.title)", 316 "NS=\(event.nameservers.joined(separator: " | ").nilIfEmpty ?? "-")",
309 "Security Grade: \(report.web.securityGrade ?? "Unavailable")", 317 "source=\(event.source)"
310 "HTTP Status: \(report.web.statusCode.map(String.init) ?? "Unavailable")", 318 ].joined(separator: " | ")
311 "Protocol: \(report.web.httpProtocol ?? "Unavailable")",
312 "HTTP/3 Advertised: \(report.web.http3Advertised ? "Yes" : "No")",
313 "Final URL: \(report.web.finalURL ?? "Unavailable")",
314 "HSTS Preloaded: \(booleanLabel(report.web.hstsPreloaded))",
315 "Header Count: \(report.web.headerCount)"
316 ]
317 if let provenance = report.sectionProvenance[.ssl] {
318 webLines.append("TLS Provenance: \(provenanceLabel(provenance))")
319 }
320 if let provenance = report.sectionProvenance[.httpHeaders] {
321 webLines.append("HTTP Provenance: \(provenanceLabel(provenance))")
322 }
323 if let provenance = report.sectionProvenance[.redirectChain] {
324 webLines.append("Redirect Provenance: \(provenanceLabel(provenance))")
325 }
326 if let tlsError = report.web.tlsError {
327 webLines.append("TLS Error: \(tlsError)")
328 }
329 if let headersError = report.web.headersError {
330 webLines.append("Headers Error: \(headersError)")
331 }
332 if let redirectError = report.web.redirectError {
333 webLines.append("Redirect Error: \(redirectError)")
334 }
335 if !report.web.headers.isEmpty {
336 webLines.append("Headers:")
337 for header in report.web.headers {
338 webLines.append(" \(header.name): \(header.value)")
339 }
340 }
341 if !report.web.redirectChain.isEmpty {
342 webLines.append("Redirect Chain:")
343 for hop in report.web.redirectChain {
344 webLines.append(" \(hop.stepNumber). \(hop.statusCode) \(hop.url)\(hop.isFinal ? " (final)" : "")")
345 }
346 }
347 return webLines
348 } 319 }
320 }
349 321
350 appendSection("Email", to: &lines) { 322 private static func webSection(_ report: DomainReport) -> [String] {
351 var emailLines = [report.email.summary] 323 var webLines = [
352 if let grade = report.email.grade { 324 "TLS Status: \(report.web.tlsStatus)",
353 emailLines.append("Grade: \(grade.rawValue)") 325 "TLS Grade: \(report.web.tlsGrade.rawValue)",
354 } 326 "TLS Highlights: \(report.web.tlsHighlights.joined(separator: " | "))",
355 if !report.email.reasons.isEmpty { 327 "Certificate Warning: \(report.web.certificateWarningLevel.title)",
356 emailLines.append("Why: \(report.email.reasons.joined(separator: " | "))") 328 "Security Grade: \(report.web.securityGrade ?? "Unavailable")",
357 } 329 "HTTP Status: \(report.web.statusCode.map(String.init) ?? "Unavailable")",
358 emailLines.append("Confidence: \(report.emailConfidence?.title ?? "N/A")") 330 "Protocol: \(report.web.httpProtocol ?? "Unavailable")",
359 if let provenance = report.sectionProvenance[.emailSecurity] { 331 "HTTP/3 Advertised: \(report.web.http3Advertised ? "Yes" : "No")",
360 emailLines.append("Provenance: \(provenanceLabel(provenance))") 332 "Final URL: \(report.web.finalURL ?? "Unavailable")",
361 } 333 "HSTS Preloaded: \(booleanLabel(report.web.hstsPreloaded))",
362 if let records = report.email.records { 334 "Header Count: \(report.web.headerCount)"
363 emailLines.append("SPF: \(recordLabel(records.spf))") 335 ]
364 emailLines.append("DMARC: \(recordLabel(records.dmarc))") 336 if let provenance = report.sectionProvenance[.ssl] {
365 emailLines.append("DKIM: \(recordLabel(records.dkim))") 337 webLines.append("TLS Provenance: \(provenanceLabel(provenance))")
366 emailLines.append("BIMI: \(recordLabel(records.bimi))") 338 }
367 emailLines.append("MTA-STS: \(records.mtaSts?.txtFound == true ? records.mtaSts?.policyMode ?? "found" : "Unavailable")") 339 if let provenance = report.sectionProvenance[.httpHeaders] {
340 webLines.append("HTTP Provenance: \(provenanceLabel(provenance))")
341 }
342 if let provenance = report.sectionProvenance[.redirectChain] {
343 webLines.append("Redirect Provenance: \(provenanceLabel(provenance))")
344 }
345 if let tlsError = report.web.tlsError {
346 webLines.append("TLS Error: \(tlsError)")
347 }
348 if let headersError = report.web.headersError {
349 webLines.append("Headers Error: \(headersError)")
350 }
351 if let redirectError = report.web.redirectError {
352 webLines.append("Redirect Error: \(redirectError)")
353 }
354 if !report.web.headers.isEmpty {
355 webLines.append("Headers:")
356 for header in report.web.headers {
357 webLines.append(" \(header.name): \(header.value)")
368 } 358 }
369 if let error = report.email.error { 359 }
370 emailLines.append("Error: \(error)") 360 if !report.web.redirectChain.isEmpty {
361 webLines.append("Redirect Chain:")
362 for hop in report.web.redirectChain {
363 webLines.append(" \(hop.stepNumber). \(hop.statusCode) \(hop.url)\(hop.isFinal ? " (final)" : "")")
371 } 364 }
372 return emailLines
373 } 365 }
366 return webLines
367 }
374 368
375 appendSection("Network", to: &lines) { 369 private static func emailSection(_ report: DomainReport) -> [String] {
376 var networkLines = [ 370 var emailLines = [report.email.summary]
377 "Reachability: \(report.network.reachabilitySummary)", 371 if let grade = report.email.grade {
378 "Geolocation: \(report.network.geolocationSummary)", 372 emailLines.append("Grade: \(grade.rawValue)")
379 "Geolocation Confidence: \(report.geolocationConfidence?.title ?? "N/A")", 373 }
380 "Open Ports: \(report.network.openPorts.map(String.init).joined(separator: ", ").nilIfEmpty ?? "None")" 374 if !report.email.reasons.isEmpty {
381 ] 375 emailLines.append("Why: \(report.email.reasons.joined(separator: " | "))")
382 if let provenance = report.sectionProvenance[.ipGeolocation] { 376 }
383 networkLines.append("Geolocation Provenance: \(provenanceLabel(provenance))") 377 emailLines.append("Confidence: \(report.emailConfidence?.title ?? "N/A")")
384 } 378 if let provenance = report.sectionProvenance[.emailSecurity] {
385 if let error = report.network.reachabilityError { 379 emailLines.append("Provenance: \(provenanceLabel(provenance))")
386 networkLines.append("Reachability Error: \(error)")
387 }
388 if let error = report.network.geolocationError {
389 networkLines.append("Geolocation Error: \(error)")
390 }
391 if let error = report.network.portScanError {
392 networkLines.append("Port Scan Error: \(error)")
393 }
394 if !report.network.portScan.isEmpty {
395 networkLines.append("Port Scan:")
396 for result in report.network.portScan {
397 networkLines.append(
398 " \(result.port) \(result.service): \(result.open ? "open" : "closed")\(result.banner.map { " banner=\($0)" } ?? "")"
399 )
400 }
401 }
402 return networkLines
403 } 380 }
381 if let records = report.email.records {
382 emailLines.append("SPF: \(recordLabel(records.spf))")
383 emailLines.append("DMARC: \(recordLabel(records.dmarc))")
384 emailLines.append("DKIM: \(recordLabel(records.dkim))")
385 emailLines.append("BIMI: \(recordLabel(records.bimi))")
386 emailLines.append("MTA-STS: \(records.mtaSts?.txtFound == true ? records.mtaSts?.policyMode ?? "found" : "Unavailable")")
387 }
388 if let error = report.email.error {
389 emailLines.append("Error: \(error)")
390 }
391 return emailLines
392 }
404 393
405 appendSection("Subdomains", to: &lines) { 394 private static func networkSection(_ report: DomainReport) -> [String] {
406 var values = ["Confidence: \(report.subdomainConfidence?.title ?? "N/A")"] 395 var networkLines = [
407 if let provenance = report.sectionProvenance[.subdomains] { 396 "Reachability: \(report.network.reachabilitySummary)",
408 values.append("Provenance: \(provenanceLabel(provenance))") 397 "Geolocation: \(report.network.geolocationSummary)",
409 } 398 "Geolocation Confidence: \(report.geolocationConfidence?.title ?? "N/A")",
410 if report.subdomains.isEmpty { 399 "Open Ports: \(report.network.openPorts.map(String.init).joined(separator: ", ").nilIfEmpty ?? "None")"
411 values.append("None") 400 ]
412 return values 401 if let provenance = report.sectionProvenance[.ipGeolocation] {
413 } 402 networkLines.append("Geolocation Provenance: \(provenanceLabel(provenance))")
414 if !report.subdomainGroups.isEmpty { 403 }
415 values.append("Groups: \(report.subdomainGroups.map { "\($0.label): \($0.subdomains.count)" }.joined(separator: " | "))") 404 if let error = report.network.reachabilityError {
416 } 405 networkLines.append("Reachability Error: \(error)")
417 values.append(contentsOf: report.subdomains.map { "- \($0)" }) 406 }
418 if !report.extendedSubdomains.isEmpty { 407 if let error = report.network.geolocationError {
419 values.append("Extended:") 408 networkLines.append("Geolocation Error: \(error)")
420 values.append(contentsOf: report.extendedSubdomains.map { "- \($0)" }) 409 }
410 if let error = report.network.portScanError {
411 networkLines.append("Port Scan Error: \(error)")
412 }
413 if !report.network.portScan.isEmpty {
414 networkLines.append("Port Scan:")
415 for result in report.network.portScan {
416 networkLines.append(
417 " \(result.port) \(result.service): \(result.open ? "open" : "closed")\(result.banner.map { " banner=\($0)" } ?? "")"
418 )
421 } 419 }
422 return values
423 } 420 }
421 return networkLines
422 }
424 423
425 appendSection("Pricing", to: &lines) { 424 private static func subdomainsSection(_ report: DomainReport) -> [String] {
426 guard let pricing = report.domainPricing else { 425 var values = ["Confidence: \(report.subdomainConfidence?.title ?? "N/A")"]
427 return ["External pricing unavailable"] 426 if let provenance = report.sectionProvenance[.subdomains] {
428 } 427 values.append("Provenance: \(provenanceLabel(provenance))")
428 }
429 if report.subdomains.isEmpty {
430 values.append("None")
431 return values
432 }
433 if !report.subdomainGroups.isEmpty {
434 values.append("Groups: \(report.subdomainGroups.map { "\($0.label): \($0.subdomains.count)" }.joined(separator: " | "))")
435 }
436 values.append(contentsOf: report.subdomains.map { "- \($0)" })
437 if !report.extendedSubdomains.isEmpty {
438 values.append("Extended:")
439 values.append(contentsOf: report.extendedSubdomains.map { "- \($0)" })
440 }
441 return values
442 }
429 443
430 return [ 444 private static func pricingSection(_ report: DomainReport) -> [String] {
431 "Estimated Price: \(pricing.estimatedPrice ?? "Unavailable")", 445 guard let pricing = report.domainPricing else {
432 "Premium: \(pricing.premiumIndicator == true ? "Yes" : "No")", 446 return ["External pricing unavailable"]
433 "Resale: \(pricing.resaleSignal ?? "Unavailable")",
434 "Auction: \(pricing.auctionSignal ?? "Unavailable")",
435 "Source: \(pricing.source)",
436 "Collected: \(textDateFormatter.string(from: pricing.collectedAt))"
437 ]
438 } 447 }
439 448
440 appendSection("Changes", to: &lines) { 449 return [
441 guard let changeSummary = report.changeSummary else { 450 "Estimated Price: \(pricing.estimatedPrice ?? "Unavailable")",
442 return ["No comparison available"] 451 "Premium: \(pricing.premiumIndicator == true ? "Yes" : "No")",
443 } 452 "Resale: \(pricing.resaleSignal ?? "Unavailable")",
453 "Auction: \(pricing.auctionSignal ?? "Unavailable")",
454 "Source: \(pricing.source)",
455 "Collected: \(textDateFormatter.string(from: pricing.collectedAt))"
456 ]
457 }
444 458
445 var values = [ 459 private static func changesSection(_ report: DomainReport) -> [String] {
446 "Has Changes: \(changeSummary.hasChanges ? "Yes" : "No")", 460 guard let changeSummary = report.changeSummary else {
447 "Severity: \(changeSummary.severity.title)", 461 return ["No comparison available"]
448 "Impact: \(changeSummary.impactClassification.title)",
449 "Inferred Summary: \(changeSummary.message)",
450 "Changed Sections: \(changeSummary.changedSections.isEmpty ? "None" : changeSummary.changedSections.joined(separator: ", "))"
451 ]
452 if let riskScoreDelta = changeSummary.riskScoreDelta {
453 values.append("Risk Delta: \(riskScoreDelta >= 0 ? "+" : "")\(riskScoreDelta)")
454 }
455 if !changeSummary.insights.isEmpty {
456 values.append("Insights: \(changeSummary.insights.joined(separator: " | "))")
457 }
458 if !changeSummary.observedFacts.isEmpty {
459 values.append("Observed: \(changeSummary.observedFacts.joined(separator: " | "))")
460 }
461 if let contextNote = changeSummary.contextNote {
462 values.append("Context: \(contextNote)")
463 }
464 return values
465 } 462 }
466 463
467 return lines.joined(separator: "\n") 464 var values = [
465 "Has Changes: \(changeSummary.hasChanges ? "Yes" : "No")",
466 "Severity: \(changeSummary.severity.title)",
467 "Impact: \(changeSummary.impactClassification.title)",
468 "Inferred Summary: \(changeSummary.message)",
469 "Changed Sections: \(changeSummary.changedSections.isEmpty ? "None" : changeSummary.changedSections.joined(separator: ", "))"
470 ]
471 if let riskScoreDelta = changeSummary.riskScoreDelta {
472 values.append("Risk Delta: \(riskScoreDelta >= 0 ? "+" : "")\(riskScoreDelta)")
473 }
474 if !changeSummary.insights.isEmpty {
475 values.append("Insights: \(changeSummary.insights.joined(separator: " | "))")
476 }
477 if !changeSummary.observedFacts.isEmpty {
478 values.append("Observed: \(changeSummary.observedFacts.joined(separator: " | "))")
479 }
480 if let contextNote = changeSummary.contextNote {
481 values.append("Context: \(contextNote)")
482 }
483 return values
468 } 484 }
469 485
470 static func batchText(for reports: [DomainReport], title: String) -> String { 486 static func batchText(for reports: [DomainReport], title: String) -> String {
LocalAPIService.swift +3 −30
@@ -303,47 +303,20 @@ final class LocalAPIService {
303 static let reference = "DomainDig.LocalAPI.Token" 303 static let reference = "DomainDig.LocalAPI.Token"
304 304
305 static func save(secret: String, reference: String) throws { 305 static func save(secret: String, reference: String) throws {
306 let data = Data(secret.utf8) 306 guard GenericPasswordKeychain.save(secret, reference: reference) else {
307 try? delete(reference: reference)
308
309 let query: [String: Any] = [
310 kSecClass as String: kSecClassGenericPassword,
311 kSecAttrAccount as String: reference,
312 kSecValueData as String: data,
313 kSecAttrAccessible as String: kSecAttrAccessibleAfterFirstUnlock
314 ]
315
316 let status = SecItemAdd(query as CFDictionary, nil)
317 guard status == errSecSuccess else {
318 throw LocalAPIServerError.secretPersistenceFailed 307 throw LocalAPIServerError.secretPersistenceFailed
319 } 308 }
320 } 309 }
321 310
322 static func secret(reference: String) throws -> String { 311 static func secret(reference: String) throws -> String {
323 let query: [String: Any] = [ 312 guard let secret = GenericPasswordKeychain.secret(reference: reference) else {
324 kSecClass as String: kSecClassGenericPassword,
325 kSecAttrAccount as String: reference,
326 kSecReturnData as String: true,
327 kSecMatchLimit as String: kSecMatchLimitOne
328 ]
329
330 var result: CFTypeRef?
331 let status = SecItemCopyMatching(query as CFDictionary, &result)
332 guard status == errSecSuccess,
333 let data = result as? Data,
334 let secret = String(data: data, encoding: .utf8) else {
335 throw LocalAPIServerError.missingSecret 313 throw LocalAPIServerError.missingSecret
336 } 314 }
337
338 return secret 315 return secret
339 } 316 }
340 317
341 static func delete(reference: String) throws { 318 static func delete(reference: String) throws {
342 let query: [String: Any] = [ 319 GenericPasswordKeychain.delete(reference: reference)
343 kSecClass as String: kSecClassGenericPassword,
344 kSecAttrAccount as String: reference
345 ]
346 SecItemDelete(query as CFDictionary)
347 } 320 }
348 } 321 }
349 322
LookupSnapshot.swift +119
@@ -163,3 +163,122 @@ extension HistoryEntry {
163 ) 163 )
164 } 164 }
165} 165}
166
167extension LookupSnapshot {
168 /// Whether every section that failed did so for want of a connection (a
169 /// network error, a timeout, a rate limit) and nothing worth showing came
170 /// back, so the last snapshot should stand in for this one.
171 var needsFallback: Bool {
172 let candidateMessages = [
173 dnsError,
174 httpHeadersError,
175 sslError,
176 ownershipError,
177 subdomainsError,
178 redirectChainError,
179 ipGeolocationError
180 ]
181 .compactMap { $0?.lowercased() }
182
183 guard !candidateMessages.isEmpty else { return false }
184 let connectivityFailure = candidateMessages.allSatisfy { message in
185 message.hasPrefix("network error:")
186 || message.hasPrefix("timeout:")
187 || message.hasPrefix("rate limit:")
188 }
189
190 let hasMaterialData = !dnsSections.isEmpty
191 || !httpHeaders.isEmpty
192 || sslInfo != nil
193 || ownership != nil
194 || !subdomains.isEmpty
195
196 return connectivityFailure && !hasMaterialData
197 }
198
199 /// `previous`, marked as the last known result, when this lookup
200 /// ``needsFallback``; otherwise this lookup.
201 func resolvedAfterFallback(to previous: LookupSnapshot?) -> LookupSnapshot {
202 guard needsFallback, let previous else {
203 return self
204 }
205
206 return LookupSnapshot(
207 historyEntryID: previous.historyEntryID,
208 domain: previous.domain,
209 timestamp: previous.timestamp,
210 trackedDomainID: previous.trackedDomainID,
211 note: previous.note,
212 appVersion: previous.appVersion,
213 resolverDisplayName: previous.resolverDisplayName,
214 resolverURLString: previous.resolverURLString,
215 dataSources: previous.dataSources,
216 provenanceBySection: previous.provenanceBySection,
217 availabilityConfidence: previous.availabilityConfidence,
218 ownershipConfidence: previous.ownershipConfidence,
219 subdomainConfidence: previous.subdomainConfidence,
220 emailSecurityConfidence: previous.emailSecurityConfidence,
221 geolocationConfidence: previous.geolocationConfidence,
222 errorDetails: previous.errorDetails,
223 isPartialSnapshot: previous.isPartialSnapshot,
224 validationIssues: previous.validationIssues,
225 totalLookupDurationMs: previous.totalLookupDurationMs,
226 snapshotIndex: previous.snapshotIndex,
227 previousSnapshotID: previous.previousSnapshotID,
228 changeCount: previous.changeCount,
229 severitySummary: previous.severitySummary,
230 dnsSections: previous.dnsSections,
231 dnsError: previous.dnsError,
232 availabilityResult: previous.availabilityResult,
233 suggestions: previous.suggestions,
234 sslInfo: previous.sslInfo,
235 sslError: previous.sslError,
236 hstsPreloaded: previous.hstsPreloaded,
237 httpHeaders: previous.httpHeaders,
238 httpSecurityGrade: previous.httpSecurityGrade,
239 httpStatusCode: previous.httpStatusCode,
240 httpResponseTimeMs: previous.httpResponseTimeMs,
241 httpProtocol: previous.httpProtocol,
242 http3Advertised: previous.http3Advertised,
243 httpHeadersError: previous.httpHeadersError,
244 reachabilityResults: previous.reachabilityResults,
245 reachabilityError: previous.reachabilityError,
246 ipGeolocation: previous.ipGeolocation,
247 ipGeolocationError: previous.ipGeolocationError,
248 emailSecurity: previous.emailSecurity,
249 emailSecurityError: previous.emailSecurityError,
250 ownership: previous.ownership,
251 ownershipError: previous.ownershipError,
252 ownershipHistory: previous.ownershipHistory,
253 ownershipHistoryError: previous.ownershipHistoryError,
254 inferredProvider: previous.inferredProvider,
255 priorProviders: previous.priorProviders,
256 domainClassification: previous.domainClassification,
257 ownershipTransitions: previous.ownershipTransitions,
258 hostingTransitions: previous.hostingTransitions,
259 subdomainHistory: previous.subdomainHistory,
260 riskSignals: previous.riskSignals,
261 intelligenceTimeline: previous.intelligenceTimeline,
262 ptrRecord: previous.ptrRecord,
263 ptrError: previous.ptrError,
264 redirectChain: previous.redirectChain,
265 redirectChainError: previous.redirectChainError,
266 subdomains: previous.subdomains,
267 subdomainsError: previous.subdomainsError,
268 extendedSubdomains: previous.extendedSubdomains,
269 extendedSubdomainsError: previous.extendedSubdomainsError,
270 dnsHistory: previous.dnsHistory,
271 dnsHistoryError: previous.dnsHistoryError,
272 domainPricing: previous.domainPricing,
273 domainPricingError: previous.domainPricingError,
274 reputation: previous.reputation,
275 reputationError: previous.reputationError,
276 portScanResults: previous.portScanResults,
277 portScanError: previous.portScanError,
278 changeSummary: previous.changeSummary,
279 resultSource: .snapshot,
280 cachedSections: [],
281 statusMessage: "Last known result • \(previous.timestamp.formatted(date: .abbreviated, time: .shortened))"
282 )
283 }
284}