Qlty config and code cleanup !2
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 @@ | ||
| 1 | config_version = "0" | |
| 2 | ||
| 3 | exclude_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 | ||
| 18 | test_patterns = [ | |
| 19 | "**/test/**", | |
| 20 | "**/tests/**", | |
| 21 | "**/Tests/**", | |
| 22 | "**/*_test.*", | |
| 23 | "**/test_*.*", | |
| 24 | "**/*.test.*", | |
| 25 | "**/*Tests.swift", | |
| 26 | "e2e/**", | |
| 27 | ] | |
| 28 | ||
| 29 | [[source]] | |
| 30 | name = "default" | |
| 31 | default = true | |
| 32 | ||
| 33 | [[plugin]] | |
| 34 | name = "osv-scanner" | |
| 35 | ||
| 36 | [[plugin]] | |
| 37 | name = "trufflehog" | |
| 38 | ||
| 39 | # Early returns are guard clauses, which keep the happy path unindented. | |
| 40 | [smells.return_statements] | |
| 41 | enabled = false | |
| 42 | ||
| 43 | # Function and file complexity are left to review rather than counted. | |
| 44 | [smells.function_complexity] | |
| 45 | enabled = false | |
| 46 | ||
| 47 | [smells.file_complexity] | |
| 48 | enabled = 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. | |
| 54 | filter_patterns = [ | |
| 55 | "(import_declaration _)", | |
| 56 | "(switch_statement _)", | |
| 57 | "(function_declaration name: (simple_identifier) @_n (#match? @_n \"^(ownershipHistory|dnsHistory)$\"))", | |
| 58 | ] | |
DomainDataPortabilityService.swift +36 −57
| @@ -305,7 +305,8 @@ enum DataPortabilityCSV { | ||
| 305 | 305 | } |
| 306 | 306 | |
| 307 | 307 | private nonisolated static func dictionary(for row: [String], header: [String]) -> [String: String] { |
| 308 | Dictionary(uniqueKeysWithValues: zip(header, row).map { ($0.0, $0.1) }) | |
| 308 | // A repeated column keeps its first value rather than failing the import. | |
| 309 | Dictionary(zip(header, row).map { ($0.0, $0.1) }) { first, _ in first } | |
| 309 | 310 | } |
| 310 | 311 | |
| 311 | 312 | private nonisolated static func csvLine(_ values: [String]) -> String { |
| @@ -903,76 +904,54 @@ enum DomainDataPortabilityService { | ||
| 903 | 904 | if backup.schemaVersion > DomainDigBackup.currentSchemaVersion { |
| 904 | 905 | throw DataPortabilityError.unsupportedSchema(backup.schemaVersion) |
| 905 | 906 | } |
| 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))) | |
| 911 | 908 | } |
| 912 | ||
| 913 | 909 | 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))) | |
| 919 | 911 | } |
| 920 | ||
| 921 | 912 | 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) | |
| 927 | 914 | } |
| 928 | ||
| 929 | 915 | 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) | |
| 935 | 917 | } |
| 936 | ||
| 937 | 918 | 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) | |
| 943 | 920 | } |
| 944 | ||
| 945 | 921 | 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) | |
| 951 | 923 | } |
| 924 | if fileName.lowercased().hasSuffix(".csv") { | |
| 925 | return try decodeCSVPayload(from: data, fileName: fileName) | |
| 926 | } | |
| 927 | throw DataPortabilityError.unsupportedFormat | |
| 928 | } | |
| 952 | 929 | |
| 953 | let lowercasedFileName = fileName.lowercased() | |
| 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)) | |
| 973 | 937 | } |
| 938 | return try trackedDomainsPayload(DataPortabilityCSV.parseTrackedDomains(from: string)) | |
| 939 | } | |
| 974 | 940 | |
| 975 | throw DataPortabilityError.unsupportedFormat | |
| 941 | private static func trackedDomainsPayload(_ trackedDomains: [TrackedDomain]) throws -> ImportPayload { | |
| 942 | .trackedDomains(trackedDomains, try passing(DataValidationService.validate(trackedDomains: trackedDomains))) | |
| 943 | } | |
| 944 | ||
| 945 | private static func workflowsPayload(_ workflows: [DomainWorkflow]) throws -> ImportPayload { | |
| 946 | .workflows(workflows, try passing(DataValidationService.validate(workflows: workflows))) | |
| 947 | } | |
| 948 | ||
| 949 | /// `report`, unless it found errors, which fail the import. | |
| 950 | private static func passing(_ report: DataValidationReport) throws -> DataValidationReport { | |
| 951 | guard report.errors.isEmpty else { | |
| 952 | throw DataPortabilityError.validationFailed(report.errors) | |
| 953 | } | |
| 954 | return report | |
| 976 | 955 | } |
| 977 | 956 | |
| 978 | 957 | private static func decodeLegacyBackup(from data: Data) throws -> DomainDigBackup { |
DomainDig/BatchSweepSummaryView.swift +37 −19
| @@ -28,25 +28,12 @@ struct BatchSweepSummaryView: View { | ||
| 28 | 28 | Toggle("Show unchanged domains", isOn: $showUnchangedDomains) |
| 29 | 29 | } |
| 30 | 30 | |
| 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 | ) | |
| 50 | 37 | } |
| 51 | 38 | .navigationTitle(summary.source == .watchlistRefresh ? "Sweep Summary" : "Batch Summary") |
| 52 | 39 | } |
| @@ -64,3 +51,34 @@ struct BatchSweepSummaryView: View { | ||
| 64 | 51 | } |
| 65 | 52 | } |
| 66 | 53 | } |
| 54 | ||
| 55 | /// A batch's results, each opening its history entry where one was saved. | |
| 56 | /// Titled `emptyTitle`, with `emptyText` under it, when nothing is shown. | |
| 57 | struct BatchResultsSection: View { | |
| 58 | @Bindable var viewModel: DomainViewModel | |
| 59 | let results: [BatchLookupResult] | |
| 60 | let emptyTitle: String | |
| 61 | let emptyText: String | |
| 62 | ||
| 63 | var body: some View { | |
| 64 | Section(results.isEmpty ? emptyTitle : "Results") { | |
| 65 | if results.isEmpty { | |
| 66 | Text(emptyText) | |
| 67 | .font(.system(.caption, design: .monospaced)) | |
| 68 | .foregroundStyle(Color(.appTextSecondary)) | |
| 69 | } else { | |
| 70 | ForEach(results) { result in | |
| 71 | if let entry = viewModel.historyEntry(for: result) { | |
| 72 | NavigationLink { | |
| 73 | HistoryDetailView(viewModel: viewModel, entry: entry) | |
| 74 | } label: { | |
| 75 | BatchResultRowView(result: result) | |
| 76 | } | |
| 77 | } else { | |
| 78 | BatchResultRowView(result: result) | |
| 79 | } | |
| 80 | } | |
| 81 | } | |
| 82 | } | |
| 83 | } | |
| 84 | } | |
DomainDig/CloudSyncService.swift +17 −17
| @@ -782,34 +782,34 @@ final class CloudSyncService { | ||
| 782 | 782 | _ lhs: [String: SyncedDomainNote], |
| 783 | 783 | _ rhs: [String: SyncedDomainNote] |
| 784 | 784 | ) -> (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) | |
| 798 | 787 | } |
| 799 | 788 | |
| 800 | 789 | private func mergeHistoryMetadata( |
| 801 | 790 | _ lhs: [String: SyncedHistoryMetadata], |
| 802 | 791 | _ rhs: [String: SyncedHistoryMetadata] |
| 803 | 792 | ) -> (historyMetadataByDomain: [String: SyncedHistoryMetadata], hadConflict: Bool) { |
| 793 | let result = mergeLatest(lhs, rhs, updatedAt: \.updatedAt) | |
| 794 | return (result.merged, result.hadConflict) | |
| 795 | } | |
| 796 | ||
| 797 | /// `rhs` merged over `lhs` by domain; where both differ, the newer wins | |
| 798 | /// (the local one on a tie) and the merge reports a conflict. | |
| 799 | private func mergeLatest<Value: Equatable>( | |
| 800 | _ lhs: [String: Value], | |
| 801 | _ rhs: [String: Value], | |
| 802 | updatedAt: KeyPath<Value, Date> | |
| 803 | ) -> (merged: [String: Value], hadConflict: Bool) { | |
| 804 | 804 | var merged = lhs |
| 805 | 805 | var hadConflict = false |
| 806 | 806 | |
| 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 { | |
| 809 | 809 | hadConflict = true |
| 810 | merged[domain] = localMetadata.updatedAt >= remoteMetadata.updatedAt ? localMetadata : remoteMetadata | |
| 810 | merged[domain] = local[keyPath: updatedAt] >= remote[keyPath: updatedAt] ? local : remote | |
| 811 | 811 | } else { |
| 812 | merged[domain] = remoteMetadata | |
| 812 | merged[domain] = remote | |
| 813 | 813 | } |
| 814 | 814 | } |
| 815 | 815 | |
DomainDig/ContentView.swift +2 −52
| @@ -566,32 +566,7 @@ struct ContentView: View { | ||
| 566 | 566 | .accessibilityValue(viewModel.isCurrentDomainSaved ? "Saved" : "Not saved") |
| 567 | 567 | .accessibilityAddTraits(viewModel.isCurrentDomainSaved ? .isSelected : []) |
| 568 | 568 | 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) | |
| 595 | 570 | } label: { |
| 596 | 571 | Image(systemName: "square.and.arrow.up") |
| 597 | 572 | .font(appDensity.font(.body, design: .default)) |
| @@ -619,32 +594,7 @@ struct ContentView: View { | ||
| 619 | 594 | showingBatchWorkflowSheet = true |
| 620 | 595 | } |
| 621 | 596 | 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) | |
| 648 | 598 | } label: { |
| 649 | 599 | Label("Export", systemImage: "square.and.arrow.up") |
| 650 | 600 | .font(appDensity.font(.caption)) |
DomainDig/DashboardView.swift +17 −14
| @@ -84,13 +84,8 @@ struct DashboardView: View { | ||
| 84 | 84 | dashboardEmptyRow("No recent portfolio changes") |
| 85 | 85 | } else { |
| 86 | 86 | 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) | |
| 94 | 89 | } |
| 95 | 90 | } |
| 96 | 91 | } |
| @@ -102,13 +97,8 @@ struct DashboardView: View { | ||
| 102 | 97 | dashboardEmptyRow("Nothing urgent right now") |
| 103 | 98 | } else { |
| 104 | 99 | 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) | |
| 112 | 102 | } |
| 113 | 103 | } |
| 114 | 104 | } |
| @@ -271,6 +261,19 @@ struct DashboardView: View { | ||
| 271 | 261 | return AnyShapeStyle(Color(.appSurfaceElevated)) |
| 272 | 262 | } |
| 273 | 263 | |
| 264 | /// `label`, opening the tracked domain's detail; nothing for a domain no longer tracked. | |
| 265 | @ViewBuilder | |
| 266 | private func trackedDomainLink<Label: View>(_ id: UUID, @ViewBuilder label: () -> Label) -> some View { | |
| 267 | if let trackedDomain = viewModel.trackedDomain(withID: id) { | |
| 268 | NavigationLink { | |
| 269 | TrackedDomainDetailView(viewModel: viewModel, trackedDomain: trackedDomain) | |
| 270 | } label: { | |
| 271 | label() | |
| 272 | } | |
| 273 | .buttonStyle(.plain) | |
| 274 | } | |
| 275 | } | |
| 276 | ||
| 274 | 277 | private func dashboardEmptyRow(_ message: String) -> some View { |
| 275 | 278 | Text(message) |
| 276 | 279 | .font(appDensity.font(.caption)) |
DomainDig/DataAccessService.swift +13 −11
| @@ -2,17 +2,19 @@ import Foundation | ||
| 2 | 2 | |
| 3 | 3 | enum DataAccessService { |
| 4 | 4 | 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 | ||
| 9 | extension 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 | |
| 16 | 18 | } |
| 17 | 19 | } |
| 18 | 20 | } |
DomainDig/DiffService.swift +3 −2
| @@ -329,8 +329,9 @@ enum DiffService { | ||
| 329 | 329 | } |
| 330 | 330 | |
| 331 | 331 | 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 } | |
| 334 | 335 | let recordTypes = Set(oldSections.keys).union(newSections.keys).sorted { $0.rawValue < $1.rawValue } |
| 335 | 336 | |
| 336 | 337 | var items: [DiffItem] = [ |
DomainDig/DomainDig/AuditExporter.swift +54 −68
| @@ -48,7 +48,21 @@ enum AuditExporter { | ||
| 48 | 48 | lines.append("") |
| 49 | 49 | } |
| 50 | 50 | |
| 51 | lines.append("## Findings Summary") | |
| 51 | lines += findingsSummaryLines(session) | |
| 52 | lines += keyRiskLines(session) | |
| 53 | lines.append("## Checklist") | |
| 54 | for item in session.checklist { | |
| 55 | lines.append("- [\(item.isComplete ? "x" : " ")] \(item.title): \(item.detail)") | |
| 56 | } | |
| 57 | lines.append("") | |
| 58 | lines += findingLines(session) | |
| 59 | lines += evidenceLines(session.evidence) | |
| 60 | ||
| 61 | return lines.joined(separator: "\n") | |
| 62 | } | |
| 63 | ||
| 64 | private static func findingsSummaryLines(_ session: AuditSession) -> [String] { | |
| 65 | var lines = ["## Findings Summary"] | |
| 52 | 66 | if session.findings.isEmpty { |
| 53 | 67 | lines.append("No findings recorded.") |
| 54 | 68 | } else { |
| @@ -57,8 +71,11 @@ enum AuditExporter { | ||
| 57 | 71 | } |
| 58 | 72 | } |
| 59 | 73 | lines.append("") |
| 74 | return lines | |
| 75 | } | |
| 60 | 76 | |
| 61 | lines.append("## Key Risks") | |
| 77 | private static func keyRiskLines(_ session: AuditSession) -> [String] { | |
| 78 | var lines = ["## Key Risks"] | |
| 62 | 79 | if session.keyRisks.isEmpty { |
| 63 | 80 | lines.append("No medium or high-severity risks recorded.") |
| 64 | 81 | } else { |
| @@ -67,46 +84,46 @@ enum AuditExporter { | ||
| 67 | 84 | } |
| 68 | 85 | } |
| 69 | 86 | lines.append("") |
| 87 | return lines | |
| 88 | } | |
| 70 | 89 | |
| 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"] | |
| 78 | 92 | if session.findings.isEmpty { |
| 79 | 93 | 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: ", "))") | |
| 96 | 101 | } |
| 102 | lines.append("- Summary: \(finding.summary)") | |
| 103 | if !finding.evidenceReferences.isEmpty { | |
| 104 | lines.append("- Evidence: \(finding.evidenceReferences.joined(separator: " | "))") | |
| 105 | } | |
| 106 | if !finding.notes.isEmpty { | |
| 107 | lines.append("- Notes: \(finding.notes)") | |
| 108 | } | |
| 109 | lines.append("") | |
| 97 | 110 | } |
| 111 | return lines | |
| 112 | } | |
| 98 | 113 | |
| 99 | lines.append("## Evidence Snapshot") | |
| 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 | ] | |
| 110 | 127 | } |
| 111 | 128 | |
| 112 | 129 | private static func availabilityTitle(_ status: DomainAvailabilityStatus) -> String { |
| @@ -121,37 +138,6 @@ enum AuditExporter { | ||
| 121 | 138 | } |
| 122 | 139 | |
| 123 | 140 | 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)) | |
| 156 | 142 | } |
| 157 | 143 | } |
DomainDig/DomainInsightEngine.swift +117 −104
| @@ -176,158 +176,171 @@ enum DomainInsightEngine { | ||
| 176 | 176 | tlsAssessment: TLSSummaryAssessment, |
| 177 | 177 | subdomainGroups: [SubdomainGroup] |
| 178 | 178 | ) -> DomainRiskAssessment { |
| 179 | var tally = RiskTally() | |
| 180 | scoreAvailability(snapshot, into: &tally) | |
| 181 | scoreDNS(snapshot, patterns: dnsPatterns, into: &tally) | |
| 182 | scoreTLS(snapshot, assessment: tlsAssessment, into: &tally) | |
| 183 | scoreRedirects(snapshot, into: &tally) | |
| 184 | scoreEmail(snapshot, assessment: emailAssessment, into: &tally) | |
| 185 | scorePorts(snapshot, into: &tally) | |
| 186 | scoreSubdomains(snapshot, groups: subdomainGroups, into: &tally) | |
| 187 | scoreGeolocation(snapshot, into: &tally) | |
| 188 | // Compares against the score so far, so it runs after the snapshot's own factors. | |
| 189 | if let previousSnapshot { | |
| 190 | let delta = tally.score - analyze(snapshot: previousSnapshot).riskAssessment.score | |
| 191 | if delta >= 15 { | |
| 192 | tally.add(4, "Observed risk has increased materially since the previous snapshot", .negative) | |
| 193 | } | |
| 194 | } | |
| 195 | scoreReputation(snapshot, into: &tally) | |
| 196 | ||
| 197 | let clampedScore = min(max(tally.score, 0), 100) | |
| 198 | let level: RiskLevel | |
| 199 | switch clampedScore { | |
| 200 | case 0..<35: | |
| 201 | level = .low | |
| 202 | case 35..<65: | |
| 203 | level = .medium | |
| 204 | default: | |
| 205 | level = .high | |
| 206 | } | |
| 207 | ||
| 208 | return DomainRiskAssessment(score: clampedScore, level: level, factors: tally.factors) | |
| 209 | } | |
| 210 | ||
| 211 | /// A risk score in progress, from a baseline of 18, and the factors behind it. | |
| 212 | private struct RiskTally { | |
| 179 | 213 | var score = 18 |
| 180 | 214 | var factors: [RiskFactor] = [] |
| 181 | 215 | |
| 216 | mutating func add(_ points: Int, _ description: String, _ impact: RiskImpact) { | |
| 217 | score += points | |
| 218 | factors.append(RiskFactor(description: description, impact: impact)) | |
| 219 | } | |
| 220 | } | |
| 221 | ||
| 222 | private static func scoreAvailability(_ snapshot: LookupSnapshot, into tally: inout RiskTally) { | |
| 182 | 223 | switch snapshot.availabilityResult?.status ?? .unknown { |
| 183 | 224 | 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) | |
| 186 | 226 | 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) | |
| 189 | 228 | case .registered: |
| 190 | 229 | 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) | |
| 193 | 231 | } else { |
| 194 | factors.append(.init(description: "Registered domain with limited active surface detected", impact: .neutral)) | |
| 232 | tally.add(0, "Registered domain with limited active surface detected", .neutral) | |
| 195 | 233 | } |
| 196 | 234 | } |
| 235 | } | |
| 197 | 236 | |
| 237 | private static func scoreDNS(_ snapshot: LookupSnapshot, patterns: DNSPatternSummary, into tally: inout RiskTally) { | |
| 198 | 238 | let recordTypes = snapshot.dnsSections.filter { !$0.records.isEmpty || !$0.wildcardRecords.isEmpty }.count |
| 199 | 239 | 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) | |
| 202 | 241 | } |
| 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) | |
| 206 | 244 | } |
| 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) | |
| 209 | 247 | } |
| 248 | } | |
| 210 | 249 | |
| 211 | switch tlsAssessment.grade { | |
| 250 | private static func scoreTLS(_ snapshot: LookupSnapshot, assessment: TLSSummaryAssessment, into tally: inout RiskTally) { | |
| 251 | switch assessment.grade { | |
| 212 | 252 | 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) | |
| 215 | 254 | 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) | |
| 218 | 256 | 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) | |
| 221 | 258 | 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) | |
| 224 | 260 | } |
| 225 | ||
| 226 | 261 | 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) | |
| 229 | 263 | } |
| 264 | } | |
| 230 | 265 | |
| 266 | private static func scoreRedirects(_ snapshot: LookupSnapshot, into tally: inout RiskTally) { | |
| 231 | 267 | 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) | |
| 234 | 269 | } |
| 235 | ||
| 236 | 270 | 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) | |
| 255 | 283 | } |
| 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 | |
| 259 | 285 | } |
| 286 | switch assessment.grade { | |
| 287 | case .a: | |
| 288 | tally.add(-10, "Email protections are strong and aligned", .positive) | |
| 289 | case .b: | |
| 290 | tally.add(-4, "Email protections are present with minor gaps", .positive) | |
| 291 | case .c: | |
| 292 | tally.add(8, "Email protections are partial", .negative) | |
| 293 | case .f: | |
| 294 | tally.add(18, "Email security protections are weak or absent", .negative) | |
| 295 | } | |
| 296 | } | |
| 260 | 297 | |
| 298 | private static func scorePorts(_ snapshot: LookupSnapshot, into tally: inout RiskTally) { | |
| 261 | 299 | let openPorts = snapshot.portScanResults.filter(\.open).map(\.port) |
| 262 | 300 | let sensitivePorts: Set<UInt16> = [21, 22, 23, 25, 3389, 5900] |
| 263 | 301 | let exposedSensitivePorts = openPorts.filter { sensitivePorts.contains($0) } |
| 264 | 302 | 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) | |
| 267 | 304 | } else if Set(openPorts) == Set([80, 443]) { |
| 268 | factors.append(.init(description: "Exposure is limited to standard web ports", impact: .positive)) | |
| 305 | tally.add(0, "Exposure is limited to standard web ports", .positive) | |
| 269 | 306 | } 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) | |
| 272 | 308 | } |
| 309 | } | |
| 273 | 310 | |
| 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) | |
| 288 | 316 | } |
| 317 | if labels.contains("admin") { | |
| 318 | tally.add(10, "Administrative subdomains are discoverable", .negative) | |
| 319 | } | |
| 320 | if snapshot.subdomains.count >= 8 { | |
| 321 | tally.add(6, "Large passive subdomain footprint detected", .negative) | |
| 322 | } | |
| 323 | } | |
| 289 | 324 | |
| 325 | private static func scoreGeolocation(_ snapshot: LookupSnapshot, into tally: inout RiskTally) { | |
| 290 | 326 | if snapshot.ipGeolocation == nil, |
| 291 | 327 | snapshot.availabilityResult?.status == .registered, |
| 292 | 328 | 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) | |
| 317 | 330 | } |
| 331 | } | |
| 318 | 332 | |
| 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 | |
| 328 | 343 | } |
| 329 | ||
| 330 | return DomainRiskAssessment(score: clampedScore, level: level, factors: factors) | |
| 331 | 344 | } |
| 332 | 345 | |
| 333 | 346 | private static func insights( |
DomainDig/DomainMonitoringService.swift +67 −157
| @@ -187,16 +187,11 @@ final class DomainMonitoringScheduler { | ||
| 187 | 187 | private func handleAppRefresh(task: BGAppRefreshTask) { |
| 188 | 188 | _ = syncSchedule() |
| 189 | 189 | |
| 190 | let worker = Task { | |
| 191 | let outcome = await DomainMonitoringService.shared.performMonitoring( | |
| 190 | task.run { | |
| 191 | await DomainMonitoringService.shared.performMonitoring( | |
| 192 | 192 | trigger: .background, |
| 193 | 193 | requireEnabledSetting: true |
| 194 | ) | |
| 195 | task.setTaskCompleted(success: outcome.success) | |
| 196 | } | |
| 197 | ||
| 198 | task.expirationHandler = { | |
| 199 | worker.cancel() | |
| 194 | ).success | |
| 200 | 195 | } |
| 201 | 196 | } |
| 202 | 197 | #endif |
| @@ -290,11 +285,11 @@ final class DomainMonitoringService { | ||
| 290 | 285 | domain: trackedDomain.domain, |
| 291 | 286 | previousSnapshot: previousSnapshot |
| 292 | 287 | ) |
| 293 | let snapshot = Self.resolvedSnapshotAfterFallback(inspectedSnapshot, previousSnapshot: previousSnapshot) | |
| 288 | let snapshot = inspectedSnapshot.resolvedAfterFallback(to: previousSnapshot) | |
| 294 | 289 | // When the fallback fires, `snapshot` *is* `previousSnapshot`, so |
| 295 | 290 | // every comparison below is old-against-old and would otherwise |
| 296 | 291 | // report "No meaningful changes" for a domain we never reached. |
| 297 | let unreachableReason = (previousSnapshot != nil && Self.shouldFallbackToSnapshot(inspectedSnapshot)) | |
| 292 | let unreachableReason = (previousSnapshot != nil && inspectedSnapshot.needsFallback) | |
| 298 | 293 | ? Self.firstErrorMessage(in: inspectedSnapshot) |
| 299 | 294 | : nil |
| 300 | 295 | let savedEntry: HistoryEntry? |
| @@ -602,38 +597,13 @@ final class DomainMonitoringService { | ||
| 602 | 597 | |
| 603 | 598 | if settings.alertsEnabled, |
| 604 | 599 | 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 | |
| 610 | 606 | ) |
| 611 | ||
| 612 | if isQuiet || !notificationsAuthorized { | |
| 613 | updated.pendingMonitoringAlerts = deduplicatedPendingAlerts( | |
| 614 | updated.pendingMonitoringAlerts + [pendingAlert] | |
| 615 | ) | |
| 616 | } else { | |
| 617 | let pendingAlerts = deduplicatedPendingAlerts( | |
| 618 | updated.pendingMonitoringAlerts + [pendingAlert] | |
| 619 | ) | |
| 620 | if pendingAlerts.count > 1 { | |
| 621 | await LocalNotificationService.shared.notifyMonitoringSummary( | |
| 622 | domain: trackedDomain.domain, | |
| 623 | alerts: pendingAlerts | |
| 624 | ) | |
| 625 | } else { | |
| 626 | await LocalNotificationService.shared.notifyMonitoringAlert( | |
| 627 | domain: trackedDomain.domain, | |
| 628 | message: alertDescriptor.message, | |
| 629 | severity: alertDescriptor.severity | |
| 630 | ) | |
| 631 | } | |
| 632 | alertsTriggered += 1 | |
| 633 | updated.pendingMonitoringAlerts = [] | |
| 634 | updated.lastAlertAt = now | |
| 635 | state.lastAlertDate = now | |
| 636 | } | |
| 637 | 607 | } |
| 638 | 608 | } |
| 639 | 609 | } else { |
| @@ -668,6 +638,45 @@ final class DomainMonitoringService { | ||
| 668 | 638 | return (updated, alertsTriggered) |
| 669 | 639 | } |
| 670 | 640 | |
| 641 | /// Queues the alert while notifications are deferred; otherwise notifies, folding in | |
| 642 | /// any queued alerts, and returns the number of notifications sent. | |
| 643 | private func raiseAlert( | |
| 644 | _ alertDescriptor: MonitoringAlertDescriptor, | |
| 645 | for updated: inout TrackedDomain, | |
| 646 | state: inout MonitoringState, | |
| 647 | deferred: Bool, | |
| 648 | now: Date | |
| 649 | ) async -> Int { | |
| 650 | let pendingAlert = MonitoringPendingAlert( | |
| 651 | detectedAt: now, | |
| 652 | message: alertDescriptor.message, | |
| 653 | severity: alertDescriptor.severity, | |
| 654 | changeHash: alertDescriptor.changeHash | |
| 655 | ) | |
| 656 | let pendingAlerts = deduplicatedPendingAlerts(updated.pendingMonitoringAlerts + [pendingAlert]) | |
| 657 | if deferred { | |
| 658 | updated.pendingMonitoringAlerts = pendingAlerts | |
| 659 | return 0 | |
| 660 | } | |
| 661 | ||
| 662 | if pendingAlerts.count > 1 { | |
| 663 | await LocalNotificationService.shared.notifyMonitoringSummary( | |
| 664 | domain: updated.domain, | |
| 665 | alerts: pendingAlerts | |
| 666 | ) | |
| 667 | } else { | |
| 668 | await LocalNotificationService.shared.notifyMonitoringAlert( | |
| 669 | domain: updated.domain, | |
| 670 | message: alertDescriptor.message, | |
| 671 | severity: alertDescriptor.severity | |
| 672 | ) | |
| 673 | } | |
| 674 | updated.pendingMonitoringAlerts = [] | |
| 675 | updated.lastAlertAt = now | |
| 676 | state.lastAlertDate = now | |
| 677 | return 1 | |
| 678 | } | |
| 679 | ||
| 671 | 680 | private func deduplicatedPendingAlerts(_ alerts: [MonitoringPendingAlert]) -> [MonitoringPendingAlert] { |
| 672 | 681 | var uniqueByHash: [String: MonitoringPendingAlert] = [:] |
| 673 | 682 | for alert in alerts { |
| @@ -844,95 +853,8 @@ final class DomainMonitoringService { | ||
| 844 | 853 | } |
| 845 | 854 | } |
| 846 | 855 | |
| 847 | private static func resolvedSnapshotAfterFallback( | |
| 848 | _ snapshot: LookupSnapshot, | |
| 849 | previousSnapshot: LookupSnapshot? | |
| 850 | ) -> LookupSnapshot { | |
| 851 | guard shouldFallbackToSnapshot(snapshot), let previousSnapshot else { | |
| 852 | return snapshot | |
| 853 | } | |
| 854 | ||
| 855 | return LookupSnapshot( | |
| 856 | historyEntryID: previousSnapshot.historyEntryID, | |
| 857 | domain: previousSnapshot.domain, | |
| 858 | timestamp: previousSnapshot.timestamp, | |
| 859 | trackedDomainID: previousSnapshot.trackedDomainID, | |
| 860 | note: previousSnapshot.note, | |
| 861 | appVersion: previousSnapshot.appVersion, | |
| 862 | resolverDisplayName: previousSnapshot.resolverDisplayName, | |
| 863 | resolverURLString: previousSnapshot.resolverURLString, | |
| 864 | dataSources: previousSnapshot.dataSources, | |
| 865 | provenanceBySection: previousSnapshot.provenanceBySection, | |
| 866 | availabilityConfidence: previousSnapshot.availabilityConfidence, | |
| 867 | ownershipConfidence: previousSnapshot.ownershipConfidence, | |
| 868 | subdomainConfidence: previousSnapshot.subdomainConfidence, | |
| 869 | emailSecurityConfidence: previousSnapshot.emailSecurityConfidence, | |
| 870 | geolocationConfidence: previousSnapshot.geolocationConfidence, | |
| 871 | errorDetails: previousSnapshot.errorDetails, | |
| 872 | isPartialSnapshot: previousSnapshot.isPartialSnapshot, | |
| 873 | validationIssues: previousSnapshot.validationIssues, | |
| 874 | totalLookupDurationMs: previousSnapshot.totalLookupDurationMs, | |
| 875 | snapshotIndex: previousSnapshot.snapshotIndex, | |
| 876 | previousSnapshotID: previousSnapshot.previousSnapshotID, | |
| 877 | changeCount: previousSnapshot.changeCount, | |
| 878 | severitySummary: previousSnapshot.severitySummary, | |
| 879 | dnsSections: previousSnapshot.dnsSections, | |
| 880 | dnsError: previousSnapshot.dnsError, | |
| 881 | availabilityResult: previousSnapshot.availabilityResult, | |
| 882 | suggestions: previousSnapshot.suggestions, | |
| 883 | sslInfo: previousSnapshot.sslInfo, | |
| 884 | sslError: previousSnapshot.sslError, | |
| 885 | hstsPreloaded: previousSnapshot.hstsPreloaded, | |
| 886 | httpHeaders: previousSnapshot.httpHeaders, | |
| 887 | httpSecurityGrade: previousSnapshot.httpSecurityGrade, | |
| 888 | httpStatusCode: previousSnapshot.httpStatusCode, | |
| 889 | httpResponseTimeMs: previousSnapshot.httpResponseTimeMs, | |
| 890 | httpProtocol: previousSnapshot.httpProtocol, | |
| 891 | http3Advertised: previousSnapshot.http3Advertised, | |
| 892 | httpHeadersError: previousSnapshot.httpHeadersError, | |
| 893 | reachabilityResults: previousSnapshot.reachabilityResults, | |
| 894 | reachabilityError: previousSnapshot.reachabilityError, | |
| 895 | ipGeolocation: previousSnapshot.ipGeolocation, | |
| 896 | ipGeolocationError: previousSnapshot.ipGeolocationError, | |
| 897 | emailSecurity: previousSnapshot.emailSecurity, | |
| 898 | emailSecurityError: previousSnapshot.emailSecurityError, | |
| 899 | ownership: previousSnapshot.ownership, | |
| 900 | ownershipError: previousSnapshot.ownershipError, | |
| 901 | ownershipHistory: previousSnapshot.ownershipHistory, | |
| 902 | ownershipHistoryError: previousSnapshot.ownershipHistoryError, | |
| 903 | inferredProvider: previousSnapshot.inferredProvider, | |
| 904 | priorProviders: previousSnapshot.priorProviders, | |
| 905 | domainClassification: previousSnapshot.domainClassification, | |
| 906 | ownershipTransitions: previousSnapshot.ownershipTransitions, | |
| 907 | hostingTransitions: previousSnapshot.hostingTransitions, | |
| 908 | subdomainHistory: previousSnapshot.subdomainHistory, | |
| 909 | riskSignals: previousSnapshot.riskSignals, | |
| 910 | intelligenceTimeline: previousSnapshot.intelligenceTimeline, | |
| 911 | ptrRecord: previousSnapshot.ptrRecord, | |
| 912 | ptrError: previousSnapshot.ptrError, | |
| 913 | redirectChain: previousSnapshot.redirectChain, | |
| 914 | redirectChainError: previousSnapshot.redirectChainError, | |
| 915 | subdomains: previousSnapshot.subdomains, | |
| 916 | subdomainsError: previousSnapshot.subdomainsError, | |
| 917 | extendedSubdomains: previousSnapshot.extendedSubdomains, | |
| 918 | extendedSubdomainsError: previousSnapshot.extendedSubdomainsError, | |
| 919 | dnsHistory: previousSnapshot.dnsHistory, | |
| 920 | dnsHistoryError: previousSnapshot.dnsHistoryError, | |
| 921 | domainPricing: previousSnapshot.domainPricing, | |
| 922 | domainPricingError: previousSnapshot.domainPricingError, | |
| 923 | reputation: previousSnapshot.reputation, | |
| 924 | reputationError: previousSnapshot.reputationError, | |
| 925 | portScanResults: previousSnapshot.portScanResults, | |
| 926 | portScanError: previousSnapshot.portScanError, | |
| 927 | changeSummary: previousSnapshot.changeSummary, | |
| 928 | resultSource: .snapshot, | |
| 929 | cachedSections: [], | |
| 930 | statusMessage: "Last known result • \(previousSnapshot.timestamp.formatted(date: .abbreviated, time: .shortened))" | |
| 931 | ) | |
| 932 | } | |
| 933 | ||
| 934 | 856 | /// First reported error on a snapshot, used to explain a fallback. Mirrors |
| 935 | /// the ordering `shouldFallbackToSnapshot` inspects. | |
| 857 | /// the ordering `LookupSnapshot.needsFallback` inspects. | |
| 936 | 858 | private static func firstErrorMessage(in snapshot: LookupSnapshot) -> String { |
| 937 | 859 | [ |
| 938 | 860 | snapshot.dnsError, |
| @@ -947,34 +869,6 @@ final class DomainMonitoringService { | ||
| 947 | 869 | .first ?? "The lookup could not reach the domain." |
| 948 | 870 | } |
| 949 | 871 | |
| 950 | private static func shouldFallbackToSnapshot(_ snapshot: LookupSnapshot) -> Bool { | |
| 951 | let candidateMessages = [ | |
| 952 | snapshot.dnsError, | |
| 953 | snapshot.httpHeadersError, | |
| 954 | snapshot.sslError, | |
| 955 | snapshot.ownershipError, | |
| 956 | snapshot.subdomainsError, | |
| 957 | snapshot.redirectChainError, | |
| 958 | snapshot.ipGeolocationError | |
| 959 | ] | |
| 960 | .compactMap { $0?.lowercased() } | |
| 961 | ||
| 962 | guard !candidateMessages.isEmpty else { return false } | |
| 963 | let connectivityFailure = candidateMessages.allSatisfy { message in | |
| 964 | message.hasPrefix("network error:") | |
| 965 | || message.hasPrefix("timeout:") | |
| 966 | || message.hasPrefix("rate limit:") | |
| 967 | } | |
| 968 | ||
| 969 | let hasMaterialData = !snapshot.dnsSections.isEmpty | |
| 970 | || !snapshot.httpHeaders.isEmpty | |
| 971 | || snapshot.sslInfo != nil | |
| 972 | || snapshot.ownership != nil | |
| 973 | || !snapshot.subdomains.isEmpty | |
| 974 | ||
| 975 | return connectivityFailure && !hasMaterialData | |
| 976 | } | |
| 977 | ||
| 978 | 872 | private static func primaryIPAddress(from snapshot: LookupSnapshot) -> String? { |
| 979 | 873 | snapshot.dnsSections.first(where: { $0.recordType == .A })?.records.first?.value |
| 980 | 874 | } |
| @@ -1004,3 +898,19 @@ final class DomainMonitoringService { | ||
| 1004 | 898 | return snapshot.emailSecurityError |
| 1005 | 899 | } |
| 1006 | 900 | } |
| 901 | ||
| 902 | #if canImport(BackgroundTasks) | |
| 903 | extension BGAppRefreshTask { | |
| 904 | /// Runs `work` for this refresh, completing the task with whether it succeeded, and cancels it | |
| 905 | /// when the system ends the task early. | |
| 906 | @MainActor | |
| 907 | func run(_ work: @escaping @MainActor () async -> Bool) { | |
| 908 | let worker = Task { | |
| 909 | setTaskCompleted(success: await work()) | |
| 910 | } | |
| 911 | expirationHandler = { | |
| 912 | worker.cancel() | |
| 913 | } | |
| 914 | } | |
| 915 | } | |
| 916 | #endif | |
DomainDig/DomainViewModel.swift +326 −460
| @@ -1282,101 +1282,73 @@ final class DomainViewModel { | ||
| 1282 | 1282 | } |
| 1283 | 1283 | |
| 1284 | 1284 | 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 | |
| 1289 | 1292 | } |
| 1290 | guard ownershipHistory.isEmpty else { return } | |
| 1291 | ||
| 1292 | ownershipHistoryLoading = true | |
| 1293 | ownershipHistoryError = nil | |
| 1294 | ||
| 1295 | let outcome = await ExternalDataService.shared.ownershipHistory( | |
| 1296 | domain: searchedDomain, | |
| 1297 | currentOwnership: ownershipResult, | |
| 1298 | historyEntries: history | |
| 1299 | ) | |
| 1300 | ||
| 1301 | switch outcome.value { | |
| 1302 | case let .success(events): | |
| 1303 | ownershipHistory = events | |
| 1304 | ownershipHistoryError = nil | |
| 1305 | case let .empty(message): | |
| 1306 | ownershipHistory = [] | |
| 1307 | ownershipHistoryError = message | |
| 1308 | case let .error(message): | |
| 1309 | ownershipHistory = [] | |
| 1310 | ownershipHistoryError = conciseExternalMessage(message, fallback: "Ownership history unavailable") | |
| 1311 | } | |
| 1312 | ||
| 1313 | ownershipHistoryLoading = false | |
| 1314 | _ = saveHistoryEntry(replaceLatest: true) | |
| 1315 | 1293 | } |
| 1316 | 1294 | |
| 1317 | 1295 | 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 | |
| 1344 | 1303 | } |
| 1345 | ||
| 1346 | dnsHistoryLoading = false | |
| 1347 | _ = saveHistoryEntry(replaceLatest: true) | |
| 1348 | 1304 | } |
| 1349 | 1305 | |
| 1350 | 1306 | func loadExtendedSubdomains() async { |
| 1307 | await loadLookup(.extendedSubdomains, into: \.extendedSubdomains, loading: \.extendedSubdomainsLoading, error: \.extendedSubdomainsError, | |
| 1308 | fallback: "Extended subdomains unavailable") { | |
| 1309 | await ExternalDataService.shared.extendedSubdomains( | |
| 1310 | domain: searchedDomain, | |
| 1311 | existing: subdomains | |
| 1312 | ).value | |
| 1313 | } | |
| 1314 | } | |
| 1315 | ||
| 1316 | /// Loads `capability`'s lookup for the searched domain into `items`, unless it is loaded | |
| 1317 | /// already, or shows the upgrade prompt when the plan doesn't include it. | |
| 1318 | private func loadLookup<Item>( | |
| 1319 | _ capability: DataCapability, | |
| 1320 | into items: ReferenceWritableKeyPath<DomainViewModel, [Item]>, | |
| 1321 | loading: ReferenceWritableKeyPath<DomainViewModel, Bool>, | |
| 1322 | error: ReferenceWritableKeyPath<DomainViewModel, String?>, | |
| 1323 | fallback: String, | |
| 1324 | fetch: () async -> ServiceResult<[Item]> | |
| 1325 | ) async { | |
| 1351 | 1326 | 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) | |
| 1354 | 1329 | return |
| 1355 | 1330 | } |
| 1356 | guard extendedSubdomains.isEmpty else { return } | |
| 1331 | guard self[keyPath: items].isEmpty else { return } | |
| 1357 | 1332 | |
| 1358 | extendedSubdomainsLoading = true | |
| 1359 | extendedSubdomainsError = nil | |
| 1333 | self[keyPath: loading] = true | |
| 1334 | self[keyPath: error] = nil | |
| 1360 | 1335 | |
| 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) | |
| 1365 | 1337 | |
| 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) | |
| 1370 | 1347 | case let .empty(message): |
| 1371 | extendedSubdomains = [] | |
| 1372 | extendedSubdomainsError = message | |
| 1348 | return ([], message) | |
| 1373 | 1349 | case let .error(message): |
| 1374 | extendedSubdomains = [] | |
| 1375 | extendedSubdomainsError = conciseExternalMessage(message, fallback: "Extended subdomains unavailable") | |
| 1350 | return ([], conciseExternalMessage(message, fallback: fallback)) | |
| 1376 | 1351 | } |
| 1377 | ||
| 1378 | extendedSubdomainsLoading = false | |
| 1379 | _ = saveHistoryEntry(replaceLatest: true) | |
| 1380 | 1352 | } |
| 1381 | 1353 | |
| 1382 | 1354 | func refreshUsageCredits() async { |
| @@ -1395,7 +1367,7 @@ final class DomainViewModel { | ||
| 1395 | 1367 | DomainDebugLog.debug("DomainViewModel.performLookup inspectionReturned domain=\(domain)") |
| 1396 | 1368 | guard !Task.isCancelled, isCurrentLookup(lookupID) else { return nil } |
| 1397 | 1369 | |
| 1398 | let snapshot = Self.resolvedSnapshotAfterFallback(inspectedSnapshot, previousSnapshot: previous) | |
| 1370 | let snapshot = inspectedSnapshot.resolvedAfterFallback(to: previous) | |
| 1399 | 1371 | let applyStartedAt = DomainDebugLog.signpostStart("DomainViewModel.applySnapshot", domain: domain) |
| 1400 | 1372 | applySnapshot(snapshot) |
| 1401 | 1373 | DomainDebugLog.signpostEnd("DomainViewModel.applySnapshot", start: applyStartedAt, domain: domain) |
| @@ -1506,119 +1478,6 @@ final class DomainViewModel { | ||
| 1506 | 1478 | customPortScanLoading = false |
| 1507 | 1479 | } |
| 1508 | 1480 | |
| 1509 | private static func resolvedSnapshotAfterFallback( | |
| 1510 | _ snapshot: LookupSnapshot, | |
| 1511 | previousSnapshot: LookupSnapshot? | |
| 1512 | ) -> LookupSnapshot { | |
| 1513 | guard shouldFallbackToSnapshot(snapshot), let previousSnapshot else { | |
| 1514 | return snapshot | |
| 1515 | } | |
| 1516 | ||
| 1517 | return LookupSnapshot( | |
| 1518 | historyEntryID: previousSnapshot.historyEntryID, | |
| 1519 | domain: previousSnapshot.domain, | |
| 1520 | timestamp: previousSnapshot.timestamp, | |
| 1521 | trackedDomainID: previousSnapshot.trackedDomainID, | |
| 1522 | note: previousSnapshot.note, | |
| 1523 | appVersion: previousSnapshot.appVersion, | |
| 1524 | resolverDisplayName: previousSnapshot.resolverDisplayName, | |
| 1525 | resolverURLString: previousSnapshot.resolverURLString, | |
| 1526 | dataSources: previousSnapshot.dataSources, | |
| 1527 | provenanceBySection: previousSnapshot.provenanceBySection, | |
| 1528 | availabilityConfidence: previousSnapshot.availabilityConfidence, | |
| 1529 | ownershipConfidence: previousSnapshot.ownershipConfidence, | |
| 1530 | subdomainConfidence: previousSnapshot.subdomainConfidence, | |
| 1531 | emailSecurityConfidence: previousSnapshot.emailSecurityConfidence, | |
| 1532 | geolocationConfidence: previousSnapshot.geolocationConfidence, | |
| 1533 | errorDetails: previousSnapshot.errorDetails, | |
| 1534 | isPartialSnapshot: previousSnapshot.isPartialSnapshot, | |
| 1535 | validationIssues: previousSnapshot.validationIssues, | |
| 1536 | totalLookupDurationMs: previousSnapshot.totalLookupDurationMs, | |
| 1537 | snapshotIndex: previousSnapshot.snapshotIndex, | |
| 1538 | previousSnapshotID: previousSnapshot.previousSnapshotID, | |
| 1539 | changeCount: previousSnapshot.changeCount, | |
| 1540 | severitySummary: previousSnapshot.severitySummary, | |
| 1541 | dnsSections: previousSnapshot.dnsSections, | |
| 1542 | dnsError: previousSnapshot.dnsError, | |
| 1543 | availabilityResult: previousSnapshot.availabilityResult, | |
| 1544 | suggestions: previousSnapshot.suggestions, | |
| 1545 | sslInfo: previousSnapshot.sslInfo, | |
| 1546 | sslError: previousSnapshot.sslError, | |
| 1547 | hstsPreloaded: previousSnapshot.hstsPreloaded, | |
| 1548 | httpHeaders: previousSnapshot.httpHeaders, | |
| 1549 | httpSecurityGrade: previousSnapshot.httpSecurityGrade, | |
| 1550 | httpStatusCode: previousSnapshot.httpStatusCode, | |
| 1551 | httpResponseTimeMs: previousSnapshot.httpResponseTimeMs, | |
| 1552 | httpProtocol: previousSnapshot.httpProtocol, | |
| 1553 | http3Advertised: previousSnapshot.http3Advertised, | |
| 1554 | httpHeadersError: previousSnapshot.httpHeadersError, | |
| 1555 | reachabilityResults: previousSnapshot.reachabilityResults, | |
| 1556 | reachabilityError: previousSnapshot.reachabilityError, | |
| 1557 | ipGeolocation: previousSnapshot.ipGeolocation, | |
| 1558 | ipGeolocationError: previousSnapshot.ipGeolocationError, | |
| 1559 | emailSecurity: previousSnapshot.emailSecurity, | |
| 1560 | emailSecurityError: previousSnapshot.emailSecurityError, | |
| 1561 | ownership: previousSnapshot.ownership, | |
| 1562 | ownershipError: previousSnapshot.ownershipError, | |
| 1563 | ownershipHistory: previousSnapshot.ownershipHistory, | |
| 1564 | ownershipHistoryError: previousSnapshot.ownershipHistoryError, | |
| 1565 | inferredProvider: previousSnapshot.inferredProvider, | |
| 1566 | priorProviders: previousSnapshot.priorProviders, | |
| 1567 | domainClassification: previousSnapshot.domainClassification, | |
| 1568 | ownershipTransitions: previousSnapshot.ownershipTransitions, | |
| 1569 | hostingTransitions: previousSnapshot.hostingTransitions, | |
| 1570 | subdomainHistory: previousSnapshot.subdomainHistory, | |
| 1571 | riskSignals: previousSnapshot.riskSignals, | |
| 1572 | intelligenceTimeline: previousSnapshot.intelligenceTimeline, | |
| 1573 | ptrRecord: previousSnapshot.ptrRecord, | |
| 1574 | ptrError: previousSnapshot.ptrError, | |
| 1575 | redirectChain: previousSnapshot.redirectChain, | |
| 1576 | redirectChainError: previousSnapshot.redirectChainError, | |
| 1577 | subdomains: previousSnapshot.subdomains, | |
| 1578 | subdomainsError: previousSnapshot.subdomainsError, | |
| 1579 | extendedSubdomains: previousSnapshot.extendedSubdomains, | |
| 1580 | extendedSubdomainsError: previousSnapshot.extendedSubdomainsError, | |
| 1581 | dnsHistory: previousSnapshot.dnsHistory, | |
| 1582 | dnsHistoryError: previousSnapshot.dnsHistoryError, | |
| 1583 | domainPricing: previousSnapshot.domainPricing, | |
| 1584 | domainPricingError: previousSnapshot.domainPricingError, | |
| 1585 | reputation: previousSnapshot.reputation, | |
| 1586 | reputationError: previousSnapshot.reputationError, | |
| 1587 | portScanResults: previousSnapshot.portScanResults, | |
| 1588 | portScanError: previousSnapshot.portScanError, | |
| 1589 | changeSummary: previousSnapshot.changeSummary, | |
| 1590 | resultSource: .snapshot, | |
| 1591 | cachedSections: [], | |
| 1592 | statusMessage: "Last known result • \(previousSnapshot.timestamp.formatted(date: .abbreviated, time: .shortened))" | |
| 1593 | ) | |
| 1594 | } | |
| 1595 | ||
| 1596 | private static func shouldFallbackToSnapshot(_ snapshot: LookupSnapshot) -> Bool { | |
| 1597 | let candidateMessages = [ | |
| 1598 | snapshot.dnsError, | |
| 1599 | snapshot.httpHeadersError, | |
| 1600 | snapshot.sslError, | |
| 1601 | snapshot.ownershipError, | |
| 1602 | snapshot.subdomainsError, | |
| 1603 | snapshot.redirectChainError, | |
| 1604 | snapshot.ipGeolocationError | |
| 1605 | ] | |
| 1606 | .compactMap { $0?.lowercased() } | |
| 1607 | ||
| 1608 | guard !candidateMessages.isEmpty else { return false } | |
| 1609 | let failedDueToConnectivity = candidateMessages.allSatisfy { message in | |
| 1610 | message.hasPrefix("network error:") || message.hasPrefix("timeout:") || message.hasPrefix("rate limit:") | |
| 1611 | } | |
| 1612 | ||
| 1613 | let hasMaterialData = !snapshot.dnsSections.isEmpty | |
| 1614 | || !snapshot.httpHeaders.isEmpty | |
| 1615 | || snapshot.sslInfo != nil | |
| 1616 | || snapshot.ownership != nil | |
| 1617 | || !snapshot.subdomains.isEmpty | |
| 1618 | ||
| 1619 | return failedDueToConnectivity && !hasMaterialData | |
| 1620 | } | |
| 1621 | ||
| 1622 | 1481 | private func runDNS(domain: String, lookupID: UUID) async { |
| 1623 | 1482 | let result = await DNSLookupService.lookupAll(domain: domain) |
| 1624 | 1483 | guard !Task.isCancelled, isCurrentLookup(lookupID) else { return } |
| @@ -1774,7 +1633,7 @@ final class DomainViewModel { | ||
| 1774 | 1633 | let result = await PortScanService.scanAll(domain: domain) |
| 1775 | 1634 | switch result { |
| 1776 | 1635 | case let .success(results): |
| 1777 | let enrichedResults = await enrichOpenPortBanners(in: results, domain: domain) | |
| 1636 | let enrichedResults = await PortScanService.withBanners(results, host: domain) | |
| 1778 | 1637 | guard !Task.isCancelled, isCurrentLookup(lookupID) else { return } |
| 1779 | 1638 | portScanResults = enrichedResults |
| 1780 | 1639 | portScanError = nil |
| @@ -1833,36 +1692,7 @@ final class DomainViewModel { | ||
| 1833 | 1692 | let inspectionService = DomainInspectionService() |
| 1834 | 1693 | let snapshot = await inspectionService.inspectSnapshot(domain: domain, previousSnapshot: previousSnapshot) |
| 1835 | 1694 | 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)) | |
| 1866 | 1696 | } |
| 1867 | 1697 | |
| 1868 | 1698 | @discardableResult |
| @@ -2840,32 +2670,7 @@ final class DomainViewModel { | ||
| 2840 | 2670 | private func buildAttentionQueue(from domainStates: [PortfolioDomainStatus]) -> [PortfolioAttentionItem] { |
| 2841 | 2671 | domainStates.compactMap { state in |
| 2842 | 2672 | 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) | |
| 2869 | 2674 | return PortfolioAttentionItem( |
| 2870 | 2675 | id: "\(state.trackedDomain.id.uuidString)|\(reason)", |
| 2871 | 2676 | trackedDomainID: state.trackedDomain.id, |
| @@ -2883,6 +2688,32 @@ final class DomainViewModel { | ||
| 2883 | 2688 | } |
| 2884 | 2689 | } |
| 2885 | 2690 | |
| 2691 | /// Why an unhealthy domain needs attention, most urgent cause first, and | |
| 2692 | /// when that cause was last seen. | |
| 2693 | private static func attentionReason(for state: PortfolioDomainStatus) -> (reason: String, timestamp: Date) { | |
| 2694 | let changedAt = state.lastChangeDate ?? state.trackedDomain.updatedAt | |
| 2695 | let failedAt = state.lastMonitoringFailure ?? state.trackedDomain.updatedAt | |
| 2696 | if state.isUnreachable { | |
| 2697 | return ("Endpoint is unreachable", failedAt) | |
| 2698 | } | |
| 2699 | if state.certificateExpiryState == .critical { | |
| 2700 | return ("Certificate is expiring in under 14 days", changedAt) | |
| 2701 | } | |
| 2702 | if state.certificateExpiryState == .warning { | |
| 2703 | return ("Certificate expires within 30 days", changedAt) | |
| 2704 | } | |
| 2705 | if state.recentFailureCount >= 2 || state.instabilityScore >= 70 { | |
| 2706 | return ("Repeated instability detected", failedAt) | |
| 2707 | } | |
| 2708 | if state.recentDNSChange { | |
| 2709 | return ("DNS changed recently", changedAt) | |
| 2710 | } | |
| 2711 | if state.recentCriticalChange { | |
| 2712 | return ("Recent critical change detected", changedAt) | |
| 2713 | } | |
| 2714 | return ("Needs attention", state.trackedDomain.updatedAt) | |
| 2715 | } | |
| 2716 | ||
| 2886 | 2717 | private func buildPortfolioGroups(from domainStates: [PortfolioDomainStatus]) -> [PortfolioGroup] { |
| 2887 | 2718 | Dictionary(grouping: domainStates, by: \.apexDomain) |
| 2888 | 2719 | .map { apexDomain, domains in |
| @@ -3329,40 +3160,10 @@ final class DomainViewModel { | ||
| 3329 | 3160 | ) |
| 3330 | 3161 | } |
| 3331 | 3162 | 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) | |
| 3354 | 3164 | } |
| 3355 | 3165 | 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)) | |
| 3366 | 3167 | } |
| 3367 | 3168 | if let certificateStatus = certificateBadgeLabel(from: snapshot) { |
| 3368 | 3169 | rows.insert( |
| @@ -3377,6 +3178,39 @@ final class DomainViewModel { | ||
| 3377 | 3178 | return rows |
| 3378 | 3179 | } |
| 3379 | 3180 | |
| 3181 | private static func pricingRows(_ pricing: DomainPricingInsight) -> [InfoRowViewData] { | |
| 3182 | var rows = [InfoRowViewData(label: "External Price", value: pricing.estimatedPrice ?? "Unavailable", tone: .secondary)] | |
| 3183 | if let premiumIndicator = pricing.premiumIndicator { | |
| 3184 | rows.append( | |
| 3185 | InfoRowViewData( | |
| 3186 | label: "Premium", | |
| 3187 | value: premiumIndicator ? "Yes" : "No", | |
| 3188 | tone: premiumIndicator ? .warning : .secondary | |
| 3189 | ) | |
| 3190 | ) | |
| 3191 | } | |
| 3192 | if let resaleSignal = pricing.resaleSignal { | |
| 3193 | rows.append(InfoRowViewData(label: "Resale", value: resaleSignal, tone: .secondary)) | |
| 3194 | } | |
| 3195 | if let auctionSignal = pricing.auctionSignal { | |
| 3196 | rows.append(InfoRowViewData(label: "Auction", value: auctionSignal, tone: .secondary)) | |
| 3197 | } | |
| 3198 | return rows | |
| 3199 | } | |
| 3200 | ||
| 3201 | private static func reputationRow(_ reputation: DomainReputationResult) -> InfoRowViewData { | |
| 3202 | let tone: ResultTone | |
| 3203 | switch reputation.status { | |
| 3204 | case .clean: tone = .success | |
| 3205 | case .listed: tone = .failure | |
| 3206 | case .unknown: tone = .secondary | |
| 3207 | } | |
| 3208 | let value = reputation.status == .listed && !reputation.listedSources.isEmpty | |
| 3209 | ? "\(reputation.status.title) (\(reputation.listedSources.joined(separator: ", ")))" | |
| 3210 | : reputation.status.title | |
| 3211 | return InfoRowViewData(label: "Reputation", value: value, tone: tone) | |
| 3212 | } | |
| 3213 | ||
| 3380 | 3214 | static func suggestionRows(from snapshot: LookupSnapshot) -> [DomainSuggestionViewData] { |
| 3381 | 3215 | snapshot.suggestions.map { |
| 3382 | 3216 | DomainSuggestionViewData( |
| @@ -3647,229 +3481,261 @@ final class DomainViewModel { | ||
| 3647 | 3481 | lines.append("Tracking Note: \(note)") |
| 3648 | 3482 | } |
| 3649 | 3483 | |
| 3650 | func appendSection(_ title: String, body: () -> Void) { | |
| 3484 | func appendSection(_ title: String, _ body: [String]) { | |
| 3651 | 3485 | lines.append("") |
| 3652 | 3486 | lines.append(title) |
| 3653 | 3487 | lines.append(String(repeating: "-", count: title.count)) |
| 3654 | body() | |
| 3488 | lines += body | |
| 3655 | 3489 | } |
| 3656 | 3490 | |
| 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)) | |
| 3668 | 3501 | |
| 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)") | |
| 3679 | 3531 | } |
| 3532 | } else { | |
| 3533 | lines.append(" This domain is not currently tracked.") | |
| 3680 | 3534 | } |
| 3535 | return lines | |
| 3536 | } | |
| 3681 | 3537 | |
| 3682 | appendSection("Diff Summary") { | |
| 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")") | |
| 3691 | 3547 | } |
| 3692 | 3548 | } |
| 3693 | 3549 | } |
| 3550 | return lines | |
| 3551 | } | |
| 3694 | 3552 | |
| 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))") | |
| 3706 | 3564 | } |
| 3707 | 3565 | } |
| 3566 | return lines | |
| 3567 | } | |
| 3708 | 3568 | |
| 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)") | |
| 3719 | 3573 | } |
| 3574 | if let ownershipError = snapshot.ownershipError, snapshot.ownership == nil { | |
| 3575 | lines.append(" Source: \(ownershipError)") | |
| 3576 | } | |
| 3577 | if !DataAccessService.hasAccess(to: .ownershipHistory) { | |
| 3578 | lines.append(" Ownership history (coming soon)") | |
| 3579 | } | |
| 3580 | return lines | |
| 3581 | } | |
| 3720 | 3582 | |
| 3721 | appendSection("Subdomains") { | |
| 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)") | |
| 3733 | 3592 | } |
| 3734 | 3593 | } |
| 3594 | if !DataAccessService.hasAccess(to: .extendedSubdomains) { | |
| 3595 | lines.append(" Extended subdomain discovery (Pro+)") | |
| 3596 | } | |
| 3597 | return lines | |
| 3598 | } | |
| 3735 | 3599 | |
| 3736 | appendSection("DNS") { | |
| 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)") | |
| 3763 | 3604 | } |
| 3605 | if let dnssecLabel = dnssecLabel(from: snapshot) { | |
| 3606 | lines.append(" \(dnssecLabel)") | |
| 3607 | } | |
| 3608 | for section in dnsRows(from: snapshot) { | |
| 3609 | lines += exportDNSSectionLines(section) | |
| 3610 | } | |
| 3611 | if let ptrRecord = snapshot.ptrRecord { | |
| 3612 | lines.append(" PTR: \(ptrRecord)") | |
| 3613 | } else if let ptrError = snapshot.ptrError { | |
| 3614 | lines.append(" PTR Error: \(ptrError)") | |
| 3615 | } | |
| 3616 | return lines | |
| 3617 | } | |
| 3764 | 3618 | |
| 3765 | appendSection("Web") { | |
| 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))") | |
| 3772 | 3631 | } |
| 3632 | } | |
| 3633 | return lines | |
| 3634 | } | |
| 3773 | 3635 | |
| 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)") | |
| 3788 | 3647 | } |
| 3648 | } | |
| 3649 | return lines | |
| 3650 | } | |
| 3789 | 3651 | |
| 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)") | |
| 3799 | 3659 | } |
| 3800 | 3660 | } |
| 3661 | lines += exportResponseLines(snapshot) | |
| 3801 | 3662 | |
| 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)" : "")") | |
| 3815 | 3671 | } |
| 3816 | 3672 | } |
| 3673 | return lines | |
| 3674 | } | |
| 3817 | 3675 | |
| 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)") | |
| 3827 | 3688 | } |
| 3828 | 3689 | } |
| 3690 | } | |
| 3691 | return lines | |
| 3692 | } | |
| 3829 | 3693 | |
| 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)") | |
| 3839 | 3701 | } |
| 3702 | } | |
| 3703 | return lines | |
| 3704 | } | |
| 3840 | 3705 | |
| 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)") | |
| 3843 | 3716 | } |
| 3717 | } | |
| 3844 | 3718 | |
| 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)") | |
| 3856 | 3727 | } |
| 3728 | } | |
| 3857 | 3729 | |
| 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)") | |
| 3870 | 3732 | } |
| 3871 | 3733 | |
| 3872 | return lines.joined(separator: "\n") | |
| 3734 | lines.append(" Standard Ports:") | |
| 3735 | lines += exportPortLines(portRows(from: snapshot, kind: .standard)) | |
| 3736 | lines.append(" Custom Ports:") | |
| 3737 | lines += exportPortLines(portRows(from: snapshot, kind: .custom)) | |
| 3738 | return lines | |
| 3873 | 3739 | } |
| 3874 | 3740 | |
| 3875 | 3741 | private static func primaryIPAddress(from snapshot: LookupSnapshot) -> String? { |
DomainDig/ExportPresenter.swift +32
| @@ -30,3 +30,35 @@ enum ExportPresenter { | ||
| 30 | 30 | presenter.present(activityController, animated: true) |
| 31 | 31 | } |
| 32 | 32 | } |
| 33 | ||
| 34 | /// The export menu's entries: text for everyone, the other formats with | |
| 35 | /// advanced exports, and otherwise disabled Pro upsells in their place. | |
| 36 | struct 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 @@ | ||
| 1 | import Foundation | |
| 2 | import Security | |
| 3 | ||
| 4 | /// Secrets kept as generic-password keychain items, keyed by account and | |
| 5 | /// readable after first unlock. | |
| 6 | enum GenericPasswordKeychain { | |
| 7 | /// Replaces any item under `reference`. False when the keychain refuses. | |
| 8 | static func save(_ secret: String, reference: String) -> Bool { | |
| 9 | delete(reference: reference) | |
| 10 | let query: [String: Any] = [ | |
| 11 | kSecClass as String: kSecClassGenericPassword, | |
| 12 | kSecAttrAccount as String: reference, | |
| 13 | kSecValueData as String: Data(secret.utf8), | |
| 14 | kSecAttrAccessible as String: kSecAttrAccessibleAfterFirstUnlock | |
| 15 | ] | |
| 16 | return SecItemAdd(query as CFDictionary, nil) == errSecSuccess | |
| 17 | } | |
| 18 | ||
| 19 | static func secret(reference: String) -> String? { | |
| 20 | let query: [String: Any] = [ | |
| 21 | kSecClass as String: kSecClassGenericPassword, | |
| 22 | kSecAttrAccount as String: reference, | |
| 23 | kSecReturnData as String: true, | |
| 24 | kSecMatchLimit as String: kSecMatchLimitOne | |
| 25 | ] | |
| 26 | var result: CFTypeRef? | |
| 27 | guard SecItemCopyMatching(query as CFDictionary, &result) == errSecSuccess, | |
| 28 | let data = result as? Data else { | |
| 29 | return nil | |
| 30 | } | |
| 31 | return String(data: data, encoding: .utf8) | |
| 32 | } | |
| 33 | ||
| 34 | static func delete(reference: String) { | |
| 35 | let query: [String: Any] = [ | |
| 36 | kSecClass as String: kSecClassGenericPassword, | |
| 37 | kSecAttrAccount as String: reference | |
| 38 | ] | |
| 39 | SecItemDelete(query as CFDictionary) | |
| 40 | } | |
| 41 | } | |
DomainDig/IntegrationService.swift +23 −46
| @@ -646,47 +646,20 @@ private enum HTTPIntegrationClient { | ||
| 646 | 646 | |
| 647 | 647 | private enum IntegrationSecretStore { |
| 648 | 648 | 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 { | |
| 661 | 650 | throw IntegrationError.smtp("Could not save integration secret.") |
| 662 | 651 | } |
| 663 | 652 | } |
| 664 | 653 | |
| 665 | 654 | 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 { | |
| 678 | 656 | throw IntegrationError.missingSecret |
| 679 | 657 | } |
| 680 | ||
| 681 | 658 | return secret |
| 682 | 659 | } |
| 683 | 660 | |
| 684 | 661 | 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) | |
| 690 | 663 | } |
| 691 | 664 | } |
| 692 | 665 | |
| @@ -778,23 +751,12 @@ private actor SMTPChannel { | ||
| 778 | 751 | // from the connection's queue. |
| 779 | 752 | let hasResumed = OSAllocatedUnfairLock(initialState: false) |
| 780 | 753 | 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 | |
| 797 | 758 | } |
| 759 | if isFirst { continuation.resume(with: outcome) } | |
| 798 | 760 | } |
| 799 | 761 | connection.start(queue: .global(qos: .utility)) |
| 800 | 762 | } |
| @@ -803,6 +765,21 @@ private actor SMTPChannel { | ||
| 803 | 765 | startReceiveLoop() |
| 804 | 766 | } |
| 805 | 767 | |
| 768 | /// How a connection state settles `start()`: ready succeeds, failure or | |
| 769 | /// cancellation throws, and anything else is still in progress. | |
| 770 | private static func startOutcome(for state: NWConnection.State) -> Result<Void, Error>? { | |
| 771 | switch state { | |
| 772 | case .ready: | |
| 773 | return .success(()) | |
| 774 | case .failed(let error): | |
| 775 | return .failure(error) | |
| 776 | case .cancelled: | |
| 777 | return .failure(IntegrationError.streamClosed) | |
| 778 | default: | |
| 779 | return nil | |
| 780 | } | |
| 781 | } | |
| 782 | ||
| 806 | 783 | func cancel() { |
| 807 | 784 | connection.cancel() |
| 808 | 785 | } |
DomainDig/Models.swift +1 −15
| @@ -1246,25 +1246,11 @@ struct MonitoringState: Codable, Equatable, Sendable { | ||
| 1246 | 1246 | } |
| 1247 | 1247 | |
| 1248 | 1248 | struct MonitoringPendingAlert: Codable, Identifiable, Equatable, Sendable { |
| 1249 | let id: UUID | |
| 1249 | var id = UUID() | |
| 1250 | 1250 | var detectedAt: Date |
| 1251 | 1251 | var message: String |
| 1252 | 1252 | var severity: MonitoringAlertSeverity |
| 1253 | 1253 | var changeHash: String |
| 1254 | ||
| 1255 | init( | |
| 1256 | id: UUID = UUID(), | |
| 1257 | detectedAt: Date, | |
| 1258 | message: String, | |
| 1259 | severity: MonitoringAlertSeverity, | |
| 1260 | changeHash: String | |
| 1261 | ) { | |
| 1262 | self.id = id | |
| 1263 | self.detectedAt = detectedAt | |
| 1264 | self.message = message | |
| 1265 | self.severity = severity | |
| 1266 | self.changeHash = changeHash | |
| 1267 | } | |
| 1268 | 1254 | } |
| 1269 | 1255 | |
| 1270 | 1256 | |
DomainDig/PortScanService.swift +26
| @@ -74,6 +74,32 @@ struct PortScanService { | ||
| 74 | 74 | .pipe { $0.isEmpty ? .empty("No custom port scan results") : .success($0) } |
| 75 | 75 | } |
| 76 | 76 | |
| 77 | /// `results` with each open port's banner, grabbed concurrently. | |
| 78 | static func withBanners(_ results: [PortScanResult], host: String) async -> [PortScanResult] { | |
| 79 | let banners = await withTaskGroup(of: (UInt16, String?).self, returning: [UInt16: String].self) { group in | |
| 80 | for result in results where result.open { | |
| 81 | group.addTask { | |
| 82 | let banner = await grabBanner(host: host, port: result.port) | |
| 83 | return (result.port, banner) | |
| 84 | } | |
| 85 | } | |
| 86 | ||
| 87 | var collected: [UInt16: String] = [:] | |
| 88 | for await (port, banner) in group { | |
| 89 | if let banner { | |
| 90 | collected[port] = banner | |
| 91 | } | |
| 92 | } | |
| 93 | return collected | |
| 94 | } | |
| 95 | ||
| 96 | return results.map { result in | |
| 97 | var updated = result | |
| 98 | updated.banner = banners[result.port] | |
| 99 | return updated | |
| 100 | } | |
| 101 | } | |
| 102 | ||
| 77 | 103 | static func grabBanner(host: String, port: UInt16, timeout: TimeInterval = 3.0) async -> String? { |
| 78 | 104 | await withCheckedContinuation { continuation in |
| 79 | 105 | guard let nwPort = NWEndpoint.Port(rawValue: port) else { |
DomainDig/ResultSectionViews.swift +154 −124
| @@ -234,43 +234,48 @@ struct OwnershipSectionView: View { | ||
| 234 | 234 | MessageRowView(text: error, isError: error != "Unavailable") |
| 235 | 235 | .padding(.top, 4) |
| 236 | 236 | } |
| 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)) | |
| 272 | 273 | } |
| 273 | 274 | } |
| 275 | } else if let historyError { | |
| 276 | MessageRowView(text: historyError, isError: false) | |
| 277 | } else if showsHistoryPlaceholder { | |
| 278 | MessageRowView(text: "Ownership history available in Pro+", isError: false) | |
| 274 | 279 | } |
| 275 | 280 | } |
| 276 | 281 | } |
| @@ -463,54 +468,69 @@ struct SubdomainsSectionView: View { | ||
| 463 | 468 | .buttonStyle(.bordered) |
| 464 | 469 | .font(appDensity.font(.caption2)) |
| 465 | 470 | } |
| 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()) | |
| 514 | 534 | } |
| 515 | 535 | } |
| 516 | 536 | } |
| @@ -576,21 +596,7 @@ struct DNSSectionView: View { | ||
| 576 | 596 | } else if let sectionError, sections.isEmpty { |
| 577 | 597 | MessageCardView(text: sectionError, isError: true) |
| 578 | 598 | } 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 | |
| 594 | 600 | ForEach(sections) { section in |
| 595 | 601 | CardView { |
| 596 | 602 | Text(section.title) |
| @@ -643,33 +649,57 @@ struct DNSSectionView: View { | ||
| 643 | 649 | .font(appDensity.font(.caption2)) |
| 644 | 650 | } |
| 645 | 651 | } |
| 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) | |
| 668 | 702 | } |
| 669 | } else if let historyError { | |
| 670 | MessageRowView(text: historyError, isError: false) | |
| 671 | } else if showsHistoryPlaceholder { | |
| 672 | MessageRowView(text: "DNS history available in Pro+", isError: false) | |
| 673 | 703 | } |
| 674 | 704 | } |
| 675 | 705 | } |
DomainDig/SSLCheckService.swift +42 −43
| @@ -228,24 +228,15 @@ private enum DERCertificateParser { | ||
| 228 | 228 | while pos < end { |
| 229 | 229 | // Each SET in the issuer |
| 230 | 230 | guard let setTL = readTagAndLength(bytes, offset: pos) else { break } |
| 231 | let setEnd = setTL.contentStart + setTL.length | |
| 231 | pos = setTL.contentStart + setTL.length | |
| 232 | 232 | |
| 233 | 233 | // 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) | |
| 249 | 240 | } |
| 250 | 241 | return nil |
| 251 | 242 | } |
| @@ -260,39 +251,41 @@ private enum DERCertificateParser { | ||
| 260 | 251 | let extEnd = extSeq.contentStart + extSeq.length |
| 261 | 252 | |
| 262 | 253 | // 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) | |
| 290 | 256 | } |
| 291 | 257 | pos = extEnd |
| 292 | 258 | } |
| 293 | 259 | return sans |
| 294 | 260 | } |
| 295 | 261 | |
| 262 | /// The dNSName entries of a subjectAltName extension whose value starts at `valueStart`. | |
| 263 | private static func sanDNSNames(_ bytes: [UInt8], valueStart: Int, extensionEnd: Int) -> [String] { | |
| 264 | var valuePos = valueStart | |
| 265 | // Skip optional critical BOOLEAN | |
| 266 | if valuePos < extensionEnd, bytes[valuePos] == 0x01, | |
| 267 | let boolTL = readTagAndLength(bytes, offset: valuePos) { | |
| 268 | valuePos = boolTL.contentStart + boolTL.length | |
| 269 | } | |
| 270 | // The value is an OCTET STRING wrapping a SEQUENCE of GeneralNames | |
| 271 | guard let octetTL = readTagAndLength(bytes, offset: valuePos), | |
| 272 | let sanSeq = readTagAndLength(bytes, offset: octetTL.contentStart) | |
| 273 | else { return [] } | |
| 274 | ||
| 275 | let sanEnd = sanSeq.contentStart + sanSeq.length | |
| 276 | var sanPos = sanSeq.contentStart | |
| 277 | var names: [String] = [] | |
| 278 | while sanPos < sanEnd { | |
| 279 | guard let nameTL = readTagAndLength(bytes, offset: sanPos) else { break } | |
| 280 | // Context tag [2] = dNSName (IA5String) | |
| 281 | if (bytes[sanPos] & 0x1F) == 2, let name = String(bytes: content(of: nameTL, in: bytes), encoding: .ascii) { | |
| 282 | names.append(name) | |
| 283 | } | |
| 284 | sanPos = nameTL.contentStart + nameTL.length | |
| 285 | } | |
| 286 | return names | |
| 287 | } | |
| 288 | ||
| 296 | 289 | private static func extractValidity(_ bytes: [UInt8], sequenceStart: Int, length: Int) -> (Date?, Date?) { |
| 297 | 290 | let end = sequenceStart + length |
| 298 | 291 | var position = sequenceStart |
| @@ -362,8 +355,14 @@ private enum DERCertificateParser { | ||
| 362 | 355 | length = len |
| 363 | 356 | } |
| 364 | 357 | |
| 358 | // A length past the end of the data is malformed, and slicing to it would trap. | |
| 359 | guard length <= bytes.count - pos else { return nil } | |
| 365 | 360 | return TLV(contentStart: pos, length: length) |
| 366 | 361 | } |
| 362 | ||
| 363 | private static func content(of tlv: TLV, in bytes: [UInt8]) -> ArraySlice<UInt8> { | |
| 364 | bytes[tlv.contentStart..<tlv.contentStart + tlv.length] | |
| 365 | } | |
| 367 | 366 | } |
| 368 | 367 | |
| 369 | 368 | enum SSLError: LocalizedError { |
DomainDig/ScheduledReportService.swift +3 −22
| @@ -31,25 +31,11 @@ struct ScheduledReportSettings: Codable, Equatable { | ||
| 31 | 31 | } |
| 32 | 32 | |
| 33 | 33 | struct ScheduledReportLog: Codable, Identifiable, Equatable { |
| 34 | let id: UUID | |
| 34 | var id = UUID() | |
| 35 | 35 | let generatedAt: Date |
| 36 | 36 | let domainCount: Int |
| 37 | 37 | let format: DomainExportFormat |
| 38 | 38 | let fileName: String |
| 39 | ||
| 40 | init( | |
| 41 | id: UUID = UUID(), | |
| 42 | generatedAt: Date, | |
| 43 | domainCount: Int, | |
| 44 | format: DomainExportFormat, | |
| 45 | fileName: String | |
| 46 | ) { | |
| 47 | self.id = id | |
| 48 | self.generatedAt = generatedAt | |
| 49 | self.domainCount = domainCount | |
| 50 | self.format = format | |
| 51 | self.fileName = fileName | |
| 52 | } | |
| 53 | 39 | } |
| 54 | 40 | |
| 55 | 41 | /// Local, UserDefaults-backed persistence for scheduled-report settings and |
| @@ -245,13 +231,8 @@ final class ScheduledReportScheduler { | ||
| 245 | 231 | private func handleAppRefresh(task: BGAppRefreshTask) { |
| 246 | 232 | _ = syncSchedule() |
| 247 | 233 | |
| 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 | |
| 255 | 236 | } |
| 256 | 237 | } |
| 257 | 238 | #endif |
DomainDig/SettingsViews.swift +16 −35
| @@ -483,41 +483,14 @@ private struct MonitoringSettingsView: View { | ||
| 483 | 483 | ) |
| 484 | 484 | |
| 485 | 485 | 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 | )) | |
| 521 | 494 | } |
| 522 | 495 | |
| 523 | 496 | Picker( |
| @@ -597,6 +570,14 @@ private struct MonitoringSettingsView: View { | ||
| 597 | 570 | } |
| 598 | 571 | } |
| 599 | 572 | |
| 573 | private func hourPicker(_ title: String, selection: Binding<Int>) -> some View { | |
| 574 | Picker(title, selection: selection) { | |
| 575 | ForEach(0..<24, id: \.self) { hour in | |
| 576 | Text(Self.monitoringHourLabel(for: hour)).tag(hour) | |
| 577 | } | |
| 578 | } | |
| 579 | } | |
| 580 | ||
| 600 | 581 | private static func monitoringHourLabel(for hour: Int) -> String { |
| 601 | 582 | let formatter = DateFormatter() |
| 602 | 583 | formatter.dateFormat = "h a" |
DomainDig/WatchlistView.swift +56 −89
| @@ -150,36 +150,7 @@ struct WatchlistView: View { | ||
| 150 | 150 | } |
| 151 | 151 | } |
| 152 | 152 | |
| 153 | Button("Export TXT") { | |
| 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) | |
| 183 | 154 | } label: { |
| 184 | 155 | Image(systemName: "line.3.horizontal.decrease.circle") |
| 185 | 156 | } |
| @@ -313,76 +284,72 @@ struct WatchlistView: View { | ||
| 313 | 284 | } |
| 314 | 285 | .buttonStyle(.plain) |
| 315 | 286 | .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)) | |
| 330 | 291 | } |
| 331 | 292 | .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) | |
| 347 | 296 | } |
| 348 | 297 | .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 | } | |
| 355 | 302 | |
| 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) | |
| 362 | 306 | |
| 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) | |
| 368 | 315 | .disabled(!viewModel.canEdit(trackedDomain)) |
| 369 | 316 | |
| 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) | |
| 376 | 323 | |
| 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") | |
| 383 | 351 | } |
| 384 | 352 | } |
| 385 | .listRowBackground(Color(.appSurface)) | |
| 386 | 353 | } |
| 387 | 354 | |
| 388 | 355 | private var batchSummaryBinding: Binding<BatchSweepSummary?> { |
DomainDig/WorkflowsView.swift +8 −71
| @@ -237,32 +237,7 @@ struct WorkflowDetailView: View { | ||
| 237 | 237 | if latestSummary != nil { |
| 238 | 238 | Toggle("Export all domains", isOn: $includeAllExports) |
| 239 | 239 | 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) | |
| 266 | 241 | } label: { |
| 267 | 242 | Label("Export Results", systemImage: "square.and.arrow.up") |
| 268 | 243 | } |
| @@ -512,56 +487,18 @@ struct WorkflowRunSummaryView: View { | ||
| 512 | 487 | } |
| 513 | 488 | } |
| 514 | 489 | |
| 515 | Section(visibleResults.isEmpty ? "Meaningful Changes" : "Results") { | |
| 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 | ) | |
| 534 | 496 | } |
| 535 | 497 | .navigationTitle("Workflow Summary") |
| 536 | 498 | .toolbar { |
| 537 | 499 | ToolbarItemGroup(placement: .topBarTrailing) { |
| 538 | 500 | 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) | |
| 565 | 502 | } label: { |
| 566 | 503 | Image(systemName: "square.and.arrow.up") |
| 567 | 504 | } |
DomainInspectionService.swift +120 −240
| @@ -19,11 +19,7 @@ struct DomainInspectionService { | ||
| 19 | 19 | let startedAt = Date() |
| 20 | 20 | let resolverDisplayName = DNSLookupService.currentResolverDisplayName() |
| 21 | 21 | 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) | |
| 27 | 23 | |
| 28 | 24 | async let dnsFetch = runtime.dns(domain: normalizedDomain) |
| 29 | 25 | async let availabilityFetch = runtime.availability(domain: normalizedDomain) |
| @@ -37,110 +33,46 @@ struct DomainInspectionService { | ||
| 37 | 33 | let resolvedDNS = await dnsFetch |
| 38 | 34 | DomainDebugLog.debug("Inspection.sectionComplete domain=\(normalizedDomain) section=dns source=\(resolvedDNS.source.rawValue)") |
| 39 | 35 | 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: §ionSources, | |
| 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) | |
| 50 | 38 | |
| 51 | 39 | let availability = await availabilityFetch |
| 52 | 40 | 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: §ionSources, | |
| 59 | provenanceBySection: &provenanceBySection, | |
| 60 | dataSources: &dataSources | |
| 61 | ) | |
| 41 | ledger.track(.availability, source: availability.source) | |
| 62 | 42 | |
| 63 | 43 | let resolvedSSL = await sslFetch |
| 64 | 44 | DomainDebugLog.debug("Inspection.sectionComplete domain=\(normalizedDomain) section=ssl source=\(resolvedSSL.source.rawValue)") |
| 65 | 45 | 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: §ionSources, | |
| 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) | |
| 76 | 48 | |
| 77 | 49 | let hsts = await hstsFetch |
| 78 | 50 | 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: §ionSources, | |
| 85 | provenanceBySection: &provenanceBySection, | |
| 86 | dataSources: &dataSources | |
| 87 | ) | |
| 51 | ledger.track(.hsts, source: hsts.source) | |
| 88 | 52 | |
| 89 | 53 | let http = await httpFetch |
| 90 | 54 | DomainDebugLog.debug("Inspection.sectionComplete domain=\(normalizedDomain) section=http source=\(http.source.rawValue)") |
| 91 | 55 | 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: §ionSources, | |
| 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) | |
| 102 | 58 | |
| 103 | 59 | let resolvedOwnership = await ownershipFetch |
| 104 | 60 | DomainDebugLog.debug("Inspection.sectionComplete domain=\(normalizedDomain) section=ownership source=\(resolvedOwnership.source.rawValue)") |
| 105 | 61 | 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: §ionSources, | |
| 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) | |
| 116 | 64 | |
| 117 | 65 | let redirects = await redirectFetch |
| 118 | 66 | DomainDebugLog.debug("Inspection.sectionComplete domain=\(normalizedDomain) section=redirect source=\(redirects.source.rawValue)") |
| 119 | 67 | 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: §ionSources, | |
| 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) | |
| 130 | 70 | |
| 131 | 71 | let resolvedSubdomains = await subdomainFetch |
| 132 | 72 | DomainDebugLog.debug("Inspection.sectionComplete domain=\(normalizedDomain) section=subdomains source=\(resolvedSubdomains.source.rawValue)") |
| 133 | 73 | 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: §ionSources, | |
| 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) | |
| 144 | 76 | |
| 145 | 77 | let dnsSections = mapServiceResult(dnsResult, emptyValue: []) |
| 146 | 78 | let sslInfo = mapOptionalValueServiceResult(sslResult) |
| @@ -158,85 +90,46 @@ struct DomainInspectionService { | ||
| 158 | 90 | let canReuseDNSDependents = canReuseDependentSections(from: previousSnapshot, dnsSections: dnsSections.value) |
| 159 | 91 | let canReuseIPDependents = canReuseIPBasedSections(from: previousSnapshot, primaryIP: primaryIP) |
| 160 | 92 | |
| 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) | |
| 166 | 95 | } |
| 167 | 96 | let reachabilityResult = normalizeErrors(in: reachabilityOutcome.value) |
| 168 | 97 | 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: §ionSources, | |
| 175 | provenanceBySection: &provenanceBySection, | |
| 176 | dataSources: &dataSources | |
| 177 | ) | |
| 98 | ledger.track(.reachability, source: reachabilityOutcome.source) | |
| 178 | 99 | if hasNetworkTarget { |
| 179 | captureFailure(for: .reachability, result: reachabilityResult, into: &errorDetails) | |
| 100 | ledger.captureFailure(for: .reachability, result: reachabilityResult) | |
| 180 | 101 | } |
| 181 | 102 | let reachabilityResultValue = mapServiceResult(reachabilityResult, emptyValue: []) |
| 182 | 103 | |
| 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) | |
| 188 | 106 | } |
| 189 | 107 | let portScanResult = normalizeErrors(in: portScanOutcome.value) |
| 190 | 108 | 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: §ionSources, | |
| 197 | provenanceBySection: &provenanceBySection, | |
| 198 | dataSources: &dataSources | |
| 199 | ) | |
| 109 | ledger.track(.portScan, source: portScanOutcome.source) | |
| 200 | 110 | if hasNetworkTarget { |
| 201 | captureFailure(for: .portScan, result: portScanResult, into: &errorDetails) | |
| 111 | ledger.captureFailure(for: .portScan, result: portScanResult) | |
| 202 | 112 | } |
| 203 | 113 | let portScanResults = hasNetworkTarget |
| 204 | 114 | ? await mapPortScanResult(portScanResult, domain: normalizedDomain) |
| 205 | 115 | : (value: [], message: nil) |
| 206 | 116 | |
| 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) | |
| 214 | 123 | } |
| 215 | 124 | let normalizedEmailResult = normalizeErrors(in: emailOutcome.value) |
| 216 | 125 | 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: §ionSources, | |
| 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) | |
| 227 | 128 | |
| 228 | 129 | let suggestionsOutcome: CachedLookupResult<[DomainSuggestionResult]> |
| 229 | 130 | if availability.value.status == .registered { |
| 230 | 131 | 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: §ionSources, | |
| 237 | provenanceBySection: &provenanceBySection, | |
| 238 | dataSources: &dataSources | |
| 239 | ) | |
| 132 | ledger.track(.suggestions, source: suggestionsOutcome.source) | |
| 240 | 133 | } else { |
| 241 | 134 | suggestionsOutcome = CachedLookupResult(value: [], source: .live) |
| 242 | 135 | } |
| @@ -244,48 +137,26 @@ struct DomainInspectionService { | ||
| 244 | 137 | let ptrOutcome: CachedLookupResult<ServiceResult<String>>? |
| 245 | 138 | let geoOutcome: CachedLookupResult<ServiceResult<IPGeolocation>>? |
| 246 | 139 | 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: §ionSources, | |
| 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) | |
| 275 | 146 | } |
| 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: §ionSources, | |
| 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) | |
| 288 | 153 | } |
| 154 | ledger.track(.ptr, source: ptr.source) | |
| 155 | ledger.captureFailure(for: .ptr, result: normalizeErrors(in: ptr.value)) | |
| 156 | ledger.track(.ipGeolocation, source: geo.source) | |
| 157 | ledger.captureFailure(for: .ipGeolocation, result: normalizeErrors(in: geo.value)) | |
| 158 | ptrOutcome = ptr | |
| 159 | geoOutcome = geo | |
| 289 | 160 | } else { |
| 290 | 161 | ptrOutcome = nil |
| 291 | 162 | geoOutcome = nil |
| @@ -294,12 +165,12 @@ struct DomainInspectionService { | ||
| 294 | 165 | let emailSecurity = mapOptionalValueServiceResult(normalizedEmailResult) |
| 295 | 166 | let ptrRecord = mapOptionalServiceResult(ptrOutcome.map { normalizeErrors(in: $0.value) }, missingMessage: "No A record available") |
| 296 | 167 | let geolocation = mapOptionalServiceResult(geoOutcome.map { normalizeErrors(in: $0.value) }, missingMessage: "No A record available") |
| 297 | let availabilityConfidence = confidenceForAvailability(result: availability.value, provenance: provenanceBySection[.availability]) | |
| 168 | let availabilityConfidence = confidenceForAvailability(result: availability.value, provenance: ledger.provenanceBySection[.availability]) | |
| 298 | 169 | let ownershipConfidence = confidenceForOwnership(result: ownership.value) |
| 299 | 170 | let subdomainConfidence = confidenceForSubdomains(results: subdomains.value) |
| 300 | 171 | let emailConfidence = confidenceForEmail(result: emailSecurity.value) |
| 301 | 172 | let geolocationConfidence = confidenceForGeolocation(result: geolocation.value) |
| 302 | let validationIssues = validationIssues(for: normalizedDomain, snapshotTimestamp: startedAt, availability: availability.value, dnsSections: dnsSections.value, provenanceBySection: provenanceBySection) | |
| 173 | let validationIssues = validationIssues(for: normalizedDomain, snapshotTimestamp: startedAt, availability: availability.value, dnsSections: dnsSections.value, provenanceBySection: ledger.provenanceBySection) | |
| 303 | 174 | |
| 304 | 175 | let snapshot = LookupSnapshot( |
| 305 | 176 | historyEntryID: nil, |
| @@ -310,14 +181,14 @@ struct DomainInspectionService { | ||
| 310 | 181 | appVersion: AppVersion.current, |
| 311 | 182 | resolverDisplayName: resolverDisplayName, |
| 312 | 183 | resolverURLString: resolverURLString, |
| 313 | dataSources: Array(dataSources).sorted(), | |
| 314 | provenanceBySection: provenanceBySection, | |
| 184 | dataSources: Array(ledger.dataSources).sorted(), | |
| 185 | provenanceBySection: ledger.provenanceBySection, | |
| 315 | 186 | availabilityConfidence: availabilityConfidence, |
| 316 | 187 | ownershipConfidence: ownershipConfidence, |
| 317 | 188 | subdomainConfidence: subdomainConfidence, |
| 318 | 189 | emailSecurityConfidence: emailConfidence, |
| 319 | 190 | geolocationConfidence: geolocationConfidence, |
| 320 | errorDetails: errorDetails, | |
| 191 | errorDetails: ledger.errorDetails, | |
| 321 | 192 | isPartialSnapshot: !validationIssues.isEmpty, |
| 322 | 193 | validationIssues: validationIssues, |
| 323 | 194 | totalLookupDurationMs: Int(Date().timeIntervalSince(startedAt) * 1000), |
| @@ -374,8 +245,8 @@ struct DomainInspectionService { | ||
| 374 | 245 | portScanResults: portScanResults.value, |
| 375 | 246 | portScanError: portScanResults.message, |
| 376 | 247 | 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 }, | |
| 379 | 250 | statusMessage: nil |
| 380 | 251 | ) |
| 381 | 252 | DomainDebugLog.signpostEnd( |
| @@ -396,24 +267,36 @@ struct DomainInspectionService { | ||
| 396 | 267 | .lowercased() ?? domain.lowercased() |
| 397 | 268 | } |
| 398 | 269 | |
| 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) | |
| 413 | 278 | } |
| 279 | return await fetch() | |
| 414 | 280 | } |
| 415 | 281 | |
| 416 | private func provenance( | |
| 282 | /// The previous snapshot's value, or its error, when its section can be | |
| 283 | /// reused; otherwise a fresh lookup. | |
| 284 | private func reusingPrevious<Value>( | |
| 285 | _ value: Value?, | |
| 286 | error: String?, | |
| 287 | when reusable: Bool, | |
| 288 | otherwise fetch: () async -> CachedLookupResult<ServiceResult<Value>> | |
| 289 | ) async -> CachedLookupResult<ServiceResult<Value>> { | |
| 290 | if reusable, let value { | |
| 291 | return CachedLookupResult(value: .success(value), source: .cached) | |
| 292 | } | |
| 293 | if reusable, let error { | |
| 294 | return CachedLookupResult(value: .error(error), source: .cached) | |
| 295 | } | |
| 296 | return await fetch() | |
| 297 | } | |
| 298 | ||
| 299 | fileprivate static func provenance( | |
| 417 | 300 | for section: LookupSectionKind, |
| 418 | 301 | source: LookupResultSource, |
| 419 | 302 | collectedAt: Date, |
| @@ -514,13 +397,13 @@ struct DomainInspectionService { | ||
| 514 | 397 | case let .success(value): |
| 515 | 398 | return .success(value) |
| 516 | 399 | case let .empty(message): |
| 517 | return .empty(classifyFailure(from: message, defaultKind: .unavailable).message) | |
| 400 | return .empty(Self.classifyFailure(from: message, defaultKind: .unavailable).message) | |
| 518 | 401 | case let .error(message): |
| 519 | return .error(classifyFailure(from: message).message) | |
| 402 | return .error(Self.classifyFailure(from: message).message) | |
| 520 | 403 | } |
| 521 | 404 | } |
| 522 | 405 | |
| 523 | private func classifyFailure(from message: String, defaultKind: InspectionErrorKind = .unknown) -> InspectionFailure { | |
| 406 | fileprivate static func classifyFailure(from message: String, defaultKind: InspectionErrorKind = .unknown) -> InspectionFailure { | |
| 524 | 407 | let normalizedMessage = message.trimmingCharacters(in: .whitespacesAndNewlines) |
| 525 | 408 | let lowercasedMessage = normalizedMessage.lowercased() |
| 526 | 409 | if lowercasedMessage.contains("timed out") { |
| @@ -554,21 +437,6 @@ struct DomainInspectionService { | ||
| 554 | 437 | return InspectionFailure(kind: .unknown, message: normalizedMessage.isEmpty ? defaultKind.title : normalizedMessage, details: normalizedMessage) |
| 555 | 438 | } |
| 556 | 439 | |
| 557 | private func captureFailure<Value>( | |
| 558 | for section: LookupSectionKind, | |
| 559 | result: ServiceResult<Value>, | |
| 560 | into errorDetails: inout [LookupSectionKind: InspectionFailure] | |
| 561 | ) { | |
| 562 | switch result { | |
| 563 | case .success: | |
| 564 | return | |
| 565 | case let .empty(message): | |
| 566 | errorDetails[section] = classifyFailure(from: message, defaultKind: .unavailable) | |
| 567 | case let .error(message): | |
| 568 | errorDetails[section] = classifyFailure(from: message) | |
| 569 | } | |
| 570 | } | |
| 571 | ||
| 572 | 440 | private func confidenceForAvailability(result: DomainAvailabilityResult, provenance: SectionProvenance?) -> ConfidenceLevel { |
| 573 | 441 | guard result.status != .unknown else { return .low } |
| 574 | 442 | if provenance?.provider?.localizedCaseInsensitiveContains("rdap.org") == true, result.status == .registered { |
| @@ -678,7 +546,7 @@ struct DomainInspectionService { | ||
| 678 | 546 | private func mapPortScanResult(_ result: ServiceResult<[PortScanResult]>, domain: String) async -> (value: [PortScanResult], message: String?) { |
| 679 | 547 | switch result { |
| 680 | 548 | case let .success(results): |
| 681 | return (await enrichOpenPortBanners(in: results, domain: domain), nil) | |
| 549 | return (await PortScanService.withBanners(results, host: domain), nil) | |
| 682 | 550 | case let .empty(message), let .error(message): |
| 683 | 551 | return ([], message) |
| 684 | 552 | } |
| @@ -716,29 +584,41 @@ struct DomainInspectionService { | ||
| 716 | 584 | ) |
| 717 | 585 | } |
| 718 | 586 | } |
| 587 | } | |
| 719 | 588 | |
| 720 | private func enrichOpenPortBanners(in results: [PortScanResult], domain: String) async -> [PortScanResult] { | |
| 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. | |
| 591 | private 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) | |
| 736 | 611 | } |
| 612 | } | |
| 737 | 613 | |
| 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) | |
| 742 | 622 | } |
| 743 | 623 | } |
| 744 | 624 | } |
DomainReportBuilder.swift +47 −42
| @@ -521,7 +521,8 @@ enum DomainIntelligenceService { | ||
| 521 | 521 | } |
| 522 | 522 | |
| 523 | 523 | private static func inferProvider(from snapshot: LookupSnapshot) -> InferredProviderFingerprint? { |
| 524 | let headerMap = Dictionary(uniqueKeysWithValues: snapshot.httpHeaders.map { ($0.name.lowercased(), $0.value.lowercased()) }) | |
| 524 | // A stored or imported snapshot can repeat a header name in another case. | |
| 525 | let headerMap = Dictionary(snapshot.httpHeaders.map { ($0.name.lowercased(), $0.value.lowercased()) }) { first, _ in first } | |
| 525 | 526 | let dnsProviders = dnsValues(for: .NS, in: snapshot.dnsSections) + dnsValues(for: .CNAME, in: snapshot.dnsSections) |
| 526 | 527 | let issuer = snapshot.sslInfo?.issuer.lowercased() ?? "" |
| 527 | 528 | let org = snapshot.ipGeolocation?.org?.lowercased() ?? "" |
| @@ -626,59 +627,63 @@ enum DomainIntelligenceService { | ||
| 626 | 627 | } |
| 627 | 628 | |
| 628 | 629 | 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] = [:] | |
| 638 | 631 | for snapshot in snapshots { |
| 639 | 632 | let currentHosts = Set((snapshot.subdomains + snapshot.extendedSubdomains).map { $0.hostname.lowercased() }) |
| 640 | 633 | let knownHosts = Set(states.keys).union(currentHosts) |
| 641 | 634 | for host in knownHosts { |
| 642 | 635 | 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) | |
| 653 | 638 | } 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) | |
| 661 | 640 | } |
| 662 | 641 | } |
| 663 | 642 | } |
| 664 | 643 | |
| 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 | |
| 676 | 664 | } |
| 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 | |
| 680 | 670 | } |
| 681 | return lhs.hostname < rhs.hostname | |
| 671 | if lastSeenInPreviousSnapshot != isPresent { | |
| 672 | statusChangeCount += 1 | |
| 673 | } | |
| 674 | lastSeenInPreviousSnapshot = isPresent | |
| 675 | } | |
| 676 | ||
| 677 | func entry(hostname: String) -> SubdomainHistoryEntry { | |
| 678 | SubdomainHistoryEntry( | |
| 679 | hostname: hostname, | |
| 680 | firstSeen: firstSeen, | |
| 681 | lastSeen: lastSeen, | |
| 682 | recurrenceCount: recurrenceCount, | |
| 683 | statusChangeCount: statusChangeCount, | |
| 684 | lastKnownStatus: lastSeenInPreviousSnapshot ? "Active" : "Inactive", | |
| 685 | isEphemeral: recurrenceCount <= 2 || statusChangeCount >= 2 | |
| 686 | ) | |
| 682 | 687 | } |
| 683 | 688 | } |
| 684 | 689 | |
DomainReportExporter.swift +266 −250
| @@ -156,6 +156,25 @@ enum DomainReportExporter { | ||
| 156 | 156 | } |
| 157 | 157 | |
| 158 | 158 | static func text(for report: DomainReport) -> String { |
| 159 | var lines = headerLines(report) | |
| 160 | appendSection("Summary", to: &lines) { summarySection(report) } | |
| 161 | appendSection("Risk", to: &lines) { riskSection(report) } | |
| 162 | appendSection("Insights", to: &lines) { insightsSection(report) } | |
| 163 | appendSection("Ownership", to: &lines) { ownershipSection(report) } | |
| 164 | appendSection("Ownership History", to: &lines) { ownershipHistorySection(report) } | |
| 165 | appendSection("DNS", to: &lines) { dnsSection(report) } | |
| 166 | appendSection("DNS History", to: &lines) { dnsHistorySection(report) } | |
| 167 | appendSection("Web", to: &lines) { webSection(report) } | |
| 168 | appendSection("Email", to: &lines) { emailSection(report) } | |
| 169 | appendSection("Network", to: &lines) { networkSection(report) } | |
| 170 | appendSection("Subdomains", to: &lines) { subdomainsSection(report) } | |
| 171 | appendSection("Pricing", to: &lines) { pricingSection(report) } | |
| 172 | appendSection("Changes", to: &lines) { changesSection(report) } | |
| 173 | return lines.joined(separator: "\n") | |
| 174 | } | |
| 175 | ||
| 176 | /// The report's title block: what was looked up, when, how, and with what caveats. | |
| 177 | private static func headerLines(_ report: DomainReport) -> [String] { | |
| 159 | 178 | var lines = [ |
| 160 | 179 | "DomainDig Report", |
| 161 | 180 | "Domain: \(report.domain)", |
| @@ -183,288 +202,285 @@ enum DomainReportExporter { | ||
| 183 | 202 | if let workflowContext = report.workflowContext { |
| 184 | 203 | lines.append("Workflow Context: \(workflowContext.workflowName ?? workflowContext.source)") |
| 185 | 204 | } |
| 205 | return lines | |
| 206 | } | |
| 186 | 207 | |
| 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 | } | |
| 200 | 221 | |
| 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)") | |
| 213 | 233 | } |
| 214 | return values | |
| 215 | 234 | } |
| 235 | return values | |
| 236 | } | |
| 216 | 237 | |
| 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 | } | |
| 220 | 241 | |
| 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))") | |
| 241 | 255 | } |
| 256 | if let error = report.dns.error, report.ownership == nil { | |
| 257 | ownershipLines.append("Error: \(error)") | |
| 258 | } | |
| 259 | return ownershipLines | |
| 260 | } | |
| 242 | 261 | |
| 243 | appendSection("Ownership History", to: &lines) { | |
| 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"] | |
| 255 | 265 | } |
| 256 | 266 | |
| 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: " | ") | |
| 285 | 273 | } |
| 274 | } | |
| 286 | 275 | |
| 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 | } | |
| 291 | 305 | |
| 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"] | |
| 301 | 309 | } |
| 302 | 310 | |
| 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: " | ") | |
| 348 | 319 | } |
| 320 | } | |
| 349 | 321 | |
| 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)") | |
| 368 | 358 | } |
| 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)" : "")") | |
| 371 | 364 | } |
| 372 | return emailLines | |
| 373 | 365 | } |
| 366 | return webLines | |
| 367 | } | |
| 374 | 368 | |
| 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))") | |
| 403 | 380 | } |
| 381 | if let records = report.email.records { | |
| 382 | emailLines.append("SPF: \(recordLabel(records.spf))") | |
| 383 | emailLines.append("DMARC: \(recordLabel(records.dmarc))") | |
| 384 | emailLines.append("DKIM: \(recordLabel(records.dkim))") | |
| 385 | emailLines.append("BIMI: \(recordLabel(records.bimi))") | |
| 386 | emailLines.append("MTA-STS: \(records.mtaSts?.txtFound == true ? records.mtaSts?.policyMode ?? "found" : "Unavailable")") | |
| 387 | } | |
| 388 | if let error = report.email.error { | |
| 389 | emailLines.append("Error: \(error)") | |
| 390 | } | |
| 391 | return emailLines | |
| 392 | } | |
| 404 | 393 | |
| 405 | appendSection("Subdomains", to: &lines) { | |
| 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 | ) | |
| 421 | 419 | } |
| 422 | return values | |
| 423 | 420 | } |
| 421 | return networkLines | |
| 422 | } | |
| 424 | 423 | |
| 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 | } | |
| 429 | 443 | |
| 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"] | |
| 438 | 447 | } |
| 439 | 448 | |
| 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 | } | |
| 444 | 458 | |
| 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"] | |
| 465 | 462 | } |
| 466 | 463 | |
| 467 | return lines.joined(separator: "\n") | |
| 464 | var values = [ | |
| 465 | "Has Changes: \(changeSummary.hasChanges ? "Yes" : "No")", | |
| 466 | "Severity: \(changeSummary.severity.title)", | |
| 467 | "Impact: \(changeSummary.impactClassification.title)", | |
| 468 | "Inferred Summary: \(changeSummary.message)", | |
| 469 | "Changed Sections: \(changeSummary.changedSections.isEmpty ? "None" : changeSummary.changedSections.joined(separator: ", "))" | |
| 470 | ] | |
| 471 | if let riskScoreDelta = changeSummary.riskScoreDelta { | |
| 472 | values.append("Risk Delta: \(riskScoreDelta >= 0 ? "+" : "")\(riskScoreDelta)") | |
| 473 | } | |
| 474 | if !changeSummary.insights.isEmpty { | |
| 475 | values.append("Insights: \(changeSummary.insights.joined(separator: " | "))") | |
| 476 | } | |
| 477 | if !changeSummary.observedFacts.isEmpty { | |
| 478 | values.append("Observed: \(changeSummary.observedFacts.joined(separator: " | "))") | |
| 479 | } | |
| 480 | if let contextNote = changeSummary.contextNote { | |
| 481 | values.append("Context: \(contextNote)") | |
| 482 | } | |
| 483 | return values | |
| 468 | 484 | } |
| 469 | 485 | |
| 470 | 486 | static func batchText(for reports: [DomainReport], title: String) -> String { |
LocalAPIService.swift +3 −30
| @@ -303,47 +303,20 @@ final class LocalAPIService { | ||
| 303 | 303 | static let reference = "DomainDig.LocalAPI.Token" |
| 304 | 304 | |
| 305 | 305 | 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 { | |
| 318 | 307 | throw LocalAPIServerError.secretPersistenceFailed |
| 319 | 308 | } |
| 320 | 309 | } |
| 321 | 310 | |
| 322 | 311 | 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 { | |
| 335 | 313 | throw LocalAPIServerError.missingSecret |
| 336 | 314 | } |
| 337 | ||
| 338 | 315 | return secret |
| 339 | 316 | } |
| 340 | 317 | |
| 341 | 318 | 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) | |
| 347 | 320 | } |
| 348 | 321 | } |
| 349 | 322 | |
LookupSnapshot.swift +119
| @@ -163,3 +163,122 @@ extension HistoryEntry { | ||
| 163 | 163 | ) |
| 164 | 164 | } |
| 165 | 165 | } |
| 166 | ||
| 167 | extension 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 | } | |