Commit 23128a2989

23128a29894027174cf7343e02a432c7ee6111d7

parent: 4294e59fca

Verified · cmc

cmc <hello@cleberg.net> · 2026-10-23 01:19 UTC

Split inspection, monitoring and view code; share repeated UI

- inspectSnapshot records sections in an InspectionLedger instead of
  threading four inout accumulators through 14 calls; reuse-or-fetch and
  routable-only lookups are helpers.
- Monitoring alert delivery, the SMTP connection's start outcome, and the
  watchlist row's buttons are their own functions.
- ResultSectionViews' nested blocks are named properties.
- Export menus, batch result sections, dashboard domain links, quiet-hour
  pickers, sync last-writer-wins merges and keychain access are shared.

Layout: unified · split

DomainDig/BatchSweepSummaryView.swift +37 −19
@@ -28,25 +28,12 @@ struct BatchSweepSummaryView: View {
2828 Toggle("Show unchanged domains", isOn: $showUnchangedDomains)
2929 }
3030
31 Section(visibleResults.isEmpty ? "Changed Domains" : "Results") {
32 if visibleResults.isEmpty {
33 Text("No domains with changes or warnings")
34 .font(.system(.caption, design: .monospaced))
35 .foregroundStyle(Color(.appTextSecondary))
36 } else {
37 ForEach(visibleResults) { result in
38 if let entry = viewModel.historyEntry(for: result) {
39 NavigationLink {
40 HistoryDetailView(viewModel: viewModel, entry: entry)
41 } label: {
42 BatchResultRowView(result: result)
43 }
44 } else {
45 BatchResultRowView(result: result)
46 }
47 }
48 }
49 }
31 BatchResultsSection(
32 viewModel: viewModel,
33 results: visibleResults,
34 emptyTitle: "Changed Domains",
35 emptyText: "No domains with changes or warnings"
36 )
5037 }
5138 .navigationTitle(summary.source == .watchlistRefresh ? "Sweep Summary" : "Batch Summary")
5239 }
@@ -64,3 +51,34 @@ struct BatchSweepSummaryView: View {
6451 }
6552 }
6653}
54
55/// A batch's results, each opening its history entry where one was saved.
56/// Titled `emptyTitle`, with `emptyText` under it, when nothing is shown.
57struct BatchResultsSection: View {
58 @Bindable var viewModel: DomainViewModel
59 let results: [BatchLookupResult]
60 let emptyTitle: String
61 let emptyText: String
62
63 var body: some View {
64 Section(results.isEmpty ? emptyTitle : "Results") {
65 if results.isEmpty {
66 Text(emptyText)
67 .font(.system(.caption, design: .monospaced))
68 .foregroundStyle(Color(.appTextSecondary))
69 } else {
70 ForEach(results) { result in
71 if let entry = viewModel.historyEntry(for: result) {
72 NavigationLink {
73 HistoryDetailView(viewModel: viewModel, entry: entry)
74 } label: {
75 BatchResultRowView(result: result)
76 }
77 } else {
78 BatchResultRowView(result: result)
79 }
80 }
81 }
82 }
83 }
84}
DomainDig/CloudSyncService.swift +17 −17
@@ -782,34 +782,34 @@ final class CloudSyncService {
782782 _ lhs: [String: SyncedDomainNote],
783783 _ rhs: [String: SyncedDomainNote]
784784 ) -> (notesByDomain: [String: SyncedDomainNote], hadConflict: Bool) {
785 var merged = lhs
786 var hadConflict = false
787
788 for (domain, remoteNote) in rhs {
789 if let localNote = merged[domain], localNote != remoteNote {
790 hadConflict = true
791 merged[domain] = localNote.updatedAt >= remoteNote.updatedAt ? localNote : remoteNote
792 } else {
793 merged[domain] = remoteNote
794 }
795 }
796
797 return (merged, hadConflict)
785 let result = mergeLatest(lhs, rhs, updatedAt: \.updatedAt)
786 return (result.merged, result.hadConflict)
798787 }
799788
800789 private func mergeHistoryMetadata(
801790 _ lhs: [String: SyncedHistoryMetadata],
802791 _ rhs: [String: SyncedHistoryMetadata]
803792 ) -> (historyMetadataByDomain: [String: SyncedHistoryMetadata], hadConflict: Bool) {
793 let result = mergeLatest(lhs, rhs, updatedAt: \.updatedAt)
794 return (result.merged, result.hadConflict)
795 }
796
797 /// `rhs` merged over `lhs` by domain; where both differ, the newer wins
798 /// (the local one on a tie) and the merge reports a conflict.
799 private func mergeLatest<Value: Equatable>(
800 _ lhs: [String: Value],
801 _ rhs: [String: Value],
802 updatedAt: KeyPath<Value, Date>
803 ) -> (merged: [String: Value], hadConflict: Bool) {
804804 var merged = lhs
805805 var hadConflict = false
806806
807 for (domain, remoteMetadata) in rhs {
808 if let localMetadata = merged[domain], localMetadata != remoteMetadata {
807 for (domain, remote) in rhs {
808 if let local = merged[domain], local != remote {
809809 hadConflict = true
810 merged[domain] = localMetadata.updatedAt >= remoteMetadata.updatedAt ? localMetadata : remoteMetadata
810 merged[domain] = local[keyPath: updatedAt] >= remote[keyPath: updatedAt] ? local : remote
811811 } else {
812 merged[domain] = remoteMetadata
812 merged[domain] = remote
813813 }
814814 }
815815
DomainDig/ContentView.swift +2 −52
@@ -566,32 +566,7 @@ struct ContentView: View {
566566 .accessibilityValue(viewModel.isCurrentDomainSaved ? "Saved" : "Not saved")
567567 .accessibilityAddTraits(viewModel.isCurrentDomainSaved ? .isSelected : [])
568568 Menu {
569 Button("Export TXT") {
570 shareSingleResults(format: .text)
571 }
572 if FeatureAccessService.hasAccess(to: .advancedExports) {
573 Button("Export CSV") {
574 shareSingleResults(format: .csv)
575 }
576 Button("Export JSON") {
577 shareSingleResults(format: .json)
578 }
579 Button("Export Markdown") {
580 shareSingleResults(format: .markdown)
581 }
582 Button("Export PDF") {
583 shareSingleResults(format: .pdf)
584 }
585 } else {
586 Button("CSV Export • Available in Pro") { /* Inert: disabled Pro upsell affordance. */ }
587 .disabled(true)
588 Button("JSON Export • Available in Pro") { /* Inert: disabled Pro upsell affordance. */ }
589 .disabled(true)
590 Button("Markdown Export • Available in Pro") { /* Inert: disabled Pro upsell affordance. */ }
591 .disabled(true)
592 Button("PDF Export • Available in Pro") { /* Inert: disabled Pro upsell affordance. */ }
593 .disabled(true)
594 }
569 ExportFormatButtons(share: shareSingleResults)
595570 } label: {
596571 Image(systemName: "square.and.arrow.up")
597572 .font(appDensity.font(.body, design: .default))
@@ -619,32 +594,7 @@ struct ContentView: View {
619594 showingBatchWorkflowSheet = true
620595 }
621596 Divider()
622 Button("Export Batch TXT") {
623 shareBatchResults(format: .text)
624 }
625 if FeatureAccessService.hasAccess(to: .advancedExports) {
626 Button("Export Batch CSV") {
627 shareBatchResults(format: .csv)
628 }
629 Button("Export Batch JSON") {
630 shareBatchResults(format: .json)
631 }
632 Button("Export Batch Markdown") {
633 shareBatchResults(format: .markdown)
634 }
635 Button("Export Batch PDF") {
636 shareBatchResults(format: .pdf)
637 }
638 } else {
639 Button("Batch CSV • Available in Pro") { /* Inert: disabled Pro upsell affordance. */ }
640 .disabled(true)
641 Button("Batch JSON • Available in Pro") { /* Inert: disabled Pro upsell affordance. */ }
642 .disabled(true)
643 Button("Batch Markdown • Available in Pro") { /* Inert: disabled Pro upsell affordance. */ }
644 .disabled(true)
645 Button("Batch PDF • Available in Pro") { /* Inert: disabled Pro upsell affordance. */ }
646 .disabled(true)
647 }
597 ExportFormatButtons(share: shareBatchResults, batch: true)
648598 } label: {
649599 Label("Export", systemImage: "square.and.arrow.up")
650600 .font(appDensity.font(.caption))
DomainDig/DashboardView.swift +17 −14
@@ -84,13 +84,8 @@ struct DashboardView: View {
8484 dashboardEmptyRow("No recent portfolio changes")
8585 } else {
8686 ForEach(viewModel.filteredPortfolioRecentActivity.prefix(8)) { item in
87 if let trackedDomain = viewModel.trackedDomain(withID: item.trackedDomainID) {
88 NavigationLink {
89 TrackedDomainDetailView(viewModel: viewModel, trackedDomain: trackedDomain)
90 } label: {
91 PortfolioActivityRow(item: item)
92 }
93 .buttonStyle(.plain)
87 trackedDomainLink(item.trackedDomainID) {
88 PortfolioActivityRow(item: item)
9489 }
9590 }
9691 }
@@ -102,13 +97,8 @@ struct DashboardView: View {
10297 dashboardEmptyRow("Nothing urgent right now")
10398 } else {
10499 ForEach(viewModel.filteredPortfolioAttentionRequired.prefix(8)) { item in
105 if let trackedDomain = viewModel.trackedDomain(withID: item.trackedDomainID) {
106 NavigationLink {
107 TrackedDomainDetailView(viewModel: viewModel, trackedDomain: trackedDomain)
108 } label: {
109 PortfolioAttentionRow(item: item)
110 }
111 .buttonStyle(.plain)
100 trackedDomainLink(item.trackedDomainID) {
101 PortfolioAttentionRow(item: item)
112102 }
113103 }
114104 }
@@ -271,6 +261,19 @@ struct DashboardView: View {
271261 return AnyShapeStyle(Color(.appSurfaceElevated))
272262 }
273263
264 /// `label`, opening the tracked domain's detail; nothing for a domain no longer tracked.
265 @ViewBuilder
266 private func trackedDomainLink<Label: View>(_ id: UUID, @ViewBuilder label: () -> Label) -> some View {
267 if let trackedDomain = viewModel.trackedDomain(withID: id) {
268 NavigationLink {
269 TrackedDomainDetailView(viewModel: viewModel, trackedDomain: trackedDomain)
270 } label: {
271 label()
272 }
273 .buttonStyle(.plain)
274 }
275 }
276
274277 private func dashboardEmptyRow(_ message: String) -> some View {
275278 Text(message)
276279 .font(appDensity.font(.caption))
DomainDig/DomainMonitoringService.swift +45 −31
@@ -602,38 +602,13 @@ final class DomainMonitoringService {
602602
603603 if settings.alertsEnabled,
604604 alertDescriptor.severity >= settings.alertFilter.minimumSeverity {
605 let pendingAlert = MonitoringPendingAlert(
606 detectedAt: now,
607 message: alertDescriptor.message,
608 severity: alertDescriptor.severity,
609 changeHash: alertDescriptor.changeHash
605 alertsTriggered += await raiseAlert(
606 alertDescriptor,
607 for: &updated,
608 state: &state,
609 deferred: isQuiet || !notificationsAuthorized,
610 now: now
610611 )
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 }
637612 }
638613 }
639614 } else {
@@ -668,6 +643,45 @@ final class DomainMonitoringService {
668643 return (updated, alertsTriggered)
669644 }
670645
646 /// Queues the alert while notifications are deferred; otherwise notifies, folding in
647 /// any queued alerts, and returns the number of notifications sent.
648 private func raiseAlert(
649 _ alertDescriptor: MonitoringAlertDescriptor,
650 for updated: inout TrackedDomain,
651 state: inout MonitoringState,
652 deferred: Bool,
653 now: Date
654 ) async -> Int {
655 let pendingAlert = MonitoringPendingAlert(
656 detectedAt: now,
657 message: alertDescriptor.message,
658 severity: alertDescriptor.severity,
659 changeHash: alertDescriptor.changeHash
660 )
661 let pendingAlerts = deduplicatedPendingAlerts(updated.pendingMonitoringAlerts + [pendingAlert])
662 if deferred {
663 updated.pendingMonitoringAlerts = pendingAlerts
664 return 0
665 }
666
667 if pendingAlerts.count > 1 {
668 await LocalNotificationService.shared.notifyMonitoringSummary(
669 domain: updated.domain,
670 alerts: pendingAlerts
671 )
672 } else {
673 await LocalNotificationService.shared.notifyMonitoringAlert(
674 domain: updated.domain,
675 message: alertDescriptor.message,
676 severity: alertDescriptor.severity
677 )
678 }
679 updated.pendingMonitoringAlerts = []
680 updated.lastAlertAt = now
681 state.lastAlertDate = now
682 return 1
683 }
684
671685 private func deduplicatedPendingAlerts(_ alerts: [MonitoringPendingAlert]) -> [MonitoringPendingAlert] {
672686 var uniqueByHash: [String: MonitoringPendingAlert] = [:]
673687 for alert in alerts {
DomainDig/ExportPresenter.swift +32
@@ -30,3 +30,35 @@ enum ExportPresenter {
3030 presenter.present(activityController, animated: true)
3131 }
3232}
33
34/// The export menu's entries: text for everyone, the other formats with
35/// advanced exports, and otherwise disabled Pro upsells in their place.
36struct ExportFormatButtons: View {
37 let share: (DomainExportFormat) -> Void
38 /// Labels the entries as exporting a batch.
39 var batch = false
40
41 var body: some View {
42 let noun = batch ? " Batch" : ""
43 Button("Export\(noun) TXT") {
44 share(.text)
45 }
46 if FeatureAccessService.hasAccess(to: .advancedExports) {
47 ForEach(Self.advancedFormats, id: \.label) { format in
48 Button("Export\(noun) \(format.label)") {
49 share(format.format)
50 }
51 }
52 } else {
53 ForEach(Self.advancedFormats, id: \.label) { format in
54 // Inert: disabled Pro upsell affordance.
55 Button(batch ? "Batch \(format.label) • Available in Pro" : "\(format.label) Export • Available in Pro") {}
56 .disabled(true)
57 }
58 }
59 }
60
61 private static let advancedFormats: [(label: String, format: DomainExportFormat)] = [
62 ("CSV", .csv), ("JSON", .json), ("Markdown", .markdown), ("PDF", .pdf),
63 ]
64}
DomainDig/GenericPasswordKeychain.swift added +41
@@ -0,0 +1,41 @@
1import Foundation
2import Security
3
4/// Secrets kept as generic-password keychain items, keyed by account and
5/// readable after first unlock.
6enum GenericPasswordKeychain {
7 /// Replaces any item under `reference`. False when the keychain refuses.
8 static func save(_ secret: String, reference: String) -> Bool {
9 delete(reference: reference)
10 let query: [String: Any] = [
11 kSecClass as String: kSecClassGenericPassword,
12 kSecAttrAccount as String: reference,
13 kSecValueData as String: Data(secret.utf8),
14 kSecAttrAccessible as String: kSecAttrAccessibleAfterFirstUnlock
15 ]
16 return SecItemAdd(query as CFDictionary, nil) == errSecSuccess
17 }
18
19 static func secret(reference: String) -> String? {
20 let query: [String: Any] = [
21 kSecClass as String: kSecClassGenericPassword,
22 kSecAttrAccount as String: reference,
23 kSecReturnData as String: true,
24 kSecMatchLimit as String: kSecMatchLimitOne
25 ]
26 var result: CFTypeRef?
27 guard SecItemCopyMatching(query as CFDictionary, &result) == errSecSuccess,
28 let data = result as? Data else {
29 return nil
30 }
31 return String(data: data, encoding: .utf8)
32 }
33
34 static func delete(reference: String) {
35 let query: [String: Any] = [
36 kSecClass as String: kSecClassGenericPassword,
37 kSecAttrAccount as String: reference
38 ]
39 SecItemDelete(query as CFDictionary)
40 }
41}
DomainDig/IntegrationService.swift +23 −46
@@ -646,47 +646,20 @@ private enum HTTPIntegrationClient {
646646
647647private enum IntegrationSecretStore {
648648 static func save(secret: String, reference: String) throws {
649 let data = Data(secret.utf8)
650 try? delete(reference: reference)
651
652 let query: [String: Any] = [
653 kSecClass as String: kSecClassGenericPassword,
654 kSecAttrAccount as String: reference,
655 kSecValueData as String: data,
656 kSecAttrAccessible as String: kSecAttrAccessibleAfterFirstUnlock
657 ]
658
659 let status = SecItemAdd(query as CFDictionary, nil)
660 guard status == errSecSuccess else {
649 guard GenericPasswordKeychain.save(secret, reference: reference) else {
661650 throw IntegrationError.smtp("Could not save integration secret.")
662651 }
663652 }
664653
665654 static func secret(reference: String) throws -> String {
666 let query: [String: Any] = [
667 kSecClass as String: kSecClassGenericPassword,
668 kSecAttrAccount as String: reference,
669 kSecReturnData as String: true,
670 kSecMatchLimit as String: kSecMatchLimitOne
671 ]
672
673 var result: CFTypeRef?
674 let status = SecItemCopyMatching(query as CFDictionary, &result)
675 guard status == errSecSuccess,
676 let data = result as? Data,
677 let secret = String(data: data, encoding: .utf8) else {
655 guard let secret = GenericPasswordKeychain.secret(reference: reference) else {
678656 throw IntegrationError.missingSecret
679657 }
680
681658 return secret
682659 }
683660
684661 static func delete(reference: String) throws {
685 let query: [String: Any] = [
686 kSecClass as String: kSecClassGenericPassword,
687 kSecAttrAccount as String: reference
688 ]
689 SecItemDelete(query as CFDictionary)
662 GenericPasswordKeychain.delete(reference: reference)
690663 }
691664}
692665
@@ -778,23 +751,12 @@ private actor SMTPChannel {
778751 // from the connection's queue.
779752 let hasResumed = OSAllocatedUnfairLock(initialState: false)
780753 connection.stateUpdateHandler = { state in
781 let isFirst: () -> Bool = {
782 hasResumed.withLock { resumed in
783 if resumed { return false }
784 resumed = true
785 return true
786 }
787 }
788 switch state {
789 case .ready:
790 if isFirst() { continuation.resume() }
791 case .failed(let error):
792 if isFirst() { continuation.resume(throwing: error) }
793 case .cancelled:
794 if isFirst() { continuation.resume(throwing: IntegrationError.streamClosed) }
795 default:
796 break
754 guard let outcome = Self.startOutcome(for: state) else { return }
755 let isFirst = hasResumed.withLock { resumed in
756 defer { resumed = true }
757 return !resumed
797758 }
759 if isFirst { continuation.resume(with: outcome) }
798760 }
799761 connection.start(queue: .global(qos: .utility))
800762 }
@@ -803,6 +765,21 @@ private actor SMTPChannel {
803765 startReceiveLoop()
804766 }
805767
768 /// How a connection state settles `start()`: ready succeeds, failure or
769 /// cancellation throws, and anything else is still in progress.
770 private static func startOutcome(for state: NWConnection.State) -> Result<Void, Error>? {
771 switch state {
772 case .ready:
773 return .success(())
774 case .failed(let error):
775 return .failure(error)
776 case .cancelled:
777 return .failure(IntegrationError.streamClosed)
778 default:
779 return nil
780 }
781 }
782
806783 func cancel() {
807784 connection.cancel()
808785 }
DomainDig/ResultSectionViews.swift +154 −124
@@ -234,43 +234,48 @@ struct OwnershipSectionView: View {
234234 MessageRowView(text: error, isError: error != "Unavailable")
235235 .padding(.top, 4)
236236 }
237 VStack(alignment: .leading, spacing: 8) {
238 HStack {
239 Text("History")
240 .font(appDensity.font(.caption))
241 .foregroundStyle(Color(.appTextSecondary))
242 Spacer()
243 if let onLoadHistory, history.isEmpty, !historyLoading, !showsHistoryPlaceholder {
244 Button("Load") {
245 onLoadHistory()
246 }
247 .buttonStyle(.bordered)
248 .font(appDensity.font(.caption2))
249 }
250 }
251 if historyLoading {
252 ProgressView("Loading history…")
253 .appLoadingStyle()
254 } else if !history.isEmpty {
255 ForEach(history) { event in
256 VStack(alignment: .leading, spacing: 3) {
257 Text(event.date.formatted(date: .abbreviated, time: .omitted))
258 .font(appDensity.font(.caption2))
259 .foregroundStyle(Color(.appTextSecondary))
260 Text(event.summary)
261 .font(appDensity.font(.caption))
262 Text(event.source)
263 .font(appDensity.font(.caption2))
264 .foregroundStyle(Color(.appTextSecondary))
265 }
266 }
267 } else if let historyError {
268 MessageRowView(text: historyError, isError: false)
269 } else if showsHistoryPlaceholder {
270 MessageRowView(text: "Ownership history available in Pro+", isError: false)
271 }
237 historyBlock
238 }
239 }
240 }
241 }
242
243 @ViewBuilder
244 private var historyBlock: some View {
245 VStack(alignment: .leading, spacing: 8) {
246 HStack {
247 Text("History")
248 .font(appDensity.font(.caption))
249 .foregroundStyle(Color(.appTextSecondary))
250 Spacer()
251 if let onLoadHistory, history.isEmpty, !historyLoading, !showsHistoryPlaceholder {
252 Button("Load") {
253 onLoadHistory()
254 }
255 .buttonStyle(.bordered)
256 .font(appDensity.font(.caption2))
257 }
258 }
259 if historyLoading {
260 ProgressView("Loading history…")
261 .appLoadingStyle()
262 } else if !history.isEmpty {
263 ForEach(history) { event in
264 VStack(alignment: .leading, spacing: 3) {
265 Text(event.date.formatted(date: .abbreviated, time: .omitted))
266 .font(appDensity.font(.caption2))
267 .foregroundStyle(Color(.appTextSecondary))
268 Text(event.summary)
269 .font(appDensity.font(.caption))
270 Text(event.source)
271 .font(appDensity.font(.caption2))
272 .foregroundStyle(Color(.appTextSecondary))
272273 }
273274 }
275 } else if let historyError {
276 MessageRowView(text: historyError, isError: false)
277 } else if showsHistoryPlaceholder {
278 MessageRowView(text: "Ownership history available in Pro+", isError: false)
274279 }
275280 }
276281 }
@@ -463,54 +468,69 @@ struct SubdomainsSectionView: View {
463468 .buttonStyle(.bordered)
464469 .font(appDensity.font(.caption2))
465470 }
466 if !groups.isEmpty {
467 Text("Groups")
468 .font(appDensity.font(.caption2))
469 .foregroundStyle(Color(.appTextSecondary))
470 ForEach(groups) { group in
471 HStack {
472 Text("\(group.label).*")
473 .font(appDensity.font(.caption))
474 .foregroundStyle(Color(.statusInfo))
475 Spacer()
476 Text("\(group.subdomains.count)")
477 .font(appDensity.font(.caption2))
478 .foregroundStyle(Color(.appTextSecondary))
479 }
480 }
481 }
482 ForEach(rows) { row in
483 HStack(spacing: 8) {
484 Text(row.hostname)
485 .font(appDensity.font(.caption))
486 .foregroundStyle(.primary)
487 .textSelection(.enabled)
488 Spacer()
489 if row.isInteresting {
490 Text("Interesting")
491 .font(.system(.caption2, design: .monospaced))
492 .foregroundStyle(Color(.statusWarning))
493 .padding(.horizontal, 8)
494 .padding(.vertical, 4)
495 .background(Color(.statusWarningSurface))
496 .clipShape(Capsule())
497 }
498 }
499 }
500 if extendedLoading {
501 ProgressView("Loading extended subdomains…")
502 .appLoadingStyle()
503 .padding(.top, 4)
504 } else if extendedCount > 0 {
505 MessageRowView(text: "\(extendedCount) extended results included", isError: false)
506 .padding(.top, 4)
507 } else if let extendedError {
508 MessageRowView(text: extendedError, isError: false)
509 .padding(.top, 4)
510 } else if showsExtendedPlaceholder {
511 MessageRowView(text: "Extended subdomain discovery available in Pro+", isError: false)
512 .padding(.top, 4)
513 }
471 groupList
472 subdomainRows
473 extendedStatus
474 }
475 }
476 }
477 }
478
479 @ViewBuilder
480 private var extendedStatus: some View {
481 if extendedLoading {
482 ProgressView("Loading extended subdomains…")
483 .appLoadingStyle()
484 .padding(.top, 4)
485 } else if extendedCount > 0 {
486 MessageRowView(text: "\(extendedCount) extended results included", isError: false)
487 .padding(.top, 4)
488 } else if let extendedError {
489 MessageRowView(text: extendedError, isError: false)
490 .padding(.top, 4)
491 } else if showsExtendedPlaceholder {
492 MessageRowView(text: "Extended subdomain discovery available in Pro+", isError: false)
493 .padding(.top, 4)
494 }
495 }
496
497 @ViewBuilder
498 private var groupList: some View {
499 if !groups.isEmpty {
500 Text("Groups")
501 .font(appDensity.font(.caption2))
502 .foregroundStyle(Color(.appTextSecondary))
503 ForEach(groups) { group in
504 HStack {
505 Text("\(group.label).*")
506 .font(appDensity.font(.caption))
507 .foregroundStyle(Color(.statusInfo))
508 Spacer()
509 Text("\(group.subdomains.count)")
510 .font(appDensity.font(.caption2))
511 .foregroundStyle(Color(.appTextSecondary))
512 }
513 }
514 }
515 }
516
517 @ViewBuilder
518 private var subdomainRows: some View {
519 ForEach(rows) { row in
520 HStack(spacing: 8) {
521 Text(row.hostname)
522 .font(appDensity.font(.caption))
523 .foregroundStyle(.primary)
524 .textSelection(.enabled)
525 Spacer()
526 if row.isInteresting {
527 Text("Interesting")
528 .font(.system(.caption2, design: .monospaced))
529 .foregroundStyle(Color(.statusWarning))
530 .padding(.horizontal, 8)
531 .padding(.vertical, 4)
532 .background(Color(.statusWarningSurface))
533 .clipShape(Capsule())
514534 }
515535 }
516536 }
@@ -576,21 +596,7 @@ struct DNSSectionView: View {
576596 } else if let sectionError, sections.isEmpty {
577597 MessageCardView(text: sectionError, isError: true)
578598 } else {
579 if dnsProvenance != nil {
580 CardView(allowsHorizontalScroll: false) {
581 SectionTrustMetadataView(provenance: dnsProvenance, confidence: nil)
582 if let patternSummary {
583 if !patternSummary.providers.isEmpty {
584 MessageRowView(text: "Providers: \(patternSummary.providers.joined(separator: ", "))", isError: false)
585 }
586 if !patternSummary.patterns.isEmpty {
587 ForEach(Array(patternSummary.patterns.enumerated()), id: \.offset) { _, pattern in
588 MessageRowView(text: pattern, isError: false)
589 }
590 }
591 }
592 }
593 }
599 provenanceCard
594600 ForEach(sections) { section in
595601 CardView {
596602 Text(section.title)
@@ -643,33 +649,57 @@ struct DNSSectionView: View {
643649 .font(appDensity.font(.caption2))
644650 }
645651 }
646 if historyLoading {
647 ProgressView("Loading DNS history…")
648 .appLoadingStyle()
649 } else if !history.isEmpty {
650 ForEach(history) { event in
651 VStack(alignment: .leading, spacing: 3) {
652 Text(event.date.formatted(date: .abbreviated, time: .omitted))
653 .font(appDensity.font(.caption2))
654 .foregroundStyle(Color(.appTextSecondary))
655 Text(event.summary)
656 .font(appDensity.font(.caption))
657 if !event.aRecords.isEmpty {
658 Text("A: \(event.aRecords.joined(separator: ", "))")
659 .font(appDensity.font(.caption2))
660 .foregroundStyle(Color(.appTextSecondary))
661 }
662 if !event.nameservers.isEmpty {
663 Text("NS: \(event.nameservers.joined(separator: ", "))")
664 .font(appDensity.font(.caption2))
665 .foregroundStyle(Color(.appTextSecondary))
666 }
667 }
652 historyContent
653 }
654 }
655 }
656 }
657
658 @ViewBuilder
659 private var historyContent: some View {
660 if historyLoading {
661 ProgressView("Loading DNS history…")
662 .appLoadingStyle()
663 } else if !history.isEmpty {
664 ForEach(history) { event in
665 VStack(alignment: .leading, spacing: 3) {
666 Text(event.date.formatted(date: .abbreviated, time: .omitted))
667 .font(appDensity.font(.caption2))
668 .foregroundStyle(Color(.appTextSecondary))
669 Text(event.summary)
670 .font(appDensity.font(.caption))
671 if !event.aRecords.isEmpty {
672 Text("A: \(event.aRecords.joined(separator: ", "))")
673 .font(appDensity.font(.caption2))
674 .foregroundStyle(Color(.appTextSecondary))
675 }
676 if !event.nameservers.isEmpty {
677 Text("NS: \(event.nameservers.joined(separator: ", "))")
678 .font(appDensity.font(.caption2))
679 .foregroundStyle(Color(.appTextSecondary))
680 }
681 }
682 }
683 } else if let historyError {
684 MessageRowView(text: historyError, isError: false)
685 } else if showsHistoryPlaceholder {
686 MessageRowView(text: "DNS history available in Pro+", isError: false)
687 }
688 }
689
690 @ViewBuilder
691 private var provenanceCard: some View {
692 if dnsProvenance != nil {
693 CardView(allowsHorizontalScroll: false) {
694 SectionTrustMetadataView(provenance: dnsProvenance, confidence: nil)
695 if let patternSummary {
696 if !patternSummary.providers.isEmpty {
697 MessageRowView(text: "Providers: \(patternSummary.providers.joined(separator: ", "))", isError: false)
698 }
699 if !patternSummary.patterns.isEmpty {
700 ForEach(Array(patternSummary.patterns.enumerated()), id: \.offset) { _, pattern in
701 MessageRowView(text: pattern, isError: false)
668702 }
669 } else if let historyError {
670 MessageRowView(text: historyError, isError: false)
671 } else if showsHistoryPlaceholder {
672 MessageRowView(text: "DNS history available in Pro+", isError: false)
673703 }
674704 }
675705 }
DomainDig/SettingsViews.swift +16 −35
@@ -483,41 +483,14 @@ private struct MonitoringSettingsView: View {
483483 )
484484
485485 if viewModel.monitoringSettings.quietHours != nil {
486 Picker(
487 "Quiet Starts",
488 selection: Binding(
489 get: { quietHoursStart },
490 set: { startHour in
491 viewModel.setMonitoringQuietHours(
492 startHour: startHour,
493 endHour: quietHoursEnd,
494 isEnabled: true
495 )
496 }
497 )
498 ) {
499 ForEach(0..<24, id: \.self) { hour in
500 Text(Self.monitoringHourLabel(for: hour)).tag(hour)
501 }
502 }
503
504 Picker(
505 "Quiet Ends",
506 selection: Binding(
507 get: { quietHoursEnd },
508 set: { endHour in
509 viewModel.setMonitoringQuietHours(
510 startHour: quietHoursStart,
511 endHour: endHour,
512 isEnabled: true
513 )
514 }
515 )
516 ) {
517 ForEach(0..<24, id: \.self) { hour in
518 Text(Self.monitoringHourLabel(for: hour)).tag(hour)
519 }
520 }
486 hourPicker("Quiet Starts", selection: Binding(
487 get: { quietHoursStart },
488 set: { viewModel.setMonitoringQuietHours(startHour: $0, endHour: quietHoursEnd, isEnabled: true) }
489 ))
490 hourPicker("Quiet Ends", selection: Binding(
491 get: { quietHoursEnd },
492 set: { viewModel.setMonitoringQuietHours(startHour: quietHoursStart, endHour: $0, isEnabled: true) }
493 ))
521494 }
522495
523496 Picker(
@@ -597,6 +570,14 @@ private struct MonitoringSettingsView: View {
597570 }
598571 }
599572
573 private func hourPicker(_ title: String, selection: Binding<Int>) -> some View {
574 Picker(title, selection: selection) {
575 ForEach(0..<24, id: \.self) { hour in
576 Text(Self.monitoringHourLabel(for: hour)).tag(hour)
577 }
578 }
579 }
580
600581 private static func monitoringHourLabel(for hour: Int) -> String {
601582 let formatter = DateFormatter()
602583 formatter.dateFormat = "h a"
DomainDig/WatchlistView.swift +56 −89
@@ -150,36 +150,7 @@ struct WatchlistView: View {
150150 }
151151 }
152152
153 Button("Export TXT") {
154 shareTrackedDomains(format: .text)
155 }
156
157 if FeatureAccessService.hasAccess(to: .advancedExports) {
158 Button("Export CSV") {
159 shareTrackedDomains(format: .csv)
160 }
161
162 Button("Export JSON") {
163 shareTrackedDomains(format: .json)
164 }
165
166 Button("Export Markdown") {
167 shareTrackedDomains(format: .markdown)
168 }
169
170 Button("Export PDF") {
171 shareTrackedDomains(format: .pdf)
172 }
173 } else {
174 Button("CSV Export • Available in Pro") { /* Inert: disabled Pro upsell affordance. */ }
175 .disabled(true)
176 Button("JSON Export • Available in Pro") { /* Inert: disabled Pro upsell affordance. */ }
177 .disabled(true)
178 Button("Markdown Export • Available in Pro") { /* Inert: disabled Pro upsell affordance. */ }
179 .disabled(true)
180 Button("PDF Export • Available in Pro") { /* Inert: disabled Pro upsell affordance. */ }
181 .disabled(true)
182 }
153 ExportFormatButtons(share: shareTrackedDomains)
183154 } label: {
184155 Image(systemName: "line.3.horizontal.decrease.circle")
185156 }
@@ -313,76 +284,72 @@ struct WatchlistView: View {
313284 }
314285 .buttonStyle(.plain)
315286 .swipeActions(edge: .leading, allowsFullSwipe: false) {
316 Button {
317 AppHaptics.refresh()
318 viewModel.refreshTrackedDomain(trackedDomain)
319 } label: {
320 Label("Refresh", systemImage: "arrow.clockwise")
321 }
322 .tint(Color(.statusInfo))
323
324 Button {
325 viewModel.togglePinned(for: trackedDomain)
326 } label: {
327 Label(trackedDomain.isPinned ? "Unpin" : "Pin", systemImage: trackedDomain.isPinned ? "pin.slash" : "pin")
328 }
329 .tint(Color(.statusWarning))
287 refreshButton(trackedDomain)
288 .tint(Color(.statusInfo))
289 pinButton(trackedDomain)
290 .tint(Color(.statusWarning))
330291 }
331292 .swipeActions(edge: .trailing, allowsFullSwipe: false) {
332 Button {
333 AppHaptics.refresh()
334 viewModel.refreshTrackedDomain(trackedDomain)
335 } label: {
336 Label("Refresh", systemImage: "arrow.clockwise")
337 }
338 .tint(Color(.statusInfo))
339
340 if viewModel.canDelete(trackedDomain) {
341 Button(role: .destructive) {
342 viewModel.deleteTrackedDomain(trackedDomain)
343 } label: {
344 Label("Delete", systemImage: "trash")
345 }
346 }
293 refreshButton(trackedDomain)
294 .tint(Color(.statusInfo))
295 deleteButton(trackedDomain)
347296 }
348297 .contextMenu {
349 Button {
350 AppHaptics.refresh()
351 viewModel.refreshTrackedDomain(trackedDomain)
352 } label: {
353 Label("Refresh", systemImage: "arrow.clockwise")
354 }
298 rowMenu(trackedDomain)
299 }
300 .listRowBackground(Color(.appSurface))
301 }
355302
356 Button {
357 dismiss()
358 viewModel.rerunInspection(for: trackedDomain)
359 } label: {
360 Label("Open Inspection", systemImage: "magnifyingglass")
361 }
303 @ViewBuilder
304 private func rowMenu(_ trackedDomain: TrackedDomain) -> some View {
305 refreshButton(trackedDomain)
362306
363 Button {
364 viewModel.togglePinned(for: trackedDomain)
365 } label: {
366 Label(trackedDomain.isPinned ? "Unpin" : "Pin", systemImage: trackedDomain.isPinned ? "pin.slash" : "pin")
367 }
307 Button {
308 dismiss()
309 viewModel.rerunInspection(for: trackedDomain)
310 } label: {
311 Label("Open Inspection", systemImage: "magnifyingglass")
312 }
313
314 pinButton(trackedDomain)
368315 .disabled(!viewModel.canEdit(trackedDomain))
369316
370 Button {
371 // The system sharing UI manages participants and permissions.
372 } label: {
373 Label(trackedDomain.collaboration?.isShared == true ? "Shared" : "Private", systemImage: "person.2")
374 }
375 .disabled(true)
317 Button {
318 // The system sharing UI manages participants and permissions.
319 } label: {
320 Label(trackedDomain.collaboration?.isShared == true ? "Shared" : "Private", systemImage: "person.2")
321 }
322 .disabled(true)
376323
377 if viewModel.canDelete(trackedDomain) {
378 Button(role: .destructive) {
379 viewModel.deleteTrackedDomain(trackedDomain)
380 } label: {
381 Label("Delete", systemImage: "trash")
382 }
324 deleteButton(trackedDomain)
325 }
326
327 private func refreshButton(_ trackedDomain: TrackedDomain) -> some View {
328 Button {
329 AppHaptics.refresh()
330 viewModel.refreshTrackedDomain(trackedDomain)
331 } label: {
332 Label("Refresh", systemImage: "arrow.clockwise")
333 }
334 }
335
336 private func pinButton(_ trackedDomain: TrackedDomain) -> some View {
337 Button {
338 viewModel.togglePinned(for: trackedDomain)
339 } label: {
340 Label(trackedDomain.isPinned ? "Unpin" : "Pin", systemImage: trackedDomain.isPinned ? "pin.slash" : "pin")
341 }
342 }
343
344 @ViewBuilder
345 private func deleteButton(_ trackedDomain: TrackedDomain) -> some View {
346 if viewModel.canDelete(trackedDomain) {
347 Button(role: .destructive) {
348 viewModel.deleteTrackedDomain(trackedDomain)
349 } label: {
350 Label("Delete", systemImage: "trash")
383351 }
384352 }
385 .listRowBackground(Color(.appSurface))
386353 }
387354
388355 private var batchSummaryBinding: Binding<BatchSweepSummary?> {
DomainDig/WorkflowsView.swift +8 −71
@@ -237,32 +237,7 @@ struct WorkflowDetailView: View {
237237 if latestSummary != nil {
238238 Toggle("Export all domains", isOn: $includeAllExports)
239239 Menu {
240 Button("Export TXT") {
241 shareWorkflowResults(format: .text)
242 }
243 if FeatureAccessService.hasAccess(to: .advancedExports) {
244 Button("Export CSV") {
245 shareWorkflowResults(format: .csv)
246 }
247 Button("Export JSON") {
248 shareWorkflowResults(format: .json)
249 }
250 Button("Export Markdown") {
251 shareWorkflowResults(format: .markdown)
252 }
253 Button("Export PDF") {
254 shareWorkflowResults(format: .pdf)
255 }
256 } else {
257 Button("CSV Export • Available in Pro") { /* Inert: disabled Pro upsell affordance. */ }
258 .disabled(true)
259 Button("JSON Export • Available in Pro") { /* Inert: disabled Pro upsell affordance. */ }
260 .disabled(true)
261 Button("Markdown Export • Available in Pro") { /* Inert: disabled Pro upsell affordance. */ }
262 .disabled(true)
263 Button("PDF Export • Available in Pro") { /* Inert: disabled Pro upsell affordance. */ }
264 .disabled(true)
265 }
240 ExportFormatButtons(share: shareWorkflowResults)
266241 } label: {
267242 Label("Export Results", systemImage: "square.and.arrow.up")
268243 }
@@ -512,56 +487,18 @@ struct WorkflowRunSummaryView: View {
512487 }
513488 }
514489
515 Section(visibleResults.isEmpty ? "Meaningful Changes" : "Results") {
516 if visibleResults.isEmpty {
517 Text("No domains with meaningful changes or warnings")
518 .font(.system(.caption, design: .monospaced))
519 .foregroundStyle(Color(.appTextSecondary))
520 } else {
521 ForEach(visibleResults) { result in
522 if let entry = viewModel.historyEntry(for: result) {
523 NavigationLink {
524 HistoryDetailView(viewModel: viewModel, entry: entry)
525 } label: {
526 BatchResultRowView(result: result)
527 }
528 } else {
529 BatchResultRowView(result: result)
530 }
531 }
532 }
533 }
490 BatchResultsSection(
491 viewModel: viewModel,
492 results: visibleResults,
493 emptyTitle: "Meaningful Changes",
494 emptyText: "No domains with meaningful changes or warnings"
495 )
534496 }
535497 .navigationTitle("Workflow Summary")
536498 .toolbar {
537499 ToolbarItemGroup(placement: .topBarTrailing) {
538500 Menu {
539 Button("Export TXT") {
540 share(format: .text)
541 }
542 if FeatureAccessService.hasAccess(to: .advancedExports) {
543 Button("Export CSV") {
544 share(format: .csv)
545 }
546 Button("Export JSON") {
547 share(format: .json)
548 }
549 Button("Export Markdown") {
550 share(format: .markdown)
551 }
552 Button("Export PDF") {
553 share(format: .pdf)
554 }
555 } else {
556 Button("CSV Export • Available in Pro") { /* Inert: disabled Pro upsell affordance. */ }
557 .disabled(true)
558 Button("JSON Export • Available in Pro") { /* Inert: disabled Pro upsell affordance. */ }
559 .disabled(true)
560 Button("Markdown Export • Available in Pro") { /* Inert: disabled Pro upsell affordance. */ }
561 .disabled(true)
562 Button("PDF Export • Available in Pro") { /* Inert: disabled Pro upsell affordance. */ }
563 .disabled(true)
564 }
501 ExportFormatButtons(share: share)
565502 } label: {
566503 Image(systemName: "square.and.arrow.up")
567504 }
DomainInspectionService.swift +124 −219
@@ -19,11 +19,7 @@ struct DomainInspectionService {
1919 let startedAt = Date()
2020 let resolverDisplayName = DNSLookupService.currentResolverDisplayName()
2121 let resolverURLString = DNSLookupService.currentResolverURLString()
22 var cachedSections = Set<LookupSectionKind>()
23 var sectionSources: [LookupResultSource] = []
24 var provenanceBySection: [LookupSectionKind: SectionProvenance] = [:]
25 var dataSources = Set<String>()
26 var errorDetails: [LookupSectionKind: InspectionFailure] = [:]
22 var ledger = InspectionLedger(resolverDisplayName: resolverDisplayName)
2723
2824 async let dnsFetch = runtime.dns(domain: normalizedDomain)
2925 async let availabilityFetch = runtime.availability(domain: normalizedDomain)
@@ -37,110 +33,46 @@ struct DomainInspectionService {
3733 let resolvedDNS = await dnsFetch
3834 DomainDebugLog.debug("Inspection.sectionComplete domain=\(normalizedDomain) section=dns source=\(resolvedDNS.source.rawValue)")
3935 let dnsResult = normalizeErrors(in: resolvedDNS.value)
40 track(
41 .dns,
42 source: resolvedDNS.source,
43 provenance: provenance(for: .dns, source: resolvedDNS.source, collectedAt: Date(), resolverDisplayName: resolverDisplayName),
44 cachedSections: &cachedSections,
45 sectionSources: &sectionSources,
46 provenanceBySection: &provenanceBySection,
47 dataSources: &dataSources
48 )
49 captureFailure(for: .dns, result: dnsResult, into: &errorDetails)
36 ledger.track(.dns, source: resolvedDNS.source)
37 ledger.captureFailure(for: .dns, result: dnsResult)
5038
5139 let availability = await availabilityFetch
5240 DomainDebugLog.debug("Inspection.sectionComplete domain=\(normalizedDomain) section=availability source=\(availability.source.rawValue)")
53 track(
54 .availability,
55 source: availability.source,
56 provenance: provenance(for: .availability, source: availability.source, collectedAt: Date(), resolverDisplayName: resolverDisplayName),
57 cachedSections: &cachedSections,
58 sectionSources: &sectionSources,
59 provenanceBySection: &provenanceBySection,
60 dataSources: &dataSources
61 )
41 ledger.track(.availability, source: availability.source)
6242
6343 let resolvedSSL = await sslFetch
6444 DomainDebugLog.debug("Inspection.sectionComplete domain=\(normalizedDomain) section=ssl source=\(resolvedSSL.source.rawValue)")
6545 let sslResult = normalizeErrors(in: resolvedSSL.value)
66 track(
67 .ssl,
68 source: resolvedSSL.source,
69 provenance: provenance(for: .ssl, source: resolvedSSL.source, collectedAt: Date(), resolverDisplayName: resolverDisplayName),
70 cachedSections: &cachedSections,
71 sectionSources: &sectionSources,
72 provenanceBySection: &provenanceBySection,
73 dataSources: &dataSources
74 )
75 captureFailure(for: .ssl, result: sslResult, into: &errorDetails)
46 ledger.track(.ssl, source: resolvedSSL.source)
47 ledger.captureFailure(for: .ssl, result: sslResult)
7648
7749 let hsts = await hstsFetch
7850 DomainDebugLog.debug("Inspection.sectionComplete domain=\(normalizedDomain) section=hsts source=\(hsts.source.rawValue)")
79 track(
80 .hsts,
81 source: hsts.source,
82 provenance: provenance(for: .hsts, source: hsts.source, collectedAt: Date(), resolverDisplayName: resolverDisplayName),
83 cachedSections: &cachedSections,
84 sectionSources: &sectionSources,
85 provenanceBySection: &provenanceBySection,
86 dataSources: &dataSources
87 )
51 ledger.track(.hsts, source: hsts.source)
8852
8953 let http = await httpFetch
9054 DomainDebugLog.debug("Inspection.sectionComplete domain=\(normalizedDomain) section=http source=\(http.source.rawValue)")
9155 let httpResult = normalizeErrors(in: http.value)
92 track(
93 .httpHeaders,
94 source: http.source,
95 provenance: provenance(for: .httpHeaders, source: http.source, collectedAt: Date(), resolverDisplayName: resolverDisplayName),
96 cachedSections: &cachedSections,
97 sectionSources: &sectionSources,
98 provenanceBySection: &provenanceBySection,
99 dataSources: &dataSources
100 )
101 captureFailure(for: .httpHeaders, result: httpResult, into: &errorDetails)
56 ledger.track(.httpHeaders, source: http.source)
57 ledger.captureFailure(for: .httpHeaders, result: httpResult)
10258
10359 let resolvedOwnership = await ownershipFetch
10460 DomainDebugLog.debug("Inspection.sectionComplete domain=\(normalizedDomain) section=ownership source=\(resolvedOwnership.source.rawValue)")
10561 let ownershipResult = normalizeErrors(in: resolvedOwnership.value)
106 track(
107 .ownership,
108 source: resolvedOwnership.source,
109 provenance: provenance(for: .ownership, source: resolvedOwnership.source, collectedAt: Date(), resolverDisplayName: resolverDisplayName),
110 cachedSections: &cachedSections,
111 sectionSources: &sectionSources,
112 provenanceBySection: &provenanceBySection,
113 dataSources: &dataSources
114 )
115 captureFailure(for: .ownership, result: ownershipResult, into: &errorDetails)
62 ledger.track(.ownership, source: resolvedOwnership.source)
63 ledger.captureFailure(for: .ownership, result: ownershipResult)
11664
11765 let redirects = await redirectFetch
11866 DomainDebugLog.debug("Inspection.sectionComplete domain=\(normalizedDomain) section=redirect source=\(redirects.source.rawValue)")
11967 let redirectResult = normalizeErrors(in: redirects.value)
120 track(
121 .redirectChain,
122 source: redirects.source,
123 provenance: provenance(for: .redirectChain, source: redirects.source, collectedAt: Date(), resolverDisplayName: resolverDisplayName),
124 cachedSections: &cachedSections,
125 sectionSources: &sectionSources,
126 provenanceBySection: &provenanceBySection,
127 dataSources: &dataSources
128 )
129 captureFailure(for: .redirectChain, result: redirectResult, into: &errorDetails)
68 ledger.track(.redirectChain, source: redirects.source)
69 ledger.captureFailure(for: .redirectChain, result: redirectResult)
13070
13171 let resolvedSubdomains = await subdomainFetch
13272 DomainDebugLog.debug("Inspection.sectionComplete domain=\(normalizedDomain) section=subdomains source=\(resolvedSubdomains.source.rawValue)")
13373 let subdomainResult = normalizeErrors(in: resolvedSubdomains.value)
134 track(
135 .subdomains,
136 source: resolvedSubdomains.source,
137 provenance: provenance(for: .subdomains, source: resolvedSubdomains.source, collectedAt: Date(), resolverDisplayName: resolverDisplayName),
138 cachedSections: &cachedSections,
139 sectionSources: &sectionSources,
140 provenanceBySection: &provenanceBySection,
141 dataSources: &dataSources
142 )
143 captureFailure(for: .subdomains, result: subdomainResult, into: &errorDetails)
74 ledger.track(.subdomains, source: resolvedSubdomains.source)
75 ledger.captureFailure(for: .subdomains, result: subdomainResult)
14476
14577 let dnsSections = mapServiceResult(dnsResult, emptyValue: [])
14678 let sslInfo = mapOptionalValueServiceResult(sslResult)
@@ -158,85 +90,46 @@ struct DomainInspectionService {
15890 let canReuseDNSDependents = canReuseDependentSections(from: previousSnapshot, dnsSections: dnsSections.value)
15991 let canReuseIPDependents = canReuseIPBasedSections(from: previousSnapshot, primaryIP: primaryIP)
16092
161 let reachabilityOutcome: CachedLookupResult<ServiceResult<[PortReachability]>>
162 if hasNetworkTarget {
163 reachabilityOutcome = await runtime.reachability(domain: normalizedDomain)
164 } else {
165 reachabilityOutcome = CachedLookupResult(value: .empty("No routable address available"), source: .live)
93 let reachabilityOutcome = await whenRoutable(hasNetworkTarget) {
94 await runtime.reachability(domain: normalizedDomain)
16695 }
16796 let reachabilityResult = normalizeErrors(in: reachabilityOutcome.value)
16897 DomainDebugLog.debug("Inspection.sectionComplete domain=\(normalizedDomain) section=reachability hasNetworkTarget=\(hasNetworkTarget) source=\(reachabilityOutcome.source.rawValue)")
169 track(
170 .reachability,
171 source: reachabilityOutcome.source,
172 provenance: provenance(for: .reachability, source: reachabilityOutcome.source, collectedAt: Date(), resolverDisplayName: resolverDisplayName),
173 cachedSections: &cachedSections,
174 sectionSources: &sectionSources,
175 provenanceBySection: &provenanceBySection,
176 dataSources: &dataSources
177 )
98 ledger.track(.reachability, source: reachabilityOutcome.source)
17899 if hasNetworkTarget {
179 captureFailure(for: .reachability, result: reachabilityResult, into: &errorDetails)
100 ledger.captureFailure(for: .reachability, result: reachabilityResult)
180101 }
181102 let reachabilityResultValue = mapServiceResult(reachabilityResult, emptyValue: [])
182103
183 let portScanOutcome: CachedLookupResult<ServiceResult<[PortScanResult]>>
184 if hasNetworkTarget {
185 portScanOutcome = await runtime.portScan(domain: normalizedDomain)
186 } else {
187 portScanOutcome = CachedLookupResult(value: .empty("No routable address available"), source: .live)
104 let portScanOutcome = await whenRoutable(hasNetworkTarget) {
105 await runtime.portScan(domain: normalizedDomain)
188106 }
189107 let portScanResult = normalizeErrors(in: portScanOutcome.value)
190108 DomainDebugLog.debug("Inspection.sectionComplete domain=\(normalizedDomain) section=portScan hasNetworkTarget=\(hasNetworkTarget) source=\(portScanOutcome.source.rawValue)")
191 track(
192 .portScan,
193 source: portScanOutcome.source,
194 provenance: provenance(for: .portScan, source: portScanOutcome.source, collectedAt: Date(), resolverDisplayName: resolverDisplayName),
195 cachedSections: &cachedSections,
196 sectionSources: &sectionSources,
197 provenanceBySection: &provenanceBySection,
198 dataSources: &dataSources
199 )
109 ledger.track(.portScan, source: portScanOutcome.source)
200110 if hasNetworkTarget {
201 captureFailure(for: .portScan, result: portScanResult, into: &errorDetails)
111 ledger.captureFailure(for: .portScan, result: portScanResult)
202112 }
203113 let portScanResults = hasNetworkTarget
204114 ? await mapPortScanResult(portScanResult, domain: normalizedDomain)
205115 : (value: [], message: nil)
206116
207 let emailOutcome: CachedLookupResult<ServiceResult<EmailSecurityResult>>
208 if canReuseDNSDependents, let previousSnapshot, let emailSecurity = previousSnapshot.emailSecurity {
209 emailOutcome = CachedLookupResult(value: .success(emailSecurity), source: .cached)
210 } else if canReuseDNSDependents, let previousSnapshot, let error = previousSnapshot.emailSecurityError {
211 emailOutcome = CachedLookupResult(value: .error(error), source: .cached)
212 } else {
213 emailOutcome = await runtime.email(domain: normalizedDomain, txtRecords: txtRecords)
117 let emailOutcome = await reusingPrevious(
118 previousSnapshot?.emailSecurity,
119 error: previousSnapshot?.emailSecurityError,
120 when: canReuseDNSDependents
121 ) {
122 await runtime.email(domain: normalizedDomain, txtRecords: txtRecords)
214123 }
215124 let normalizedEmailResult = normalizeErrors(in: emailOutcome.value)
216125 DomainDebugLog.debug("Inspection.sectionComplete domain=\(normalizedDomain) section=email source=\(emailOutcome.source.rawValue)")
217 track(
218 .emailSecurity,
219 source: emailOutcome.source,
220 provenance: provenance(for: .emailSecurity, source: emailOutcome.source, collectedAt: Date(), resolverDisplayName: resolverDisplayName),
221 cachedSections: &cachedSections,
222 sectionSources: &sectionSources,
223 provenanceBySection: &provenanceBySection,
224 dataSources: &dataSources
225 )
226 captureFailure(for: .emailSecurity, result: normalizedEmailResult, into: &errorDetails)
126 ledger.track(.emailSecurity, source: emailOutcome.source)
127 ledger.captureFailure(for: .emailSecurity, result: normalizedEmailResult)
227128
228129 let suggestionsOutcome: CachedLookupResult<[DomainSuggestionResult]>
229130 if availability.value.status == .registered {
230131 suggestionsOutcome = await runtime.suggestions(domain: normalizedDomain)
231 track(
232 .suggestions,
233 source: suggestionsOutcome.source,
234 provenance: provenance(for: .suggestions, source: suggestionsOutcome.source, collectedAt: Date(), resolverDisplayName: resolverDisplayName),
235 cachedSections: &cachedSections,
236 sectionSources: &sectionSources,
237 provenanceBySection: &provenanceBySection,
238 dataSources: &dataSources
239 )
132 ledger.track(.suggestions, source: suggestionsOutcome.source)
240133 } else {
241134 suggestionsOutcome = CachedLookupResult(value: [], source: .live)
242135 }
@@ -244,48 +137,26 @@ struct DomainInspectionService {
244137 let ptrOutcome: CachedLookupResult<ServiceResult<String>>?
245138 let geoOutcome: CachedLookupResult<ServiceResult<IPGeolocation>>?
246139 if let primaryIP {
247 if canReuseIPDependents, let previousSnapshot, let ptrRecord = previousSnapshot.ptrRecord {
248 ptrOutcome = CachedLookupResult(value: .success(ptrRecord), source: .cached)
249 } else if canReuseIPDependents, let previousSnapshot, let ptrError = previousSnapshot.ptrError {
250 ptrOutcome = CachedLookupResult(value: .error(ptrError), source: .cached)
251 } else {
252 ptrOutcome = await runtime.ptr(ip: primaryIP, resolverURLString: resolverURLString)
140 let ptr = await reusingPrevious(
141 previousSnapshot?.ptrRecord,
142 error: previousSnapshot?.ptrError,
143 when: canReuseIPDependents
144 ) {
145 await runtime.ptr(ip: primaryIP, resolverURLString: resolverURLString)
253146 }
254
255 if canReuseIPDependents, let previousSnapshot, let ipGeolocation = previousSnapshot.ipGeolocation {
256 geoOutcome = CachedLookupResult(value: .success(ipGeolocation), source: .cached)
257 } else if canReuseIPDependents, let previousSnapshot, let ipGeolocationError = previousSnapshot.ipGeolocationError {
258 geoOutcome = CachedLookupResult(value: .error(ipGeolocationError), source: .cached)
259 } else {
260 geoOutcome = await runtime.ipGeolocation(ip: primaryIP)
261 }
262
263 if let ptrOutcome {
264 let normalizedPTRResult = normalizeErrors(in: ptrOutcome.value)
265 track(
266 .ptr,
267 source: ptrOutcome.source,
268 provenance: provenance(for: .ptr, source: ptrOutcome.source, collectedAt: Date(), resolverDisplayName: resolverDisplayName),
269 cachedSections: &cachedSections,
270 sectionSources: &sectionSources,
271 provenanceBySection: &provenanceBySection,
272 dataSources: &dataSources
273 )
274 captureFailure(for: .ptr, result: normalizedPTRResult, into: &errorDetails)
275 }
276 if let geoOutcome {
277 let normalizedGeoResult = normalizeErrors(in: geoOutcome.value)
278 track(
279 .ipGeolocation,
280 source: geoOutcome.source,
281 provenance: provenance(for: .ipGeolocation, source: geoOutcome.source, collectedAt: Date(), resolverDisplayName: resolverDisplayName),
282 cachedSections: &cachedSections,
283 sectionSources: &sectionSources,
284 provenanceBySection: &provenanceBySection,
285 dataSources: &dataSources
286 )
287 captureFailure(for: .ipGeolocation, result: normalizedGeoResult, into: &errorDetails)
147 let geo = await reusingPrevious(
148 previousSnapshot?.ipGeolocation,
149 error: previousSnapshot?.ipGeolocationError,
150 when: canReuseIPDependents
151 ) {
152 await runtime.ipGeolocation(ip: primaryIP)
288153 }
154 ledger.track(.ptr, source: ptr.source)
155 ledger.captureFailure(for: .ptr, result: normalizeErrors(in: ptr.value))
156 ledger.track(.ipGeolocation, source: geo.source)
157 ledger.captureFailure(for: .ipGeolocation, result: normalizeErrors(in: geo.value))
158 ptrOutcome = ptr
159 geoOutcome = geo
289160 } else {
290161 ptrOutcome = nil
291162 geoOutcome = nil
@@ -294,12 +165,12 @@ struct DomainInspectionService {
294165 let emailSecurity = mapOptionalValueServiceResult(normalizedEmailResult)
295166 let ptrRecord = mapOptionalServiceResult(ptrOutcome.map { normalizeErrors(in: $0.value) }, missingMessage: "No A record available")
296167 let geolocation = mapOptionalServiceResult(geoOutcome.map { normalizeErrors(in: $0.value) }, missingMessage: "No A record available")
297 let availabilityConfidence = confidenceForAvailability(result: availability.value, provenance: provenanceBySection[.availability])
168 let availabilityConfidence = confidenceForAvailability(result: availability.value, provenance: ledger.provenanceBySection[.availability])
298169 let ownershipConfidence = confidenceForOwnership(result: ownership.value)
299170 let subdomainConfidence = confidenceForSubdomains(results: subdomains.value)
300171 let emailConfidence = confidenceForEmail(result: emailSecurity.value)
301172 let geolocationConfidence = confidenceForGeolocation(result: geolocation.value)
302 let validationIssues = validationIssues(for: normalizedDomain, snapshotTimestamp: startedAt, availability: availability.value, dnsSections: dnsSections.value, provenanceBySection: provenanceBySection)
173 let validationIssues = validationIssues(for: normalizedDomain, snapshotTimestamp: startedAt, availability: availability.value, dnsSections: dnsSections.value, provenanceBySection: ledger.provenanceBySection)
303174
304175 let snapshot = LookupSnapshot(
305176 historyEntryID: nil,
@@ -310,14 +181,14 @@ struct DomainInspectionService {
310181 appVersion: AppVersion.current,
311182 resolverDisplayName: resolverDisplayName,
312183 resolverURLString: resolverURLString,
313 dataSources: Array(dataSources).sorted(),
314 provenanceBySection: provenanceBySection,
184 dataSources: Array(ledger.dataSources).sorted(),
185 provenanceBySection: ledger.provenanceBySection,
315186 availabilityConfidence: availabilityConfidence,
316187 ownershipConfidence: ownershipConfidence,
317188 subdomainConfidence: subdomainConfidence,
318189 emailSecurityConfidence: emailConfidence,
319190 geolocationConfidence: geolocationConfidence,
320 errorDetails: errorDetails,
191 errorDetails: ledger.errorDetails,
321192 isPartialSnapshot: !validationIssues.isEmpty,
322193 validationIssues: validationIssues,
323194 totalLookupDurationMs: Int(Date().timeIntervalSince(startedAt) * 1000),
@@ -374,8 +245,8 @@ struct DomainInspectionService {
374245 portScanResults: portScanResults.value,
375246 portScanError: portScanResults.message,
376247 changeSummary: nil,
377 resultSource: aggregateSource(sectionSources),
378 cachedSections: Array(cachedSections).sorted { $0.rawValue < $1.rawValue },
248 resultSource: aggregateSource(ledger.sectionSources),
249 cachedSections: Array(ledger.cachedSections).sorted { $0.rawValue < $1.rawValue },
379250 statusMessage: nil
380251 )
381252 DomainDebugLog.signpostEnd(
@@ -396,24 +267,36 @@ struct DomainInspectionService {
396267 .lowercased() ?? domain.lowercased()
397268 }
398269
399 private func track(
400 _ section: LookupSectionKind,
401 source: LookupResultSource,
402 provenance: SectionProvenance,
403 cachedSections: inout Set<LookupSectionKind>,
404 sectionSources: inout [LookupResultSource],
405 provenanceBySection: inout [LookupSectionKind: SectionProvenance],
406 dataSources: inout Set<String>
407 ) {
408 sectionSources.append(source)
409 provenanceBySection[section] = provenance
410 dataSources.insert(provenance.provider ?? provenance.source)
411 if source != .live {
412 cachedSections.insert(section)
270 /// A lookup that needs an address to reach, or an empty result when the
271 /// domain has none.
272 private func whenRoutable<Value>(
273 _ hasNetworkTarget: Bool,
274 fetch: () async -> CachedLookupResult<ServiceResult<Value>>
275 ) async -> CachedLookupResult<ServiceResult<Value>> {
276 guard hasNetworkTarget else {
277 return CachedLookupResult(value: .empty("No routable address available"), source: .live)
413278 }
279 return await fetch()
280 }
281
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()
414297 }
415298
416 private func provenance(
299 fileprivate static func provenance(
417300 for section: LookupSectionKind,
418301 source: LookupResultSource,
419302 collectedAt: Date,
@@ -514,13 +397,13 @@ struct DomainInspectionService {
514397 case let .success(value):
515398 return .success(value)
516399 case let .empty(message):
517 return .empty(classifyFailure(from: message, defaultKind: .unavailable).message)
400 return .empty(Self.classifyFailure(from: message, defaultKind: .unavailable).message)
518401 case let .error(message):
519 return .error(classifyFailure(from: message).message)
402 return .error(Self.classifyFailure(from: message).message)
520403 }
521404 }
522405
523 private func classifyFailure(from message: String, defaultKind: InspectionErrorKind = .unknown) -> InspectionFailure {
406 fileprivate static func classifyFailure(from message: String, defaultKind: InspectionErrorKind = .unknown) -> InspectionFailure {
524407 let normalizedMessage = message.trimmingCharacters(in: .whitespacesAndNewlines)
525408 let lowercasedMessage = normalizedMessage.lowercased()
526409 if lowercasedMessage.contains("timed out") {
@@ -554,21 +437,6 @@ struct DomainInspectionService {
554437 return InspectionFailure(kind: .unknown, message: normalizedMessage.isEmpty ? defaultKind.title : normalizedMessage, details: normalizedMessage)
555438 }
556439
557 private func captureFailure<Value>(
558 for section: LookupSectionKind,
559 result: ServiceResult<Value>,
560 into errorDetails: inout [LookupSectionKind: InspectionFailure]
561 ) {
562 switch result {
563 case .success:
564 return
565 case let .empty(message):
566 errorDetails[section] = classifyFailure(from: message, defaultKind: .unavailable)
567 case let .error(message):
568 errorDetails[section] = classifyFailure(from: message)
569 }
570 }
571
572440 private func confidenceForAvailability(result: DomainAvailabilityResult, provenance: SectionProvenance?) -> ConfidenceLevel {
573441 guard result.status != .unknown else { return .low }
574442 if provenance?.provider?.localizedCaseInsensitiveContains("rdap.org") == true, result.status == .registered {
@@ -717,3 +585,40 @@ struct DomainInspectionService {
717585 }
718586 }
719587}
588
589/// What an inspection has learned about its sections so far: where each came
590/// from, which were served from cache, and which failed.
591private struct InspectionLedger {
592 let resolverDisplayName: String
593 var cachedSections = Set<LookupSectionKind>()
594 var sectionSources: [LookupResultSource] = []
595 var provenanceBySection: [LookupSectionKind: SectionProvenance] = [:]
596 var dataSources = Set<String>()
597 var errorDetails: [LookupSectionKind: InspectionFailure] = [:]
598
599 mutating func track(_ section: LookupSectionKind, source: LookupResultSource) {
600 let provenance = DomainInspectionService.provenance(
601 for: section,
602 source: source,
603 collectedAt: Date(),
604 resolverDisplayName: resolverDisplayName
605 )
606 sectionSources.append(source)
607 provenanceBySection[section] = provenance
608 dataSources.insert(provenance.provider ?? provenance.source)
609 if source != .live {
610 cachedSections.insert(section)
611 }
612 }
613
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)
622 }
623 }
624}
LocalAPIService.swift +3 −30
@@ -303,47 +303,20 @@ final class LocalAPIService {
303303 static let reference = "DomainDig.LocalAPI.Token"
304304
305305 static func save(secret: String, reference: String) throws {
306 let data = Data(secret.utf8)
307 try? delete(reference: reference)
308
309 let query: [String: Any] = [
310 kSecClass as String: kSecClassGenericPassword,
311 kSecAttrAccount as String: reference,
312 kSecValueData as String: data,
313 kSecAttrAccessible as String: kSecAttrAccessibleAfterFirstUnlock
314 ]
315
316 let status = SecItemAdd(query as CFDictionary, nil)
317 guard status == errSecSuccess else {
306 guard GenericPasswordKeychain.save(secret, reference: reference) else {
318307 throw LocalAPIServerError.secretPersistenceFailed
319308 }
320309 }
321310
322311 static func secret(reference: String) throws -> String {
323 let query: [String: Any] = [
324 kSecClass as String: kSecClassGenericPassword,
325 kSecAttrAccount as String: reference,
326 kSecReturnData as String: true,
327 kSecMatchLimit as String: kSecMatchLimitOne
328 ]
329
330 var result: CFTypeRef?
331 let status = SecItemCopyMatching(query as CFDictionary, &result)
332 guard status == errSecSuccess,
333 let data = result as? Data,
334 let secret = String(data: data, encoding: .utf8) else {
312 guard let secret = GenericPasswordKeychain.secret(reference: reference) else {
335313 throw LocalAPIServerError.missingSecret
336314 }
337
338315 return secret
339316 }
340317
341318 static func delete(reference: String) throws {
342 let query: [String: Any] = [
343 kSecClass as String: kSecClassGenericPassword,
344 kSecAttrAccount as String: reference
345 ]
346 SecItemDelete(query as CFDictionary)
319 GenericPasswordKeychain.delete(reference: reference)
347320 }
348321 }
349322