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 {
305305 }
306306
307307 private nonisolated static func dictionary(for row: [String], header: [String]) -> [String: String] {
308 Dictionary(uniqueKeysWithValues: zip(header, row).map { ($0.0, $0.1) })
308 // A repeated column keeps its first value rather than failing the import.
309 Dictionary(zip(header, row).map { ($0.0, $0.1) }) { first, _ in first }
309310 }
310311
311312 private nonisolated static func csvLine(_ values: [String]) -> String {
@@ -903,76 +904,54 @@ enum DomainDataPortabilityService {
903904 if backup.schemaVersion > DomainDigBackup.currentSchemaVersion {
904905 throw DataPortabilityError.unsupportedSchema(backup.schemaVersion)
905906 }
906 let report = DataValidationService.validate(backup: backup)
907 if !report.errors.isEmpty {
908 throw DataPortabilityError.validationFailed(report.errors)
909 }
910 return .backup(backup, report)
907 return .backup(backup, try passing(DataValidationService.validate(backup: backup)))
911908 }
912
913909 if let backup = try? decodeLegacyBackup(from: data) {
914 let report = DataValidationService.validate(backup: backup)
915 if !report.errors.isEmpty {
916 throw DataPortabilityError.validationFailed(report.errors)
917 }
918 return .backup(backup, report)
910 return .backup(backup, try passing(DataValidationService.validate(backup: backup)))
919911 }
920
921912 if let export = try? decoder.decode(TrackedDomainsExport.self, from: data) {
922 let report = DataValidationService.validate(trackedDomains: export.trackedDomains)
923 if !report.errors.isEmpty {
924 throw DataPortabilityError.validationFailed(report.errors)
925 }
926 return .trackedDomains(export.trackedDomains, report)
913 return try trackedDomainsPayload(export.trackedDomains)
927914 }
928
929915 if let export = try? decoder.decode(WorkflowsExport.self, from: data) {
930 let report = DataValidationService.validate(workflows: export.workflows)
931 if !report.errors.isEmpty {
932 throw DataPortabilityError.validationFailed(report.errors)
933 }
934 return .workflows(export.workflows, report)
916 return try workflowsPayload(export.workflows)
935917 }
936
937918 if let trackedDomains = try? decoder.decode([TrackedDomain].self, from: data) {
938 let report = DataValidationService.validate(trackedDomains: trackedDomains)
939 if !report.errors.isEmpty {
940 throw DataPortabilityError.validationFailed(report.errors)
941 }
942 return .trackedDomains(trackedDomains, report)
919 return try trackedDomainsPayload(trackedDomains)
943920 }
944
945921 if let workflows = try? decoder.decode([DomainWorkflow].self, from: data) {
946 let report = DataValidationService.validate(workflows: workflows)
947 if !report.errors.isEmpty {
948 throw DataPortabilityError.validationFailed(report.errors)
949 }
950 return .workflows(workflows, report)
922 return try workflowsPayload(workflows)
951923 }
924 if fileName.lowercased().hasSuffix(".csv") {
925 return try decodeCSVPayload(from: data, fileName: fileName)
926 }
927 throw DataPortabilityError.unsupportedFormat
928 }
952929
953 let lowercasedFileName = fileName.lowercased()
954 if lowercasedFileName.hasSuffix(".csv") {
955 guard let string = String(data: data, encoding: .utf8) else {
956 throw DataPortabilityError.unreadableFile
957 }
958 if lowercasedFileName.contains("workflow") {
959 let workflows = try DataPortabilityCSV.parseWorkflows(from: string)
960 let report = DataValidationService.validate(workflows: workflows)
961 if !report.errors.isEmpty {
962 throw DataPortabilityError.validationFailed(report.errors)
963 }
964 return .workflows(workflows, report)
965 }
966
967 let trackedDomains = try DataPortabilityCSV.parseTrackedDomains(from: string)
968 let report = DataValidationService.validate(trackedDomains: trackedDomains)
969 if !report.errors.isEmpty {
970 throw DataPortabilityError.validationFailed(report.errors)
971 }
972 return .trackedDomains(trackedDomains, report)
930 /// A CSV holds workflows when its name says so, and tracked domains otherwise.
931 private static func decodeCSVPayload(from data: Data, fileName: String) throws -> ImportPayload {
932 guard let string = String(data: data, encoding: .utf8) else {
933 throw DataPortabilityError.unreadableFile
934 }
935 if fileName.lowercased().contains("workflow") {
936 return try workflowsPayload(DataPortabilityCSV.parseWorkflows(from: string))
973937 }
938 return try trackedDomainsPayload(DataPortabilityCSV.parseTrackedDomains(from: string))
939 }
974940
975 throw DataPortabilityError.unsupportedFormat
941 private static func trackedDomainsPayload(_ trackedDomains: [TrackedDomain]) throws -> ImportPayload {
942 .trackedDomains(trackedDomains, try passing(DataValidationService.validate(trackedDomains: trackedDomains)))
943 }
944
945 private static func workflowsPayload(_ workflows: [DomainWorkflow]) throws -> ImportPayload {
946 .workflows(workflows, try passing(DataValidationService.validate(workflows: workflows)))
947 }
948
949 /// `report`, unless it found errors, which fail the import.
950 private static func passing(_ report: DataValidationReport) throws -> DataValidationReport {
951 guard report.errors.isEmpty else {
952 throw DataPortabilityError.validationFailed(report.errors)
953 }
954 return report
976955 }
977956
978957 private static func decodeLegacyBackup(from data: Data) throws -> DomainDigBackup {
DomainDig/BatchSweepSummaryView.swift +37 −19
@@ -28,25 +28,12 @@ struct BatchSweepSummaryView: View {
2828 Toggle("Show unchanged domains", isOn: $showUnchangedDomains)
2929 }
3030
31 Section(visibleResults.isEmpty ? "Changed Domains" : "Results") {
32 if visibleResults.isEmpty {
33 Text("No domains with changes or warnings")
34 .font(.system(.caption, design: .monospaced))
35 .foregroundStyle(Color(.appTextSecondary))
36 } else {
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 }
31 BatchResultsSection(
32 viewModel: viewModel,
33 results: visibleResults,
34 emptyTitle: "Changed Domains",
35 emptyText: "No domains with changes or warnings"
36 )
5037 }
5138 .navigationTitle(summary.source == .watchlistRefresh ? "Sweep Summary" : "Batch Summary")
5239 }
@@ -64,3 +51,34 @@ struct BatchSweepSummaryView: View {
6451 }
6552 }
6653}
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 {
782782 _ lhs: [String: SyncedDomainNote],
783783 _ rhs: [String: SyncedDomainNote]
784784 ) -> (notesByDomain: [String: SyncedDomainNote], hadConflict: Bool) {
785 var merged = lhs
786 var hadConflict = false
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)
785 let result = mergeLatest(lhs, rhs, updatedAt: \.updatedAt)
786 return (result.merged, result.hadConflict)
798787 }
799788
800789 private func mergeHistoryMetadata(
801790 _ lhs: [String: SyncedHistoryMetadata],
802791 _ rhs: [String: SyncedHistoryMetadata]
803792 ) -> (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) {
804804 var merged = lhs
805805 var hadConflict = false
806806
807 for (domain, remoteMetadata) in rhs {
808 if let localMetadata = merged[domain], localMetadata != remoteMetadata {
807 for (domain, remote) in rhs {
808 if let local = merged[domain], local != remote {
809809 hadConflict = true
810 merged[domain] = localMetadata.updatedAt >= remoteMetadata.updatedAt ? localMetadata : remoteMetadata
810 merged[domain] = local[keyPath: updatedAt] >= remote[keyPath: updatedAt] ? local : remote
811811 } else {
812 merged[domain] = remoteMetadata
812 merged[domain] = remote
813813 }
814814 }
815815
DomainDig/ContentView.swift +2 −52
@@ -566,32 +566,7 @@ struct ContentView: View {
566566 .accessibilityValue(viewModel.isCurrentDomainSaved ? "Saved" : "Not saved")
567567 .accessibilityAddTraits(viewModel.isCurrentDomainSaved ? .isSelected : [])
568568 Menu {
569 Button("Export TXT") {
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 }
569 ExportFormatButtons(share: shareSingleResults)
595570 } label: {
596571 Image(systemName: "square.and.arrow.up")
597572 .font(appDensity.font(.body, design: .default))
@@ -619,32 +594,7 @@ struct ContentView: View {
619594 showingBatchWorkflowSheet = true
620595 }
621596 Divider()
622 Button("Export Batch TXT") {
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 }
597 ExportFormatButtons(share: shareBatchResults, batch: true)
648598 } label: {
649599 Label("Export", systemImage: "square.and.arrow.up")
650600 .font(appDensity.font(.caption))
DomainDig/DashboardView.swift +17 −14
@@ -84,13 +84,8 @@ struct DashboardView: View {
8484 dashboardEmptyRow("No recent portfolio changes")
8585 } else {
8686 ForEach(viewModel.filteredPortfolioRecentActivity.prefix(8)) { item in
87 if let trackedDomain = viewModel.trackedDomain(withID: item.trackedDomainID) {
88 NavigationLink {
89 TrackedDomainDetailView(viewModel: viewModel, trackedDomain: trackedDomain)
90 } label: {
91 PortfolioActivityRow(item: item)
92 }
93 .buttonStyle(.plain)
87 trackedDomainLink(item.trackedDomainID) {
88 PortfolioActivityRow(item: item)
9489 }
9590 }
9691 }
@@ -102,13 +97,8 @@ struct DashboardView: View {
10297 dashboardEmptyRow("Nothing urgent right now")
10398 } else {
10499 ForEach(viewModel.filteredPortfolioAttentionRequired.prefix(8)) { item in
105 if let trackedDomain = viewModel.trackedDomain(withID: item.trackedDomainID) {
106 NavigationLink {
107 TrackedDomainDetailView(viewModel: viewModel, trackedDomain: trackedDomain)
108 } label: {
109 PortfolioAttentionRow(item: item)
110 }
111 .buttonStyle(.plain)
100 trackedDomainLink(item.trackedDomainID) {
101 PortfolioAttentionRow(item: item)
112102 }
113103 }
114104 }
@@ -271,6 +261,19 @@ struct DashboardView: View {
271261 return AnyShapeStyle(Color(.appSurfaceElevated))
272262 }
273263
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
274277 private func dashboardEmptyRow(_ message: String) -> some View {
275278 Text(message)
276279 .font(appDensity.font(.caption))
DomainDig/DataAccessService.swift +13 −11
@@ -2,17 +2,19 @@ import Foundation
22
33enum DataAccessService {
44 static func hasAccess(to capability: DataCapability) -> Bool {
5 switch capability {
6 case .ownershipHistory:
7 return FeatureAccessService.hasAccess(to: .ownershipHistory)
8 case .dnsHistory:
9 return FeatureAccessService.hasAccess(to: .dnsHistory)
10 case .extendedSubdomains:
11 return FeatureAccessService.hasAccess(to: .extendedSubdomains)
12 case .domainPricing:
13 return FeatureAccessService.hasAccess(to: .domainPricing)
14 case .reputation:
15 return FeatureAccessService.hasAccess(to: .reputation)
5 FeatureAccessService.hasAccess(to: capability.feature)
6 }
7}
8
9extension DataCapability {
10 /// The plan feature that unlocks this data.
11 var feature: FeatureCapability {
12 switch self {
13 case .ownershipHistory: .ownershipHistory
14 case .dnsHistory: .dnsHistory
15 case .extendedSubdomains: .extendedSubdomains
16 case .domainPricing: .domainPricing
17 case .reputation: .reputation
1618 }
1719 }
1820}
DomainDig/DiffService.swift +3 −2
@@ -329,8 +329,9 @@ enum DiffService {
329329 }
330330
331331 private static func dnsSection(from oldReport: DomainReport, to newReport: DomainReport) -> DiffSection {
332 let oldSections = Dictionary(uniqueKeysWithValues: oldReport.dns.recordSections.map { ($0.recordType, $0) })
333 let newSections = Dictionary(uniqueKeysWithValues: newReport.dns.recordSections.map { ($0.recordType, $0) })
332 // Imported reports are not guaranteed one section per record type.
333 let oldSections = Dictionary(oldReport.dns.recordSections.map { ($0.recordType, $0) }) { first, _ in first }
334 let newSections = Dictionary(newReport.dns.recordSections.map { ($0.recordType, $0) }) { first, _ in first }
334335 let recordTypes = Set(oldSections.keys).union(newSections.keys).sorted { $0.rawValue < $1.rawValue }
335336
336337 var items: [DiffItem] = [
DomainDig/DomainDig/AuditExporter.swift +54 −68
@@ -48,7 +48,21 @@ enum AuditExporter {
4848 lines.append("")
4949 }
5050
51 lines.append("## Findings Summary")
51 lines += findingsSummaryLines(session)
52 lines += keyRiskLines(session)
53 lines.append("## Checklist")
54 for item in session.checklist {
55 lines.append("- [\(item.isComplete ? "x" : " ")] \(item.title): \(item.detail)")
56 }
57 lines.append("")
58 lines += findingLines(session)
59 lines += evidenceLines(session.evidence)
60
61 return lines.joined(separator: "\n")
62 }
63
64 private static func findingsSummaryLines(_ session: AuditSession) -> [String] {
65 var lines = ["## Findings Summary"]
5266 if session.findings.isEmpty {
5367 lines.append("No findings recorded.")
5468 } else {
@@ -57,8 +71,11 @@ enum AuditExporter {
5771 }
5872 }
5973 lines.append("")
74 return lines
75 }
6076
61 lines.append("## Key Risks")
77 private static func keyRiskLines(_ session: AuditSession) -> [String] {
78 var lines = ["## Key Risks"]
6279 if session.keyRisks.isEmpty {
6380 lines.append("No medium or high-severity risks recorded.")
6481 } else {
@@ -67,46 +84,46 @@ enum AuditExporter {
6784 }
6885 }
6986 lines.append("")
87 return lines
88 }
7089
71 lines.append("## Checklist")
72 for item in session.checklist {
73 lines.append("- [\(item.isComplete ? "x" : " ")] \(item.title): \(item.detail)")
74 }
75 lines.append("")
76
77 lines.append("## Findings")
90 private static func findingLines(_ session: AuditSession) -> [String] {
91 var lines = ["## Findings"]
7892 if session.findings.isEmpty {
7993 lines.append("No findings recorded.")
80 } else {
81 for finding in session.findings {
82 lines.append("### \(finding.title)")
83 lines.append("- Severity: \(finding.severity.title)")
84 lines.append("- Status: \(finding.status.title)")
85 if !finding.checklistAreas.isEmpty {
86 lines.append("- Checklist Areas: \(finding.checklistAreas.map(\.title).joined(separator: ", "))")
87 }
88 lines.append("- Summary: \(finding.summary)")
89 if !finding.evidenceReferences.isEmpty {
90 lines.append("- Evidence: \(finding.evidenceReferences.joined(separator: " | "))")
91 }
92 if !finding.notes.isEmpty {
93 lines.append("- Notes: \(finding.notes)")
94 }
95 lines.append("")
94 }
95 for finding in session.findings {
96 lines.append("### \(finding.title)")
97 lines.append("- Severity: \(finding.severity.title)")
98 lines.append("- Status: \(finding.status.title)")
99 if !finding.checklistAreas.isEmpty {
100 lines.append("- Checklist Areas: \(finding.checklistAreas.map(\.title).joined(separator: ", "))")
96101 }
102 lines.append("- Summary: \(finding.summary)")
103 if !finding.evidenceReferences.isEmpty {
104 lines.append("- Evidence: \(finding.evidenceReferences.joined(separator: " | "))")
105 }
106 if !finding.notes.isEmpty {
107 lines.append("- Notes: \(finding.notes)")
108 }
109 lines.append("")
97110 }
111 return lines
112 }
98113
99 lines.append("## Evidence Snapshot")
100 lines.append("- Availability: \(availabilityTitle(session.evidence.report.availability))")
101 lines.append("- Risk Score: \(session.evidence.report.riskAssessment.score) (\(session.evidence.report.riskAssessment.level.title))")
102 lines.append("- TLS Status: \(session.evidence.report.web.tlsStatus)")
103 lines.append("- Final URL: \(session.evidence.report.web.finalURL ?? "Unavailable")")
104 lines.append("- Primary IP: \(session.evidence.report.dns.primaryIP ?? "Unavailable")")
105 lines.append("- Reachability: \(session.evidence.report.network.reachabilitySummary)")
106 lines.append("- Ownership: \(session.evidence.report.ownership?.registrar ?? "Unavailable")")
107 lines.append("- Historical Context Snapshots: \(session.evidence.historicalContext.count)")
108
109 return lines.joined(separator: "\n")
114 private static func evidenceLines(_ evidence: AuditEvidenceSnapshot) -> [String] {
115 let report = evidence.report
116 return [
117 "## Evidence Snapshot",
118 "- Availability: \(availabilityTitle(report.availability))",
119 "- Risk Score: \(report.riskAssessment.score) (\(report.riskAssessment.level.title))",
120 "- TLS Status: \(report.web.tlsStatus)",
121 "- Final URL: \(report.web.finalURL ?? "Unavailable")",
122 "- Primary IP: \(report.dns.primaryIP ?? "Unavailable")",
123 "- Reachability: \(report.network.reachabilitySummary)",
124 "- Ownership: \(report.ownership?.registrar ?? "Unavailable")",
125 "- Historical Context Snapshots: \(evidence.historicalContext.count)",
126 ]
110127 }
111128
112129 private static func availabilityTitle(_ status: DomainAvailabilityStatus) -> String {
@@ -121,37 +138,6 @@ enum AuditExporter {
121138 }
122139
123140 private static func pdfData(for session: AuditSession) throws -> Data {
124 let markdown = markdown(for: session)
125 #if canImport(UIKit)
126 let renderer = UIGraphicsPDFRenderer(bounds: CGRect(x: 0, y: 0, width: 612, height: 792))
127 return renderer.pdfData { context in
128 let lines = markdown.components(separatedBy: .newlines)
129 let paragraphStyle = NSMutableParagraphStyle()
130 paragraphStyle.lineBreakMode = .byWordWrapping
131 let attributes: [NSAttributedString.Key: Any] = [
132 .font: UIFont.monospacedSystemFont(ofSize: 11, weight: .regular),
133 .paragraphStyle: paragraphStyle
134 ]
135
136 var yOffset: CGFloat = 36
137 context.beginPage()
138
139 for line in lines {
140 if yOffset > 744 {
141 context.beginPage()
142 yOffset = 36
143 }
144
145 let renderedLine = NSString(string: line.isEmpty ? " " : line)
146 renderedLine.draw(
147 in: CGRect(x: 36, y: yOffset, width: 540, height: 22),
148 withAttributes: attributes
149 )
150 yOffset += 16
151 }
152 }
153 #else
154 return Data(markdown.utf8)
155 #endif
141 DomainReportExporter.pdfData(fromMarkdown: markdown(for: session))
156142 }
157143}
DomainDig/DomainInsightEngine.swift +117 −104
@@ -176,158 +176,171 @@ enum DomainInsightEngine {
176176 tlsAssessment: TLSSummaryAssessment,
177177 subdomainGroups: [SubdomainGroup]
178178 ) -> DomainRiskAssessment {
179 var tally = RiskTally()
180 scoreAvailability(snapshot, into: &tally)
181 scoreDNS(snapshot, patterns: dnsPatterns, into: &tally)
182 scoreTLS(snapshot, assessment: tlsAssessment, into: &tally)
183 scoreRedirects(snapshot, into: &tally)
184 scoreEmail(snapshot, assessment: emailAssessment, into: &tally)
185 scorePorts(snapshot, into: &tally)
186 scoreSubdomains(snapshot, groups: subdomainGroups, into: &tally)
187 scoreGeolocation(snapshot, into: &tally)
188 // Compares against the score so far, so it runs after the snapshot's own factors.
189 if let previousSnapshot {
190 let delta = tally.score - analyze(snapshot: previousSnapshot).riskAssessment.score
191 if delta >= 15 {
192 tally.add(4, "Observed risk has increased materially since the previous snapshot", .negative)
193 }
194 }
195 scoreReputation(snapshot, into: &tally)
196
197 let clampedScore = min(max(tally.score, 0), 100)
198 let level: RiskLevel
199 switch clampedScore {
200 case 0..<35:
201 level = .low
202 case 35..<65:
203 level = .medium
204 default:
205 level = .high
206 }
207
208 return DomainRiskAssessment(score: clampedScore, level: level, factors: tally.factors)
209 }
210
211 /// A risk score in progress, from a baseline of 18, and the factors behind it.
212 private struct RiskTally {
179213 var score = 18
180214 var factors: [RiskFactor] = []
181215
216 mutating func add(_ points: Int, _ description: String, _ impact: RiskImpact) {
217 score += points
218 factors.append(RiskFactor(description: description, impact: impact))
219 }
220 }
221
222 private static func scoreAvailability(_ snapshot: LookupSnapshot, into tally: inout RiskTally) {
182223 switch snapshot.availabilityResult?.status ?? .unknown {
183224 case .available:
184 score -= 12
185 factors.append(.init(description: "Domain appears available rather than actively deployed", impact: .positive))
225 tally.add(-12, "Domain appears available rather than actively deployed", .positive)
186226 case .unknown:
187 score += 8
188 factors.append(.init(description: "Ownership and availability could not be confirmed", impact: .negative))
227 tally.add(8, "Ownership and availability could not be confirmed", .negative)
189228 case .registered:
190229 if !snapshot.dnsSections.isEmpty || snapshot.sslInfo != nil || !snapshot.redirectChain.isEmpty {
191 score += 6
192 factors.append(.init(description: "Registered domain exposes active infrastructure", impact: .negative))
230 tally.add(6, "Registered domain exposes active infrastructure", .negative)
193231 } else {
194 factors.append(.init(description: "Registered domain with limited active surface detected", impact: .neutral))
232 tally.add(0, "Registered domain with limited active surface detected", .neutral)
195233 }
196234 }
235 }
197236
237 private static func scoreDNS(_ snapshot: LookupSnapshot, patterns: DNSPatternSummary, into tally: inout RiskTally) {
198238 let recordTypes = snapshot.dnsSections.filter { !$0.records.isEmpty || !$0.wildcardRecords.isEmpty }.count
199239 if recordTypes >= 5 {
200 score += 8
201 factors.append(.init(description: "DNS configuration is broad across multiple record types", impact: .negative))
240 tally.add(8, "DNS configuration is broad across multiple record types", .negative)
202241 }
203 if dnsPatterns.wildcardDetected {
204 score += 12
205 factors.append(.init(description: "Wildcard DNS is enabled", impact: .negative))
242 if patterns.wildcardDetected {
243 tally.add(12, "Wildcard DNS is enabled", .negative)
206244 }
207 if let firstPattern = dnsPatterns.patterns.first {
208 factors.append(.init(description: firstPattern, impact: .neutral))
245 if let firstPattern = patterns.patterns.first {
246 tally.add(0, firstPattern, .neutral)
209247 }
248 }
210249
211 switch tlsAssessment.grade {
250 private static func scoreTLS(_ snapshot: LookupSnapshot, assessment: TLSSummaryAssessment, into tally: inout RiskTally) {
251 switch assessment.grade {
212252 case .a:
213 score -= 8
214 factors.append(.init(description: "TLS configuration looks current and stable", impact: .positive))
253 tally.add(-8, "TLS configuration looks current and stable", .positive)
215254 case .b:
216 score -= 3
217 factors.append(.init(description: "TLS is valid with minor concerns", impact: .positive))
255 tally.add(-3, "TLS is valid with minor concerns", .positive)
218256 case .c:
219 score += 10
220 factors.append(.init(description: "TLS configuration has visible weaknesses", impact: .negative))
257 tally.add(10, "TLS configuration has visible weaknesses", .negative)
221258 case .f:
222 score += 22
223 factors.append(.init(description: "TLS is missing, invalid, or near failure", impact: .negative))
259 tally.add(22, "TLS is missing, invalid, or near failure", .negative)
224260 }
225
226261 if let daysUntilExpiry = snapshot.sslInfo?.daysUntilExpiry, daysUntilExpiry <= 14 {
227 score += 10
228 factors.append(.init(description: "Certificate expires within 14 days", impact: .negative))
262 tally.add(10, "Certificate expires within 14 days", .negative)
229263 }
264 }
230265
266 private static func scoreRedirects(_ snapshot: LookupSnapshot, into tally: inout RiskTally) {
231267 if snapshot.redirectChain.count >= 3 {
232 score += 8
233 factors.append(.init(description: "Redirect chain is longer than expected", impact: .negative))
268 tally.add(8, "Redirect chain is longer than expected", .negative)
234269 }
235
236270 if redirectLooksSensitive(snapshot.redirectChain.last?.url) {
237 score += 6
238 factors.append(.init(description: "Redirect target looks like an auth or account gateway", impact: .negative))
239 }
240
241 if let emailAssessment {
242 switch emailAssessment.grade {
243 case .a:
244 score -= 10
245 factors.append(.init(description: "Email protections are strong and aligned", impact: .positive))
246 case .b:
247 score -= 4
248 factors.append(.init(description: "Email protections are present with minor gaps", impact: .positive))
249 case .c:
250 score += 8
251 factors.append(.init(description: "Email protections are partial", impact: .negative))
252 case .f:
253 score += 18
254 factors.append(.init(description: "Email security protections are weak or absent", impact: .negative))
271 tally.add(6, "Redirect target looks like an auth or account gateway", .negative)
272 }
273 }
274
275 private static func scoreEmail(
276 _ snapshot: LookupSnapshot,
277 assessment: EmailSecurityAssessment?,
278 into tally: inout RiskTally
279 ) {
280 guard let assessment else {
281 if hasMXRecords(snapshot) {
282 tally.add(14, "Mail is configured without enough email security evidence", .negative)
255283 }
256 } else if hasMXRecords(snapshot) {
257 score += 14
258 factors.append(.init(description: "Mail is configured without enough email security evidence", impact: .negative))
284 return
259285 }
286 switch assessment.grade {
287 case .a:
288 tally.add(-10, "Email protections are strong and aligned", .positive)
289 case .b:
290 tally.add(-4, "Email protections are present with minor gaps", .positive)
291 case .c:
292 tally.add(8, "Email protections are partial", .negative)
293 case .f:
294 tally.add(18, "Email security protections are weak or absent", .negative)
295 }
296 }
260297
298 private static func scorePorts(_ snapshot: LookupSnapshot, into tally: inout RiskTally) {
261299 let openPorts = snapshot.portScanResults.filter(\.open).map(\.port)
262300 let sensitivePorts: Set<UInt16> = [21, 22, 23, 25, 3389, 5900]
263301 let exposedSensitivePorts = openPorts.filter { sensitivePorts.contains($0) }
264302 if !exposedSensitivePorts.isEmpty {
265 score += min(18, exposedSensitivePorts.count * 6)
266 factors.append(.init(description: "Sensitive management or mail ports are exposed", impact: .negative))
303 tally.add(min(18, exposedSensitivePorts.count * 6), "Sensitive management or mail ports are exposed", .negative)
267304 } else if Set(openPorts) == Set([80, 443]) {
268 factors.append(.init(description: "Exposure is limited to standard web ports", impact: .positive))
305 tally.add(0, "Exposure is limited to standard web ports", .positive)
269306 } else if openPorts.count >= 3 {
270 score += 8
271 factors.append(.init(description: "Multiple open services expand the attack surface", impact: .negative))
307 tally.add(8, "Multiple open services expand the attack surface", .negative)
272308 }
309 }
273310
274 if !subdomainGroups.isEmpty {
275 let labels = Set(subdomainGroups.map(\.label))
276 if labels.contains("dev") || labels.contains("staging") {
277 score += 8
278 factors.append(.init(description: "Development or staging subdomains are discoverable", impact: .negative))
279 }
280 if labels.contains("admin") {
281 score += 10
282 factors.append(.init(description: "Administrative subdomains are discoverable", impact: .negative))
283 }
284 if snapshot.subdomains.count >= 8 {
285 score += 6
286 factors.append(.init(description: "Large passive subdomain footprint detected", impact: .negative))
287 }
311 private static func scoreSubdomains(_ snapshot: LookupSnapshot, groups: [SubdomainGroup], into tally: inout RiskTally) {
312 guard !groups.isEmpty else { return }
313 let labels = Set(groups.map(\.label))
314 if labels.contains("dev") || labels.contains("staging") {
315 tally.add(8, "Development or staging subdomains are discoverable", .negative)
288316 }
317 if labels.contains("admin") {
318 tally.add(10, "Administrative subdomains are discoverable", .negative)
319 }
320 if snapshot.subdomains.count >= 8 {
321 tally.add(6, "Large passive subdomain footprint detected", .negative)
322 }
323 }
289324
325 private static func scoreGeolocation(_ snapshot: LookupSnapshot, into tally: inout RiskTally) {
290326 if snapshot.ipGeolocation == nil,
291327 snapshot.availabilityResult?.status == .registered,
292328 snapshot.dnsSections.contains(where: { $0.recordType == .A && !$0.records.isEmpty }) {
293 score += 4
294 factors.append(.init(description: "Active host could not be geolocated", impact: .neutral))
295 }
296
297 if let previousSnapshot {
298 let previousAnalysis = analyze(snapshot: previousSnapshot)
299 let delta = score - previousAnalysis.riskAssessment.score
300 if delta >= 15 {
301 score += 4
302 factors.append(.init(description: "Observed risk has increased materially since the previous snapshot", impact: .negative))
303 }
304 }
305
306 if let reputation = snapshot.reputation {
307 switch reputation.status {
308 case .listed:
309 score += 25
310 let sourceList = reputation.listedSources.isEmpty ? "" : " (\(reputation.listedSources.joined(separator: ", ")))"
311 factors.append(.init(description: "Domain is flagged by a configured reputation source\(sourceList)", impact: .negative))
312 case .clean:
313 factors.append(.init(description: "Domain is clean against the configured reputation source", impact: .positive))
314 case .unknown:
315 break
316 }
329 tally.add(4, "Active host could not be geolocated", .neutral)
317330 }
331 }
318332
319 let clampedScore = min(max(score, 0), 100)
320 let level: RiskLevel
321 switch clampedScore {
322 case 0..<35:
323 level = .low
324 case 35..<65:
325 level = .medium
326 default:
327 level = .high
333 private static func scoreReputation(_ snapshot: LookupSnapshot, into tally: inout RiskTally) {
334 guard let reputation = snapshot.reputation else { return }
335 switch reputation.status {
336 case .listed:
337 let sourceList = reputation.listedSources.isEmpty ? "" : " (\(reputation.listedSources.joined(separator: ", ")))"
338 tally.add(25, "Domain is flagged by a configured reputation source\(sourceList)", .negative)
339 case .clean:
340 tally.add(0, "Domain is clean against the configured reputation source", .positive)
341 case .unknown:
342 break
328343 }
329
330 return DomainRiskAssessment(score: clampedScore, level: level, factors: factors)
331344 }
332345
333346 private static func insights(
DomainDig/DomainMonitoringService.swift +67 −157
@@ -187,16 +187,11 @@ final class DomainMonitoringScheduler {
187187 private func handleAppRefresh(task: BGAppRefreshTask) {
188188 _ = syncSchedule()
189189
190 let worker = Task {
191 let outcome = await DomainMonitoringService.shared.performMonitoring(
190 task.run {
191 await DomainMonitoringService.shared.performMonitoring(
192192 trigger: .background,
193193 requireEnabledSetting: true
194 )
195 task.setTaskCompleted(success: outcome.success)
196 }
197
198 task.expirationHandler = {
199 worker.cancel()
194 ).success
200195 }
201196 }
202197#endif
@@ -290,11 +285,11 @@ final class DomainMonitoringService {
290285 domain: trackedDomain.domain,
291286 previousSnapshot: previousSnapshot
292287 )
293 let snapshot = Self.resolvedSnapshotAfterFallback(inspectedSnapshot, previousSnapshot: previousSnapshot)
288 let snapshot = inspectedSnapshot.resolvedAfterFallback(to: previousSnapshot)
294289 // When the fallback fires, `snapshot` *is* `previousSnapshot`, so
295290 // every comparison below is old-against-old and would otherwise
296291 // 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)
298293 ? Self.firstErrorMessage(in: inspectedSnapshot)
299294 : nil
300295 let savedEntry: HistoryEntry?
@@ -602,38 +597,13 @@ final class DomainMonitoringService {
602597
603598 if settings.alertsEnabled,
604599 alertDescriptor.severity >= settings.alertFilter.minimumSeverity {
605 let pendingAlert = MonitoringPendingAlert(
606 detectedAt: now,
607 message: alertDescriptor.message,
608 severity: alertDescriptor.severity,
609 changeHash: alertDescriptor.changeHash
600 alertsTriggered += await raiseAlert(
601 alertDescriptor,
602 for: &updated,
603 state: &state,
604 deferred: isQuiet || !notificationsAuthorized,
605 now: now
610606 )
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 }
637607 }
638608 }
639609 } else {
@@ -668,6 +638,45 @@ final class DomainMonitoringService {
668638 return (updated, alertsTriggered)
669639 }
670640
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
671680 private func deduplicatedPendingAlerts(_ alerts: [MonitoringPendingAlert]) -> [MonitoringPendingAlert] {
672681 var uniqueByHash: [String: MonitoringPendingAlert] = [:]
673682 for alert in alerts {
@@ -844,95 +853,8 @@ final class DomainMonitoringService {
844853 }
845854 }
846855
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
934856 /// First reported error on a snapshot, used to explain a fallback. Mirrors
935 /// the ordering `shouldFallbackToSnapshot` inspects.
857 /// the ordering `LookupSnapshot.needsFallback` inspects.
936858 private static func firstErrorMessage(in snapshot: LookupSnapshot) -> String {
937859 [
938860 snapshot.dnsError,
@@ -947,34 +869,6 @@ final class DomainMonitoringService {
947869 .first ?? "The lookup could not reach the domain."
948870 }
949871
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
978872 private static func primaryIPAddress(from snapshot: LookupSnapshot) -> String? {
979873 snapshot.dnsSections.first(where: { $0.recordType == .A })?.records.first?.value
980874 }
@@ -1004,3 +898,19 @@ final class DomainMonitoringService {
1004898 return snapshot.emailSecurityError
1005899 }
1006900}
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 {
12821282 }
12831283
12841284 func loadOwnershipHistory() async {
1285 guard !searchedDomain.isEmpty else { return }
1286 guard DataAccessService.hasAccess(to: .ownershipHistory) else {
1287 upgradePrompt = FeatureAccessService.upgradePrompt(for: .ownershipHistory)
1288 return
1285 await loadLookup(.ownershipHistory, into: \.ownershipHistory, loading: \.ownershipHistoryLoading, error: \.ownershipHistoryError,
1286 fallback: "Ownership history unavailable") {
1287 await ExternalDataService.shared.ownershipHistory(
1288 domain: searchedDomain,
1289 currentOwnership: ownershipResult,
1290 historyEntries: history
1291 ).value
12891292 }
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)
13151293 }
13161294
13171295 func loadDNSHistory() async {
1318 guard !searchedDomain.isEmpty else { return }
1319 guard DataAccessService.hasAccess(to: .dnsHistory) else {
1320 upgradePrompt = FeatureAccessService.upgradePrompt(for: .dnsHistory)
1321 return
1322 }
1323 guard dnsHistory.isEmpty else { return }
1324
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")
1296 await loadLookup(.dnsHistory, into: \.dnsHistory, loading: \.dnsHistoryLoading, error: \.dnsHistoryError,
1297 fallback: "DNS history unavailable") {
1298 await ExternalDataService.shared.dnsHistory(
1299 domain: searchedDomain,
1300 dnsSections: dnsSections,
1301 historyEntries: history
1302 ).value
13441303 }
1345
1346 dnsHistoryLoading = false
1347 _ = saveHistoryEntry(replaceLatest: true)
13481304 }
13491305
13501306 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 {
13511326 guard !searchedDomain.isEmpty else { return }
1352 guard DataAccessService.hasAccess(to: .extendedSubdomains) else {
1353 upgradePrompt = FeatureAccessService.upgradePrompt(for: .extendedSubdomains)
1327 guard DataAccessService.hasAccess(to: capability) else {
1328 upgradePrompt = FeatureAccessService.upgradePrompt(for: capability.feature)
13541329 return
13551330 }
1356 guard extendedSubdomains.isEmpty else { return }
1331 guard self[keyPath: items].isEmpty else { return }
13571332
1358 extendedSubdomainsLoading = true
1359 extendedSubdomainsError = nil
1333 self[keyPath: loading] = true
1334 self[keyPath: error] = nil
13601335
1361 let outcome = await ExternalDataService.shared.extendedSubdomains(
1362 domain: searchedDomain,
1363 existing: subdomains
1364 )
1336 (self[keyPath: items], self[keyPath: error]) = found(await fetch(), fallback: fallback)
13651337
1366 switch outcome.value {
1367 case let .success(results):
1368 extendedSubdomains = results
1369 extendedSubdomainsError = nil
1338 self[keyPath: loading] = false
1339 _ = saveHistoryEntry(replaceLatest: true)
1340 }
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)
13701347 case let .empty(message):
1371 extendedSubdomains = []
1372 extendedSubdomainsError = message
1348 return ([], message)
13731349 case let .error(message):
1374 extendedSubdomains = []
1375 extendedSubdomainsError = conciseExternalMessage(message, fallback: "Extended subdomains unavailable")
1350 return ([], conciseExternalMessage(message, fallback: fallback))
13761351 }
1377
1378 extendedSubdomainsLoading = false
1379 _ = saveHistoryEntry(replaceLatest: true)
13801352 }
13811353
13821354 func refreshUsageCredits() async {
@@ -1395,7 +1367,7 @@ final class DomainViewModel {
13951367 DomainDebugLog.debug("DomainViewModel.performLookup inspectionReturned domain=\(domain)")
13961368 guard !Task.isCancelled, isCurrentLookup(lookupID) else { return nil }
13971369
1398 let snapshot = Self.resolvedSnapshotAfterFallback(inspectedSnapshot, previousSnapshot: previous)
1370 let snapshot = inspectedSnapshot.resolvedAfterFallback(to: previous)
13991371 let applyStartedAt = DomainDebugLog.signpostStart("DomainViewModel.applySnapshot", domain: domain)
14001372 applySnapshot(snapshot)
14011373 DomainDebugLog.signpostEnd("DomainViewModel.applySnapshot", start: applyStartedAt, domain: domain)
@@ -1506,119 +1478,6 @@ final class DomainViewModel {
15061478 customPortScanLoading = false
15071479 }
15081480
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
16221481 private func runDNS(domain: String, lookupID: UUID) async {
16231482 let result = await DNSLookupService.lookupAll(domain: domain)
16241483 guard !Task.isCancelled, isCurrentLookup(lookupID) else { return }
@@ -1774,7 +1633,7 @@ final class DomainViewModel {
17741633 let result = await PortScanService.scanAll(domain: domain)
17751634 switch result {
17761635 case let .success(results):
1777 let enrichedResults = await enrichOpenPortBanners(in: results, domain: domain)
1636 let enrichedResults = await PortScanService.withBanners(results, host: domain)
17781637 guard !Task.isCancelled, isCurrentLookup(lookupID) else { return }
17791638 portScanResults = enrichedResults
17801639 portScanError = nil
@@ -1833,36 +1692,7 @@ final class DomainViewModel {
18331692 let inspectionService = DomainInspectionService()
18341693 let snapshot = await inspectionService.inspectSnapshot(domain: domain, previousSnapshot: previousSnapshot)
18351694 guard !Task.isCancelled else { return nil }
1836 return BatchLookupPayload(snapshot: resolvedSnapshotAfterFallback(snapshot, previousSnapshot: previousSnapshot))
1837 }
1838
1839 private static func enrichOpenPortBanners(_ results: [PortScanResult], domain: String) async -> [PortScanResult] {
1840 let banners = await withTaskGroup(of: (UInt16, String?).self, returning: [UInt16: String].self) { group in
1841 for result in results where result.open {
1842 group.addTask {
1843 let banner = await PortScanService.grabBanner(host: domain, port: result.port)
1844 return (result.port, banner)
1845 }
1846 }
1847
1848 var collected: [UInt16: String] = [:]
1849 for await (port, banner) in group {
1850 if let banner {
1851 collected[port] = banner
1852 }
1853 }
1854 return collected
1855 }
1856
1857 return results.map { result in
1858 var updated = result
1859 updated.banner = banners[result.port]
1860 return updated
1861 }
1862 }
1863
1864 private func enrichOpenPortBanners(in results: [PortScanResult], domain: String) async -> [PortScanResult] {
1865 await Self.enrichOpenPortBanners(results, domain: domain)
1695 return BatchLookupPayload(snapshot: snapshot.resolvedAfterFallback(to: previousSnapshot))
18661696 }
18671697
18681698 @discardableResult
@@ -2840,32 +2670,7 @@ final class DomainViewModel {
28402670 private func buildAttentionQueue(from domainStates: [PortfolioDomainStatus]) -> [PortfolioAttentionItem] {
28412671 domainStates.compactMap { state in
28422672 guard state.health != .healthy else { return nil }
2843 let reason: String
2844 let timestamp: Date
2845
2846 if state.isUnreachable {
2847 reason = "Endpoint is unreachable"
2848 timestamp = state.lastMonitoringFailure ?? state.trackedDomain.updatedAt
2849 } else if state.certificateExpiryState == .critical {
2850 reason = "Certificate is expiring in under 14 days"
2851 timestamp = state.lastChangeDate ?? state.trackedDomain.updatedAt
2852 } else if state.certificateExpiryState == .warning {
2853 reason = "Certificate expires within 30 days"
2854 timestamp = state.lastChangeDate ?? state.trackedDomain.updatedAt
2855 } else if state.recentFailureCount >= 2 || state.instabilityScore >= 70 {
2856 reason = "Repeated instability detected"
2857 timestamp = state.lastMonitoringFailure ?? state.trackedDomain.updatedAt
2858 } else if state.recentDNSChange {
2859 reason = "DNS changed recently"
2860 timestamp = state.lastChangeDate ?? state.trackedDomain.updatedAt
2861 } else if state.recentCriticalChange {
2862 reason = "Recent critical change detected"
2863 timestamp = state.lastChangeDate ?? state.trackedDomain.updatedAt
2864 } else {
2865 reason = "Needs attention"
2866 timestamp = state.trackedDomain.updatedAt
2867 }
2868
2673 let (reason, timestamp) = Self.attentionReason(for: state)
28692674 return PortfolioAttentionItem(
28702675 id: "\(state.trackedDomain.id.uuidString)|\(reason)",
28712676 trackedDomainID: state.trackedDomain.id,
@@ -2883,6 +2688,32 @@ final class DomainViewModel {
28832688 }
28842689 }
28852690
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
28862717 private func buildPortfolioGroups(from domainStates: [PortfolioDomainStatus]) -> [PortfolioGroup] {
28872718 Dictionary(grouping: domainStates, by: \.apexDomain)
28882719 .map { apexDomain, domains in
@@ -3329,40 +3160,10 @@ final class DomainViewModel {
33293160 )
33303161 }
33313162 if let pricing = snapshot.domainPricing {
3332 rows.append(
3333 InfoRowViewData(
3334 label: "External Price",
3335 value: pricing.estimatedPrice ?? "Unavailable",
3336 tone: .secondary
3337 )
3338 )
3339 if let premiumIndicator = pricing.premiumIndicator {
3340 rows.append(
3341 InfoRowViewData(
3342 label: "Premium",
3343 value: premiumIndicator ? "Yes" : "No",
3344 tone: premiumIndicator ? .warning : .secondary
3345 )
3346 )
3347 }
3348 if let resaleSignal = pricing.resaleSignal {
3349 rows.append(InfoRowViewData(label: "Resale", value: resaleSignal, tone: .secondary))
3350 }
3351 if let auctionSignal = pricing.auctionSignal {
3352 rows.append(InfoRowViewData(label: "Auction", value: auctionSignal, tone: .secondary))
3353 }
3163 rows += pricingRows(pricing)
33543164 }
33553165 if let reputation = snapshot.reputation {
3356 let tone: ResultTone
3357 switch reputation.status {
3358 case .clean: tone = .success
3359 case .listed: tone = .failure
3360 case .unknown: tone = .secondary
3361 }
3362 let value = reputation.status == .listed && !reputation.listedSources.isEmpty
3363 ? "\(reputation.status.title) (\(reputation.listedSources.joined(separator: ", ")))"
3364 : reputation.status.title
3365 rows.append(InfoRowViewData(label: "Reputation", value: value, tone: tone))
3166 rows.append(reputationRow(reputation))
33663167 }
33673168 if let certificateStatus = certificateBadgeLabel(from: snapshot) {
33683169 rows.insert(
@@ -3377,6 +3178,39 @@ final class DomainViewModel {
33773178 return rows
33783179 }
33793180
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
33803214 static func suggestionRows(from snapshot: LookupSnapshot) -> [DomainSuggestionViewData] {
33813215 snapshot.suggestions.map {
33823216 DomainSuggestionViewData(
@@ -3647,229 +3481,261 @@ final class DomainViewModel {
36473481 lines.append("Tracking Note: \(note)")
36483482 }
36493483
3650 func appendSection(_ title: String, body: () -> Void) {
3484 func appendSection(_ title: String, _ body: [String]) {
36513485 lines.append("")
36523486 lines.append(title)
36533487 lines.append(String(repeating: "-", count: title.count))
3654 body()
3488 lines += body
36553489 }
36563490
3657 appendSection("Summary") {
3658 for item in summaryFields(from: snapshot) {
3659 lines.append(" \(item.label): \(item.value)")
3660 }
3661 if let changeSummary {
3662 lines.append(" Change Summary: \(changeSummary.message)")
3663 lines.append(" Severity: \(changeSummary.severity.title)")
3664 lines.append(" Changed Sections: \(changeSummary.changedSections.isEmpty ? "None" : changeSummary.changedSections.joined(separator: ", "))")
3665 lines.append(" Compared At: \(exportDateFormatter.string(from: changeSummary.generatedAt))")
3666 }
3667 }
3491 appendSection("Summary", exportSummaryLines(snapshot, changeSummary: changeSummary, exportDateFormatter: exportDateFormatter))
3492 appendSection("Tracking", exportTrackingLines(trackedDomain, exportDateFormatter: exportDateFormatter))
3493 appendSection("Diff Summary", exportDiffSummaryLines(diffSections))
3494 appendSection("Domain", exportDomainLines(snapshot))
3495 appendSection("Ownership", exportOwnershipLines(snapshot))
3496 appendSection("Subdomains", exportSubdomainsLines(snapshot))
3497 appendSection("DNS", exportDnsLines(snapshot))
3498 appendSection("Web", exportWebLines(snapshot))
3499 appendSection("Email", exportEmailLines(snapshot))
3500 appendSection("Network", exportNetworkLines(snapshot))
36683501
3669 appendSection("Tracking") {
3670 if let trackedDomain {
3671 lines.append(" Pinned: \(trackedDomain.isPinned ? "Yes" : "No")")
3672 lines.append(" Last Refresh: \(exportDateFormatter.string(from: trackedDomain.updatedAt))")
3673 lines.append(" Last Known Availability: \(availabilityLabel(trackedDomain.lastKnownAvailability))")
3674 if let note = trackedDomain.note?.nilIfEmpty {
3675 lines.append(" Note: \(note)")
3676 }
3677 } else {
3678 lines.append(" This domain is not currently tracked.")
3502 return lines.joined(separator: "\n")
3503 }
3504
3505 private static func exportSummaryLines(
3506 _ snapshot: LookupSnapshot,
3507 changeSummary: DomainChangeSummary?,
3508 exportDateFormatter: DateFormatter
3509 ) -> [String] {
3510 var lines: [String] = []
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)")
36793531 }
3532 } else {
3533 lines.append(" This domain is not currently tracked.")
36803534 }
3535 return lines
3536 }
36813537
3682 appendSection("Diff Summary") {
3683 if diffSections.isEmpty {
3684 lines.append(" No comparison available")
3685 } else {
3686 for section in diffSections where section.items.contains(where: { $0.changeType != .unchanged }) {
3687 lines.append(" \(section.title)")
3688 for item in section.items where item.changeType != .unchanged {
3689 lines.append(" [\(item.changeType.rawValue.capitalized)] \(item.label): \(item.oldValue ?? "None") -> \(item.newValue ?? "None")")
3690 }
3538 private static func exportDiffSummaryLines(_ diffSections: [DomainDiffSection]) -> [String] {
3539 var lines: [String] = []
3540 if diffSections.isEmpty {
3541 lines.append(" No comparison available")
3542 } else {
3543 for section in diffSections where section.items.contains(where: { $0.changeType != .unchanged }) {
3544 lines.append(" \(section.title)")
3545 for item in section.items where item.changeType != .unchanged {
3546 lines.append(" [\(item.changeType.rawValue.capitalized)] \(item.label): \(item.oldValue ?? "None") -> \(item.newValue ?? "None")")
36913547 }
36923548 }
36933549 }
3550 return lines
3551 }
36943552
3695 appendSection("Domain") {
3696 for row in domainRows(from: snapshot) {
3697 lines.append(" \(row.label): \(row.value)")
3698 }
3699 if snapshot.suggestions.isEmpty {
3700 lines.append(" Suggestions: None")
3701 } else {
3702 lines.append(" Suggestions:")
3703 for suggestion in snapshot.suggestions {
3704 lines.append(" \(suggestion.domain): \(availabilityLabel(suggestion.status))")
3705 }
3553 private static func exportDomainLines(_ snapshot: LookupSnapshot) -> [String] {
3554 var lines: [String] = []
3555 for row in domainRows(from: snapshot) {
3556 lines.append(" \(row.label): \(row.value)")
3557 }
3558 if snapshot.suggestions.isEmpty {
3559 lines.append(" Suggestions: None")
3560 } else {
3561 lines.append(" Suggestions:")
3562 for suggestion in snapshot.suggestions {
3563 lines.append(" \(suggestion.domain): \(availabilityLabel(suggestion.status))")
37063564 }
37073565 }
3566 return lines
3567 }
37083568
3709 appendSection("Ownership") {
3710 for row in ownershipRows(from: snapshot) {
3711 lines.append(" \(row.label): \(row.value)")
3712 }
3713 if let ownershipError = snapshot.ownershipError, snapshot.ownership == nil {
3714 lines.append(" Source: \(ownershipError)")
3715 }
3716 if !DataAccessService.hasAccess(to: .ownershipHistory) {
3717 lines.append(" Ownership history (coming soon)")
3718 }
3569 private static func exportOwnershipLines(_ snapshot: LookupSnapshot) -> [String] {
3570 var lines: [String] = []
3571 for row in ownershipRows(from: snapshot) {
3572 lines.append(" \(row.label): \(row.value)")
37193573 }
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 }
37203582
3721 appendSection("Subdomains") {
3722 lines.append(" Count: \(snapshot.subdomains.count)")
3723 if snapshot.subdomains.isEmpty {
3724 lines.append(" \(snapshot.subdomainsError ?? "No passive subdomains found")")
3725 } else {
3726 for subdomain in subdomainRows(from: snapshot) {
3727 let marker = subdomain.isInteresting ? " [interesting]" : ""
3728 lines.append(" \(subdomain.hostname)\(marker)")
3729 }
3730 }
3731 if !DataAccessService.hasAccess(to: .extendedSubdomains) {
3732 lines.append(" Extended subdomain discovery (Pro+)")
3583 private static func exportSubdomainsLines(_ snapshot: LookupSnapshot) -> [String] {
3584 var lines: [String] = []
3585 lines.append(" Count: \(snapshot.subdomains.count)")
3586 if snapshot.subdomains.isEmpty {
3587 lines.append(" \(snapshot.subdomainsError ?? "No passive subdomains found")")
3588 } else {
3589 for subdomain in subdomainRows(from: snapshot) {
3590 let marker = subdomain.isInteresting ? " [interesting]" : ""
3591 lines.append(" \(subdomain.hostname)\(marker)")
37333592 }
37343593 }
3594 if !DataAccessService.hasAccess(to: .extendedSubdomains) {
3595 lines.append(" Extended subdomain discovery (Pro+)")
3596 }
3597 return lines
3598 }
37353599
3736 appendSection("DNS") {
3737 if let dnsError = snapshot.dnsError {
3738 lines.append(" Error: \(dnsError)")
3739 }
3740 if let dnssecLabel = dnssecLabel(from: snapshot) {
3741 lines.append(" \(dnssecLabel)")
3742 }
3743 for section in dnsRows(from: snapshot) {
3744 lines.append(" \(section.title)")
3745 if let message = section.message {
3746 lines.append(" \(message.isError ? "Error" : "Info"): \(message.text)")
3747 }
3748 for row in section.rows {
3749 lines.append(" \(row.value) (\(row.label))")
3750 }
3751 if let wildcardTitle = section.wildcardTitle {
3752 lines.append(" \(wildcardTitle)")
3753 for row in section.wildcardRows {
3754 lines.append(" \(row.value) (\(row.label))")
3755 }
3756 }
3757 }
3758 if let ptrRecord = snapshot.ptrRecord {
3759 lines.append(" PTR: \(ptrRecord)")
3760 } else if let ptrError = snapshot.ptrError {
3761 lines.append(" PTR Error: \(ptrError)")
3762 }
3600 private static func exportDnsLines(_ snapshot: LookupSnapshot) -> [String] {
3601 var lines: [String] = []
3602 if let dnsError = snapshot.dnsError {
3603 lines.append(" Error: \(dnsError)")
37633604 }
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 }
37643618
3765 appendSection("Web") {
3766 if let sslError = snapshot.sslError {
3767 lines.append(" TLS Error: \(sslError)")
3768 } else {
3769 for row in webCertificateRows(from: snapshot) {
3770 lines.append(" \(row.label): \(row.value)")
3771 }
3619 private static func exportDNSSectionLines(_ section: DNSRecordSectionViewData) -> [String] {
3620 var lines = [" \(section.title)"]
3621 if let message = section.message {
3622 lines.append(" \(message.isError ? "Error" : "Info"): \(message.text)")
3623 }
3624 for row in section.rows {
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))")
37723631 }
3632 }
3633 return lines
3634 }
37733635
3774 if let httpHeadersError = snapshot.httpHeadersError {
3775 lines.append(" Headers Error: \(httpHeadersError)")
3776 } else {
3777 for row in webResponseRows(from: snapshot) {
3778 lines.append(" \(row.label): \(row.value)")
3779 }
3780 if snapshot.httpHeaders.isEmpty {
3781 lines.append(" Headers: No headers returned")
3782 } else {
3783 lines.append(" Headers:")
3784 for header in snapshot.httpHeaders {
3785 lines.append(" \(header.name): \(header.value)")
3786 }
3787 }
3636 private static func exportResponseLines(_ snapshot: LookupSnapshot) -> [String] {
3637 if let httpHeadersError = snapshot.httpHeadersError {
3638 return [" Headers Error: \(httpHeadersError)"]
3639 }
3640 var lines = webResponseRows(from: snapshot).map { " \($0.label): \($0.value)" }
3641 if snapshot.httpHeaders.isEmpty {
3642 lines.append(" Headers: No headers returned")
3643 } else {
3644 lines.append(" Headers:")
3645 for header in snapshot.httpHeaders {
3646 lines.append(" \(header.name): \(header.value)")
37883647 }
3648 }
3649 return lines
3650 }
37893651
3790 if let redirectChainError = snapshot.redirectChainError {
3791 lines.append(" Redirect Error: \(redirectChainError)")
3792 } else if snapshot.redirectChain.isEmpty {
3793 lines.append(" Redirects: No redirect data available")
3794 } else {
3795 lines.append(" Redirects:")
3796 for hop in redirectRows(from: snapshot) {
3797 lines.append(" \(hop.stepLabel). \(hop.statusCode) \(hop.url)\(hop.isFinal ? " (final)" : "")")
3798 }
3652 private static func exportWebLines(_ snapshot: LookupSnapshot) -> [String] {
3653 var lines: [String] = []
3654 if let sslError = snapshot.sslError {
3655 lines.append(" TLS Error: \(sslError)")
3656 } else {
3657 for row in webCertificateRows(from: snapshot) {
3658 lines.append(" \(row.label): \(row.value)")
37993659 }
38003660 }
3661 lines += exportResponseLines(snapshot)
38013662
3802 appendSection("Email") {
3803 if let emailSecurityError = snapshot.emailSecurityError {
3804 lines.append(" Error: \(emailSecurityError)")
3805 } else if emailRows(from: snapshot).isEmpty {
3806 lines.append(" No email security records found")
3807 } else {
3808 for row in emailRows(from: snapshot) {
3809 lines.append(" \(row.label): \(row.status)")
3810 lines.append(" \(row.detail)")
3811 if let auxiliaryDetail = row.auxiliaryDetail {
3812 lines.append(" \(auxiliaryDetail)")
3813 }
3814 }
3663 if let redirectChainError = snapshot.redirectChainError {
3664 lines.append(" Redirect Error: \(redirectChainError)")
3665 } else if snapshot.redirectChain.isEmpty {
3666 lines.append(" Redirects: No redirect data available")
3667 } else {
3668 lines.append(" Redirects:")
3669 for hop in redirectRows(from: snapshot) {
3670 lines.append(" \(hop.stepLabel). \(hop.statusCode) \(hop.url)\(hop.isFinal ? " (final)" : "")")
38153671 }
38163672 }
3673 return lines
3674 }
38173675
3818 appendSection("Network") {
3819 if let reachabilityError = snapshot.reachabilityError {
3820 lines.append(" Reachability Error: \(reachabilityError)")
3821 } else if reachabilityRows(from: snapshot).isEmpty {
3822 lines.append(" Reachability: No results")
3823 } else {
3824 lines.append(" Reachability:")
3825 for row in reachabilityRows(from: snapshot) {
3826 lines.append(" \(row.portLabel): \(row.statusLabel) \(row.latencyLabel)")
3676 private static func exportEmailLines(_ snapshot: LookupSnapshot) -> [String] {
3677 var lines: [String] = []
3678 if let emailSecurityError = snapshot.emailSecurityError {
3679 lines.append(" Error: \(emailSecurityError)")
3680 } else if emailRows(from: snapshot).isEmpty {
3681 lines.append(" No email security records found")
3682 } else {
3683 for row in emailRows(from: snapshot) {
3684 lines.append(" \(row.label): \(row.status)")
3685 lines.append(" \(row.detail)")
3686 if let auxiliaryDetail = row.auxiliaryDetail {
3687 lines.append(" \(auxiliaryDetail)")
38273688 }
38283689 }
3690 }
3691 return lines
3692 }
38293693
3830 if let ipGeolocationError = snapshot.ipGeolocationError, snapshot.ipGeolocation == nil {
3831 lines.append(" Location Error: \(ipGeolocationError)")
3832 } else if locationRows(from: snapshot).isEmpty {
3833 lines.append(" Location: No data")
3834 } else {
3835 lines.append(" Location:")
3836 for row in locationRows(from: snapshot) {
3837 lines.append(" \(row.label): \(row.value)")
3838 }
3694 private static func exportPortLines(_ rows: [PortScanRowViewData]) -> [String] {
3695 guard !rows.isEmpty else { return [" No results"] }
3696 var lines: [String] = []
3697 for row in rows {
3698 lines.append(" \(row.portLabel) \(row.service): \(row.statusLabel)\(row.durationLabel.map { " \($0)" } ?? "")")
3699 if let banner = row.banner {
3700 lines.append(" Banner: \(banner)")
38393701 }
3702 }
3703 return lines
3704 }
38403705
3841 if let portScanError = snapshot.portScanError, snapshot.portScanResults.isEmpty {
3842 lines.append(" Port Scan Error: \(portScanError)")
3706 private static func exportNetworkLines(_ snapshot: LookupSnapshot) -> [String] {
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)")
38433716 }
3717 }
38443718
3845 lines.append(" Standard Ports:")
3846 let standardRows = portRows(from: snapshot, kind: .standard)
3847 if standardRows.isEmpty {
3848 lines.append(" No results")
3849 } else {
3850 for row in standardRows {
3851 lines.append(" \(row.portLabel) \(row.service): \(row.statusLabel)\(row.durationLabel.map { " \($0)" } ?? "")")
3852 if let banner = row.banner {
3853 lines.append(" Banner: \(banner)")
3854 }
3855 }
3719 if let ipGeolocationError = snapshot.ipGeolocationError, snapshot.ipGeolocation == nil {
3720 lines.append(" Location Error: \(ipGeolocationError)")
3721 } else if locationRows(from: snapshot).isEmpty {
3722 lines.append(" Location: No data")
3723 } else {
3724 lines.append(" Location:")
3725 for row in locationRows(from: snapshot) {
3726 lines.append(" \(row.label): \(row.value)")
38563727 }
3728 }
38573729
3858 lines.append(" Custom Ports:")
3859 let customRows = portRows(from: snapshot, kind: .custom)
3860 if customRows.isEmpty {
3861 lines.append(" No results")
3862 } else {
3863 for row in customRows {
3864 lines.append(" \(row.portLabel) \(row.service): \(row.statusLabel)\(row.durationLabel.map { " \($0)" } ?? "")")
3865 if let banner = row.banner {
3866 lines.append(" Banner: \(banner)")
3867 }
3868 }
3869 }
3730 if let portScanError = snapshot.portScanError, snapshot.portScanResults.isEmpty {
3731 lines.append(" Port Scan Error: \(portScanError)")
38703732 }
38713733
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
38733739 }
38743740
38753741 private static func primaryIPAddress(from snapshot: LookupSnapshot) -> String? {
DomainDig/ExportPresenter.swift +32
@@ -30,3 +30,35 @@ enum ExportPresenter {
3030 presenter.present(activityController, animated: true)
3131 }
3232}
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 {
646646
647647private enum IntegrationSecretStore {
648648 static func save(secret: String, reference: String) throws {
649 let data = Data(secret.utf8)
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 {
649 guard GenericPasswordKeychain.save(secret, reference: reference) else {
661650 throw IntegrationError.smtp("Could not save integration secret.")
662651 }
663652 }
664653
665654 static func secret(reference: String) throws -> String {
666 let query: [String: Any] = [
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 {
655 guard let secret = GenericPasswordKeychain.secret(reference: reference) else {
678656 throw IntegrationError.missingSecret
679657 }
680
681658 return secret
682659 }
683660
684661 static func delete(reference: String) throws {
685 let query: [String: Any] = [
686 kSecClass as String: kSecClassGenericPassword,
687 kSecAttrAccount as String: reference
688 ]
689 SecItemDelete(query as CFDictionary)
662 GenericPasswordKeychain.delete(reference: reference)
690663 }
691664}
692665
@@ -778,23 +751,12 @@ private actor SMTPChannel {
778751 // from the connection's queue.
779752 let hasResumed = OSAllocatedUnfairLock(initialState: false)
780753 connection.stateUpdateHandler = { state in
781 let isFirst: () -> Bool = {
782 hasResumed.withLock { resumed in
783 if resumed { return false }
784 resumed = true
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
754 guard let outcome = Self.startOutcome(for: state) else { return }
755 let isFirst = hasResumed.withLock { resumed in
756 defer { resumed = true }
757 return !resumed
797758 }
759 if isFirst { continuation.resume(with: outcome) }
798760 }
799761 connection.start(queue: .global(qos: .utility))
800762 }
@@ -803,6 +765,21 @@ private actor SMTPChannel {
803765 startReceiveLoop()
804766 }
805767
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
806783 func cancel() {
807784 connection.cancel()
808785 }
DomainDig/Models.swift +1 −15
@@ -1246,25 +1246,11 @@ struct MonitoringState: Codable, Equatable, Sendable {
12461246}
12471247
12481248struct MonitoringPendingAlert: Codable, Identifiable, Equatable, Sendable {
1249 let id: UUID
1249 var id = UUID()
12501250 var detectedAt: Date
12511251 var message: String
12521252 var severity: MonitoringAlertSeverity
12531253 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 }
12681254}
12691255
12701256
DomainDig/PortScanService.swift +26
@@ -74,6 +74,32 @@ struct PortScanService {
7474 .pipe { $0.isEmpty ? .empty("No custom port scan results") : .success($0) }
7575 }
7676
77 /// `results` with each open port's banner, grabbed concurrently.
78 static func withBanners(_ results: [PortScanResult], host: String) async -> [PortScanResult] {
79 let banners = await withTaskGroup(of: (UInt16, String?).self, returning: [UInt16: String].self) { group in
80 for result in results where result.open {
81 group.addTask {
82 let banner = await grabBanner(host: host, port: result.port)
83 return (result.port, banner)
84 }
85 }
86
87 var collected: [UInt16: String] = [:]
88 for await (port, banner) in group {
89 if let banner {
90 collected[port] = banner
91 }
92 }
93 return collected
94 }
95
96 return results.map { result in
97 var updated = result
98 updated.banner = banners[result.port]
99 return updated
100 }
101 }
102
77103 static func grabBanner(host: String, port: UInt16, timeout: TimeInterval = 3.0) async -> String? {
78104 await withCheckedContinuation { continuation in
79105 guard let nwPort = NWEndpoint.Port(rawValue: port) else {
DomainDig/ResultSectionViews.swift +154 −124
@@ -234,43 +234,48 @@ struct OwnershipSectionView: View {
234234 MessageRowView(text: error, isError: error != "Unavailable")
235235 .padding(.top, 4)
236236 }
237 VStack(alignment: .leading, spacing: 8) {
238 HStack {
239 Text("History")
240 .font(appDensity.font(.caption))
241 .foregroundStyle(Color(.appTextSecondary))
242 Spacer()
243 if let onLoadHistory, history.isEmpty, !historyLoading, !showsHistoryPlaceholder {
244 Button("Load") {
245 onLoadHistory()
246 }
247 .buttonStyle(.bordered)
248 .font(appDensity.font(.caption2))
249 }
250 }
251 if historyLoading {
252 ProgressView("Loading history…")
253 .appLoadingStyle()
254 } else if !history.isEmpty {
255 ForEach(history) { event in
256 VStack(alignment: .leading, spacing: 3) {
257 Text(event.date.formatted(date: .abbreviated, time: .omitted))
258 .font(appDensity.font(.caption2))
259 .foregroundStyle(Color(.appTextSecondary))
260 Text(event.summary)
261 .font(appDensity.font(.caption))
262 Text(event.source)
263 .font(appDensity.font(.caption2))
264 .foregroundStyle(Color(.appTextSecondary))
265 }
266 }
267 } else if let historyError {
268 MessageRowView(text: historyError, isError: false)
269 } else if showsHistoryPlaceholder {
270 MessageRowView(text: "Ownership history available in Pro+", isError: false)
271 }
237 historyBlock
238 }
239 }
240 }
241 }
242
243 @ViewBuilder
244 private var historyBlock: some View {
245 VStack(alignment: .leading, spacing: 8) {
246 HStack {
247 Text("History")
248 .font(appDensity.font(.caption))
249 .foregroundStyle(Color(.appTextSecondary))
250 Spacer()
251 if let onLoadHistory, history.isEmpty, !historyLoading, !showsHistoryPlaceholder {
252 Button("Load") {
253 onLoadHistory()
254 }
255 .buttonStyle(.bordered)
256 .font(appDensity.font(.caption2))
257 }
258 }
259 if historyLoading {
260 ProgressView("Loading history…")
261 .appLoadingStyle()
262 } else if !history.isEmpty {
263 ForEach(history) { event in
264 VStack(alignment: .leading, spacing: 3) {
265 Text(event.date.formatted(date: .abbreviated, time: .omitted))
266 .font(appDensity.font(.caption2))
267 .foregroundStyle(Color(.appTextSecondary))
268 Text(event.summary)
269 .font(appDensity.font(.caption))
270 Text(event.source)
271 .font(appDensity.font(.caption2))
272 .foregroundStyle(Color(.appTextSecondary))
272273 }
273274 }
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)
274279 }
275280 }
276281 }
@@ -463,54 +468,69 @@ struct SubdomainsSectionView: View {
463468 .buttonStyle(.bordered)
464469 .font(appDensity.font(.caption2))
465470 }
466 if !groups.isEmpty {
467 Text("Groups")
468 .font(appDensity.font(.caption2))
469 .foregroundStyle(Color(.appTextSecondary))
470 ForEach(groups) { group in
471 HStack {
472 Text("\(group.label).*")
473 .font(appDensity.font(.caption))
474 .foregroundStyle(Color(.statusInfo))
475 Spacer()
476 Text("\(group.subdomains.count)")
477 .font(appDensity.font(.caption2))
478 .foregroundStyle(Color(.appTextSecondary))
479 }
480 }
481 }
482 ForEach(rows) { row in
483 HStack(spacing: 8) {
484 Text(row.hostname)
485 .font(appDensity.font(.caption))
486 .foregroundStyle(.primary)
487 .textSelection(.enabled)
488 Spacer()
489 if row.isInteresting {
490 Text("Interesting")
491 .font(.system(.caption2, design: .monospaced))
492 .foregroundStyle(Color(.statusWarning))
493 .padding(.horizontal, 8)
494 .padding(.vertical, 4)
495 .background(Color(.statusWarningSurface))
496 .clipShape(Capsule())
497 }
498 }
499 }
500 if extendedLoading {
501 ProgressView("Loading extended subdomains…")
502 .appLoadingStyle()
503 .padding(.top, 4)
504 } else if extendedCount > 0 {
505 MessageRowView(text: "\(extendedCount) extended results included", isError: false)
506 .padding(.top, 4)
507 } else if let extendedError {
508 MessageRowView(text: extendedError, isError: false)
509 .padding(.top, 4)
510 } else if showsExtendedPlaceholder {
511 MessageRowView(text: "Extended subdomain discovery available in Pro+", isError: false)
512 .padding(.top, 4)
513 }
471 groupList
472 subdomainRows
473 extendedStatus
474 }
475 }
476 }
477 }
478
479 @ViewBuilder
480 private var extendedStatus: some View {
481 if extendedLoading {
482 ProgressView("Loading extended subdomains…")
483 .appLoadingStyle()
484 .padding(.top, 4)
485 } else if extendedCount > 0 {
486 MessageRowView(text: "\(extendedCount) extended results included", isError: false)
487 .padding(.top, 4)
488 } else if let extendedError {
489 MessageRowView(text: extendedError, isError: false)
490 .padding(.top, 4)
491 } else if showsExtendedPlaceholder {
492 MessageRowView(text: "Extended subdomain discovery available in Pro+", isError: false)
493 .padding(.top, 4)
494 }
495 }
496
497 @ViewBuilder
498 private var groupList: some View {
499 if !groups.isEmpty {
500 Text("Groups")
501 .font(appDensity.font(.caption2))
502 .foregroundStyle(Color(.appTextSecondary))
503 ForEach(groups) { group in
504 HStack {
505 Text("\(group.label).*")
506 .font(appDensity.font(.caption))
507 .foregroundStyle(Color(.statusInfo))
508 Spacer()
509 Text("\(group.subdomains.count)")
510 .font(appDensity.font(.caption2))
511 .foregroundStyle(Color(.appTextSecondary))
512 }
513 }
514 }
515 }
516
517 @ViewBuilder
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())
514534 }
515535 }
516536 }
@@ -576,21 +596,7 @@ struct DNSSectionView: View {
576596 } else if let sectionError, sections.isEmpty {
577597 MessageCardView(text: sectionError, isError: true)
578598 } else {
579 if dnsProvenance != nil {
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 }
599 provenanceCard
594600 ForEach(sections) { section in
595601 CardView {
596602 Text(section.title)
@@ -643,33 +649,57 @@ struct DNSSectionView: View {
643649 .font(appDensity.font(.caption2))
644650 }
645651 }
646 if historyLoading {
647 ProgressView("Loading DNS history…")
648 .appLoadingStyle()
649 } else if !history.isEmpty {
650 ForEach(history) { event in
651 VStack(alignment: .leading, spacing: 3) {
652 Text(event.date.formatted(date: .abbreviated, time: .omitted))
653 .font(appDensity.font(.caption2))
654 .foregroundStyle(Color(.appTextSecondary))
655 Text(event.summary)
656 .font(appDensity.font(.caption))
657 if !event.aRecords.isEmpty {
658 Text("A: \(event.aRecords.joined(separator: ", "))")
659 .font(appDensity.font(.caption2))
660 .foregroundStyle(Color(.appTextSecondary))
661 }
662 if !event.nameservers.isEmpty {
663 Text("NS: \(event.nameservers.joined(separator: ", "))")
664 .font(appDensity.font(.caption2))
665 .foregroundStyle(Color(.appTextSecondary))
666 }
667 }
652 historyContent
653 }
654 }
655 }
656 }
657
658 @ViewBuilder
659 private var historyContent: some View {
660 if historyLoading {
661 ProgressView("Loading DNS history…")
662 .appLoadingStyle()
663 } else if !history.isEmpty {
664 ForEach(history) { event in
665 VStack(alignment: .leading, spacing: 3) {
666 Text(event.date.formatted(date: .abbreviated, time: .omitted))
667 .font(appDensity.font(.caption2))
668 .foregroundStyle(Color(.appTextSecondary))
669 Text(event.summary)
670 .font(appDensity.font(.caption))
671 if !event.aRecords.isEmpty {
672 Text("A: \(event.aRecords.joined(separator: ", "))")
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)
668702 }
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)
673703 }
674704 }
675705 }
DomainDig/SSLCheckService.swift +42 −43
@@ -228,24 +228,15 @@ private enum DERCertificateParser {
228228 while pos < end {
229229 // Each SET in the issuer
230230 guard let setTL = readTagAndLength(bytes, offset: pos) else { break }
231 let setEnd = setTL.contentStart + setTL.length
231 pos = setTL.contentStart + setTL.length
232232
233233 // Inside the SET is a SEQUENCE with OID + value
234 if let seqTL = readTagAndLength(bytes, offset: setTL.contentStart) {
235 let seqEnd = seqTL.contentStart + seqTL.length
236 if let oidTL = readTagAndLength(bytes, offset: seqTL.contentStart) {
237 let oidBytes = Array(bytes[oidTL.contentStart..<oidTL.contentStart + oidTL.length])
238 if oidBytes == cnOID {
239 let valueStart = oidTL.contentStart + oidTL.length
240 if let valueTL = readTagAndLength(bytes, offset: valueStart) {
241 let strBytes = bytes[valueTL.contentStart..<valueTL.contentStart + valueTL.length]
242 return String(bytes: strBytes, encoding: .utf8)
243 }
244 }
245 _ = seqEnd // suppress unused warning
246 }
247 }
248 pos = setEnd
234 guard let seqTL = readTagAndLength(bytes, offset: setTL.contentStart),
235 let oidTL = readTagAndLength(bytes, offset: seqTL.contentStart),
236 content(of: oidTL, in: bytes).elementsEqual(cnOID),
237 let valueTL = readTagAndLength(bytes, offset: oidTL.contentStart + oidTL.length)
238 else { continue }
239 return String(bytes: content(of: valueTL, in: bytes), encoding: .utf8)
249240 }
250241 return nil
251242 }
@@ -260,39 +251,41 @@ private enum DERCertificateParser {
260251 let extEnd = extSeq.contentStart + extSeq.length
261252
262253 // Each extension is SEQUENCE { OID, [critical], value }
263 if let oidTL = readTagAndLength(bytes, offset: extSeq.contentStart) {
264 let oidBytes = Array(bytes[oidTL.contentStart..<oidTL.contentStart + oidTL.length])
265 if oidBytes == sanOID {
266 var valuePos = oidTL.contentStart + oidTL.length
267 // Skip optional critical BOOLEAN
268 if valuePos < extEnd, bytes[valuePos] == 0x01,
269 let boolTL = readTagAndLength(bytes, offset: valuePos) {
270 valuePos = boolTL.contentStart + boolTL.length
271 }
272 // The value is an OCTET STRING wrapping a SEQUENCE of GeneralNames
273 if let octetTL = readTagAndLength(bytes, offset: valuePos),
274 let sanSeq = readTagAndLength(bytes, offset: octetTL.contentStart) {
275 let sanEnd = sanSeq.contentStart + sanSeq.length
276 var sanPos = sanSeq.contentStart
277 while sanPos < sanEnd {
278 guard let nameTL = readTagAndLength(bytes, offset: sanPos) else { break }
279 // Context tag [2] = dNSName (IA5String)
280 if (bytes[sanPos] & 0x1F) == 2 {
281 let nameBytes = bytes[nameTL.contentStart..<nameTL.contentStart + nameTL.length]
282 if let name = String(bytes: nameBytes, encoding: .ascii) {
283 sans.append(name)
284 }
285 }
286 sanPos = nameTL.contentStart + nameTL.length
287 }
288 }
289 }
254 if let oidTL = readTagAndLength(bytes, offset: extSeq.contentStart), content(of: oidTL, in: bytes).elementsEqual(sanOID) {
255 sans += sanDNSNames(bytes, valueStart: oidTL.contentStart + oidTL.length, extensionEnd: extEnd)
290256 }
291257 pos = extEnd
292258 }
293259 return sans
294260 }
295261
262 /// The dNSName entries of a subjectAltName extension whose value starts at `valueStart`.
263 private static func sanDNSNames(_ bytes: [UInt8], valueStart: Int, extensionEnd: Int) -> [String] {
264 var valuePos = valueStart
265 // Skip optional critical BOOLEAN
266 if valuePos < extensionEnd, bytes[valuePos] == 0x01,
267 let boolTL = readTagAndLength(bytes, offset: valuePos) {
268 valuePos = boolTL.contentStart + boolTL.length
269 }
270 // The value is an OCTET STRING wrapping a SEQUENCE of GeneralNames
271 guard let octetTL = readTagAndLength(bytes, offset: valuePos),
272 let sanSeq = readTagAndLength(bytes, offset: octetTL.contentStart)
273 else { return [] }
274
275 let sanEnd = sanSeq.contentStart + sanSeq.length
276 var sanPos = sanSeq.contentStart
277 var names: [String] = []
278 while sanPos < sanEnd {
279 guard let nameTL = readTagAndLength(bytes, offset: sanPos) else { break }
280 // Context tag [2] = dNSName (IA5String)
281 if (bytes[sanPos] & 0x1F) == 2, let name = String(bytes: content(of: nameTL, in: bytes), encoding: .ascii) {
282 names.append(name)
283 }
284 sanPos = nameTL.contentStart + nameTL.length
285 }
286 return names
287 }
288
296289 private static func extractValidity(_ bytes: [UInt8], sequenceStart: Int, length: Int) -> (Date?, Date?) {
297290 let end = sequenceStart + length
298291 var position = sequenceStart
@@ -362,8 +355,14 @@ private enum DERCertificateParser {
362355 length = len
363356 }
364357
358 // A length past the end of the data is malformed, and slicing to it would trap.
359 guard length <= bytes.count - pos else { return nil }
365360 return TLV(contentStart: pos, length: length)
366361 }
362
363 private static func content(of tlv: TLV, in bytes: [UInt8]) -> ArraySlice<UInt8> {
364 bytes[tlv.contentStart..<tlv.contentStart + tlv.length]
365 }
367366}
368367
369368enum SSLError: LocalizedError {
DomainDig/ScheduledReportService.swift +3 −22
@@ -31,25 +31,11 @@ struct ScheduledReportSettings: Codable, Equatable {
3131}
3232
3333struct ScheduledReportLog: Codable, Identifiable, Equatable {
34 let id: UUID
34 var id = UUID()
3535 let generatedAt: Date
3636 let domainCount: Int
3737 let format: DomainExportFormat
3838 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 }
5339}
5440
5541/// Local, UserDefaults-backed persistence for scheduled-report settings and
@@ -245,13 +231,8 @@ final class ScheduledReportScheduler {
245231 private func handleAppRefresh(task: BGAppRefreshTask) {
246232 _ = syncSchedule()
247233
248 let worker = Task {
249 let outcome = await ScheduledReportService.shared.generateReport(trigger: .background, requireEnabledSetting: true)
250 task.setTaskCompleted(success: outcome.success)
251 }
252
253 task.expirationHandler = {
254 worker.cancel()
234 task.run {
235 await ScheduledReportService.shared.generateReport(trigger: .background, requireEnabledSetting: true).success
255236 }
256237 }
257238 #endif
DomainDig/SettingsViews.swift +16 −35
@@ -483,41 +483,14 @@ private struct MonitoringSettingsView: View {
483483 )
484484
485485 if viewModel.monitoringSettings.quietHours != nil {
486 Picker(
487 "Quiet Starts",
488 selection: Binding(
489 get: { quietHoursStart },
490 set: { startHour in
491 viewModel.setMonitoringQuietHours(
492 startHour: startHour,
493 endHour: quietHoursEnd,
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 }
486 hourPicker("Quiet Starts", selection: Binding(
487 get: { quietHoursStart },
488 set: { viewModel.setMonitoringQuietHours(startHour: $0, endHour: quietHoursEnd, isEnabled: true) }
489 ))
490 hourPicker("Quiet Ends", selection: Binding(
491 get: { quietHoursEnd },
492 set: { viewModel.setMonitoringQuietHours(startHour: quietHoursStart, endHour: $0, isEnabled: true) }
493 ))
521494 }
522495
523496 Picker(
@@ -597,6 +570,14 @@ private struct MonitoringSettingsView: View {
597570 }
598571 }
599572
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
600581 private static func monitoringHourLabel(for hour: Int) -> String {
601582 let formatter = DateFormatter()
602583 formatter.dateFormat = "h a"
DomainDig/WatchlistView.swift +56 −89
@@ -150,36 +150,7 @@ struct WatchlistView: View {
150150 }
151151 }
152152
153 Button("Export TXT") {
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 }
153 ExportFormatButtons(share: shareTrackedDomains)
183154 } label: {
184155 Image(systemName: "line.3.horizontal.decrease.circle")
185156 }
@@ -313,76 +284,72 @@ struct WatchlistView: View {
313284 }
314285 .buttonStyle(.plain)
315286 .swipeActions(edge: .leading, allowsFullSwipe: false) {
316 Button {
317 AppHaptics.refresh()
318 viewModel.refreshTrackedDomain(trackedDomain)
319 } label: {
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))
287 refreshButton(trackedDomain)
288 .tint(Color(.statusInfo))
289 pinButton(trackedDomain)
290 .tint(Color(.statusWarning))
330291 }
331292 .swipeActions(edge: .trailing, allowsFullSwipe: false) {
332 Button {
333 AppHaptics.refresh()
334 viewModel.refreshTrackedDomain(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 }
293 refreshButton(trackedDomain)
294 .tint(Color(.statusInfo))
295 deleteButton(trackedDomain)
347296 }
348297 .contextMenu {
349 Button {
350 AppHaptics.refresh()
351 viewModel.refreshTrackedDomain(trackedDomain)
352 } label: {
353 Label("Refresh", systemImage: "arrow.clockwise")
354 }
298 rowMenu(trackedDomain)
299 }
300 .listRowBackground(Color(.appSurface))
301 }
355302
356 Button {
357 dismiss()
358 viewModel.rerunInspection(for: trackedDomain)
359 } label: {
360 Label("Open Inspection", systemImage: "magnifyingglass")
361 }
303 @ViewBuilder
304 private func rowMenu(_ trackedDomain: TrackedDomain) -> some View {
305 refreshButton(trackedDomain)
362306
363 Button {
364 viewModel.togglePinned(for: trackedDomain)
365 } label: {
366 Label(trackedDomain.isPinned ? "Unpin" : "Pin", systemImage: trackedDomain.isPinned ? "pin.slash" : "pin")
367 }
307 Button {
308 dismiss()
309 viewModel.rerunInspection(for: trackedDomain)
310 } label: {
311 Label("Open Inspection", systemImage: "magnifyingglass")
312 }
313
314 pinButton(trackedDomain)
368315 .disabled(!viewModel.canEdit(trackedDomain))
369316
370 Button {
371 // The system sharing UI manages participants and permissions.
372 } label: {
373 Label(trackedDomain.collaboration?.isShared == true ? "Shared" : "Private", systemImage: "person.2")
374 }
375 .disabled(true)
317 Button {
318 // The system sharing UI manages participants and permissions.
319 } label: {
320 Label(trackedDomain.collaboration?.isShared == true ? "Shared" : "Private", systemImage: "person.2")
321 }
322 .disabled(true)
376323
377 if viewModel.canDelete(trackedDomain) {
378 Button(role: .destructive) {
379 viewModel.deleteTrackedDomain(trackedDomain)
380 } label: {
381 Label("Delete", systemImage: "trash")
382 }
324 deleteButton(trackedDomain)
325 }
326
327 private func refreshButton(_ trackedDomain: TrackedDomain) -> some View {
328 Button {
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")
383351 }
384352 }
385 .listRowBackground(Color(.appSurface))
386353 }
387354
388355 private var batchSummaryBinding: Binding<BatchSweepSummary?> {
DomainDig/WorkflowsView.swift +8 −71
@@ -237,32 +237,7 @@ struct WorkflowDetailView: View {
237237 if latestSummary != nil {
238238 Toggle("Export all domains", isOn: $includeAllExports)
239239 Menu {
240 Button("Export TXT") {
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 }
240 ExportFormatButtons(share: shareWorkflowResults)
266241 } label: {
267242 Label("Export Results", systemImage: "square.and.arrow.up")
268243 }
@@ -512,56 +487,18 @@ struct WorkflowRunSummaryView: View {
512487 }
513488 }
514489
515 Section(visibleResults.isEmpty ? "Meaningful Changes" : "Results") {
516 if visibleResults.isEmpty {
517 Text("No domains with meaningful changes or warnings")
518 .font(.system(.caption, design: .monospaced))
519 .foregroundStyle(Color(.appTextSecondary))
520 } else {
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 }
490 BatchResultsSection(
491 viewModel: viewModel,
492 results: visibleResults,
493 emptyTitle: "Meaningful Changes",
494 emptyText: "No domains with meaningful changes or warnings"
495 )
534496 }
535497 .navigationTitle("Workflow Summary")
536498 .toolbar {
537499 ToolbarItemGroup(placement: .topBarTrailing) {
538500 Menu {
539 Button("Export TXT") {
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 }
501 ExportFormatButtons(share: share)
565502 } label: {
566503 Image(systemName: "square.and.arrow.up")
567504 }
DomainInspectionService.swift +120 −240
@@ -19,11 +19,7 @@ struct DomainInspectionService {
1919 let startedAt = Date()
2020 let resolverDisplayName = DNSLookupService.currentResolverDisplayName()
2121 let resolverURLString = DNSLookupService.currentResolverURLString()
22 var cachedSections = Set<LookupSectionKind>()
23 var sectionSources: [LookupResultSource] = []
24 var provenanceBySection: [LookupSectionKind: SectionProvenance] = [:]
25 var dataSources = Set<String>()
26 var errorDetails: [LookupSectionKind: InspectionFailure] = [:]
22 var ledger = InspectionLedger(resolverDisplayName: resolverDisplayName)
2723
2824 async let dnsFetch = runtime.dns(domain: normalizedDomain)
2925 async let availabilityFetch = runtime.availability(domain: normalizedDomain)
@@ -37,110 +33,46 @@ struct DomainInspectionService {
3733 let resolvedDNS = await dnsFetch
3834 DomainDebugLog.debug("Inspection.sectionComplete domain=\(normalizedDomain) section=dns source=\(resolvedDNS.source.rawValue)")
3935 let dnsResult = normalizeErrors(in: resolvedDNS.value)
40 track(
41 .dns,
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)
36 ledger.track(.dns, source: resolvedDNS.source)
37 ledger.captureFailure(for: .dns, result: dnsResult)
5038
5139 let availability = await availabilityFetch
5240 DomainDebugLog.debug("Inspection.sectionComplete domain=\(normalizedDomain) section=availability source=\(availability.source.rawValue)")
53 track(
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 )
41 ledger.track(.availability, source: availability.source)
6242
6343 let resolvedSSL = await sslFetch
6444 DomainDebugLog.debug("Inspection.sectionComplete domain=\(normalizedDomain) section=ssl source=\(resolvedSSL.source.rawValue)")
6545 let sslResult = normalizeErrors(in: resolvedSSL.value)
66 track(
67 .ssl,
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)
46 ledger.track(.ssl, source: resolvedSSL.source)
47 ledger.captureFailure(for: .ssl, result: sslResult)
7648
7749 let hsts = await hstsFetch
7850 DomainDebugLog.debug("Inspection.sectionComplete domain=\(normalizedDomain) section=hsts source=\(hsts.source.rawValue)")
79 track(
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 )
51 ledger.track(.hsts, source: hsts.source)
8852
8953 let http = await httpFetch
9054 DomainDebugLog.debug("Inspection.sectionComplete domain=\(normalizedDomain) section=http source=\(http.source.rawValue)")
9155 let httpResult = normalizeErrors(in: http.value)
92 track(
93 .httpHeaders,
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)
56 ledger.track(.httpHeaders, source: http.source)
57 ledger.captureFailure(for: .httpHeaders, result: httpResult)
10258
10359 let resolvedOwnership = await ownershipFetch
10460 DomainDebugLog.debug("Inspection.sectionComplete domain=\(normalizedDomain) section=ownership source=\(resolvedOwnership.source.rawValue)")
10561 let ownershipResult = normalizeErrors(in: resolvedOwnership.value)
106 track(
107 .ownership,
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)
62 ledger.track(.ownership, source: resolvedOwnership.source)
63 ledger.captureFailure(for: .ownership, result: ownershipResult)
11664
11765 let redirects = await redirectFetch
11866 DomainDebugLog.debug("Inspection.sectionComplete domain=\(normalizedDomain) section=redirect source=\(redirects.source.rawValue)")
11967 let redirectResult = normalizeErrors(in: redirects.value)
120 track(
121 .redirectChain,
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)
68 ledger.track(.redirectChain, source: redirects.source)
69 ledger.captureFailure(for: .redirectChain, result: redirectResult)
13070
13171 let resolvedSubdomains = await subdomainFetch
13272 DomainDebugLog.debug("Inspection.sectionComplete domain=\(normalizedDomain) section=subdomains source=\(resolvedSubdomains.source.rawValue)")
13373 let subdomainResult = normalizeErrors(in: resolvedSubdomains.value)
134 track(
135 .subdomains,
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)
74 ledger.track(.subdomains, source: resolvedSubdomains.source)
75 ledger.captureFailure(for: .subdomains, result: subdomainResult)
14476
14577 let dnsSections = mapServiceResult(dnsResult, emptyValue: [])
14678 let sslInfo = mapOptionalValueServiceResult(sslResult)
@@ -158,85 +90,46 @@ struct DomainInspectionService {
15890 let canReuseDNSDependents = canReuseDependentSections(from: previousSnapshot, dnsSections: dnsSections.value)
15991 let canReuseIPDependents = canReuseIPBasedSections(from: previousSnapshot, primaryIP: primaryIP)
16092
161 let reachabilityOutcome: CachedLookupResult<ServiceResult<[PortReachability]>>
162 if hasNetworkTarget {
163 reachabilityOutcome = await runtime.reachability(domain: normalizedDomain)
164 } else {
165 reachabilityOutcome = CachedLookupResult(value: .empty("No routable address available"), source: .live)
93 let reachabilityOutcome = await whenRoutable(hasNetworkTarget) {
94 await runtime.reachability(domain: normalizedDomain)
16695 }
16796 let reachabilityResult = normalizeErrors(in: reachabilityOutcome.value)
16897 DomainDebugLog.debug("Inspection.sectionComplete domain=\(normalizedDomain) section=reachability hasNetworkTarget=\(hasNetworkTarget) source=\(reachabilityOutcome.source.rawValue)")
169 track(
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 )
98 ledger.track(.reachability, source: reachabilityOutcome.source)
17899 if hasNetworkTarget {
179 captureFailure(for: .reachability, result: reachabilityResult, into: &errorDetails)
100 ledger.captureFailure(for: .reachability, result: reachabilityResult)
180101 }
181102 let reachabilityResultValue = mapServiceResult(reachabilityResult, emptyValue: [])
182103
183 let portScanOutcome: CachedLookupResult<ServiceResult<[PortScanResult]>>
184 if hasNetworkTarget {
185 portScanOutcome = await runtime.portScan(domain: normalizedDomain)
186 } else {
187 portScanOutcome = CachedLookupResult(value: .empty("No routable address available"), source: .live)
104 let portScanOutcome = await whenRoutable(hasNetworkTarget) {
105 await runtime.portScan(domain: normalizedDomain)
188106 }
189107 let portScanResult = normalizeErrors(in: portScanOutcome.value)
190108 DomainDebugLog.debug("Inspection.sectionComplete domain=\(normalizedDomain) section=portScan hasNetworkTarget=\(hasNetworkTarget) source=\(portScanOutcome.source.rawValue)")
191 track(
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 )
109 ledger.track(.portScan, source: portScanOutcome.source)
200110 if hasNetworkTarget {
201 captureFailure(for: .portScan, result: portScanResult, into: &errorDetails)
111 ledger.captureFailure(for: .portScan, result: portScanResult)
202112 }
203113 let portScanResults = hasNetworkTarget
204114 ? await mapPortScanResult(portScanResult, domain: normalizedDomain)
205115 : (value: [], message: nil)
206116
207 let emailOutcome: CachedLookupResult<ServiceResult<EmailSecurityResult>>
208 if canReuseDNSDependents, let previousSnapshot, let emailSecurity = previousSnapshot.emailSecurity {
209 emailOutcome = CachedLookupResult(value: .success(emailSecurity), source: .cached)
210 } else if canReuseDNSDependents, let previousSnapshot, let error = previousSnapshot.emailSecurityError {
211 emailOutcome = CachedLookupResult(value: .error(error), source: .cached)
212 } else {
213 emailOutcome = await runtime.email(domain: normalizedDomain, txtRecords: txtRecords)
117 let emailOutcome = await reusingPrevious(
118 previousSnapshot?.emailSecurity,
119 error: previousSnapshot?.emailSecurityError,
120 when: canReuseDNSDependents
121 ) {
122 await runtime.email(domain: normalizedDomain, txtRecords: txtRecords)
214123 }
215124 let normalizedEmailResult = normalizeErrors(in: emailOutcome.value)
216125 DomainDebugLog.debug("Inspection.sectionComplete domain=\(normalizedDomain) section=email source=\(emailOutcome.source.rawValue)")
217 track(
218 .emailSecurity,
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)
126 ledger.track(.emailSecurity, source: emailOutcome.source)
127 ledger.captureFailure(for: .emailSecurity, result: normalizedEmailResult)
227128
228129 let suggestionsOutcome: CachedLookupResult<[DomainSuggestionResult]>
229130 if availability.value.status == .registered {
230131 suggestionsOutcome = await runtime.suggestions(domain: normalizedDomain)
231 track(
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 )
132 ledger.track(.suggestions, source: suggestionsOutcome.source)
240133 } else {
241134 suggestionsOutcome = CachedLookupResult(value: [], source: .live)
242135 }
@@ -244,48 +137,26 @@ struct DomainInspectionService {
244137 let ptrOutcome: CachedLookupResult<ServiceResult<String>>?
245138 let geoOutcome: CachedLookupResult<ServiceResult<IPGeolocation>>?
246139 if let primaryIP {
247 if canReuseIPDependents, let previousSnapshot, let ptrRecord = previousSnapshot.ptrRecord {
248 ptrOutcome = CachedLookupResult(value: .success(ptrRecord), source: .cached)
249 } else if canReuseIPDependents, let previousSnapshot, let ptrError = previousSnapshot.ptrError {
250 ptrOutcome = CachedLookupResult(value: .error(ptrError), source: .cached)
251 } else {
252 ptrOutcome = 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)
140 let ptr = await reusingPrevious(
141 previousSnapshot?.ptrRecord,
142 error: previousSnapshot?.ptrError,
143 when: canReuseIPDependents
144 ) {
145 await runtime.ptr(ip: primaryIP, resolverURLString: resolverURLString)
275146 }
276 if let geoOutcome {
277 let normalizedGeoResult = normalizeErrors(in: geoOutcome.value)
278 track(
279 .ipGeolocation,
280 source: geoOutcome.source,
281 provenance: provenance(for: .ipGeolocation, source: geoOutcome.source, collectedAt: Date(), resolverDisplayName: resolverDisplayName),
282 cachedSections: &cachedSections,
283 sectionSources: &sectionSources,
284 provenanceBySection: &provenanceBySection,
285 dataSources: &dataSources
286 )
287 captureFailure(for: .ipGeolocation, result: normalizedGeoResult, into: &errorDetails)
147 let geo = await reusingPrevious(
148 previousSnapshot?.ipGeolocation,
149 error: previousSnapshot?.ipGeolocationError,
150 when: canReuseIPDependents
151 ) {
152 await runtime.ipGeolocation(ip: primaryIP)
288153 }
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
289160 } else {
290161 ptrOutcome = nil
291162 geoOutcome = nil
@@ -294,12 +165,12 @@ struct DomainInspectionService {
294165 let emailSecurity = mapOptionalValueServiceResult(normalizedEmailResult)
295166 let ptrRecord = mapOptionalServiceResult(ptrOutcome.map { normalizeErrors(in: $0.value) }, missingMessage: "No A record available")
296167 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])
298169 let ownershipConfidence = confidenceForOwnership(result: ownership.value)
299170 let subdomainConfidence = confidenceForSubdomains(results: subdomains.value)
300171 let emailConfidence = confidenceForEmail(result: emailSecurity.value)
301172 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)
303174
304175 let snapshot = LookupSnapshot(
305176 historyEntryID: nil,
@@ -310,14 +181,14 @@ struct DomainInspectionService {
310181 appVersion: AppVersion.current,
311182 resolverDisplayName: resolverDisplayName,
312183 resolverURLString: resolverURLString,
313 dataSources: Array(dataSources).sorted(),
314 provenanceBySection: provenanceBySection,
184 dataSources: Array(ledger.dataSources).sorted(),
185 provenanceBySection: ledger.provenanceBySection,
315186 availabilityConfidence: availabilityConfidence,
316187 ownershipConfidence: ownershipConfidence,
317188 subdomainConfidence: subdomainConfidence,
318189 emailSecurityConfidence: emailConfidence,
319190 geolocationConfidence: geolocationConfidence,
320 errorDetails: errorDetails,
191 errorDetails: ledger.errorDetails,
321192 isPartialSnapshot: !validationIssues.isEmpty,
322193 validationIssues: validationIssues,
323194 totalLookupDurationMs: Int(Date().timeIntervalSince(startedAt) * 1000),
@@ -374,8 +245,8 @@ struct DomainInspectionService {
374245 portScanResults: portScanResults.value,
375246 portScanError: portScanResults.message,
376247 changeSummary: nil,
377 resultSource: aggregateSource(sectionSources),
378 cachedSections: Array(cachedSections).sorted { $0.rawValue < $1.rawValue },
248 resultSource: aggregateSource(ledger.sectionSources),
249 cachedSections: Array(ledger.cachedSections).sorted { $0.rawValue < $1.rawValue },
379250 statusMessage: nil
380251 )
381252 DomainDebugLog.signpostEnd(
@@ -396,24 +267,36 @@ struct DomainInspectionService {
396267 .lowercased() ?? domain.lowercased()
397268 }
398269
399 private func track(
400 _ section: LookupSectionKind,
401 source: LookupResultSource,
402 provenance: SectionProvenance,
403 cachedSections: inout Set<LookupSectionKind>,
404 sectionSources: inout [LookupResultSource],
405 provenanceBySection: inout [LookupSectionKind: SectionProvenance],
406 dataSources: inout Set<String>
407 ) {
408 sectionSources.append(source)
409 provenanceBySection[section] = provenance
410 dataSources.insert(provenance.provider ?? provenance.source)
411 if source != .live {
412 cachedSections.insert(section)
270 /// A lookup that needs an address to reach, or an empty result when the
271 /// domain has none.
272 private func whenRoutable<Value>(
273 _ hasNetworkTarget: Bool,
274 fetch: () async -> CachedLookupResult<ServiceResult<Value>>
275 ) async -> CachedLookupResult<ServiceResult<Value>> {
276 guard hasNetworkTarget else {
277 return CachedLookupResult(value: .empty("No routable address available"), source: .live)
413278 }
279 return await fetch()
414280 }
415281
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(
417300 for section: LookupSectionKind,
418301 source: LookupResultSource,
419302 collectedAt: Date,
@@ -514,13 +397,13 @@ struct DomainInspectionService {
514397 case let .success(value):
515398 return .success(value)
516399 case let .empty(message):
517 return .empty(classifyFailure(from: message, defaultKind: .unavailable).message)
400 return .empty(Self.classifyFailure(from: message, defaultKind: .unavailable).message)
518401 case let .error(message):
519 return .error(classifyFailure(from: message).message)
402 return .error(Self.classifyFailure(from: message).message)
520403 }
521404 }
522405
523 private func classifyFailure(from message: String, defaultKind: InspectionErrorKind = .unknown) -> InspectionFailure {
406 fileprivate static func classifyFailure(from message: String, defaultKind: InspectionErrorKind = .unknown) -> InspectionFailure {
524407 let normalizedMessage = message.trimmingCharacters(in: .whitespacesAndNewlines)
525408 let lowercasedMessage = normalizedMessage.lowercased()
526409 if lowercasedMessage.contains("timed out") {
@@ -554,21 +437,6 @@ struct DomainInspectionService {
554437 return InspectionFailure(kind: .unknown, message: normalizedMessage.isEmpty ? defaultKind.title : normalizedMessage, details: normalizedMessage)
555438 }
556439
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
572440 private func confidenceForAvailability(result: DomainAvailabilityResult, provenance: SectionProvenance?) -> ConfidenceLevel {
573441 guard result.status != .unknown else { return .low }
574442 if provenance?.provider?.localizedCaseInsensitiveContains("rdap.org") == true, result.status == .registered {
@@ -678,7 +546,7 @@ struct DomainInspectionService {
678546 private func mapPortScanResult(_ result: ServiceResult<[PortScanResult]>, domain: String) async -> (value: [PortScanResult], message: String?) {
679547 switch result {
680548 case let .success(results):
681 return (await enrichOpenPortBanners(in: results, domain: domain), nil)
549 return (await PortScanService.withBanners(results, host: domain), nil)
682550 case let .empty(message), let .error(message):
683551 return ([], message)
684552 }
@@ -716,29 +584,41 @@ struct DomainInspectionService {
716584 )
717585 }
718586 }
587}
719588
720 private func enrichOpenPortBanners(in results: [PortScanResult], domain: String) async -> [PortScanResult] {
721 let banners = await withTaskGroup(of: (UInt16, String?).self, returning: [UInt16: String].self) { group in
722 for result in results where result.open {
723 group.addTask {
724 let banner = await PortScanService.grabBanner(host: domain, port: result.port)
725 return (result.port, banner)
726 }
727 }
728
729 var collected: [UInt16: String] = [:]
730 for await (port, banner) in group {
731 if let banner {
732 collected[port] = banner
733 }
734 }
735 return collected
589/// What an inspection has learned about its sections so far: where each came
590/// from, which were served from cache, and which failed.
591private struct InspectionLedger {
592 let resolverDisplayName: String
593 var cachedSections = Set<LookupSectionKind>()
594 var sectionSources: [LookupResultSource] = []
595 var provenanceBySection: [LookupSectionKind: SectionProvenance] = [:]
596 var dataSources = Set<String>()
597 var errorDetails: [LookupSectionKind: InspectionFailure] = [:]
598
599 mutating func track(_ section: LookupSectionKind, source: LookupResultSource) {
600 let provenance = DomainInspectionService.provenance(
601 for: section,
602 source: source,
603 collectedAt: Date(),
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)
736611 }
612 }
737613
738 return results.map { result in
739 var updated = result
740 updated.banner = banners[result.port]
741 return updated
614 mutating func captureFailure<Value>(for section: LookupSectionKind, result: ServiceResult<Value>) {
615 switch result {
616 case .success:
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)
742622 }
743623 }
744624}
DomainReportBuilder.swift +47 −42
@@ -521,7 +521,8 @@ enum DomainIntelligenceService {
521521 }
522522
523523 private static func inferProvider(from snapshot: LookupSnapshot) -> InferredProviderFingerprint? {
524 let headerMap = Dictionary(uniqueKeysWithValues: snapshot.httpHeaders.map { ($0.name.lowercased(), $0.value.lowercased()) })
524 // A stored or imported snapshot can repeat a header name in another case.
525 let headerMap = Dictionary(snapshot.httpHeaders.map { ($0.name.lowercased(), $0.value.lowercased()) }) { first, _ in first }
525526 let dnsProviders = dnsValues(for: .NS, in: snapshot.dnsSections) + dnsValues(for: .CNAME, in: snapshot.dnsSections)
526527 let issuer = snapshot.sslInfo?.issuer.lowercased() ?? ""
527528 let org = snapshot.ipGeolocation?.org?.lowercased() ?? ""
@@ -626,59 +627,63 @@ enum DomainIntelligenceService {
626627 }
627628
628629 private static func buildSubdomainHistory(from snapshots: [LookupSnapshot]) -> [SubdomainHistoryEntry] {
629 struct WorkingState {
630 var firstSeen: Date
631 var lastSeen: Date
632 var recurrenceCount: Int
633 var statusChangeCount: Int
634 var lastSeenInPreviousSnapshot: Bool
635 }
636
637 var states: [String: WorkingState] = [:]
630 var states: [String: SubdomainPresence] = [:]
638631 for snapshot in snapshots {
639632 let currentHosts = Set((snapshot.subdomains + snapshot.extendedSubdomains).map { $0.hostname.lowercased() })
640633 let knownHosts = Set(states.keys).union(currentHosts)
641634 for host in knownHosts {
642635 let isPresent = currentHosts.contains(host)
643 if var state = states[host] {
644 if isPresent {
645 state.lastSeen = snapshot.timestamp
646 state.recurrenceCount += 1
647 }
648 if state.lastSeenInPreviousSnapshot != isPresent {
649 state.statusChangeCount += 1
650 }
651 state.lastSeenInPreviousSnapshot = isPresent
652 states[host] = state
636 if states[host] != nil {
637 states[host]?.observe(isPresent: isPresent, at: snapshot.timestamp)
653638 } else if isPresent {
654 states[host] = WorkingState(
655 firstSeen: snapshot.timestamp,
656 lastSeen: snapshot.timestamp,
657 recurrenceCount: 1,
658 statusChangeCount: 0,
659 lastSeenInPreviousSnapshot: true
660 )
639 states[host] = SubdomainPresence(firstSeen: snapshot.timestamp)
661640 }
662641 }
663642 }
664643
665 return states.map { host, state in
666 let isEphemeral = state.recurrenceCount <= 2 || state.statusChangeCount >= 2
667 return SubdomainHistoryEntry(
668 hostname: host,
669 firstSeen: state.firstSeen,
670 lastSeen: state.lastSeen,
671 recurrenceCount: state.recurrenceCount,
672 statusChangeCount: state.statusChangeCount,
673 lastKnownStatus: state.lastSeenInPreviousSnapshot ? "Active" : "Inactive",
674 isEphemeral: isEphemeral
675 )
644 return states.map { host, state in state.entry(hostname: host) }
645 .sorted { lhs, rhs in
646 if lhs.isEphemeral != rhs.isEphemeral {
647 return lhs.isEphemeral && !rhs.isEphemeral
648 }
649 return lhs.hostname < rhs.hostname
650 }
651 }
652
653 /// One subdomain's presence across a run of snapshots, from the first that saw it.
654 private struct SubdomainPresence {
655 var firstSeen: Date
656 var lastSeen: Date
657 var recurrenceCount = 1
658 var statusChangeCount = 0
659 var lastSeenInPreviousSnapshot = true
660
661 init(firstSeen: Date) {
662 self.firstSeen = firstSeen
663 lastSeen = firstSeen
676664 }
677 .sorted { lhs, rhs in
678 if lhs.isEphemeral != rhs.isEphemeral {
679 return lhs.isEphemeral && !rhs.isEphemeral
665
666 mutating func observe(isPresent: Bool, at timestamp: Date) {
667 if isPresent {
668 lastSeen = timestamp
669 recurrenceCount += 1
680670 }
681 return lhs.hostname < rhs.hostname
671 if lastSeenInPreviousSnapshot != isPresent {
672 statusChangeCount += 1
673 }
674 lastSeenInPreviousSnapshot = isPresent
675 }
676
677 func entry(hostname: String) -> SubdomainHistoryEntry {
678 SubdomainHistoryEntry(
679 hostname: hostname,
680 firstSeen: firstSeen,
681 lastSeen: lastSeen,
682 recurrenceCount: recurrenceCount,
683 statusChangeCount: statusChangeCount,
684 lastKnownStatus: lastSeenInPreviousSnapshot ? "Active" : "Inactive",
685 isEphemeral: recurrenceCount <= 2 || statusChangeCount >= 2
686 )
682687 }
683688 }
684689
DomainReportExporter.swift +266 −250
@@ -156,6 +156,25 @@ enum DomainReportExporter {
156156 }
157157
158158 static func text(for report: DomainReport) -> String {
159 var lines = headerLines(report)
160 appendSection("Summary", to: &lines) { summarySection(report) }
161 appendSection("Risk", to: &lines) { riskSection(report) }
162 appendSection("Insights", to: &lines) { insightsSection(report) }
163 appendSection("Ownership", to: &lines) { ownershipSection(report) }
164 appendSection("Ownership History", to: &lines) { ownershipHistorySection(report) }
165 appendSection("DNS", to: &lines) { dnsSection(report) }
166 appendSection("DNS History", to: &lines) { dnsHistorySection(report) }
167 appendSection("Web", to: &lines) { webSection(report) }
168 appendSection("Email", to: &lines) { emailSection(report) }
169 appendSection("Network", to: &lines) { networkSection(report) }
170 appendSection("Subdomains", to: &lines) { subdomainsSection(report) }
171 appendSection("Pricing", to: &lines) { pricingSection(report) }
172 appendSection("Changes", to: &lines) { changesSection(report) }
173 return lines.joined(separator: "\n")
174 }
175
176 /// The report's title block: what was looked up, when, how, and with what caveats.
177 private static func headerLines(_ report: DomainReport) -> [String] {
159178 var lines = [
160179 "DomainDig Report",
161180 "Domain: \(report.domain)",
@@ -183,288 +202,285 @@ enum DomainReportExporter {
183202 if let workflowContext = report.workflowContext {
184203 lines.append("Workflow Context: \(workflowContext.workflowName ?? workflowContext.source)")
185204 }
205 return lines
206 }
186207
187 appendSection("Summary", to: &lines) {
188 [
189 "Primary IP: \(report.dns.primaryIP ?? "Unavailable")",
190 "Risk Score: \(report.riskAssessment.score) (\(report.riskAssessment.level.title))",
191 "TLS Status: \(report.web.tlsStatus)",
192 "HTTP: \(httpSummary(for: report))",
193 "Email: \(report.email.summary)",
194 "Subdomains: \(report.subdomains.count)",
195 "Extended Subdomains: \(report.extendedSubdomains.count)",
196 "External Price: \(report.domainPricing?.estimatedPrice ?? "Unavailable")",
197 "Reputation: \(report.reputation?.status.title ?? "Unavailable")"
198 ]
199 }
208 private static func summarySection(_ report: DomainReport) -> [String] {
209 [
210 "Primary IP: \(report.dns.primaryIP ?? "Unavailable")",
211 "Risk Score: \(report.riskAssessment.score) (\(report.riskAssessment.level.title))",
212 "TLS Status: \(report.web.tlsStatus)",
213 "HTTP: \(httpSummary(for: report))",
214 "Email: \(report.email.summary)",
215 "Subdomains: \(report.subdomains.count)",
216 "Extended Subdomains: \(report.extendedSubdomains.count)",
217 "External Price: \(report.domainPricing?.estimatedPrice ?? "Unavailable")",
218 "Reputation: \(report.reputation?.status.title ?? "Unavailable")"
219 ]
220 }
200221
201 appendSection("Risk", to: &lines) {
202 var values = [
203 "Score: \(report.riskAssessment.score)",
204 "Level: \(report.riskAssessment.level.title)"
205 ]
206 if report.riskAssessment.factors.isEmpty {
207 values.append("Factors: None")
208 } else {
209 values.append("Factors:")
210 for factor in report.riskAssessment.factors {
211 values.append(" [\(factor.impact.rawValue)] \(factor.description)")
212 }
222 private static func riskSection(_ report: DomainReport) -> [String] {
223 var values = [
224 "Score: \(report.riskAssessment.score)",
225 "Level: \(report.riskAssessment.level.title)"
226 ]
227 if report.riskAssessment.factors.isEmpty {
228 values.append("Factors: None")
229 } else {
230 values.append("Factors:")
231 for factor in report.riskAssessment.factors {
232 values.append(" [\(factor.impact.rawValue)] \(factor.description)")
213233 }
214 return values
215234 }
235 return values
236 }
216237
217 appendSection("Insights", to: &lines) {
218 report.insights.isEmpty ? ["No deterministic insights triggered"] : report.insights.map { "- \($0)" }
219 }
238 private static func insightsSection(_ report: DomainReport) -> [String] {
239 report.insights.isEmpty ? ["No deterministic insights triggered"] : report.insights.map { "- \($0)" }
240 }
220241
221 appendSection("Ownership", to: &lines) {
222 var ownershipLines = [
223 "Registrar: \(report.ownership?.registrar ?? "Unavailable")",
224 "Confidence: \(report.ownershipConfidence?.title ?? "N/A")",
225 "Created: \(ownershipDateLabel(report.ownership?.createdDate))",
226 "Expires: \(ownershipDateLabel(report.ownership?.expirationDate))",
227 "Registrant: \(report.ownership?.registrant ?? "Unavailable")",
228 "Nameservers: \(joined(report.ownership?.nameservers) ?? "Unavailable")",
229 "Status: \(joined(report.ownership?.status) ?? "Unavailable")",
230 "Abuse Contact: \(report.ownership?.abuseEmail ?? "Unavailable")"
231 ]
232 if let provenance = report.sectionProvenance[.ownership] {
233 ownershipLines.append("Provenance: \(provenanceLabel(provenance))")
234 }
235 if let error = report.dns.error, report.ownership == nil {
236 ownershipLines.append("Error: \(error)")
237 } else if let error = report.changeSummary?.message, report.ownership == nil, report.ownership == nil {
238 _ = error
239 }
240 return ownershipLines
242 private static func ownershipSection(_ report: DomainReport) -> [String] {
243 var ownershipLines = [
244 "Registrar: \(report.ownership?.registrar ?? "Unavailable")",
245 "Confidence: \(report.ownershipConfidence?.title ?? "N/A")",
246 "Created: \(ownershipDateLabel(report.ownership?.createdDate))",
247 "Expires: \(ownershipDateLabel(report.ownership?.expirationDate))",
248 "Registrant: \(report.ownership?.registrant ?? "Unavailable")",
249 "Nameservers: \(joined(report.ownership?.nameservers) ?? "Unavailable")",
250 "Status: \(joined(report.ownership?.status) ?? "Unavailable")",
251 "Abuse Contact: \(report.ownership?.abuseEmail ?? "Unavailable")"
252 ]
253 if let provenance = report.sectionProvenance[.ownership] {
254 ownershipLines.append("Provenance: \(provenanceLabel(provenance))")
241255 }
256 if let error = report.dns.error, report.ownership == nil {
257 ownershipLines.append("Error: \(error)")
258 }
259 return ownershipLines
260 }
242261
243 appendSection("Ownership History", to: &lines) {
244 guard !report.ownershipHistory.isEmpty else {
245 return ["No ownership history available"]
246 }
247
248 return report.ownershipHistory.map { event in
249 [
250 textDateFormatter.string(from: event.date),
251 event.summary,
252 "source=\(event.source)"
253 ].joined(separator: " | ")
254 }
262 private static func ownershipHistorySection(_ report: DomainReport) -> [String] {
263 guard !report.ownershipHistory.isEmpty else {
264 return ["No ownership history available"]
255265 }
256266
257 appendSection("DNS", to: &lines) {
258 var dnsLines = [
259 "Lookup Duration: \(durationLabel(report.dns.lookupDurationMs))",
260 "Primary IP: \(report.dns.primaryIP ?? "Unavailable")",
261 "PTR: \(report.dns.ptrRecord ?? report.dns.ptrError ?? "Unavailable")",
262 "DNSSEC: \(dnssecLabel(report.dns.dnssecSigned))",
263 "Patterns: \(report.dns.patternSummary.patterns.joined(separator: " | ").nilIfEmpty ?? "None")"
264 ]
265 if let provenance = report.sectionProvenance[.dns] {
266 dnsLines.append("Provenance: \(provenanceLabel(provenance))")
267 }
268 if let error = report.dns.error {
269 dnsLines.append("Error: \(error)")
270 }
271 if report.dns.recordSections.isEmpty {
272 dnsLines.append("Records: None")
273 } else {
274 dnsLines.append("Records:")
275 for section in report.dns.recordSections {
276 var seen: Set<String> = []
277 let values = (section.records + section.wildcardRecords)
278 .map(\.value)
279 .filter { seen.insert($0).inserted }
280 let renderedValues = values.isEmpty ? "None" : values.joined(separator: " | ")
281 dnsLines.append(" \(section.recordType.rawValue): \(renderedValues)")
282 }
283 }
284 return dnsLines
267 return report.ownershipHistory.map { event in
268 [
269 textDateFormatter.string(from: event.date),
270 event.summary,
271 "source=\(event.source)"
272 ].joined(separator: " | ")
285273 }
274 }
286275
287 appendSection("DNS History", to: &lines) {
288 guard !report.dnsHistory.isEmpty else {
289 return ["No DNS history available"]
290 }
276 private static func dnsSection(_ report: DomainReport) -> [String] {
277 var dnsLines = [
278 "Lookup Duration: \(durationLabel(report.dns.lookupDurationMs))",
279 "Primary IP: \(report.dns.primaryIP ?? "Unavailable")",
280 "PTR: \(report.dns.ptrRecord ?? report.dns.ptrError ?? "Unavailable")",
281 "DNSSEC: \(dnssecLabel(report.dns.dnssecSigned))",
282 "Patterns: \(report.dns.patternSummary.patterns.joined(separator: " | ").nilIfEmpty ?? "None")"
283 ]
284 if let provenance = report.sectionProvenance[.dns] {
285 dnsLines.append("Provenance: \(provenanceLabel(provenance))")
286 }
287 if let error = report.dns.error {
288 dnsLines.append("Error: \(error)")
289 }
290 if report.dns.recordSections.isEmpty {
291 dnsLines.append("Records: None")
292 } else {
293 dnsLines.append("Records:")
294 for section in report.dns.recordSections {
295 var seen: Set<String> = []
296 let values = (section.records + section.wildcardRecords)
297 .map(\.value)
298 .filter { seen.insert($0).inserted }
299 let renderedValues = values.isEmpty ? "None" : values.joined(separator: " | ")
300 dnsLines.append(" \(section.recordType.rawValue): \(renderedValues)")
301 }
302 }
303 return dnsLines
304 }
291305
292 return report.dnsHistory.map { event in
293 [
294 textDateFormatter.string(from: event.date),
295 event.summary,
296 "A=\(event.aRecords.joined(separator: " | ").nilIfEmpty ?? "-")",
297 "NS=\(event.nameservers.joined(separator: " | ").nilIfEmpty ?? "-")",
298 "source=\(event.source)"
299 ].joined(separator: " | ")
300 }
306 private static func dnsHistorySection(_ report: DomainReport) -> [String] {
307 guard !report.dnsHistory.isEmpty else {
308 return ["No DNS history available"]
301309 }
302310
303 appendSection("Web", to: &lines) {
304 var webLines = [
305 "TLS Status: \(report.web.tlsStatus)",
306 "TLS Grade: \(report.web.tlsGrade.rawValue)",
307 "TLS Highlights: \(report.web.tlsHighlights.joined(separator: " | "))",
308 "Certificate Warning: \(report.web.certificateWarningLevel.title)",
309 "Security Grade: \(report.web.securityGrade ?? "Unavailable")",
310 "HTTP Status: \(report.web.statusCode.map(String.init) ?? "Unavailable")",
311 "Protocol: \(report.web.httpProtocol ?? "Unavailable")",
312 "HTTP/3 Advertised: \(report.web.http3Advertised ? "Yes" : "No")",
313 "Final URL: \(report.web.finalURL ?? "Unavailable")",
314 "HSTS Preloaded: \(booleanLabel(report.web.hstsPreloaded))",
315 "Header Count: \(report.web.headerCount)"
316 ]
317 if let provenance = report.sectionProvenance[.ssl] {
318 webLines.append("TLS Provenance: \(provenanceLabel(provenance))")
319 }
320 if let provenance = report.sectionProvenance[.httpHeaders] {
321 webLines.append("HTTP Provenance: \(provenanceLabel(provenance))")
322 }
323 if let provenance = report.sectionProvenance[.redirectChain] {
324 webLines.append("Redirect Provenance: \(provenanceLabel(provenance))")
325 }
326 if let tlsError = report.web.tlsError {
327 webLines.append("TLS Error: \(tlsError)")
328 }
329 if let headersError = report.web.headersError {
330 webLines.append("Headers Error: \(headersError)")
331 }
332 if let redirectError = report.web.redirectError {
333 webLines.append("Redirect Error: \(redirectError)")
334 }
335 if !report.web.headers.isEmpty {
336 webLines.append("Headers:")
337 for header in report.web.headers {
338 webLines.append(" \(header.name): \(header.value)")
339 }
340 }
341 if !report.web.redirectChain.isEmpty {
342 webLines.append("Redirect Chain:")
343 for hop in report.web.redirectChain {
344 webLines.append(" \(hop.stepNumber). \(hop.statusCode) \(hop.url)\(hop.isFinal ? " (final)" : "")")
345 }
346 }
347 return webLines
311 return report.dnsHistory.map { event in
312 [
313 textDateFormatter.string(from: event.date),
314 event.summary,
315 "A=\(event.aRecords.joined(separator: " | ").nilIfEmpty ?? "-")",
316 "NS=\(event.nameservers.joined(separator: " | ").nilIfEmpty ?? "-")",
317 "source=\(event.source)"
318 ].joined(separator: " | ")
348319 }
320 }
349321
350 appendSection("Email", to: &lines) {
351 var emailLines = [report.email.summary]
352 if let grade = report.email.grade {
353 emailLines.append("Grade: \(grade.rawValue)")
354 }
355 if !report.email.reasons.isEmpty {
356 emailLines.append("Why: \(report.email.reasons.joined(separator: " | "))")
357 }
358 emailLines.append("Confidence: \(report.emailConfidence?.title ?? "N/A")")
359 if let provenance = report.sectionProvenance[.emailSecurity] {
360 emailLines.append("Provenance: \(provenanceLabel(provenance))")
361 }
362 if let records = report.email.records {
363 emailLines.append("SPF: \(recordLabel(records.spf))")
364 emailLines.append("DMARC: \(recordLabel(records.dmarc))")
365 emailLines.append("DKIM: \(recordLabel(records.dkim))")
366 emailLines.append("BIMI: \(recordLabel(records.bimi))")
367 emailLines.append("MTA-STS: \(records.mtaSts?.txtFound == true ? records.mtaSts?.policyMode ?? "found" : "Unavailable")")
322 private static func webSection(_ report: DomainReport) -> [String] {
323 var webLines = [
324 "TLS Status: \(report.web.tlsStatus)",
325 "TLS Grade: \(report.web.tlsGrade.rawValue)",
326 "TLS Highlights: \(report.web.tlsHighlights.joined(separator: " | "))",
327 "Certificate Warning: \(report.web.certificateWarningLevel.title)",
328 "Security Grade: \(report.web.securityGrade ?? "Unavailable")",
329 "HTTP Status: \(report.web.statusCode.map(String.init) ?? "Unavailable")",
330 "Protocol: \(report.web.httpProtocol ?? "Unavailable")",
331 "HTTP/3 Advertised: \(report.web.http3Advertised ? "Yes" : "No")",
332 "Final URL: \(report.web.finalURL ?? "Unavailable")",
333 "HSTS Preloaded: \(booleanLabel(report.web.hstsPreloaded))",
334 "Header Count: \(report.web.headerCount)"
335 ]
336 if let provenance = report.sectionProvenance[.ssl] {
337 webLines.append("TLS Provenance: \(provenanceLabel(provenance))")
338 }
339 if let provenance = report.sectionProvenance[.httpHeaders] {
340 webLines.append("HTTP Provenance: \(provenanceLabel(provenance))")
341 }
342 if let provenance = report.sectionProvenance[.redirectChain] {
343 webLines.append("Redirect Provenance: \(provenanceLabel(provenance))")
344 }
345 if let tlsError = report.web.tlsError {
346 webLines.append("TLS Error: \(tlsError)")
347 }
348 if let headersError = report.web.headersError {
349 webLines.append("Headers Error: \(headersError)")
350 }
351 if let redirectError = report.web.redirectError {
352 webLines.append("Redirect Error: \(redirectError)")
353 }
354 if !report.web.headers.isEmpty {
355 webLines.append("Headers:")
356 for header in report.web.headers {
357 webLines.append(" \(header.name): \(header.value)")
368358 }
369 if let error = report.email.error {
370 emailLines.append("Error: \(error)")
359 }
360 if !report.web.redirectChain.isEmpty {
361 webLines.append("Redirect Chain:")
362 for hop in report.web.redirectChain {
363 webLines.append(" \(hop.stepNumber). \(hop.statusCode) \(hop.url)\(hop.isFinal ? " (final)" : "")")
371364 }
372 return emailLines
373365 }
366 return webLines
367 }
374368
375 appendSection("Network", to: &lines) {
376 var networkLines = [
377 "Reachability: \(report.network.reachabilitySummary)",
378 "Geolocation: \(report.network.geolocationSummary)",
379 "Geolocation Confidence: \(report.geolocationConfidence?.title ?? "N/A")",
380 "Open Ports: \(report.network.openPorts.map(String.init).joined(separator: ", ").nilIfEmpty ?? "None")"
381 ]
382 if let provenance = report.sectionProvenance[.ipGeolocation] {
383 networkLines.append("Geolocation Provenance: \(provenanceLabel(provenance))")
384 }
385 if let error = report.network.reachabilityError {
386 networkLines.append("Reachability Error: \(error)")
387 }
388 if let error = report.network.geolocationError {
389 networkLines.append("Geolocation Error: \(error)")
390 }
391 if let error = report.network.portScanError {
392 networkLines.append("Port Scan Error: \(error)")
393 }
394 if !report.network.portScan.isEmpty {
395 networkLines.append("Port Scan:")
396 for result in report.network.portScan {
397 networkLines.append(
398 " \(result.port) \(result.service): \(result.open ? "open" : "closed")\(result.banner.map { " banner=\($0)" } ?? "")"
399 )
400 }
401 }
402 return networkLines
369 private static func emailSection(_ report: DomainReport) -> [String] {
370 var emailLines = [report.email.summary]
371 if let grade = report.email.grade {
372 emailLines.append("Grade: \(grade.rawValue)")
373 }
374 if !report.email.reasons.isEmpty {
375 emailLines.append("Why: \(report.email.reasons.joined(separator: " | "))")
376 }
377 emailLines.append("Confidence: \(report.emailConfidence?.title ?? "N/A")")
378 if let provenance = report.sectionProvenance[.emailSecurity] {
379 emailLines.append("Provenance: \(provenanceLabel(provenance))")
403380 }
381 if let records = report.email.records {
382 emailLines.append("SPF: \(recordLabel(records.spf))")
383 emailLines.append("DMARC: \(recordLabel(records.dmarc))")
384 emailLines.append("DKIM: \(recordLabel(records.dkim))")
385 emailLines.append("BIMI: \(recordLabel(records.bimi))")
386 emailLines.append("MTA-STS: \(records.mtaSts?.txtFound == true ? records.mtaSts?.policyMode ?? "found" : "Unavailable")")
387 }
388 if let error = report.email.error {
389 emailLines.append("Error: \(error)")
390 }
391 return emailLines
392 }
404393
405 appendSection("Subdomains", to: &lines) {
406 var values = ["Confidence: \(report.subdomainConfidence?.title ?? "N/A")"]
407 if let provenance = report.sectionProvenance[.subdomains] {
408 values.append("Provenance: \(provenanceLabel(provenance))")
409 }
410 if report.subdomains.isEmpty {
411 values.append("None")
412 return values
413 }
414 if !report.subdomainGroups.isEmpty {
415 values.append("Groups: \(report.subdomainGroups.map { "\($0.label): \($0.subdomains.count)" }.joined(separator: " | "))")
416 }
417 values.append(contentsOf: report.subdomains.map { "- \($0)" })
418 if !report.extendedSubdomains.isEmpty {
419 values.append("Extended:")
420 values.append(contentsOf: report.extendedSubdomains.map { "- \($0)" })
394 private static func networkSection(_ report: DomainReport) -> [String] {
395 var networkLines = [
396 "Reachability: \(report.network.reachabilitySummary)",
397 "Geolocation: \(report.network.geolocationSummary)",
398 "Geolocation Confidence: \(report.geolocationConfidence?.title ?? "N/A")",
399 "Open Ports: \(report.network.openPorts.map(String.init).joined(separator: ", ").nilIfEmpty ?? "None")"
400 ]
401 if let provenance = report.sectionProvenance[.ipGeolocation] {
402 networkLines.append("Geolocation Provenance: \(provenanceLabel(provenance))")
403 }
404 if let error = report.network.reachabilityError {
405 networkLines.append("Reachability Error: \(error)")
406 }
407 if let error = report.network.geolocationError {
408 networkLines.append("Geolocation Error: \(error)")
409 }
410 if let error = report.network.portScanError {
411 networkLines.append("Port Scan Error: \(error)")
412 }
413 if !report.network.portScan.isEmpty {
414 networkLines.append("Port Scan:")
415 for result in report.network.portScan {
416 networkLines.append(
417 " \(result.port) \(result.service): \(result.open ? "open" : "closed")\(result.banner.map { " banner=\($0)" } ?? "")"
418 )
421419 }
422 return values
423420 }
421 return networkLines
422 }
424423
425 appendSection("Pricing", to: &lines) {
426 guard let pricing = report.domainPricing else {
427 return ["External pricing unavailable"]
428 }
424 private static func subdomainsSection(_ report: DomainReport) -> [String] {
425 var values = ["Confidence: \(report.subdomainConfidence?.title ?? "N/A")"]
426 if let provenance = report.sectionProvenance[.subdomains] {
427 values.append("Provenance: \(provenanceLabel(provenance))")
428 }
429 if report.subdomains.isEmpty {
430 values.append("None")
431 return values
432 }
433 if !report.subdomainGroups.isEmpty {
434 values.append("Groups: \(report.subdomainGroups.map { "\($0.label): \($0.subdomains.count)" }.joined(separator: " | "))")
435 }
436 values.append(contentsOf: report.subdomains.map { "- \($0)" })
437 if !report.extendedSubdomains.isEmpty {
438 values.append("Extended:")
439 values.append(contentsOf: report.extendedSubdomains.map { "- \($0)" })
440 }
441 return values
442 }
429443
430 return [
431 "Estimated Price: \(pricing.estimatedPrice ?? "Unavailable")",
432 "Premium: \(pricing.premiumIndicator == true ? "Yes" : "No")",
433 "Resale: \(pricing.resaleSignal ?? "Unavailable")",
434 "Auction: \(pricing.auctionSignal ?? "Unavailable")",
435 "Source: \(pricing.source)",
436 "Collected: \(textDateFormatter.string(from: pricing.collectedAt))"
437 ]
444 private static func pricingSection(_ report: DomainReport) -> [String] {
445 guard let pricing = report.domainPricing else {
446 return ["External pricing unavailable"]
438447 }
439448
440 appendSection("Changes", to: &lines) {
441 guard let changeSummary = report.changeSummary else {
442 return ["No comparison available"]
443 }
449 return [
450 "Estimated Price: \(pricing.estimatedPrice ?? "Unavailable")",
451 "Premium: \(pricing.premiumIndicator == true ? "Yes" : "No")",
452 "Resale: \(pricing.resaleSignal ?? "Unavailable")",
453 "Auction: \(pricing.auctionSignal ?? "Unavailable")",
454 "Source: \(pricing.source)",
455 "Collected: \(textDateFormatter.string(from: pricing.collectedAt))"
456 ]
457 }
444458
445 var values = [
446 "Has Changes: \(changeSummary.hasChanges ? "Yes" : "No")",
447 "Severity: \(changeSummary.severity.title)",
448 "Impact: \(changeSummary.impactClassification.title)",
449 "Inferred Summary: \(changeSummary.message)",
450 "Changed Sections: \(changeSummary.changedSections.isEmpty ? "None" : changeSummary.changedSections.joined(separator: ", "))"
451 ]
452 if let riskScoreDelta = changeSummary.riskScoreDelta {
453 values.append("Risk Delta: \(riskScoreDelta >= 0 ? "+" : "")\(riskScoreDelta)")
454 }
455 if !changeSummary.insights.isEmpty {
456 values.append("Insights: \(changeSummary.insights.joined(separator: " | "))")
457 }
458 if !changeSummary.observedFacts.isEmpty {
459 values.append("Observed: \(changeSummary.observedFacts.joined(separator: " | "))")
460 }
461 if let contextNote = changeSummary.contextNote {
462 values.append("Context: \(contextNote)")
463 }
464 return values
459 private static func changesSection(_ report: DomainReport) -> [String] {
460 guard let changeSummary = report.changeSummary else {
461 return ["No comparison available"]
465462 }
466463
467 return lines.joined(separator: "\n")
464 var values = [
465 "Has Changes: \(changeSummary.hasChanges ? "Yes" : "No")",
466 "Severity: \(changeSummary.severity.title)",
467 "Impact: \(changeSummary.impactClassification.title)",
468 "Inferred Summary: \(changeSummary.message)",
469 "Changed Sections: \(changeSummary.changedSections.isEmpty ? "None" : changeSummary.changedSections.joined(separator: ", "))"
470 ]
471 if let riskScoreDelta = changeSummary.riskScoreDelta {
472 values.append("Risk Delta: \(riskScoreDelta >= 0 ? "+" : "")\(riskScoreDelta)")
473 }
474 if !changeSummary.insights.isEmpty {
475 values.append("Insights: \(changeSummary.insights.joined(separator: " | "))")
476 }
477 if !changeSummary.observedFacts.isEmpty {
478 values.append("Observed: \(changeSummary.observedFacts.joined(separator: " | "))")
479 }
480 if let contextNote = changeSummary.contextNote {
481 values.append("Context: \(contextNote)")
482 }
483 return values
468484 }
469485
470486 static func batchText(for reports: [DomainReport], title: String) -> String {
LocalAPIService.swift +3 −30
@@ -303,47 +303,20 @@ final class LocalAPIService {
303303 static let reference = "DomainDig.LocalAPI.Token"
304304
305305 static func save(secret: String, reference: String) throws {
306 let data = Data(secret.utf8)
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 {
306 guard GenericPasswordKeychain.save(secret, reference: reference) else {
318307 throw LocalAPIServerError.secretPersistenceFailed
319308 }
320309 }
321310
322311 static func secret(reference: String) throws -> String {
323 let query: [String: Any] = [
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 {
312 guard let secret = GenericPasswordKeychain.secret(reference: reference) else {
335313 throw LocalAPIServerError.missingSecret
336314 }
337
338315 return secret
339316 }
340317
341318 static func delete(reference: String) throws {
342 let query: [String: Any] = [
343 kSecClass as String: kSecClassGenericPassword,
344 kSecAttrAccount as String: reference
345 ]
346 SecItemDelete(query as CFDictionary)
319 GenericPasswordKeychain.delete(reference: reference)
347320 }
348321 }
349322
LookupSnapshot.swift +119
@@ -163,3 +163,122 @@ extension HistoryEntry {
163163 )
164164 }
165165}
166
167extension LookupSnapshot {
168 /// Whether every section that failed did so for want of a connection (a
169 /// network error, a timeout, a rate limit) and nothing worth showing came
170 /// back, so the last snapshot should stand in for this one.
171 var needsFallback: Bool {
172 let candidateMessages = [
173 dnsError,
174 httpHeadersError,
175 sslError,
176 ownershipError,
177 subdomainsError,
178 redirectChainError,
179 ipGeolocationError
180 ]
181 .compactMap { $0?.lowercased() }
182
183 guard !candidateMessages.isEmpty else { return false }
184 let connectivityFailure = candidateMessages.allSatisfy { message in
185 message.hasPrefix("network error:")
186 || message.hasPrefix("timeout:")
187 || message.hasPrefix("rate limit:")
188 }
189
190 let hasMaterialData = !dnsSections.isEmpty
191 || !httpHeaders.isEmpty
192 || sslInfo != nil
193 || ownership != nil
194 || !subdomains.isEmpty
195
196 return connectivityFailure && !hasMaterialData
197 }
198
199 /// `previous`, marked as the last known result, when this lookup
200 /// ``needsFallback``; otherwise this lookup.
201 func resolvedAfterFallback(to previous: LookupSnapshot?) -> LookupSnapshot {
202 guard needsFallback, let previous else {
203 return self
204 }
205
206 return LookupSnapshot(
207 historyEntryID: previous.historyEntryID,
208 domain: previous.domain,
209 timestamp: previous.timestamp,
210 trackedDomainID: previous.trackedDomainID,
211 note: previous.note,
212 appVersion: previous.appVersion,
213 resolverDisplayName: previous.resolverDisplayName,
214 resolverURLString: previous.resolverURLString,
215 dataSources: previous.dataSources,
216 provenanceBySection: previous.provenanceBySection,
217 availabilityConfidence: previous.availabilityConfidence,
218 ownershipConfidence: previous.ownershipConfidence,
219 subdomainConfidence: previous.subdomainConfidence,
220 emailSecurityConfidence: previous.emailSecurityConfidence,
221 geolocationConfidence: previous.geolocationConfidence,
222 errorDetails: previous.errorDetails,
223 isPartialSnapshot: previous.isPartialSnapshot,
224 validationIssues: previous.validationIssues,
225 totalLookupDurationMs: previous.totalLookupDurationMs,
226 snapshotIndex: previous.snapshotIndex,
227 previousSnapshotID: previous.previousSnapshotID,
228 changeCount: previous.changeCount,
229 severitySummary: previous.severitySummary,
230 dnsSections: previous.dnsSections,
231 dnsError: previous.dnsError,
232 availabilityResult: previous.availabilityResult,
233 suggestions: previous.suggestions,
234 sslInfo: previous.sslInfo,
235 sslError: previous.sslError,
236 hstsPreloaded: previous.hstsPreloaded,
237 httpHeaders: previous.httpHeaders,
238 httpSecurityGrade: previous.httpSecurityGrade,
239 httpStatusCode: previous.httpStatusCode,
240 httpResponseTimeMs: previous.httpResponseTimeMs,
241 httpProtocol: previous.httpProtocol,
242 http3Advertised: previous.http3Advertised,
243 httpHeadersError: previous.httpHeadersError,
244 reachabilityResults: previous.reachabilityResults,
245 reachabilityError: previous.reachabilityError,
246 ipGeolocation: previous.ipGeolocation,
247 ipGeolocationError: previous.ipGeolocationError,
248 emailSecurity: previous.emailSecurity,
249 emailSecurityError: previous.emailSecurityError,
250 ownership: previous.ownership,
251 ownershipError: previous.ownershipError,
252 ownershipHistory: previous.ownershipHistory,
253 ownershipHistoryError: previous.ownershipHistoryError,
254 inferredProvider: previous.inferredProvider,
255 priorProviders: previous.priorProviders,
256 domainClassification: previous.domainClassification,
257 ownershipTransitions: previous.ownershipTransitions,
258 hostingTransitions: previous.hostingTransitions,
259 subdomainHistory: previous.subdomainHistory,
260 riskSignals: previous.riskSignals,
261 intelligenceTimeline: previous.intelligenceTimeline,
262 ptrRecord: previous.ptrRecord,
263 ptrError: previous.ptrError,
264 redirectChain: previous.redirectChain,
265 redirectChainError: previous.redirectChainError,
266 subdomains: previous.subdomains,
267 subdomainsError: previous.subdomainsError,
268 extendedSubdomains: previous.extendedSubdomains,
269 extendedSubdomainsError: previous.extendedSubdomainsError,
270 dnsHistory: previous.dnsHistory,
271 dnsHistoryError: previous.dnsHistoryError,
272 domainPricing: previous.domainPricing,
273 domainPricingError: previous.domainPricingError,
274 reputation: previous.reputation,
275 reputationError: previous.reputationError,
276 portScanResults: previous.portScanResults,
277 portScanError: previous.portScanError,
278 changeSummary: previous.changeSummary,
279 resultSource: .snapshot,
280 cachedSections: [],
281 statusMessage: "Last known result • \(previous.timestamp.formatted(date: .abbreviated, time: .shortened))"
282 )
283 }
284}