DomainDig/DomainViewModel.swift
3409 lines · 145023 bytes
1import Foundation
2import SwiftUI
3import UserNotifications
4
5enum ResultTone {
6 case primary
7 case secondary
8 case success
9 case warning
10 case failure
11}
12
13struct SummaryFieldViewData: Identifiable {
14 let id = UUID()
15 let label: String
16 let value: String
17 let tone: ResultTone
18}
19
20/// How VoiceOver should pronounce a row's value.
21///
22/// DNS records, cipher suites, and the like are read as prose by default, which
23/// mangles load-bearing punctuation (`;`, `~`, `_`) and technical tokens. See
24/// `Docs/ACCESSIBILITY.md`.
25enum RowSpeechStyle {
26 /// Normal prose.
27 case plain
28 /// Record values and identifiers: include punctuation, use code heuristics.
29 case technical
30}
31
32struct InfoRowViewData: Identifiable {
33 let id = UUID()
34 let label: String
35 let value: String
36 let tone: ResultTone
37 var speechStyle: RowSpeechStyle = .plain
38}
39
40struct SectionMessageViewData {
41 let text: String
42 let isError: Bool
43}
44
45struct DNSRecordSectionViewData: Identifiable {
46 let id = UUID()
47 let title: String
48 let rows: [InfoRowViewData]
49 let wildcardRows: [InfoRowViewData]
50 let wildcardTitle: String?
51 let message: SectionMessageViewData?
52}
53
54struct EmailRowViewData: Identifiable {
55 let id = UUID()
56 let label: String
57 let status: String
58 let statusTone: ResultTone
59 let detail: String
60 let auxiliaryDetail: String?
61}
62
63struct RedirectHopViewData: Identifiable {
64 let id = UUID()
65 let stepLabel: String
66 let statusCode: String
67 let url: String
68 let isFinal: Bool
69}
70
71struct ReachabilityRowViewData: Identifiable {
72 let id = UUID()
73 let portLabel: String
74 let latencyLabel: String
75 let statusLabel: String
76 let statusTone: ResultTone
77}
78
79struct PortScanRowViewData: Identifiable {
80 let id = UUID()
81 let portLabel: String
82 let service: String
83 let statusLabel: String
84 let statusTone: ResultTone
85 let banner: String?
86 let durationLabel: String?
87}
88
89struct SubdomainRowViewData: Identifiable {
90 let id: String
91 let hostname: String
92 let isInteresting: Bool
93
94 init(hostname: String, isInteresting: Bool) {
95 self.id = hostname
96 self.hostname = hostname
97 self.isInteresting = isInteresting
98 }
99}
100
101struct DomainSuggestionViewData: Identifiable {
102 let id: UUID
103 let domain: String
104 let availabilityStatus: DomainAvailabilityStatus
105 let status: String
106 let tone: ResultTone
107}
108
109private struct BatchLookupPayload {
110 let snapshot: LookupSnapshot
111}
112
113@MainActor
114@Observable
115final class DomainViewModel {
116 var domain: String = ""
117 var bulkInput: String = ""
118 var domainInputError: String?
119
120 // MARK: Section state
121
122 /// Each section's value, phase and error as one stored property, so the
123 /// three are written together or not at all. There were 20 `*Loading`
124 /// flags and 19 `*Error` strings before, independently assignable (A2).
125 ///
126 /// The accessors below keep the names every reader already uses. They are
127 /// a staging layer: the next step is views reading the state directly, as
128 /// the Web and Network slices already do.
129 var dnsState = SectionState<[DNSSection]>()
130 var availabilityState = SectionState<DomainAvailabilityResult>()
131 var suggestionsState = SectionState<[DomainSuggestionResult]>()
132 var sslState = SectionState<SSLCertificateInfo>()
133 var hstsState = SectionState<Bool>()
134 var httpHeadersState = SectionState<[HTTPHeader]>()
135 var reachabilityState = SectionState<[PortReachability]>()
136 var ipGeolocationState = SectionState<IPGeolocation>()
137 var emailSecurityState = SectionState<EmailSecurityResult>()
138 var ownershipState = SectionState<DomainOwnership>()
139 var ownershipHistoryState = SectionState<[DomainOwnershipHistoryEvent]>()
140 var ptrState = SectionState<String>()
141 var redirectChainState = SectionState<[RedirectHop]>()
142 var subdomainsState = SectionState<[DiscoveredSubdomain]>()
143 var extendedSubdomainsState = SectionState<[DiscoveredSubdomain]>()
144 var dnsHistoryState = SectionState<[DNSHistoryEvent]>()
145 var domainPricingState = SectionState<DomainPricingInsight>()
146 var reputationState = SectionState<DomainReputationResult>()
147 var portScanState = SectionState<[PortScanResult]>()
148 var customPortScanState = SectionState<[PortScanResult]>()
149
150 var dnsSections: [DNSSection] { dnsState.items }
151 var dnsLoading: Bool { dnsState.isLoading }
152 var dnsError: String? { dnsState.error }
153
154 var availabilityResult: DomainAvailabilityResult? { availabilityState.value }
155 var availabilityLoading: Bool { availabilityState.isLoading }
156
157 var suggestions: [DomainSuggestionResult] { suggestionsState.items }
158 var suggestionsLoading: Bool { suggestionsState.isLoading }
159
160 var sslInfo: SSLCertificateInfo? { sslState.value }
161 var sslLoading: Bool { sslState.isLoading }
162 var sslError: String? { sslState.error }
163
164 var hstsPreloaded: Bool? { hstsState.value }
165 var hstsLoading: Bool { hstsState.isLoading }
166
167 var httpHeaders: [HTTPHeader] { httpHeadersState.items }
168 var httpHeadersLoading: Bool { httpHeadersState.isLoading }
169 var httpHeadersError: String? { httpHeadersState.error }
170
171 var reachabilityResults: [PortReachability] { reachabilityState.items }
172 var reachabilityLoading: Bool { reachabilityState.isLoading }
173 var reachabilityError: String? { reachabilityState.error }
174
175 var ipGeolocation: IPGeolocation? { ipGeolocationState.value }
176 var ipGeolocationLoading: Bool { ipGeolocationState.isLoading }
177 var ipGeolocationError: String? { ipGeolocationState.error }
178
179 var emailSecurity: EmailSecurityResult? { emailSecurityState.value }
180 var emailSecurityLoading: Bool { emailSecurityState.isLoading }
181 var emailSecurityError: String? { emailSecurityState.error }
182
183 var ownershipResult: DomainOwnership? { ownershipState.value }
184 var ownershipLoading: Bool { ownershipState.isLoading }
185 var ownershipError: String? { ownershipState.error }
186
187 var ownershipHistory: [DomainOwnershipHistoryEvent] { ownershipHistoryState.items }
188 var ownershipHistoryLoading: Bool { ownershipHistoryState.isLoading }
189 var ownershipHistoryError: String? { ownershipHistoryState.error }
190
191 var ptrRecord: String? { ptrState.value }
192 var ptrLoading: Bool { ptrState.isLoading }
193 var ptrError: String? { ptrState.error }
194
195 var redirectChain: [RedirectHop] { redirectChainState.items }
196 var redirectChainLoading: Bool { redirectChainState.isLoading }
197 var redirectChainError: String? { redirectChainState.error }
198
199 var subdomains: [DiscoveredSubdomain] { subdomainsState.items }
200 var subdomainsLoading: Bool { subdomainsState.isLoading }
201 var subdomainsError: String? { subdomainsState.error }
202
203 var extendedSubdomains: [DiscoveredSubdomain] { extendedSubdomainsState.items }
204 var extendedSubdomainsLoading: Bool { extendedSubdomainsState.isLoading }
205 var extendedSubdomainsError: String? { extendedSubdomainsState.error }
206
207 var dnsHistory: [DNSHistoryEvent] { dnsHistoryState.items }
208 var dnsHistoryLoading: Bool { dnsHistoryState.isLoading }
209 var dnsHistoryError: String? { dnsHistoryState.error }
210
211 var domainPricing: DomainPricingInsight? { domainPricingState.value }
212 var domainPricingLoading: Bool { domainPricingState.isLoading }
213 var domainPricingError: String? { domainPricingState.error }
214
215 var reputation: DomainReputationResult? { reputationState.value }
216 var reputationLoading: Bool { reputationState.isLoading }
217 var reputationError: String? { reputationState.error }
218
219 var portScanResults: [PortScanResult] { portScanState.items }
220 var portScanLoading: Bool { portScanState.isLoading }
221 var portScanError: String? { portScanState.error }
222
223 var customPortResults: [PortScanResult] { customPortScanState.items }
224 var customPortScanLoading: Bool { customPortScanState.isLoading }
225 var customPortScanError: String? { customPortScanState.error }
226
227 var httpSecurityGrade: String?
228 var httpStatusCode: Int?
229 var httpResponseTimeMs: Int?
230 var httpProtocol: String?
231 var http3Advertised = false
232
233 var hasRun = false
234 private(set) var searchedDomain: String = ""
235 private(set) var lastLookupDurationMs: Int?
236 private(set) var currentDiffSections: [DomainDiffSection] = []
237 private(set) var currentChangeSummary: DomainChangeSummary?
238 private(set) var ownershipDiff: [DomainDiffItem] = []
239 private(set) var refreshingTrackedDomainID: UUID?
240 private(set) var rerunNavigationToken = UUID()
241 private(set) var batchResults: [BatchLookupResult] = []
242 private(set) var batchLookupSource: BatchLookupSource = .manual
243 private(set) var batchCurrentDomain: String?
244 private(set) var batchCompletedCount = 0
245 private(set) var batchTotalCount = 0
246 private(set) var batchLookupRunning = false
247 var latestBatchSweepSummary: BatchSweepSummary?
248 var latestWorkflowRunSummary: WorkflowRunSummary?
249 private(set) var notificationsAuthorized = false
250
251 private var lookupTask: Task<Void, Never>?
252 private var customPortScanTask: Task<Void, Never>?
253 private var batchTask: Task<Void, Never>?
254 private var activeLookupID = UUID()
255 private var lookupStartedAt: Date?
256 private var activeBatchDomains: [String] = []
257 private var lastBatchStartedAt: Date?
258 var activeWorkflowRunID: UUID?
259 var activeWorkflowRunName: String?
260 private var historyPersistenceSuspended = false
261 private var trackedDomainsPersistenceSuspended = false
262 private var historyPersistenceDirty = false
263 private var trackedDomainsPersistenceDirty = false
264 private let reportBuilder = DomainReportBuilder()
265 private let inspectionService = DomainInspectionService()
266 private(set) var currentResultSource: LookupResultSource = .live
267 private(set) var currentCachedSections: [LookupSectionKind] = []
268 private(set) var currentStatusMessage: String?
269 private(set) var currentSnapshotTimestamp = Date()
270 private(set) var currentHistoryEntryID: UUID?
271 /// The metadata the current lookup produced, in preference to whatever the
272 /// saved entry holds. Nil outside a lookup, when the saved entry is the
273 /// only source there is.
274 private(set) var currentInspectionMetadata: InspectionMetadata?
275 private(set) var currentReport: DomainReport?
276
277 private static let recentSearchesKey = "recentSearches"
278 private static let maxRecent = 20
279 var recentSearches: [String]
280
281
282 private static let trackedDomainsKey = "trackedDomains"
283 private static let legacyWatchedDomainsKey = "watchedDomains"
284 var trackedDomains: [TrackedDomain]
285
286 private static let historyKey = "lookupHistory"
287 var history: [HistoryEntry]
288 var auditSessions: [AuditSession]
289 private static let workflowsKey = "domainWorkflows"
290 var workflows: [DomainWorkflow]
291 var historySearchText = ""
292 var historyDateFilter: HistoryDateFilter = .all
293 var historyChangeFilter: ChangeFilterOption = .all
294 var historySortOption: HistorySortOption = .newest
295 var timelineGrouping: TimelineGroupingOption = .relativeDay
296 var timelineDomainFilter = ""
297 var watchlistSearchText = ""
298 var watchlistFilter: WatchlistFilterOption = .all
299 var watchlistSortOption: WatchlistSortOption = .pinned
300 var watchlistTagFilter: String?
301 var watchlistSavedViews: [WatchlistSavedView]
302 var dashboardSearchText = ""
303 var dashboardFilter: PortfolioFilterOption = .all
304 var monitoringSettings: MonitoringSettings
305 var monitoringLogs: [MonitoringLog]
306 var monitoringRunInProgress = false
307 var monitoringStatusMessage: String?
308 var monitoringNotificationStatus: UNAuthorizationStatus = .notDetermined
309 var dataLifecycleSummary: DataLifecycleSummary
310 var portabilityStatusMessage: String?
311 var upgradePrompt: UpgradePromptContext?
312 var isPaywallPresented = false
313 var selectedSnapshotIDs = Set<UUID>()
314 var activeDomainDiff: DomainDiff?
315 var activeDiffChangeIndex = 0
316
317 private static let historyAutoPruneKey = "historyAutoPrune"
318 var historyAutoPruneOption: HistoryAutoPruneOption
319
320 /// The store every persisted property is read from and written back to.
321 /// Injected so a test can drive the whole lifecycle — history pruning,
322 /// tracking limits, batch state — against a scratch store instead of the
323 /// one the app is using.
324 let defaults: UserDefaults
325
326 /// History lives in files rather than in `defaults`, so the directory is
327 /// injected alongside the store it used to be part of.
328 let historyLocation: HistoryFileStore.Location
329
330 init(
331 defaults: UserDefaults = .standard,
332 historyLocation: HistoryFileStore.Location = .default
333 ) {
334 self.defaults = defaults
335 self.historyLocation = historyLocation
336 recentSearches = DomainDataPortabilityService.loadRecentSearches(defaults: defaults)
337 trackedDomains = DomainViewModel.loadTrackedDomains(defaults: defaults, historyLocation: historyLocation)
338 history = DomainViewModel.loadHistoryEntries(defaults: defaults, historyLocation: historyLocation)
339 auditSessions = DomainDataPortabilityService.loadAuditSessions(defaults: defaults)
340 workflows = DomainViewModel.loadWorkflows(defaults: defaults, historyLocation: historyLocation)
341 watchlistSavedViews = DomainViewModel.loadWatchlistSavedViews(defaults: defaults)
342 monitoringSettings = MonitoringStorage.loadSettings(defaults: defaults)
343 monitoringLogs = MonitoringStorage.loadLogs(defaults: defaults)
344 dataLifecycleSummary = DomainDataPortabilityService.lifecycleSummary(defaults: defaults, historyLocation: historyLocation)
345 historyAutoPruneOption = DomainViewModel.loadHistoryAutoPruneOption(defaults: defaults)
346 }
347
348 var trimmedDomain: String {
349 domain
350 .trimmingCharacters(in: .whitespacesAndNewlines)
351 .replacingOccurrences(of: "https://", with: "")
352 .replacingOccurrences(of: "http://", with: "")
353 .components(separatedBy: "/").first ?? ""
354 }
355
356 var resultsLoaded: Bool {
357 guard hasRun else { return false }
358 return [
359 dnsState.isSettled,
360 availabilityState.isSettled,
361 suggestionsState.isSettled,
362 sslState.isSettled,
363 hstsState.isSettled,
364 httpHeadersState.isSettled,
365 reachabilityState.isSettled,
366 ipGeolocationState.isSettled,
367 emailSecurityState.isSettled,
368 ownershipState.isSettled,
369 ptrState.isSettled,
370 redirectChainState.isSettled,
371 subdomainsState.isSettled,
372 portScanState.isSettled,
373 !customPortScanState.isLoading
374 ].allSatisfy { $0 }
375 }
376
377 /// A single lookup is in flight. `hasRun` is set when one starts and the
378 /// sections settle as they land, so this is the window in which cancelling
379 /// means something — the counterpart to `batchLookupRunning`.
380 var singleLookupRunning: Bool {
381 hasRun && !resultsLoaded
382 }
383
384 var activeLoadingLabels: [String] {
385 var labels: [String] = []
386 if availabilityLoading { labels.append("Availability") }
387 if dnsLoading { labels.append("DNS") }
388 if sslLoading || hstsLoading { labels.append("TLS") }
389 if httpHeadersLoading { labels.append("HTTP") }
390 if ownershipLoading { labels.append("Ownership") }
391 if ownershipHistoryLoading { labels.append("Ownership History") }
392 if emailSecurityLoading { labels.append("Email") }
393 if subdomainsLoading { labels.append("Subdomains") }
394 if extendedSubdomainsLoading { labels.append("Extended Subdomains") }
395 if dnsHistoryLoading { labels.append("DNS History") }
396 if domainPricingLoading { labels.append("Pricing") }
397 if redirectChainLoading { labels.append("Redirects") }
398 if reachabilityLoading { labels.append("Reachability") }
399 if ipGeolocationLoading { labels.append("Geolocation") }
400 if ptrLoading { labels.append("PTR") }
401 if portScanLoading { labels.append("Port Scan") }
402 if customPortScanLoading { labels.append("Custom Ports") }
403 return labels
404 }
405
406 var isCloudflareProxied: Bool {
407 httpHeaders.contains { $0.name.lowercased() == "cf-ray" }
408 }
409
410 var sortedTrackedDomains: [TrackedDomain] {
411 sortedTrackedDomains(from: trackedDomains, using: .pinned)
412 }
413
414 var filteredHistory: [HistoryEntry] {
415 let calendar = Calendar.current
416 let now = Date()
417 let query = historySearchText.trimmingCharacters(in: .whitespacesAndNewlines)
418
419 return history
420 .lazy
421 .filter { entry in
422 query.isEmpty || entry.domain.localizedCaseInsensitiveContains(query)
423 }
424 .filter { entry in
425 switch self.historyDateFilter {
426 case .today:
427 return calendar.isDate(entry.timestamp, inSameDayAs: now)
428 case .last7Days:
429 guard let startDate = calendar.date(byAdding: .day, value: -7, to: now) else { return true }
430 return entry.timestamp >= startDate
431 case .all:
432 return true
433 }
434 }
435 .filter { entry in
436 switch self.historyChangeFilter {
437 case .all:
438 return true
439 case .changed:
440 return entry.changeSummary?.hasChanges == true
441 case .unchanged:
442 return entry.changeSummary?.hasChanges != true
443 }
444 }
445 .sorted(by: historySortPredicate)
446 }
447
448 var filteredTrackedDomains: [TrackedDomain] {
449 let query = watchlistSearchText.trimmingCharacters(in: .whitespacesAndNewlines)
450 let filtered = trackedDomains.filter { trackedDomain in
451 if !query.isEmpty, !trackedDomain.domain.localizedCaseInsensitiveContains(query) {
452 return false
453 }
454
455 if let watchlistTagFilter, !trackedDomain.tags.contains(watchlistTagFilter) {
456 return false
457 }
458
459 switch watchlistFilter {
460 case .all:
461 return true
462 case .pinnedOnly:
463 return trackedDomain.isPinned
464 case .changedOnly:
465 return trackedDomain.lastChangeSummary?.hasChanges == true
466 }
467 }
468
469 return sortedTrackedDomains(from: filtered, using: watchlistSortOption)
470 }
471
472 /// Builds the dashboard. Uncached, deliberately: the cache this replaces
473 /// was keyed on a signature of every tracked domain, the last 250 history
474 /// rows and the last 100 monitoring logs, built with
475 /// `.formatted(.number.precision(.fractionLength(3)))` — roughly 350
476 /// interpolations per access, and the dashboard reads this more than twenty
477 /// times per render, so checking the cache cost far more than the build it
478 /// was avoiding (A4).
479 ///
480 /// Callers that need it more than once should read it once and filter with
481 /// `filtered(by:searchText:)`, which is what `DashboardView` does.
482 var portfolioDashboardData: PortfolioDashboardData {
483 let domainStates = buildPortfolioDomainStates()
484 let recentActivity = buildPortfolioActivity(from: domainStates)
485 let attentionRequired = buildAttentionQueue(from: domainStates)
486 let expiringSoon = domainStates
487 .filter { $0.certificateExpiryState != .none }
488 .sorted {
489 ($0.certificateDaysRemaining ?? .max, $0.trackedDomain.domain)
490 < ($1.certificateDaysRemaining ?? .max, $1.trackedDomain.domain)
491 }
492 let groups = PortfolioDashboardData.groups(from: domainStates)
493 let snapshot = PortfolioSnapshot(
494 totalDomains: domainStates.count,
495 healthyCount: domainStates.filter { $0.health == .healthy }.count,
496 warningCount: domainStates.filter { $0.health == .warning }.count,
497 criticalCount: domainStates.filter { $0.health == .critical }.count,
498 changedLast24h: domainStates.filter {
499 guard let lastChangeDate = $0.lastChangeDate else { return false }
500 return Date().timeIntervalSince(lastChangeDate) <= 24 * 60 * 60
501 }.count,
502 expiringSoonCount: expiringSoon.count,
503 unreachableCount: domainStates.filter(\.isUnreachable).count
504 )
505 return PortfolioDashboardData(
506 snapshot: snapshot,
507 domainStates: domainStates,
508 recentActivity: recentActivity,
509 attentionRequired: attentionRequired,
510 expiringSoon: expiringSoon,
511 groups: groups
512 )
513 }
514
515 var timelineDomains: [String] {
516 let query = timelineDomainFilter.trimmingCharacters(in: .whitespacesAndNewlines)
517 let domains = history.map(\.domain)
518 let filtered = query.isEmpty
519 ? domains
520 : domains.filter { $0.localizedCaseInsensitiveContains(query) }
521 return Array(Set(filtered)).sorted()
522 }
523
524 var batchProgressLabel: String {
525 guard batchTotalCount > 0 else { return "No active batch" }
526 if !batchLookupRunning, batchCompletedCount >= batchTotalCount {
527 return "\(batchCompletedCount)/\(batchTotalCount) • Complete"
528 }
529 let domainLabel = activeBatchDomains.first ?? batchCurrentDomain ?? "Preparing"
530 return "\(batchCompletedCount)/\(batchTotalCount) • \(domainLabel)"
531 }
532
533 var currentBatchResultEntries: [HistoryEntry] {
534 batchResults.compactMap { result in
535 guard let historyEntryID = result.historyEntryID else { return nil }
536 return history.first(where: { $0.id == historyEntryID })
537 }
538 }
539
540 var currentTrackedDomain: TrackedDomain? {
541 guard !searchedDomain.isEmpty else { return nil }
542 return trackedDomain(for: searchedDomain)
543 }
544
545 var currentDomainWorkflows: [DomainWorkflow] {
546 guard !searchedDomain.isEmpty else { return [] }
547 return workflowsContaining(domain: searchedDomain)
548 }
549
550 var isCurrentDomainTracked: Bool {
551 currentTrackedDomain != nil
552 }
553
554 var trackingLimitMessage: String? {
555 FeatureAccessService.trackedDomainLimitMessage(currentCount: trackedDomains.count)
556 }
557
558 var canTrackCurrentDomain: Bool {
559 FeatureAccessService.canAddTrackedDomain(currentCount: trackedDomains.count)
560 }
561
562 var resolverDisplayName: String {
563 DNSLookupService.currentResolverDisplayName()
564 }
565
566 var resolverURLString: String {
567 DNSLookupService.currentResolverURLString()
568 }
569
570 var allPortScanResults: [PortScanResult] {
571 (portScanResults + customPortResults).sorted {
572 if $0.kind == $1.kind {
573 return $0.port < $1.port
574 }
575 return $0.kind == .standard
576 }
577 }
578
579 var currentSnapshot: LookupSnapshot {
580 LookupSnapshot(
581 historyEntryID: currentHistoryEntryID,
582 domain: searchedDomain,
583 timestamp: currentSnapshotTimestamp,
584 trackedDomainID: currentTrackedDomain?.id,
585 note: currentHistoryEntry?.note ?? currentTrackedDomain?.note,
586 appVersion: AppVersion.current,
587 resolverDisplayName: resolverDisplayName,
588 resolverURLString: resolverURLString,
589 dataSources: currentInspectionMetadata?.dataSources ?? currentHistoryEntry?.dataSources ?? [],
590 provenanceBySection: currentInspectionMetadata?.provenanceBySection ?? currentHistoryEntry?.provenanceBySection ?? [:],
591 availabilityConfidence: currentInspectionMetadata?.availabilityConfidence ?? currentHistoryEntry?.availabilityConfidence,
592 ownershipConfidence: currentInspectionMetadata?.ownershipConfidence ?? currentHistoryEntry?.ownershipConfidence,
593 subdomainConfidence: currentInspectionMetadata?.subdomainConfidence ?? currentHistoryEntry?.subdomainConfidence,
594 emailSecurityConfidence: currentInspectionMetadata?.emailSecurityConfidence ?? currentHistoryEntry?.emailSecurityConfidence,
595 geolocationConfidence: currentInspectionMetadata?.geolocationConfidence ?? currentHistoryEntry?.geolocationConfidence,
596 errorDetails: currentInspectionMetadata?.errorDetails ?? currentHistoryEntry?.errorDetails ?? [:],
597 isPartialSnapshot: currentInspectionMetadata?.isPartialSnapshot ?? currentHistoryEntry?.isPartialSnapshot ?? false,
598 validationIssues: currentInspectionMetadata?.validationIssues ?? currentHistoryEntry?.validationIssues ?? [],
599 totalLookupDurationMs: lastLookupDurationMs,
600 snapshotIndex: currentInspectionMetadata?.snapshotIndex ?? currentHistoryEntry?.snapshotIndex,
601 previousSnapshotID: currentInspectionMetadata?.previousSnapshotID ?? currentHistoryEntry?.previousSnapshotID,
602 changeCount: currentHistoryEntry?.changeCount ?? currentChangeSummary?.changedSections.count ?? 0,
603 severitySummary: currentHistoryEntry?.severitySummary ?? currentChangeSummary?.severity,
604 dnsSections: dnsSections,
605 dnsError: dnsError,
606 availabilityResult: availabilityResult,
607 suggestions: suggestions,
608 sslInfo: sslInfo,
609 sslError: sslError,
610 hstsPreloaded: hstsPreloaded,
611 httpHeaders: httpHeaders,
612 httpSecurityGrade: httpSecurityGrade,
613 httpStatusCode: httpStatusCode,
614 httpResponseTimeMs: httpResponseTimeMs,
615 httpProtocol: httpProtocol,
616 http3Advertised: http3Advertised,
617 httpHeadersError: httpHeadersError,
618 reachabilityResults: reachabilityResults,
619 reachabilityError: reachabilityError,
620 ipGeolocation: ipGeolocation,
621 ipGeolocationError: ipGeolocationError,
622 emailSecurity: emailSecurity,
623 emailSecurityError: emailSecurityError,
624 ownership: ownershipResult,
625 ownershipError: ownershipError,
626 ownershipHistory: ownershipHistory,
627 ownershipHistoryError: ownershipHistoryError,
628 inferredProvider: currentHistoryEntry?.inferredProvider ?? currentReport?.inferredProvider,
629 priorProviders: currentHistoryEntry?.priorProviders ?? currentReport?.priorProviders ?? [],
630 domainClassification: currentHistoryEntry?.domainClassification ?? currentReport?.domainClassification,
631 ownershipTransitions: currentHistoryEntry?.ownershipTransitions ?? currentReport?.ownershipTransitions ?? [],
632 hostingTransitions: currentHistoryEntry?.hostingTransitions ?? currentReport?.hostingTransitions ?? [],
633 subdomainHistory: currentHistoryEntry?.subdomainHistory ?? currentReport?.subdomainHistory ?? [],
634 riskSignals: currentHistoryEntry?.riskSignals ?? currentReport?.riskSignals ?? [],
635 intelligenceTimeline: currentHistoryEntry?.intelligenceTimeline ?? currentReport?.intelligenceTimeline ?? [],
636 ptrRecord: ptrRecord,
637 ptrError: ptrError,
638 redirectChain: redirectChain,
639 redirectChainError: redirectChainError,
640 subdomains: subdomains,
641 subdomainsError: subdomainsError,
642 extendedSubdomains: extendedSubdomains,
643 extendedSubdomainsError: extendedSubdomainsError,
644 dnsHistory: dnsHistory,
645 dnsHistoryError: dnsHistoryError,
646 domainPricing: domainPricing,
647 domainPricingError: domainPricingError,
648 reputation: reputation,
649 reputationError: reputationError,
650 portScanResults: allPortScanResults,
651 portScanError: combinedPortScanError,
652 changeSummary: currentChangeSummary,
653 resultSource: currentResultSource,
654 cachedSections: currentCachedSections,
655 statusMessage: currentStatusMessage
656 )
657 }
658
659 private var currentHistoryEntry: HistoryEntry? {
660 guard let currentHistoryEntryID else { return nil }
661 return history.first(where: { $0.id == currentHistoryEntryID })
662 }
663
664 var currentRiskAssessment: DomainRiskAssessment? {
665 currentReport?.riskAssessment
666 }
667
668 var currentInsights: [String] {
669 currentReport?.insights ?? []
670 }
671
672 var currentSubdomainGroups: [SubdomainGroup] {
673 currentReport?.subdomainGroups ?? []
674 }
675
676 var currentDNSPatterns: DNSPatternSummary? {
677 currentReport?.dns.patternSummary
678 }
679
680 var currentEmailAssessment: EmailSecuritySummary? {
681 currentReport?.email
682 }
683
684 var currentTLSSummary: WebResultSummary? {
685 currentReport?.web
686 }
687
688 var combinedSubdomains: [DiscoveredSubdomain] {
689 let existingHosts = Set(subdomains.map { $0.hostname.lowercased() })
690 return subdomains + extendedSubdomains.filter { !existingHosts.contains($0.hostname.lowercased()) }
691 }
692
693 var summaryFields: [SummaryFieldViewData] {
694 Self.summaryFields(from: currentSnapshot)
695 }
696
697 var domainRows: [InfoRowViewData] {
698 Self.domainRows(from: currentSnapshot)
699 }
700
701 var dnsRows: [DNSRecordSectionViewData] {
702 Self.dnsRows(from: currentSnapshot)
703 }
704
705 var suggestionRows: [DomainSuggestionViewData] {
706 Self.suggestionRows(from: currentSnapshot)
707 }
708
709 var dnssecLabel: String? {
710 Self.dnssecLabel(from: currentSnapshot)
711 }
712
713 var ptrMessage: SectionMessageViewData? {
714 Self.ptrMessage(from: currentSnapshot)
715 }
716
717 /// The same two slices built from a stored snapshot, for the history
718 /// detail view. Nothing is in flight there, so every panel is settled.
719 static func webSectionData(from snapshot: LookupSnapshot, report: DomainReport) -> WebSectionViewData {
720 WebSectionViewData(
721 tls: SectionPanelViewData(
722 error: snapshot.sslError,
723 provenance: snapshot.provenanceBySection[.ssl]
724 ),
725 certificateRows: webCertificateRows(from: snapshot),
726 sslInfo: snapshot.sslInfo,
727 tlsSummary: report.web,
728 http: SectionPanelViewData(
729 error: snapshot.httpHeadersError,
730 provenance: snapshot.provenanceBySection[.httpHeaders]
731 ),
732 responseRows: webResponseRows(from: snapshot),
733 headers: snapshot.httpHeaders,
734 redirect: SectionPanelViewData(
735 error: snapshot.redirectChainError,
736 provenance: snapshot.provenanceBySection[.redirectChain]
737 ),
738 redirectRows: redirectRows(from: snapshot),
739 finalURL: snapshot.redirectChain.last?.url
740 )
741 }
742
743 static func networkSectionData(from snapshot: LookupSnapshot) -> NetworkSectionViewData {
744 NetworkSectionViewData(
745 reachability: SectionPanelViewData(
746 error: snapshot.reachabilityError,
747 provenance: snapshot.provenanceBySection[.reachability]
748 ),
749 reachabilityRows: reachabilityRows(from: snapshot),
750 location: SectionPanelViewData(
751 error: snapshot.ipGeolocationError,
752 provenance: snapshot.provenanceBySection[.ipGeolocation],
753 confidence: snapshot.geolocationConfidence
754 ),
755 locationRows: locationRows(from: snapshot),
756 geolocation: snapshot.ipGeolocation,
757 portScan: SectionPanelViewData(
758 error: snapshot.portScanError,
759 provenance: snapshot.provenanceBySection[.portScan]
760 ),
761 standardPortRows: portRows(from: snapshot, kind: .standard),
762 customPortRows: portRows(from: snapshot, kind: .custom),
763 isCloudflareProxied: snapshot.httpHeaders.contains { $0.name.lowercased() == "cf-ray" }
764 )
765 }
766
767 /// Everything the Web section draws, assembled in one place. The call
768 /// site used to name seventeen arguments and had to keep their order
769 /// straight; this groups them by the card they belong to (A10).
770 var webSectionData: WebSectionViewData {
771 WebSectionViewData(
772 tls: SectionPanelViewData(
773 isLoading: sslLoading || hstsLoading,
774 error: sslError,
775 provenance: currentSnapshot.provenanceBySection[.ssl]
776 ),
777 certificateRows: webCertificateRows,
778 sslInfo: sslInfo,
779 tlsSummary: currentTLSSummary,
780 http: SectionPanelViewData(
781 isLoading: httpHeadersLoading,
782 error: httpHeadersError,
783 provenance: currentSnapshot.provenanceBySection[.httpHeaders]
784 ),
785 responseRows: webResponseRows,
786 headers: httpHeaders,
787 redirect: SectionPanelViewData(
788 isLoading: redirectChainLoading,
789 error: redirectChainError,
790 provenance: currentSnapshot.provenanceBySection[.redirectChain]
791 ),
792 redirectRows: redirectRows,
793 finalURL: currentSnapshot.redirectChain.last?.url
794 )
795 }
796
797 /// Everything the Network section draws. Twenty-two arguments before.
798 var networkSectionData: NetworkSectionViewData {
799 NetworkSectionViewData(
800 reachability: SectionPanelViewData(
801 isLoading: reachabilityLoading,
802 error: reachabilityError,
803 provenance: currentSnapshot.provenanceBySection[.reachability]
804 ),
805 reachabilityRows: reachabilityRows,
806 location: SectionPanelViewData(
807 isLoading: ipGeolocationLoading,
808 error: ipGeolocationError,
809 provenance: currentSnapshot.provenanceBySection[.ipGeolocation],
810 confidence: currentSnapshot.geolocationConfidence
811 ),
812 locationRows: locationRows,
813 geolocation: ipGeolocation,
814 portScan: SectionPanelViewData(
815 isLoading: portScanLoading,
816 error: portScanError,
817 provenance: currentSnapshot.provenanceBySection[.portScan]
818 ),
819 standardPortRows: standardPortRows,
820 customPortRows: customPortRows,
821 customPortScan: SectionPanelViewData(
822 isLoading: customPortScanLoading,
823 error: customPortScanError
824 ),
825 isCloudflareProxied: isCloudflareProxied
826 )
827 }
828
829 var webCertificateRows: [InfoRowViewData] {
830 Self.webCertificateRows(from: currentSnapshot)
831 }
832
833 var webResponseRows: [InfoRowViewData] {
834 Self.webResponseRows(from: currentSnapshot)
835 }
836
837 var redirectRows: [RedirectHopViewData] {
838 Self.redirectRows(from: currentSnapshot)
839 }
840
841 var emailRows: [EmailRowViewData] {
842 Self.emailRows(from: currentSnapshot)
843 }
844
845 var ownershipRows: [InfoRowViewData] {
846 Self.ownershipRows(from: currentSnapshot)
847 }
848
849 var subdomainRows: [SubdomainRowViewData] {
850 Self.subdomainRows(from: combinedSubdomains)
851 }
852
853 var reachabilityRows: [ReachabilityRowViewData] {
854 Self.reachabilityRows(from: currentSnapshot)
855 }
856
857 var locationRows: [InfoRowViewData] {
858 Self.locationRows(from: currentSnapshot)
859 }
860
861 var standardPortRows: [PortScanRowViewData] {
862 Self.portRows(from: currentSnapshot, kind: .standard)
863 }
864
865 var customPortRows: [PortScanRowViewData] {
866 Self.portRows(from: currentSnapshot, kind: .custom)
867 }
868
869 var combinedPortScanError: String? {
870 [portScanError, customPortScanError].compactMap { $0 }.joined(separator: "\n").nilIfEmpty
871 }
872
873 @discardableResult
874 func trackCurrentDomain() -> Bool {
875 guard !searchedDomain.isEmpty else { return false }
876 return trackDomain(domain: searchedDomain, availabilityStatus: availabilityResult?.status)
877 }
878
879 @discardableResult
880 func trackDomain(domain: String, availabilityStatus: DomainAvailabilityStatus?) -> Bool {
881 let normalizedDomain = normalizedDomain(domain)
882 guard !normalizedDomain.isEmpty else { return false }
883
884 if trackedDomain(for: normalizedDomain) != nil {
885 return true
886 }
887
888 guard FeatureAccessService.canAddTrackedDomain(currentCount: trackedDomains.count) else {
889 upgradePrompt = FeatureAccessService.upgradePromptForTrackedDomains(currentCount: trackedDomains.count)
890 return false
891 }
892
893 trackedDomains.insert(
894 TrackedDomain(
895 domain: normalizedDomain,
896 createdAt: Date(),
897 updatedAt: Date(),
898 lastKnownAvailability: availabilityStatus,
899 collaboration: CollaborationMetadata(
900 scope: .privateDatabase,
901 ownership: .owner,
902 permission: .editable
903 )
904 ),
905 at: 0
906 )
907 persistTrackedDomains()
908 sanitizeMonitoringSelection()
909 linkTrackedDomainHistory(for: normalizedDomain)
910 return true
911 }
912
913 func refreshTrackedDomain(_ trackedDomain: TrackedDomain) {
914 refreshingTrackedDomainID = trackedDomain.id
915 domain = trackedDomain.domain
916 Task { [weak self] in
917 guard let self else { return }
918 self.notificationsAuthorized = await LocalNotificationService.shared.requestAuthorizationIfNeeded()
919 }
920 run()
921 }
922
923 func rerunInspection(for trackedDomain: TrackedDomain) {
924 rerunInspection(for: trackedDomain, useSnapshotResolver: false)
925 }
926
927 func deleteTrackedDomains(at offsets: IndexSet) {
928 let removedDomains = offsets.map { sortedTrackedDomains[$0] }
929 let ids = removedDomains.map(\.id)
930 CloudSyncService.shared.recordTrackedDomainReset(removedDomains)
931 trackedDomains.removeAll { ids.contains($0.id) }
932 var relinked: [HistoryEntry] = []
933 history.indices.forEach { index in
934 if let trackedDomainID = history[index].trackedDomainID, ids.contains(trackedDomainID) {
935 history[index].trackedDomainID = nil
936 relinked.append(history[index])
937 }
938 }
939 persistTrackedDomains()
940 relinked.forEach { updateStoredHistory($0) }
941 sanitizeMonitoringSelection()
942 }
943
944 func deleteTrackedDomain(_ trackedDomain: TrackedDomain) {
945 guard canDelete(trackedDomain) else { return }
946 CloudSyncService.shared.recordTrackedDomainDeletion(trackedDomain)
947 trackedDomains.removeAll { $0.id == trackedDomain.id }
948 var relinked: [HistoryEntry] = []
949 history.indices.forEach { index in
950 if history[index].trackedDomainID == trackedDomain.id {
951 history[index].trackedDomainID = nil
952 relinked.append(history[index])
953 }
954 }
955 persistTrackedDomains()
956 relinked.forEach { updateStoredHistory($0) }
957 sanitizeMonitoringSelection()
958 }
959
960 func togglePinned(for trackedDomain: TrackedDomain) {
961 guard canEdit(trackedDomain) else { return }
962 guard let index = trackedDomains.firstIndex(where: { $0.id == trackedDomain.id }) else { return }
963 trackedDomains[index].isPinned.toggle()
964 trackedDomains[index].updatedAt = Date()
965 persistTrackedDomains()
966 }
967
968 func updateNote(_ note: String, for trackedDomain: TrackedDomain) {
969 guard canEdit(trackedDomain) else { return }
970 guard let index = trackedDomains.firstIndex(where: { $0.id == trackedDomain.id }) else { return }
971 trackedDomains[index].note = note.trimmingCharacters(in: .whitespacesAndNewlines).nilIfEmpty
972 trackedDomains[index].updatedAt = Date()
973 CloudSyncService.shared.markNoteChanged(for: trackedDomains[index].domain, updatedAt: trackedDomains[index].updatedAt)
974 persistTrackedDomains()
975 }
976
977 func updateTags(_ tags: [String], for trackedDomain: TrackedDomain) {
978 guard canEdit(trackedDomain) else { return }
979 guard let index = trackedDomains.firstIndex(where: { $0.id == trackedDomain.id }) else { return }
980 let normalized = Self.normalizedTags(tags)
981 trackedDomains[index].tags = normalized
982 trackedDomains[index].updatedAt = Date()
983 persistTrackedDomains()
984 }
985
986 /// All tags currently in use across the watchlist, sorted for stable display.
987 var allWatchlistTags: [String] {
988 Array(Set(trackedDomains.flatMap(\.tags))).sorted()
989 }
990
991 func saveCurrentWatchlistView(name: String) {
992 let trimmedName = name.trimmingCharacters(in: .whitespacesAndNewlines)
993 guard !trimmedName.isEmpty else { return }
994 let view = WatchlistSavedView(
995 name: trimmedName,
996 tag: watchlistTagFilter,
997 filter: watchlistFilter,
998 sort: watchlistSortOption
999 )
1000 watchlistSavedViews.append(view)
1001 persistWatchlistSavedViews()
1002 }
1003
1004 func applyWatchlistSavedView(_ view: WatchlistSavedView) {
1005 watchlistTagFilter = view.tag
1006 watchlistFilter = view.filter
1007 watchlistSortOption = view.sort
1008 }
1009
1010 func deleteWatchlistSavedViews(at offsets: IndexSet) {
1011 watchlistSavedViews.remove(atOffsets: offsets)
1012 persistWatchlistSavedViews()
1013 }
1014
1015 private static let watchlistSavedViewsKey = "watchlistSavedViews"
1016
1017 private static func loadWatchlistSavedViews(defaults: UserDefaults) -> [WatchlistSavedView] {
1018 guard let data = defaults.data(forKey: watchlistSavedViewsKey),
1019 let views = try? JSONDecoder().decode([WatchlistSavedView].self, from: data)
1020 else { return [] }
1021 return views
1022 }
1023
1024 private func persistWatchlistSavedViews() {
1025 guard let data = try? JSONEncoder().encode(watchlistSavedViews) else { return }
1026 defaults.set(data, forKey: Self.watchlistSavedViewsKey)
1027 }
1028
1029 private static func normalizedTags(_ tags: [String]) -> [String] {
1030 var seen = Set<String>()
1031 var normalized: [String] = []
1032 for tag in tags {
1033 let trimmed = tag.trimmingCharacters(in: .whitespacesAndNewlines)
1034 guard !trimmed.isEmpty, seen.insert(trimmed.lowercased()).inserted else { continue }
1035 normalized.append(trimmed)
1036 }
1037 return normalized.sorted()
1038 }
1039
1040 func removeHistoryEntries(at offsets: IndexSet) {
1041 let removed = Set(offsets.map { history[$0].id })
1042 history.remove(atOffsets: offsets)
1043 removeStoredHistory(ids: removed)
1044 }
1045
1046 func removeHistoryEntries(withIDs ids: [UUID]) {
1047 history.removeAll { ids.contains($0.id) }
1048 removeStoredHistory(ids: Set(ids))
1049 }
1050
1051 func clearHistory() {
1052 history.removeAll()
1053 DomainDataPortabilityService.removeAllHistoryEntries(
1054 defaults: defaults,
1055 historyLocation: historyLocation
1056 )
1057 refreshDataLifecycleSummary()
1058 clearMonitoringLogs()
1059 refreshDataLifecycleSummary()
1060 }
1061
1062 func clearLookupCache() {
1063 Task {
1064 await LookupRuntime.shared.clearCache()
1065 }
1066 }
1067
1068 func clearWorkflows() {
1069 CloudSyncService.shared.recordWorkflowReset(workflows)
1070 workflows.removeAll()
1071 latestWorkflowRunSummary = nil
1072 persistWorkflows()
1073 refreshDataLifecycleSummary()
1074 }
1075
1076 func clearTrackedDomains() {
1077 CloudSyncService.shared.recordTrackedDomainReset(trackedDomains)
1078 trackedDomains.removeAll()
1079 refreshingTrackedDomainID = nil
1080 persistTrackedDomains()
1081 sanitizeMonitoringSelection()
1082 clearMonitoringLogs()
1083 refreshDataLifecycleSummary()
1084 }
1085
1086 func clearRecentSearches() {
1087 recentSearches.removeAll()
1088 DomainDataPortabilityService.saveRecentSearches([], defaults: defaults)
1089 CloudSyncService.shared.markAppSettingsChanged()
1090 refreshDataLifecycleSummary()
1091 }
1092
1093 func refreshMonitoringState() {
1094 #if DEBUG
1095 // Runs right after fixture seeding in the app task (and again on every
1096 // scene activation); the disk reload below would wipe the fixtures.
1097 if auditFixturesActive { return }
1098 #endif
1099 DataMigrationService.migrateIfNeeded(defaults: defaults, historyLocation: historyLocation)
1100 trackedDomains = Self.loadTrackedDomains(defaults: defaults, historyLocation: historyLocation)
1101 history = Self.loadHistoryEntries(defaults: defaults, historyLocation: historyLocation)
1102 monitoringSettings = MonitoringStorage.sanitizeSettings(
1103 MonitoringStorage.loadSettings(defaults: defaults),
1104 trackedDomains: trackedDomains
1105 )
1106 monitoringLogs = MonitoringStorage.loadLogs(defaults: defaults)
1107 persistMonitoringSettings()
1108 refreshDataLifecycleSummary()
1109 }
1110
1111 func refreshDataLifecycleSummary() {
1112 dataLifecycleSummary = DomainDataPortabilityService.lifecycleSummary(defaults: defaults, historyLocation: historyLocation)
1113 }
1114
1115 func refreshPersistedData() {
1116 #if DEBUG
1117 // A reload from disk would silently replace the in-memory fixtures.
1118 if auditFixturesActive { return }
1119 #endif
1120 recentSearches = DomainDataPortabilityService.loadRecentSearches(defaults: defaults)
1121 trackedDomains = Self.loadTrackedDomains(defaults: defaults, historyLocation: historyLocation)
1122 history = Self.loadHistoryEntries(defaults: defaults, historyLocation: historyLocation)
1123 auditSessions = DomainDataPortabilityService.loadAuditSessions(defaults: defaults)
1124 workflows = Self.loadWorkflows(defaults: defaults, historyLocation: historyLocation)
1125 monitoringSettings = MonitoringStorage.sanitizeSettings(
1126 MonitoringStorage.loadSettings(defaults: defaults),
1127 trackedDomains: trackedDomains
1128 )
1129 monitoringLogs = MonitoringStorage.loadLogs(defaults: defaults)
1130 refreshDataLifecycleSummary()
1131 }
1132
1133 func applyLocalDataReset() async {
1134 domain = ""
1135 bulkInput = ""
1136 reset()
1137
1138 recentSearches = []
1139 trackedDomains = []
1140 history = []
1141 auditSessions = []
1142 workflows = []
1143 historySearchText = ""
1144 historyDateFilter = .all
1145 historyChangeFilter = .all
1146 historySortOption = .newest
1147 timelineGrouping = .relativeDay
1148 timelineDomainFilter = ""
1149 watchlistSearchText = ""
1150 watchlistFilter = .all
1151 watchlistSortOption = .pinned
1152 dashboardSearchText = ""
1153 dashboardFilter = .all
1154 monitoringSettings = MonitoringSettings()
1155 monitoringLogs = []
1156 notificationsAuthorized = false
1157 monitoringRunInProgress = false
1158 monitoringStatusMessage = nil
1159 portabilityStatusMessage = "All local data removed."
1160 upgradePrompt = nil
1161 isPaywallPresented = false
1162 selectedSnapshotIDs.removeAll()
1163 activeDomainDiff = nil
1164 activeDiffChangeIndex = 0
1165 latestBatchSweepSummary = nil
1166 latestWorkflowRunSummary = nil
1167 historyAutoPruneOption = Self.loadHistoryAutoPruneOption(defaults: defaults)
1168 refreshDataLifecycleSummary()
1169 await refreshMonitoringAuthorizationStatus()
1170 }
1171
1172 func rerunLookup(from entry: HistoryEntry, useSnapshotResolver: Bool) {
1173 if useSnapshotResolver {
1174 defaults.set(entry.resolverURLString, forKey: DNSResolverOption.userDefaultsKey)
1175 }
1176 domain = entry.domain
1177 run()
1178 rerunNavigationToken = UUID()
1179 }
1180
1181 func rerunInspection(for trackedDomain: TrackedDomain, useSnapshotResolver: Bool) {
1182 if useSnapshotResolver, let snapshot = latestSnapshot(for: trackedDomain) {
1183 defaults.set(snapshot.resolverURLString, forKey: DNSResolverOption.userDefaultsKey)
1184 }
1185 domain = trackedDomain.domain
1186 run()
1187 rerunNavigationToken = UUID()
1188 }
1189
1190 func openInspection(for domain: String) {
1191 self.domain = normalizedDomain(domain)
1192 run()
1193 rerunNavigationToken = UUID()
1194 }
1195
1196 func reset() {
1197 lookupTask?.cancel()
1198 customPortScanTask?.cancel()
1199 batchTask?.cancel()
1200 hasRun = false
1201 searchedDomain = ""
1202 lastLookupDurationMs = nil
1203 currentDiffSections = []
1204 currentChangeSummary = nil
1205 ownershipDiff = []
1206 currentReport = nil
1207 refreshingTrackedDomainID = nil
1208 clearBatchState()
1209 clearLookupState()
1210 }
1211
1212 func clearPresentedResults() {
1213 reset()
1214 }
1215
1216 func run() {
1217 let target: String
1218 switch DomainName.validate(trimmedDomain) {
1219 case .success(let host):
1220 target = host
1221 domainInputError = nil
1222 case .failure(let error):
1223 domainInputError = error.localizedDescription
1224 return
1225 }
1226
1227 clearBatchState()
1228 let lookupID = beginLookup(for: target)
1229
1230 lookupTask = Task { [weak self] in
1231 guard let self else { return }
1232 _ = await self.performLookup(domain: target, lookupID: lookupID)
1233 }
1234 }
1235
1236 func runBulkLookup() {
1237 let domains = parsedDomains(from: bulkInput)
1238 guard !domains.isEmpty else { return }
1239 guard FeatureAccessService.canRunBatch(domainCount: domains.count) else {
1240 upgradePrompt = FeatureAccessService.upgradePromptForBatch(domainCount: domains.count)
1241 return
1242 }
1243 startBatchLookup(domains: domains, source: .manual)
1244 }
1245
1246 func refreshAllTrackedDomains() {
1247 guard FeatureAccessService.canRunBatch(domainCount: sortedTrackedDomains.count) else {
1248 upgradePrompt = FeatureAccessService.upgradePromptForBatch(domainCount: sortedTrackedDomains.count)
1249 return
1250 }
1251 startBatchLookup(domains: sortedTrackedDomains.map(\.domain), source: .watchlistRefresh)
1252 }
1253
1254 func cancelBatchLookup() {
1255 batchTask?.cancel()
1256 batchLookupRunning = false
1257 batchCurrentDomain = nil
1258 activeBatchDomains = []
1259 refreshingTrackedDomainID = nil
1260
1261 for index in batchResults.indices where batchResults[index].status == .pending || batchResults[index].status == .running {
1262 batchResults[index] = BatchLookupResult(
1263 id: batchResults[index].id,
1264 domain: batchResults[index].domain,
1265 historyEntryID: batchResults[index].historyEntryID,
1266 availability: batchResults[index].availability,
1267 primaryIP: batchResults[index].primaryIP,
1268 quickStatus: "Cancelled",
1269 summaryMessage: batchResults[index].summaryMessage,
1270 changeSeverity: batchResults[index].changeSeverity,
1271 changeClassification: batchResults[index].changeClassification,
1272 certificateWarningLevel: batchResults[index].certificateWarningLevel,
1273 riskScore: batchResults[index].riskScore,
1274 riskLevel: batchResults[index].riskLevel,
1275 timestamp: Date(),
1276 status: .failed,
1277 errorMessage: "Lookup cancelled"
1278 )
1279 }
1280 }
1281
1282 func canEdit(_ trackedDomain: TrackedDomain) -> Bool {
1283 trackedDomain.collaboration?.canEdit ?? true
1284 }
1285
1286 func canDelete(_ trackedDomain: TrackedDomain) -> Bool {
1287 trackedDomain.collaboration?.isOwner ?? true
1288 }
1289
1290 func collaborationLabel(for trackedDomain: TrackedDomain) -> String? {
1291 guard let collaboration = trackedDomain.collaboration, collaboration.isShared else { return nil }
1292 return "\(collaboration.ownership.title) • \(collaboration.permission.title)"
1293 }
1294
1295 func runCustomPortScan(ports: [UInt16]) async {
1296 guard !searchedDomain.isEmpty else {
1297 customPortScanState = .settled(value: [], error: "Run a domain lookup first")
1298 return
1299 }
1300
1301 guard !ports.isEmpty else {
1302 customPortScanState = .settled(value: [], error: "Enter at least one valid port")
1303 return
1304 }
1305
1306 customPortScanTask?.cancel()
1307 let domain = searchedDomain
1308 let lookupID = activeLookupID
1309
1310 customPortScanState = .loading
1311
1312 customPortScanTask = Task { [weak self] in
1313 guard let self else { return }
1314 let result = await PortScanService.scanPorts(domain: domain, ports: ports, timeout: 3.0)
1315 guard !Task.isCancelled, self.isCurrentLookup(lookupID) else { return }
1316 self.applyCustomPortResult(result)
1317 }
1318 }
1319
1320 @discardableResult
1321 func startAudit(for domain: String, reviewer: String? = nil) async -> AuditSession? {
1322 let normalizedDomain = domain
1323 .trimmingCharacters(in: .whitespacesAndNewlines)
1324 .replacingOccurrences(of: "https://", with: "")
1325 .replacingOccurrences(of: "http://", with: "")
1326 .components(separatedBy: "/").first?
1327 .lowercased() ?? domain.lowercased()
1328 guard !normalizedDomain.isEmpty else { return nil }
1329
1330 // Free keeps one audit open at a time so the feature stays discoverable;
1331 // finishing one frees the slot. Existing sessions are never closed off.
1332 if let limit = FeatureAccessService.entitlements.activeAuditSessionLimit,
1333 auditSessions.filter({ $0.status != .complete }).count >= limit {
1334 upgradePrompt = FeatureAccessService.upgradePrompt(for: .auditDepth)
1335 return nil
1336 }
1337
1338 let previous = historyEntries(for: normalizedDomain).first?.snapshot
1339 let snapshot = await inspectionService.inspectSnapshot(
1340 domain: normalizedDomain,
1341 previousSnapshot: previous,
1342 scope: InspectionScope.current(defaults: defaults)
1343 )
1344 guard let entry = saveHistoryEntry(
1345 from: snapshot,
1346 replaceLatest: false,
1347 updateCurrentState: searchedDomain.caseInsensitiveCompare(normalizedDomain) == .orderedSame
1348 ) else {
1349 return nil
1350 }
1351
1352 let report = report(for: entry)
1353 let historicalContext = Array(historyEntries(for: normalizedDomain).dropFirst().prefix(6)).map(\.snapshotSummary)
1354 let screenshots = snapshotEvidenceAssets(from: report)
1355 let session = AuditSession(
1356 domain: normalizedDomain,
1357 createdAt: entry.timestamp,
1358 reviewer: (reviewer?.trimmingCharacters(in: .whitespacesAndNewlines).nilIfEmpty) ?? Self.defaultAuditReviewer,
1359 status: .draft,
1360 evidence: AuditEvidenceSnapshot(
1361 capturedAt: entry.timestamp,
1362 lookup: entry,
1363 report: report,
1364 historicalContext: historicalContext,
1365 screenshots: screenshots
1366 ),
1367 findings: [],
1368 notes: "",
1369 checklist: AuditChecklistArea.defaultItems
1370 )
1371
1372 auditSessions.insert(session, at: 0)
1373 persistAuditSessions()
1374 return session
1375 }
1376
1377 func loadOwnershipHistory() async {
1378 await loadLookup(into: \.ownershipHistoryState, fallback: "Ownership history unavailable") {
1379 await ExternalDataService.shared.ownershipHistory(
1380 domain: searchedDomain,
1381 currentOwnership: ownershipResult,
1382 historyEntries: history
1383 ).value
1384 }
1385 }
1386
1387 func loadDNSHistory() async {
1388 await loadLookup(into: \.dnsHistoryState, fallback: "DNS history unavailable") {
1389 await ExternalDataService.shared.dnsHistory(
1390 domain: searchedDomain,
1391 dnsSections: dnsSections,
1392 historyEntries: history
1393 ).value
1394 }
1395 }
1396
1397 func loadExtendedSubdomains() async {
1398 await loadLookup(
1399 .extendedSubdomains,
1400 into: \.extendedSubdomainsState,
1401 fallback: "Extended subdomains unavailable"
1402 ) {
1403 await ExternalDataService.shared.extendedSubdomains(
1404 domain: searchedDomain,
1405 existing: subdomains
1406 ).value
1407 }
1408 }
1409
1410 /// Loads a lookup for the searched domain into `items`, unless it is loaded
1411 /// already. With a `capability`, shows the upgrade prompt when the plan
1412 /// doesn't include it; without one the lookup is open to every tier.
1413 private func loadLookup<Item>(
1414 _ capability: FeatureCapability? = nil,
1415 into state: ReferenceWritableKeyPath<DomainViewModel, SectionState<[Item]>>,
1416 fallback: String,
1417 fetch: () async -> ServiceResult<[Item]>
1418 ) async {
1419 guard !searchedDomain.isEmpty else { return }
1420 if let capability, !FeatureAccessService.hasAccess(to: capability) {
1421 upgradePrompt = FeatureAccessService.upgradePrompt(for: capability)
1422 return
1423 }
1424 guard self[keyPath: state].items.isEmpty else { return }
1425
1426 self[keyPath: state] = .loading
1427 let (items, message) = found(await fetch(), fallback: fallback)
1428 self[keyPath: state] = .settled(value: items, error: message)
1429 _ = saveHistoryEntry(replaceLatest: true)
1430 }
1431
1432 /// What a lookup found, and the message to show when it found nothing or failed.
1433 private func found<Item>(_ result: ServiceResult<[Item]>, fallback: String) -> ([Item], String?) {
1434 switch result {
1435 case let .success(items):
1436 return (items, nil)
1437 case let .empty(message):
1438 return ([], message)
1439 case let .error(message):
1440 return ([], conciseExternalMessage(message, fallback: fallback))
1441 }
1442 }
1443
1444 private func performLookup(domain: String, lookupID: UUID) async -> HistoryEntry? {
1445 let lookupStartedAt = DomainDebugLog.signpostStart("DomainViewModel.performLookup", domain: domain)
1446 let previous = previousSnapshot(
1447 for: domain,
1448 trackedDomainID: currentTrackedDomain?.id,
1449 replacingLatest: false
1450 )
1451 let inspectedSnapshot = await inspectionService.inspectSnapshot(
1452 domain: domain,
1453 previousSnapshot: previous,
1454 scope: InspectionScope.current(defaults: defaults)
1455 )
1456 DomainDebugLog.debug("DomainViewModel.performLookup inspectionReturned domain=\(domain)")
1457 guard !Task.isCancelled, isCurrentLookup(lookupID) else { return nil }
1458
1459 let snapshot = inspectedSnapshot.resolvedAfterFallback(to: previous)
1460 let applyStartedAt = DomainDebugLog.signpostStart("DomainViewModel.applySnapshot", domain: domain)
1461 applySnapshot(snapshot)
1462 DomainDebugLog.signpostEnd("DomainViewModel.applySnapshot", start: applyStartedAt, domain: domain)
1463 lastLookupDurationMs = snapshot.totalLookupDurationMs
1464 refreshingTrackedDomainID = nil
1465
1466 guard snapshot.statusMessage == nil else {
1467 return history.first(where: { $0.id == snapshot.historyEntryID })
1468 }
1469
1470 let saveStartedAt = DomainDebugLog.signpostStart("DomainViewModel.saveHistoryEntry", domain: domain)
1471 let entry = saveHistoryEntry(replaceLatest: false, reuseCurrentAnalysis: true)
1472 DomainDebugLog.signpostEnd("DomainViewModel.saveHistoryEntry", start: saveStartedAt, domain: domain)
1473 // Opt-in, and off by default: this fires on every Run, so a target
1474 // that enabled it ships an object per tap.
1475 IntegrationService.shared.enqueueExports(domains: [domain], trigger: .interactiveRun)
1476 DomainDebugLog.signpostEnd("DomainViewModel.performLookup", start: lookupStartedAt, domain: domain)
1477 return entry
1478 }
1479
1480 /// The single place section state is written from an inspection result.
1481 /// Internal so the tests that pin what each section ends up showing can
1482 /// reach it without a live lookup.
1483 func applySnapshot(_ snapshot: LookupSnapshot) {
1484 currentInspectionMetadata = InspectionMetadata(snapshot: snapshot)
1485 currentHistoryEntryID = snapshot.historyEntryID
1486 currentSnapshotTimestamp = snapshot.timestamp
1487 currentResultSource = snapshot.resultSource
1488 currentCachedSections = snapshot.cachedSections
1489 currentStatusMessage = snapshot.statusMessage
1490 currentDiffSections = []
1491 ownershipDiff = []
1492 let reportStartedAt = DomainDebugLog.signpostStart("DomainViewModel.reportBuilder.build", domain: snapshot.domain)
1493 currentReport = reportBuilder.build(
1494 from: snapshot,
1495 previousSnapshot: previousSnapshot(
1496 for: snapshot.domain,
1497 trackedDomainID: snapshot.trackedDomainID ?? trackedDomain(for: snapshot.domain)?.id,
1498 replacingLatest: false
1499 ),
1500 historyEntries: historyEntries(for: snapshot.domain)
1501 )
1502 DomainDebugLog.signpostEnd("DomainViewModel.reportBuilder.build", start: reportStartedAt, domain: snapshot.domain)
1503 currentChangeSummary = currentReport?.changeSummary ?? snapshot.changeSummary
1504
1505 dnsState = .settled(value: snapshot.dnsSections, error: snapshot.dnsError)
1506 availabilityState = .settled(value: snapshot.availabilityResult)
1507 suggestionsState = .settled(value: snapshot.suggestions)
1508 sslState = .settled(value: snapshot.sslInfo, error: snapshot.sslError)
1509 hstsState = .settled(value: snapshot.hstsPreloaded)
1510 httpHeadersState = .settled(value: snapshot.httpHeaders, error: snapshot.httpHeadersError)
1511 httpSecurityGrade = snapshot.httpSecurityGrade
1512 httpStatusCode = snapshot.httpStatusCode
1513 httpResponseTimeMs = snapshot.httpResponseTimeMs
1514 httpProtocol = snapshot.httpProtocol
1515 http3Advertised = snapshot.http3Advertised
1516 reachabilityState = .settled(value: snapshot.reachabilityResults, error: snapshot.reachabilityError)
1517 ipGeolocationState = .settled(value: snapshot.ipGeolocation, error: snapshot.ipGeolocationError)
1518 emailSecurityState = .settled(value: snapshot.emailSecurity, error: snapshot.emailSecurityError)
1519 ownershipState = .settled(value: snapshot.ownership, error: snapshot.ownershipError)
1520 ownershipHistoryState = .settled(value: snapshot.ownershipHistory, error: snapshot.ownershipHistoryError)
1521 ptrState = .settled(value: snapshot.ptrRecord, error: snapshot.ptrError)
1522 redirectChainState = .settled(value: snapshot.redirectChain, error: snapshot.redirectChainError)
1523 subdomainsState = .settled(value: snapshot.subdomains, error: snapshot.subdomainsError)
1524 extendedSubdomainsState = .settled(value: snapshot.extendedSubdomains, error: snapshot.extendedSubdomainsError)
1525 dnsHistoryState = .settled(value: snapshot.dnsHistory, error: snapshot.dnsHistoryError)
1526 domainPricingState = .settled(value: snapshot.domainPricing, error: snapshot.domainPricingError)
1527 reputationState = .settled(value: snapshot.reputation, error: snapshot.reputationError)
1528 portScanState = .settled(
1529 value: snapshot.portScanResults.filter { $0.kind == .standard },
1530 error: snapshot.portScanError
1531 )
1532 customPortScanState = .settled(value: snapshot.portScanResults.filter { $0.kind == .custom })
1533 }
1534
1535 private func applyCustomPortResult(_ result: ServiceResult<[PortScanResult]>) {
1536 switch result {
1537 case let .success(results):
1538 customPortScanState = .settled(value: results)
1539 _ = saveHistoryEntry(replaceLatest: true)
1540 case let .empty(message), let .error(message):
1541 customPortScanState = .settled(value: [], error: message)
1542 }
1543 }
1544
1545 private static func performBatchLookup(
1546 domain: String,
1547 previousSnapshot: LookupSnapshot?,
1548 scope: InspectionScope
1549 ) async -> BatchLookupPayload? {
1550 guard !Task.isCancelled else { return nil }
1551 let inspectionService = DomainInspectionService()
1552 let snapshot = await inspectionService.inspectSnapshot(domain: domain, previousSnapshot: previousSnapshot, scope: scope)
1553 guard !Task.isCancelled else { return nil }
1554 return BatchLookupPayload(snapshot: snapshot.resolvedAfterFallback(to: previousSnapshot))
1555 }
1556
1557 @discardableResult
1558 private func saveHistoryEntry(replaceLatest: Bool, reuseCurrentAnalysis: Bool = false) -> HistoryEntry? {
1559 guard !searchedDomain.isEmpty else { return nil }
1560 return saveHistoryEntry(
1561 from: currentSnapshot,
1562 replaceLatest: replaceLatest,
1563 updateCurrentState: true,
1564 reuseCurrentAnalysis: reuseCurrentAnalysis
1565 )
1566 }
1567
1568 @discardableResult
1569 private func saveHistoryEntry(
1570 from snapshot: LookupSnapshot,
1571 replaceLatest: Bool,
1572 updateCurrentState: Bool,
1573 reuseCurrentAnalysis: Bool = false
1574 ) -> HistoryEntry? {
1575 let trackedDomainID = snapshot.trackedDomainID ?? trackedDomain(for: snapshot.domain)?.id
1576 let previousSnapshot = previousSnapshot(for: snapshot.domain, trackedDomainID: trackedDomainID, replacingLatest: replaceLatest)
1577 let domainHistoryEntries = history.filter {
1578 $0.domain.caseInsensitiveCompare(snapshot.domain) == .orderedSame
1579 }
1580 let analysis = reuseCurrentAnalysis ? nil : DomainInsightEngine.analyze(snapshot: snapshot, previousSnapshot: previousSnapshot)
1581 let intelligence = DomainIntelligenceService.derive(
1582 snapshot: snapshot,
1583 previousSnapshot: previousSnapshot,
1584 historyEntries: domainHistoryEntries
1585 )
1586 let changeSummary = reuseCurrentAnalysis
1587 ? currentChangeSummary ?? snapshot.changeSummary
1588 : previousSnapshot.map {
1589 DiffService.summary(
1590 from: $0,
1591 to: snapshot,
1592 generatedAt: snapshot.timestamp,
1593 riskAssessment: analysis?.riskAssessment,
1594 insights: analysis?.insights
1595 )
1596 }
1597 let domainDiff = reuseCurrentAnalysis
1598 ? previousSnapshot.map {
1599 DomainDiff(
1600 domain: snapshot.domain,
1601 fromTimestamp: $0.timestamp,
1602 toTimestamp: snapshot.timestamp,
1603 sections: currentDiffSections,
1604 changedSectionIDs: currentDiffSections.filter(\.hasChanges).map(\.id),
1605 changedSectionTitles: currentDiffSections.filter(\.hasChanges).map(\.title),
1606 contextNote: currentChangeSummary?.contextNote
1607 )
1608 }
1609 : previousSnapshot.map { DiffService.compare(from: $0, to: snapshot) }
1610 let diffSections = domainDiff?.sections ?? currentDiffSections
1611 let previousSnapshotID = previousSnapshot?.historyEntryID
1612 let nextSnapshotIndex = nextSnapshotIndex(for: snapshot.domain, trackedDomainID: trackedDomainID)
1613
1614 if updateCurrentState {
1615 currentChangeSummary = changeSummary
1616 currentDiffSections = diffSections
1617 ownershipDiff = diffSections.first(where: { $0.title == "Ownership" })?.items.filter(\.hasChanges) ?? []
1618 if !reuseCurrentAnalysis {
1619 currentReport = reportBuilder.build(
1620 from: snapshot,
1621 previousSnapshot: previousSnapshot,
1622 historyEntries: domainHistoryEntries
1623 )
1624 }
1625 }
1626
1627 let entry = HistoryEntry(
1628 identity: HistoryEntry.Identity(
1629 domain: snapshot.domain,
1630 timestamp: snapshot.timestamp,
1631 trackedDomainID: trackedDomainID,
1632 note: currentHistoryEntry?.note
1633 ),
1634 inspection: .init(snapshot: snapshot),
1635 registration: HistoryEntry.Registration(
1636 ownership: snapshot.ownership,
1637 ownershipHistory: snapshot.ownershipHistory,
1638 inferredProvider: intelligence.inferredProvider,
1639 priorProviders: intelligence.priorProviders,
1640 domainClassification: intelligence.domainClassification,
1641 ownershipTransitions: intelligence.ownershipTransitions,
1642 hostingTransitions: intelligence.hostingTransitions,
1643 domainPricing: snapshot.domainPricing
1644 ),
1645 intelligence: HistoryEntry.Intelligence(
1646 subdomainHistory: intelligence.subdomainHistory,
1647 riskSignals: intelligence.riskSignals,
1648 intelligenceTimeline: intelligence.timelineEvents,
1649 reputation: snapshot.reputation
1650 ),
1651 provenance: .init(snapshot: snapshot),
1652 summary: HistoryEntry.Summary(
1653 primaryIP: Self.primaryIPAddress(from: snapshot),
1654 finalRedirectURL: Self.finalRedirectTarget(from: snapshot),
1655 tlsStatusSummary: Self.httpsSummary(from: snapshot),
1656 emailSecuritySummary: Self.emailSummary(from: snapshot),
1657 httpGradeSummary: snapshot.httpSecurityGrade ?? snapshot.httpHeadersError,
1658 changeSummary: changeSummary,
1659 snapshotIndex: nextSnapshotIndex,
1660 previousSnapshotID: previousSnapshotID,
1661 changeCount: domainDiff?.changeCount ?? changeSummary?.changedSections.count ?? 0,
1662 severitySummary: changeSummary?.severity
1663 ),
1664 failures: .init(snapshot: snapshot)
1665 )
1666
1667 if updateCurrentState {
1668 currentHistoryEntryID = entry.id
1669 }
1670
1671 // Before the insert: afterwards `history.count` includes this entry
1672 // and `growthHistoryLimit` would never prune anything.
1673 let storedLimit = growthHistoryLimit
1674 let replacedLatest = replaceLatest
1675 && !history.isEmpty
1676 && history[0].domain.caseInsensitiveCompare(snapshot.domain) == .orderedSame
1677 if replacedLatest {
1678 history[0] = entry
1679 } else {
1680 history.insert(entry, at: 0)
1681 history = Array(history.prefix(storedLimit))
1682 }
1683
1684 updateTrackedDomainSnapshotMetadata(
1685 domain: snapshot.domain,
1686 snapshotID: entry.id,
1687 availabilityStatus: snapshot.availabilityResult?.status,
1688 updatedAt: snapshot.timestamp,
1689 changeSummary: changeSummary,
1690 changeSeverity: changeSummary?.severity,
1691 certificateWarningLevel: DomainDiffService.certificateWarningLevel(for: snapshot),
1692 certificateDaysRemaining: snapshot.sslInfo?.daysUntilExpiry
1693 )
1694 if replacedLatest {
1695 updateStoredHistory(entry)
1696 } else {
1697 appendStoredHistory(entry, cap: storedLimit)
1698 }
1699 notifyIfNeeded(for: entry, snapshot: snapshot, previousSnapshot: previousSnapshot)
1700 return entry
1701 }
1702
1703 /// A single snapshot written on its own. `persistHistory` rewrites every
1704 /// row because it cannot tell what changed; these callers can, and at the
1705 /// Pro+ cap that is the difference between 23 ms and 656 ms.
1706 /// Replaces one stored snapshot. No cap: an update changes a row that is
1707 /// already there and cannot push the store past its limit.
1708 private func updateStoredHistory(_ entry: HistoryEntry) {
1709 if historyPersistenceSuspended {
1710 historyPersistenceDirty = true
1711 return
1712 }
1713 DomainDataPortabilityService.updateHistoryEntry(
1714 entry,
1715 defaults: defaults,
1716 historyLocation: historyLocation
1717 )
1718 refreshDataLifecycleSummary()
1719 }
1720
1721 /// Stores a new snapshot under `cap`, which the caller reads before its
1722 /// own insert so the row being added does not raise its own ceiling.
1723 private func appendStoredHistory(_ entry: HistoryEntry, cap: Int) {
1724 if historyPersistenceSuspended {
1725 historyPersistenceDirty = true
1726 return
1727 }
1728 DomainDataPortabilityService.appendHistoryEntry(
1729 entry,
1730 cap: cap,
1731 defaults: defaults,
1732 historyLocation: historyLocation
1733 )
1734 refreshDataLifecycleSummary()
1735 }
1736
1737 private func removeStoredHistory(ids: Set<UUID>) {
1738 if historyPersistenceSuspended {
1739 historyPersistenceDirty = true
1740 return
1741 }
1742 DomainDataPortabilityService.removeHistoryEntries(
1743 ids: ids,
1744 defaults: defaults,
1745 historyLocation: historyLocation
1746 )
1747 refreshDataLifecycleSummary()
1748 }
1749
1750 /// Rewrites the whole store. Only the auto-prune setting needs this — it
1751 /// drops rows from the middle and cannot say which. Every other writer
1752 /// goes through `appendStoredHistory`, `updateStoredHistory` or
1753 /// `removeStoredHistory`.
1754 private func persistHistory() {
1755 if historyPersistenceSuspended {
1756 historyPersistenceDirty = true
1757 return
1758 }
1759 let persistStartedAt = DomainDebugLog.signpostStart("DomainViewModel.persistHistory")
1760 DomainDataPortabilityService.saveHistoryEntries(history, defaults: defaults, historyLocation: historyLocation)
1761 refreshDataLifecycleSummary()
1762 DomainDebugLog.signpostEnd("DomainViewModel.persistHistory", start: persistStartedAt, extra: "count=\(history.count)")
1763 }
1764
1765 func persistAuditSessions() {
1766 DomainDataPortabilityService.saveAuditSessions(auditSessions, defaults: defaults)
1767 refreshDataLifecycleSummary()
1768 }
1769
1770 func setHistoryAutoPruneOption(_ option: HistoryAutoPruneOption) {
1771 historyAutoPruneOption = option
1772 defaults.set(option.rawValue, forKey: Self.historyAutoPruneKey)
1773 history = Array(history.prefix(requestedHistoryLimit))
1774 persistHistory()
1775 }
1776
1777 func updateHistoryNote(_ note: String, for entry: HistoryEntry) {
1778 guard let index = history.firstIndex(where: { $0.id == entry.id }) else { return }
1779 history[index].note = note.trimmingCharacters(in: .whitespacesAndNewlines).nilIfEmpty
1780 updateStoredHistory(history[index])
1781 }
1782
1783 #if DEBUG
1784 /// True when this session was launched with `DOMAIN_DIG_SEED_FIXTURES`.
1785 /// Blocks tracked-domain persistence, widget-store writes, and persisted-data
1786 /// reloads so fixture data stays strictly in-memory — the audit suite relies
1787 /// on every launch starting from the same state.
1788 private(set) var auditFixturesActive = false
1789
1790 func seedAuditFixturesIfRequested() {
1791 guard AuditFixtures.requested, !auditFixturesActive else { return }
1792 auditFixturesActive = true
1793 trackedDomains = AuditFixtures.trackedDomains
1794 batchResults = AuditFixtures.batchResults
1795 }
1796 #endif
1797
1798 private func persistTrackedDomains() {
1799 #if DEBUG
1800 if auditFixturesActive { return }
1801 #endif
1802 if trackedDomainsPersistenceSuspended {
1803 trackedDomainsPersistenceDirty = true
1804 return
1805 }
1806 DomainDataPortabilityService.saveTrackedDomains(trackedDomains, defaults: defaults)
1807 CloudSyncService.shared.scheduleSyncIfNeeded()
1808 refreshDataLifecycleSummary()
1809 refreshWidgetData()
1810 }
1811
1812 private func beginBulkPersistenceDeferral() {
1813 historyPersistenceSuspended = true
1814 trackedDomainsPersistenceSuspended = true
1815 historyPersistenceDirty = false
1816 trackedDomainsPersistenceDirty = false
1817 }
1818
1819 private func endBulkPersistenceDeferral() {
1820 historyPersistenceSuspended = false
1821 trackedDomainsPersistenceSuspended = false
1822
1823 if trackedDomainsPersistenceDirty {
1824 trackedDomainsPersistenceDirty = false
1825 DomainDataPortabilityService.saveTrackedDomains(trackedDomains, defaults: defaults)
1826 CloudSyncService.shared.scheduleSyncIfNeeded()
1827 }
1828
1829 if historyPersistenceDirty {
1830 historyPersistenceDirty = false
1831 DomainDataPortabilityService.saveHistoryEntries(history, defaults: defaults, historyLocation: historyLocation)
1832 }
1833
1834 refreshDataLifecycleSummary()
1835 }
1836
1837 /// What Settings says under the auto-prune picker. The old copy claimed
1838 /// auto-prune "defaults to unlimited", which was never true — there has
1839 /// always been a hard ceiling, and under D1 it is the tier's.
1840 var historyRetentionCaption: String {
1841 let limit = tierHistoryLimit
1842 let base = "History stays on this device. Your plan keeps up to \(limit) snapshots"
1843 guard history.count > limit else {
1844 return base + "; auto-prune trims to fewer if you want."
1845 }
1846 return base
1847 + ", and you have \(history.count). Nothing already saved is removed —"
1848 + " new snapshots replace the oldest instead."
1849 }
1850
1851 /// Snapshots this tier keeps: 50 free, 250 Pro, 2000 Pro+ under D1.
1852 private var tierHistoryLimit: Int {
1853 FeatureAccessService.historyRetentionLimit
1854 }
1855
1856 /// The ceiling a newly stored snapshot is kept under, computed before the
1857 /// insert. Never below what is already held: a lapsed Pro+ subscriber with
1858 /// 2000 snapshots keeps all 2000 (Review Focus #6), and the store holds
1859 /// there rather than draining to the lower tier a row at a time. For
1860 /// anyone at or under their tier's limit this is just that limit.
1861 var growthHistoryLimit: Int {
1862 max(tierHistoryLimit, history.count)
1863 }
1864
1865 /// What the user's own auto-prune choice asks for, which may be less than
1866 /// the tier allows but never more. This one is permitted to delete,
1867 /// because the user chose it.
1868 var requestedHistoryLimit: Int {
1869 min(historyAutoPruneOption.keepCount ?? tierHistoryLimit, tierHistoryLimit)
1870 }
1871
1872 /// Caps growth without pruning what is already stored.
1873 private func trimHistoryToLimit() {
1874 history = Array(history.prefix(growthHistoryLimit))
1875 }
1876
1877 private func nextSnapshotIndex(for domain: String, trackedDomainID: UUID?) -> Int {
1878 let siblings = history.filter { entry in
1879 if let trackedDomainID {
1880 return entry.trackedDomainID == trackedDomainID
1881 }
1882 return entry.domain.caseInsensitiveCompare(domain) == .orderedSame
1883 }
1884 let existingMax = siblings.compactMap(\.snapshotIndex).max() ?? siblings.count
1885 return existingMax + 1
1886 }
1887
1888 func persistMonitoringSettings(localActivationConfirmed: Bool = false) {
1889 monitoringSettings = MonitoringStorage.sanitizeSettings(monitoringSettings, trackedDomains: trackedDomains)
1890 MonitoringStorage.saveSettings(monitoringSettings, defaults: defaults)
1891 CloudSyncService.shared.markMonitoringSettingsChanged(localActivationConfirmed: localActivationConfirmed)
1892 }
1893
1894 func sanitizeMonitoringSelection() {
1895 monitoringSettings = MonitoringStorage.sanitizeSettings(monitoringSettings, trackedDomains: trackedDomains)
1896 MonitoringStorage.saveSettings(monitoringSettings, defaults: defaults)
1897 CloudSyncService.shared.markMonitoringSettingsChanged(localActivationConfirmed: false)
1898 }
1899
1900 private func clearMonitoringLogs() {
1901 monitoringLogs.removeAll()
1902 monitoringStatusMessage = nil
1903 MonitoringStorage.saveLogs([], defaults: defaults)
1904 }
1905
1906 private func updateTrackedDomainAvailability(for domain: String, status: DomainAvailabilityStatus) {
1907 guard let index = trackedDomains.firstIndex(where: { $0.domain.caseInsensitiveCompare(domain) == .orderedSame }) else {
1908 return
1909 }
1910 trackedDomains[index].lastKnownAvailability = status
1911 persistTrackedDomains()
1912 }
1913
1914 private func updateTrackedDomainSnapshotMetadata(
1915 domain: String,
1916 snapshotID: UUID,
1917 availabilityStatus: DomainAvailabilityStatus?,
1918 updatedAt: Date,
1919 changeSummary: DomainChangeSummary?,
1920 changeSeverity: ChangeSeverity?,
1921 certificateWarningLevel: CertificateWarningLevel,
1922 certificateDaysRemaining: Int?
1923 ) {
1924 guard let index = trackedDomains.firstIndex(where: { $0.domain.caseInsensitiveCompare(domain) == .orderedSame }) else {
1925 return
1926 }
1927 trackedDomains[index].lastSnapshotID = snapshotID
1928 trackedDomains[index].lastKnownAvailability = availabilityStatus
1929 trackedDomains[index].updatedAt = updatedAt
1930 trackedDomains[index].lastChangeSummary = changeSummary
1931 trackedDomains[index].lastChangeSeverity = changeSeverity
1932 trackedDomains[index].certificateWarningLevel = certificateWarningLevel
1933 trackedDomains[index].certificateDaysRemaining = certificateDaysRemaining
1934 persistTrackedDomains()
1935 }
1936
1937 private func notifyIfNeeded(for entry: HistoryEntry, snapshot: LookupSnapshot, previousSnapshot: LookupSnapshot?) {
1938 guard notificationsAuthorized, entry.trackedDomainID != nil else { return }
1939
1940 Task {
1941 if let summary = entry.changeSummary, summary.hasChanges {
1942 await LocalNotificationService.shared.notifyDomainEvent(
1943 domain: entry.domain,
1944 message: summary.message,
1945 severity: summary.severity
1946 )
1947 }
1948
1949 let certificateWarningLevel = DomainDiffService.certificateWarningLevel(for: snapshot)
1950 if certificateWarningLevel == .critical, let daysRemaining = snapshot.sslInfo?.daysUntilExpiry {
1951 await LocalNotificationService.shared.notifyCertificateWarning(
1952 domain: entry.domain,
1953 daysRemaining: daysRemaining
1954 )
1955 }
1956
1957 if let previousStatus = previousSnapshot?.availabilityResult?.status,
1958 let newStatus = snapshot.availabilityResult?.status,
1959 previousStatus != newStatus {
1960 await LocalNotificationService.shared.notifyDomainEvent(
1961 domain: entry.domain,
1962 message: "Availability changed",
1963 severity: .high
1964 )
1965 }
1966 }
1967 }
1968
1969 private func previousSnapshot(for domain: String, trackedDomainID: UUID?, replacingLatest: Bool) -> LookupSnapshot? {
1970 let matchingEntries = history.filter { entry in
1971 if let trackedDomainID {
1972 return entry.trackedDomainID == trackedDomainID
1973 }
1974 return entry.domain.caseInsensitiveCompare(domain) == .orderedSame
1975 }
1976
1977 if replacingLatest {
1978 return matchingEntries.dropFirst().first?.snapshot
1979 }
1980 return matchingEntries.first?.snapshot
1981 }
1982
1983 private func trackedDomain(for domain: String) -> TrackedDomain? {
1984 trackedDomains.first { $0.domain.caseInsensitiveCompare(domain) == .orderedSame }
1985 }
1986
1987 func normalizedDomain(_ domain: String) -> String {
1988 domain
1989 .trimmingCharacters(in: .whitespacesAndNewlines)
1990 .replacingOccurrences(of: "https://", with: "")
1991 .replacingOccurrences(of: "http://", with: "")
1992 .components(separatedBy: "/")
1993 .first?
1994 .lowercased() ?? ""
1995 }
1996
1997 private func linkTrackedDomainHistory(for domain: String) {
1998 guard let trackedDomain = trackedDomain(for: domain) else { return }
1999
2000 var relinked: [HistoryEntry] = []
2001 for index in history.indices where history[index].domain.caseInsensitiveCompare(domain) == .orderedSame {
2002 if history[index].trackedDomainID != trackedDomain.id {
2003 history[index].trackedDomainID = trackedDomain.id
2004 relinked.append(history[index])
2005 }
2006 }
2007
2008 relinked.forEach { updateStoredHistory($0) }
2009
2010 if let latestEntry = history.first(where: { $0.domain.caseInsensitiveCompare(domain) == .orderedSame }),
2011 let trackedIndex = trackedDomains.firstIndex(where: { $0.id == trackedDomain.id }) {
2012 trackedDomains[trackedIndex].lastSnapshotID = latestEntry.id
2013 trackedDomains[trackedIndex].lastChangeSummary = latestEntry.changeSummary
2014 trackedDomains[trackedIndex].lastChangeSeverity = latestEntry.changeSummary?.severity
2015 trackedDomains[trackedIndex].lastKnownAvailability = latestEntry.availabilityResult?.status
2016 trackedDomains[trackedIndex].certificateWarningLevel = DomainDiffService.certificateWarningLevel(for: latestEntry.snapshot)
2017 trackedDomains[trackedIndex].certificateDaysRemaining = latestEntry.sslInfo?.daysUntilExpiry
2018 trackedDomains[trackedIndex].updatedAt = latestEntry.timestamp
2019 persistTrackedDomains()
2020 }
2021 }
2022
2023 func addRecentSearch(_ domain: String) {
2024 recentSearches.removeAll { $0.lowercased() == domain.lowercased() }
2025 recentSearches.insert(domain, at: 0)
2026 if recentSearches.count > Self.maxRecent {
2027 recentSearches = Array(recentSearches.prefix(Self.maxRecent))
2028 }
2029 DomainDataPortabilityService.saveRecentSearches(recentSearches, defaults: defaults)
2030 CloudSyncService.shared.markAppSettingsChanged()
2031 refreshDataLifecycleSummary()
2032 }
2033
2034 func beginLookup(for target: String, cancelExistingTask: Bool = true) -> UUID {
2035 if cancelExistingTask {
2036 lookupTask?.cancel()
2037 }
2038 customPortScanTask?.cancel()
2039
2040 let lookupID = UUID()
2041 activeLookupID = lookupID
2042 lookupStartedAt = Date()
2043 lastLookupDurationMs = nil
2044 addRecentSearch(target)
2045 searchedDomain = target
2046 hasRun = true
2047 currentHistoryEntryID = nil
2048 currentInspectionMetadata = nil
2049 currentSnapshotTimestamp = Date()
2050 currentResultSource = .live
2051 currentCachedSections = []
2052 currentStatusMessage = nil
2053 currentDiffSections = []
2054 currentChangeSummary = nil
2055 currentReport = nil
2056 ownershipDiff = []
2057 clearLookupState()
2058 setAllLoadingStates(true)
2059 return lookupID
2060 }
2061
2062 func startBatchLookup(domains: [String], source: BatchLookupSource, workflow: DomainWorkflow? = nil) {
2063 guard !domains.isEmpty else { return }
2064 guard !batchLookupRunning else { return }
2065
2066 let now = Date()
2067 if let lastBatchStartedAt, now.timeIntervalSince(lastBatchStartedAt) < 1 {
2068 return
2069 }
2070
2071 lastBatchStartedAt = now
2072 clearBatchState()
2073 batchLookupSource = source
2074 activeWorkflowRunID = workflow?.id
2075 activeWorkflowRunName = workflow?.name
2076 batchTotalCount = domains.count
2077 batchLookupRunning = true
2078 batchResults = domains.map {
2079 BatchLookupResult(
2080 domain: $0,
2081 historyEntryID: nil,
2082 availability: nil,
2083 primaryIP: nil,
2084 quickStatus: "Pending",
2085 timestamp: Date(),
2086 status: .pending
2087 )
2088 }
2089
2090 lookupTask?.cancel()
2091 customPortScanTask?.cancel()
2092 batchTask?.cancel()
2093
2094 SweepActivityController.shared.begin(
2095 title: source == .watchlistRefresh ? "Watchlist Sweep" : "Batch Lookup",
2096 total: domains.count
2097 )
2098
2099 batchTask = Task { [weak self] in
2100 guard let self else { return }
2101 self.notificationsAuthorized = await LocalNotificationService.shared.requestAuthorizationIfNeeded()
2102 await self.runBatchLookup(domains: domains, source: source)
2103 }
2104 }
2105
2106 private func clearBatchState() {
2107 batchResults = []
2108 batchLookupSource = .manual
2109 batchCurrentDomain = nil
2110 batchCompletedCount = 0
2111 batchTotalCount = 0
2112 batchLookupRunning = false
2113 latestBatchSweepSummary = nil
2114 latestWorkflowRunSummary = nil
2115 activeBatchDomains = []
2116 activeWorkflowRunID = nil
2117 activeWorkflowRunName = nil
2118 batchTask = nil
2119 }
2120
2121 private func parsedDomains(from input: String) -> [String] {
2122 let separators = CharacterSet(charactersIn: ",").union(.whitespacesAndNewlines)
2123 var seen = Set<String>()
2124
2125 return input
2126 .components(separatedBy: separators)
2127 .compactMap { try? DomainName.validate($0).get() }
2128 .filter { seen.insert($0).inserted }
2129 }
2130
2131 private func runBatchLookup(domains: [String], source: BatchLookupSource) async {
2132 let concurrencyLimit = min(source == .watchlistRefresh ? 4 : 3, max(domains.count, 1))
2133 var nextIndex = 0
2134 beginBulkPersistenceDeferral()
2135
2136 await withTaskGroup(of: (String, BatchLookupPayload?).self) { group in
2137 for _ in 0..<concurrencyLimit {
2138 guard nextIndex < domains.count else { break }
2139 let domain = domains[nextIndex]
2140 nextIndex += 1
2141 enqueueBatchLookup(domain: domain, source: source, group: &group)
2142 }
2143
2144 while let (domain, payload) = await group.next() {
2145 completeBatchLookup(domain: domain, payload: payload)
2146
2147 if nextIndex < domains.count, !Task.isCancelled {
2148 let nextDomain = domains[nextIndex]
2149 nextIndex += 1
2150 enqueueBatchLookup(domain: nextDomain, source: source, group: &group)
2151 }
2152 }
2153 }
2154
2155 endBulkPersistenceDeferral()
2156 finishBatchLookup(source: source)
2157 }
2158
2159 private func enqueueBatchLookup(
2160 domain: String,
2161 source: BatchLookupSource,
2162 group: inout TaskGroup<(String, BatchLookupPayload?)>
2163 ) {
2164 activeBatchDomains.append(domain)
2165 batchCurrentDomain = activeBatchDomains.first
2166 if source == .watchlistRefresh {
2167 refreshingTrackedDomainID = trackedDomain(for: domain)?.id
2168 }
2169 updateBatchResult(domain: domain, status: .running, quickStatus: "Running", entry: nil, errorMessage: nil)
2170 let previousSnapshot = previousSnapshot(for: domain, trackedDomainID: trackedDomain(for: domain)?.id, replacingLatest: false)
2171
2172 group.addTask { [domain, previousSnapshot, scope = InspectionScope.current(defaults: defaults)] in
2173 let payload = await Self.performBatchLookup(domain: domain, previousSnapshot: previousSnapshot, scope: scope)
2174 return (domain, payload)
2175 }
2176 }
2177
2178 private func completeBatchLookup(domain: String, payload: BatchLookupPayload?) {
2179 activeBatchDomains.removeAll { $0.caseInsensitiveCompare(domain) == .orderedSame }
2180 batchCurrentDomain = activeBatchDomains.first
2181
2182 guard let payload else {
2183 updateBatchResult(
2184 domain: domain,
2185 status: .failed,
2186 quickStatus: "Failed",
2187 entry: nil,
2188 resultSource: .live,
2189 errorMessage: "Lookup cancelled"
2190 )
2191 batchCompletedCount += 1
2192 SweepActivityController.shared.update(
2193 completed: batchCompletedCount,
2194 total: batchTotalCount,
2195 currentDomain: batchCurrentDomain
2196 )
2197 return
2198 }
2199
2200 let entry = payload.snapshot.historyEntryID.flatMap { id in
2201 history.first(where: { $0.id == id })
2202 } ?? saveHistoryEntry(from: payload.snapshot, replaceLatest: false, updateCurrentState: false)
2203 let certificateWarningLevel = DomainDiffService.certificateWarningLevel(for: payload.snapshot)
2204 let riskAssessment = entry?.changeSummary?.riskAssessment ?? DomainInsightEngine.analyze(snapshot: payload.snapshot).riskAssessment
2205 let quickStatus: String
2206 if entry?.changeSummary?.hasChanges == true {
2207 if entry?.changeSummary?.impactClassification == .critical {
2208 quickStatus = "Critical"
2209 } else {
2210 quickStatus = entry?.changeSummary?.severity == .high ? "High" : "Changed"
2211 }
2212 } else if certificateWarningLevel != .none {
2213 quickStatus = certificateWarningLevel == .critical ? "Critical" : "Warning"
2214 } else if riskAssessment.level == .high {
2215 quickStatus = "High"
2216 } else {
2217 quickStatus = "Unchanged"
2218 }
2219
2220 updateBatchResult(
2221 domain: domain,
2222 status: .completed,
2223 quickStatus: quickStatus,
2224 entry: entry,
2225 resultSource: payload.snapshot.resultSource,
2226 errorMessage: payload.snapshot.statusMessage
2227 )
2228 batchCompletedCount += 1
2229 SweepActivityController.shared.update(
2230 completed: batchCompletedCount,
2231 total: batchTotalCount,
2232 currentDomain: batchCurrentDomain
2233 )
2234 }
2235
2236 private func finishBatchLookup(source: BatchLookupSource) {
2237 batchLookupRunning = false
2238 batchCurrentDomain = nil
2239 activeBatchDomains = []
2240 refreshingTrackedDomainID = nil
2241 batchTask = nil
2242
2243 let changedCount = batchResults.filter { $0.quickStatus == "Changed" || $0.quickStatus == "High" || $0.quickStatus == "Critical" }.count
2244 let unchangedCount = batchResults.filter { $0.quickStatus == "Unchanged" && $0.status == .completed }.count
2245 let warningCount = batchResults.filter {
2246 $0.certificateWarningLevel != .none
2247 || $0.changeClassification == .warning
2248 || $0.changeClassification == .critical
2249 || $0.riskLevel == .high
2250 }.count
2251
2252 let summary = BatchSweepSummary(
2253 source: source,
2254 totalDomains: batchResults.count,
2255 changedDomains: changedCount,
2256 unchangedDomains: unchangedCount,
2257 warningDomains: warningCount,
2258 results: batchResults.sorted { lhs, rhs in
2259 if lhs.status != rhs.status {
2260 return lhs.status.rawValue < rhs.status.rawValue
2261 }
2262 return lhs.domain.localizedCaseInsensitiveCompare(rhs.domain) == .orderedAscending
2263 },
2264 generatedAt: Date()
2265 )
2266 latestBatchSweepSummary = summary
2267 // Only the domains that actually completed: a failed lookup has no
2268 // report to upload.
2269 IntegrationService.shared.enqueueExports(
2270 domains: batchResults.filter { $0.status == .completed }.map(\.domain),
2271 trigger: .batch
2272 )
2273 SweepActivityController.shared.end(changed: changedCount, warnings: warningCount)
2274 AppAccessibility.announce(
2275 "Sweep complete. \(summary.results.count) domains, \(changedCount) changed, \(warningCount) warnings."
2276 )
2277
2278 if source == .workflow, let activeWorkflowRunID, let activeWorkflowRunName {
2279 let workflowReports: [DomainReport] = summary.results.compactMap { result in
2280 guard let entry = historyEntry(for: result) else { return nil }
2281 return report(for: entry)
2282 }
2283 latestWorkflowRunSummary = WorkflowRunSummary(
2284 workflowID: activeWorkflowRunID,
2285 workflowName: activeWorkflowRunName,
2286 totalDomains: batchResults.count,
2287 changedDomains: changedCount,
2288 unchangedDomains: unchangedCount,
2289 warningDomains: warningCount,
2290 results: summary.results,
2291 workflowInsights: DomainInsightEngine.workflowInsights(for: workflowReports),
2292 generatedAt: summary.generatedAt
2293 )
2294 }
2295
2296 if notificationsAuthorized, source != .workflow {
2297 Task {
2298 await LocalNotificationService.shared.notifySweepComplete(summary: summary)
2299 }
2300 }
2301 }
2302
2303 private func updateBatchResult(
2304 domain: String,
2305 status: BatchLookupStatus,
2306 quickStatus: String,
2307 entry: HistoryEntry?,
2308 resultSource: LookupResultSource = .live,
2309 errorMessage: String?
2310 ) {
2311 guard let index = batchResults.firstIndex(where: { $0.domain.caseInsensitiveCompare(domain) == .orderedSame }) else {
2312 return
2313 }
2314
2315 batchResults[index] = BatchLookupResult(
2316 id: batchResults[index].id,
2317 domain: domain,
2318 historyEntryID: entry?.id,
2319 resultSource: resultSource,
2320 availability: entry?.availabilityResult?.status,
2321 primaryIP: entry?.primaryIP,
2322 quickStatus: quickStatus,
2323 summaryMessage: entry?.changeSummary?.message,
2324 changeSeverity: entry?.changeSummary?.severity,
2325 changeClassification: entry?.changeSummary?.impactClassification,
2326 certificateWarningLevel: entry.map { DomainDiffService.certificateWarningLevel(for: $0.snapshot) } ?? batchResults[index].certificateWarningLevel,
2327 riskScore: entry.map { $0.changeSummary?.riskAssessment?.score ?? report(for: $0).riskAssessment.score },
2328 riskLevel: entry.map { $0.changeSummary?.riskAssessment?.level ?? report(for: $0).riskAssessment.level },
2329 timestamp: entry?.timestamp ?? Date(),
2330 status: status,
2331 errorMessage: errorMessage
2332 )
2333 }
2334
2335 /// Resets every section before a new lookup, so the previous domain's
2336 /// results cannot be mistaken for this one's. One assignment per section
2337 /// now; it used to be three.
2338 private func clearLookupState() {
2339 currentInspectionMetadata = nil
2340 dnsState = .idle
2341 availabilityState = .idle
2342 suggestionsState = .idle
2343 sslState = .idle
2344 hstsState = .idle
2345 httpHeadersState = .idle
2346 httpSecurityGrade = nil
2347 httpStatusCode = nil
2348 httpResponseTimeMs = nil
2349 httpProtocol = nil
2350 http3Advertised = false
2351 reachabilityState = .idle
2352 ipGeolocationState = .idle
2353 emailSecurityState = .idle
2354 ownershipState = .idle
2355 ownershipHistoryState = .idle
2356 ptrState = .idle
2357 redirectChainState = .idle
2358 subdomainsState = .idle
2359 extendedSubdomainsState = .idle
2360 dnsHistoryState = .idle
2361 domainPricingState = .idle
2362 reputationState = .idle
2363 portScanState = .idle
2364 customPortScanState = .idle
2365 }
2366
2367 /// Puts the sections a lookup drives into flight, and resets the
2368 /// on-demand ones — ownership history, extended subdomains, DNS history
2369 /// and pricing are fetched when the user opens them, not by the lookup, so
2370 /// they were never part of this either.
2371 private func setAllLoadingStates(_ loading: Bool) {
2372 let phase: SectionPhase = loading ? .loading : .idle
2373 dnsState.phase = phase
2374 availabilityState.phase = phase
2375 suggestionsState.phase = phase
2376 sslState.phase = phase
2377 hstsState.phase = phase
2378 httpHeadersState.phase = phase
2379 reachabilityState.phase = phase
2380 ipGeolocationState.phase = phase
2381 emailSecurityState.phase = phase
2382 ownershipState.phase = phase
2383 ptrState.phase = phase
2384 redirectChainState.phase = phase
2385 subdomainsState.phase = phase
2386 portScanState.phase = phase
2387
2388 ownershipHistoryState.phase = .idle
2389 extendedSubdomainsState.phase = .idle
2390 dnsHistoryState.phase = .idle
2391 domainPricingState.phase = .idle
2392 }
2393
2394 private func primaryIPAddress(from sections: [DNSSection]) -> String? {
2395 sections.first(where: { $0.recordType == .A })?.records.first?.value
2396 }
2397
2398 func isCurrentLookup(_ lookupID: UUID) -> Bool {
2399 activeLookupID == lookupID
2400 }
2401
2402 func recentSnapshots(for trackedDomain: TrackedDomain, limit: Int = 6) -> [HistoryEntry] {
2403 history
2404 .filter { $0.trackedDomainID == trackedDomain.id || $0.domain.caseInsensitiveCompare(trackedDomain.domain) == .orderedSame }
2405 .sorted { $0.timestamp > $1.timestamp }
2406 .prefix(limit)
2407 .map { $0 }
2408 }
2409
2410 func latestSnapshots(for domains: [TrackedDomain]) -> [HistoryEntry] {
2411 domains.compactMap { trackedDomain in
2412 recentSnapshots(for: trackedDomain, limit: 1).first
2413 }
2414 }
2415
2416 func diffSectionsForLatestSnapshots(of trackedDomain: TrackedDomain) -> [DomainDiffSection] {
2417 let snapshots = recentSnapshots(for: trackedDomain, limit: 2)
2418 guard snapshots.count == 2 else { return [] }
2419 return DomainDiffService.diff(from: snapshots[1].snapshot, to: snapshots[0].snapshot)
2420 }
2421
2422 func latestChangeSummary(for trackedDomain: TrackedDomain) -> DomainChangeSummary? {
2423 trackedDomain.lastChangeSummary ?? recentSnapshots(for: trackedDomain, limit: 1).first?.changeSummary
2424 }
2425
2426 func latestSnapshot(for trackedDomain: TrackedDomain) -> LookupSnapshot? {
2427 recentSnapshots(for: trackedDomain, limit: 1).first?.snapshot
2428 }
2429
2430 func trackedDomain(withID id: UUID) -> TrackedDomain? {
2431 trackedDomains.first(where: { $0.id == id })
2432 }
2433
2434 private func buildPortfolioDomainStates() -> [PortfolioDomainStatus] {
2435 let now = Date()
2436 return sortedTrackedDomains(from: trackedDomains, using: .pinned).map { trackedDomain in
2437 let recentEntries = recentSnapshots(for: trackedDomain, limit: 8)
2438 let latestEntry = recentEntries.first
2439 let report = latestEntry.map { self.report(for: $0) } ?? reportBuilder.build(from: placeholderSnapshot(for: trackedDomain))
2440 let recentMonitoringResults = monitoringLogs
2441 .flatMap(\.checkedDomains)
2442 .filter { $0.domain.caseInsensitiveCompare(trackedDomain.domain) == .orderedSame }
2443 .sorted { $0.checkedAt > $1.checkedAt }
2444 let recentFailureResults = recentMonitoringResults.filter {
2445 let isFailure = $0.errorMessage != nil || ($0.alertSeverity ?? .info) >= .warning
2446 return isFailure && now.timeIntervalSince($0.checkedAt) <= 7 * 24 * 60 * 60
2447 }
2448 let recentChangeCount = recentEntries.filter {
2449 guard let changeSummary = $0.changeSummary, changeSummary.hasChanges else { return false }
2450 return now.timeIntervalSince($0.timestamp) <= 7 * 24 * 60 * 60
2451 }.count
2452 let recentDNSChange = recentEntries.contains {
2453 guard let changeSummary = $0.changeSummary else { return false }
2454 return changeSummary.changedSections.contains(where: { $0.localizedCaseInsensitiveContains("dns") })
2455 && now.timeIntervalSince($0.timestamp) <= 7 * 24 * 60 * 60
2456 }
2457 let recentCriticalChange = recentEntries.contains {
2458 guard let changeSummary = $0.changeSummary else { return false }
2459 return changeSummary.impactClassification == .critical
2460 && now.timeIntervalSince($0.timestamp) <= 7 * 24 * 60 * 60
2461 }
2462 let certificateExpiryState = trackedDomain.certificateWarningLevel == .none
2463 ? report.certificateExpiryState
2464 : trackedDomain.certificateWarningLevel
2465 let isUnreachable: Bool = {
2466 if let latestEntry {
2467 if !latestEntry.reachabilityResults.isEmpty {
2468 return !latestEntry.reachabilityResults.contains(where: \.reachable)
2469 }
2470 if latestEntry.reachabilityError != nil {
2471 return true
2472 }
2473 }
2474 return recentFailureResults.contains { ($0.alertSeverity ?? .info) == .critical && $0.errorMessage != nil }
2475 }()
2476 let hasInvalidTLS = latestEntry?.sslInfo == nil && latestEntry?.sslError != nil
2477 let instabilityScore = DomainHealth.instabilityScore(
2478 recentChangeCount: recentChangeCount,
2479 recentFailureCount: recentFailureResults.count,
2480 pendingAlertCount: trackedDomain.pendingMonitoringAlerts.count,
2481 hasRecentDNSChange: recentDNSChange
2482 )
2483 let health = DomainHealth.classify(
2484 certificateExpiryState: certificateExpiryState,
2485 isReachable: !isUnreachable,
2486 recentMonitoringFailureCount: recentFailureResults.count,
2487 hasRecentDNSChange: recentDNSChange,
2488 instabilityScore: instabilityScore,
2489 hasRecentCriticalChange: recentCriticalChange,
2490 hasInvalidTLS: hasInvalidTLS
2491 )
2492
2493 return PortfolioDomainStatus(
2494 trackedDomain: trackedDomain,
2495 latestEntry: latestEntry,
2496 report: report,
2497 apexDomain: apexDomain(for: trackedDomain.domain),
2498 health: health,
2499 lastChangeDate: latestEntry?.changeSummary?.hasChanges == true
2500 ? latestEntry?.timestamp
2501 : trackedDomain.monitoringState.lastChangeDate ?? report.lastChangeDate,
2502 lastMonitoringFailure: recentFailureResults.first?.checkedAt,
2503 instabilityScore: instabilityScore,
2504 certificateExpiryState: certificateExpiryState,
2505 certificateDaysRemaining: trackedDomain.certificateDaysRemaining ?? latestEntry?.sslInfo?.daysUntilExpiry,
2506 isUnreachable: isUnreachable,
2507 recentDNSChange: recentDNSChange,
2508 recentCriticalChange: recentCriticalChange,
2509 recentFailureCount: recentFailureResults.count
2510 )
2511 }
2512 }
2513
2514 private func buildPortfolioActivity(from domainStates: [PortfolioDomainStatus]) -> [PortfolioActivityItem] {
2515 var items: [PortfolioActivityItem] = []
2516 let healthByDomainID = Dictionary(uniqueKeysWithValues: domainStates.map { ($0.trackedDomain.id, $0.health) })
2517
2518 for state in domainStates {
2519 if let latestEntry = state.latestEntry,
2520 let changeSummary = latestEntry.changeSummary,
2521 changeSummary.hasChanges {
2522 items.append(
2523 PortfolioActivityItem(
2524 id: "history|\(latestEntry.id.uuidString)",
2525 trackedDomainID: state.trackedDomain.id,
2526 domain: state.trackedDomain.domain,
2527 message: portfolioHistoryMessage(for: latestEntry),
2528 timestamp: latestEntry.timestamp,
2529 health: state.health,
2530 systemImage: portfolioHistoryIcon(for: latestEntry)
2531 )
2532 )
2533 }
2534 }
2535
2536 for log in monitoringLogs.prefix(25) {
2537 for result in log.checkedDomains where result.didChange || result.errorMessage != nil || result.certificateWarningLevel != .none {
2538 guard let trackedDomain = trackedDomain(for: result.domain) else { continue }
2539 items.append(
2540 PortfolioActivityItem(
2541 id: "monitoring|\(log.id.uuidString)|\(result.id.uuidString)",
2542 trackedDomainID: trackedDomain.id,
2543 domain: trackedDomain.domain,
2544 message: portfolioMonitoringMessage(for: result),
2545 timestamp: result.checkedAt,
2546 health: healthByDomainID[trackedDomain.id] ?? (result.alertSeverity == .critical ? .critical : .warning),
2547 systemImage: portfolioMonitoringIcon(for: result)
2548 )
2549 )
2550 }
2551 }
2552
2553 var seen = Set<String>()
2554 return items
2555 .sorted { $0.timestamp > $1.timestamp }
2556 .filter { item in
2557 let key = "\(item.domain.lowercased())|\(item.message.lowercased())"
2558 return seen.insert(key).inserted
2559 }
2560 }
2561
2562 private func buildAttentionQueue(from domainStates: [PortfolioDomainStatus]) -> [PortfolioAttentionItem] {
2563 domainStates.compactMap { state in
2564 guard state.health != .healthy else { return nil }
2565 let (reason, timestamp) = Self.attentionReason(for: state)
2566 return PortfolioAttentionItem(
2567 id: "\(state.trackedDomain.id.uuidString)|\(reason)",
2568 trackedDomainID: state.trackedDomain.id,
2569 domain: state.trackedDomain.domain,
2570 reason: reason,
2571 timestamp: timestamp,
2572 health: state.health
2573 )
2574 }
2575 .sorted { lhs, rhs in
2576 if lhs.health != rhs.health {
2577 return lhs.health.severityRank > rhs.health.severityRank
2578 }
2579 return lhs.timestamp > rhs.timestamp
2580 }
2581 }
2582
2583 /// Why an unhealthy domain needs attention, most urgent cause first, and
2584 /// when that cause was last seen.
2585 private static func attentionReason(for state: PortfolioDomainStatus) -> (reason: String, timestamp: Date) {
2586 let changedAt = state.lastChangeDate ?? state.trackedDomain.updatedAt
2587 let failedAt = state.lastMonitoringFailure ?? state.trackedDomain.updatedAt
2588 if state.isUnreachable {
2589 return ("Endpoint is unreachable", failedAt)
2590 }
2591 if state.certificateExpiryState == .critical {
2592 return ("Certificate is expiring in under 14 days", changedAt)
2593 }
2594 if state.certificateExpiryState == .warning {
2595 return ("Certificate expires within 30 days", changedAt)
2596 }
2597 if state.recentFailureCount >= 2 || state.instabilityScore >= 70 {
2598 return ("Repeated instability detected", failedAt)
2599 }
2600 if state.recentDNSChange {
2601 return ("DNS changed recently", changedAt)
2602 }
2603 if state.recentCriticalChange {
2604 return ("Recent critical change detected", changedAt)
2605 }
2606 return ("Needs attention", state.trackedDomain.updatedAt)
2607 }
2608
2609 private func portfolioHistoryMessage(for entry: HistoryEntry) -> String {
2610 guard let summary = entry.changeSummary else {
2611 return "Configuration changed for \(entry.domain)"
2612 }
2613 if summary.changedSections.contains(where: { $0.localizedCaseInsensitiveContains("dns") }) {
2614 return "DNS changed for \(entry.domain)"
2615 }
2616 if summary.changedSections.contains(where: {
2617 $0.localizedCaseInsensitiveContains("certificate")
2618 || $0.localizedCaseInsensitiveContains("tls")
2619 }) {
2620 return "Certificate updated for \(entry.domain)"
2621 }
2622 if summary.changedSections.contains(where: { $0.localizedCaseInsensitiveContains("redirect") }) {
2623 return "Redirect chain changed for \(entry.domain)"
2624 }
2625 return summary.message
2626 }
2627
2628 private func portfolioHistoryIcon(for entry: HistoryEntry) -> String {
2629 guard let summary = entry.changeSummary else { return "clock.arrow.trianglehead.counterclockwise.rotate.90" }
2630 if summary.changedSections.contains(where: { $0.localizedCaseInsensitiveContains("dns") }) {
2631 return "point.3.connected.trianglepath.dotted"
2632 }
2633 if summary.changedSections.contains(where: {
2634 $0.localizedCaseInsensitiveContains("certificate")
2635 || $0.localizedCaseInsensitiveContains("tls")
2636 }) {
2637 return "lock.rotation"
2638 }
2639 if summary.changedSections.contains(where: { $0.localizedCaseInsensitiveContains("redirect") }) {
2640 return "arrow.triangle.branch"
2641 }
2642 return "clock.arrow.trianglehead.counterclockwise.rotate.90"
2643 }
2644
2645 private func portfolioMonitoringMessage(for result: MonitoringDomainResult) -> String {
2646 if result.errorMessage != nil {
2647 return "Monitoring failed for \(result.domain)"
2648 }
2649 if result.certificateWarningLevel != .none {
2650 return "Certificate needs attention for \(result.domain)"
2651 }
2652 if result.didChange {
2653 return result.summaryMessage.isEmpty ? "Monitoring detected a change for \(result.domain)" : result.summaryMessage
2654 }
2655 return "Monitoring updated \(result.domain)"
2656 }
2657
2658 private func portfolioMonitoringIcon(for result: MonitoringDomainResult) -> String {
2659 if result.errorMessage != nil {
2660 return "xmark.octagon.fill"
2661 }
2662 if result.certificateWarningLevel != .none {
2663 return "exclamationmark.triangle.fill"
2664 }
2665 return "waveform.path.ecg"
2666 }
2667
2668 private func apexDomain(for domain: String) -> String {
2669 let parts = domain
2670 .lowercased()
2671 .split(separator: ".")
2672 .map(String.init)
2673 guard parts.count > 2 else { return domain.lowercased() }
2674 return parts.suffix(2).joined(separator: ".")
2675 }
2676
2677 private func exportSnapshots(for domains: [TrackedDomain]) -> [LookupSnapshot] {
2678 let latestEntries = latestSnapshots(for: domains)
2679
2680 return domains.map { trackedDomain in
2681 if let entry = latestEntries.first(where: { $0.trackedDomainID == trackedDomain.id || $0.domain.caseInsensitiveCompare(trackedDomain.domain) == .orderedSame }) {
2682 return entry.snapshot
2683 }
2684 return placeholderSnapshot(for: trackedDomain)
2685 }
2686 }
2687
2688 func currentBatchReports() -> [DomainReport] {
2689 currentBatchResultEntries.map { entry in
2690 report(for: entry, workflowContext: activeWorkflowContext)
2691 }
2692 }
2693
2694 func workflowReports(from summary: WorkflowRunSummary, changedOnly: Bool) -> [DomainReport] {
2695 let filteredResults = changedOnly ? summary.results.filter(\.hasMeaningfulChange) : summary.results
2696 return filteredResults.compactMap { result in
2697 guard let entry = historyEntry(for: result) else { return nil }
2698 return report(
2699 for: entry,
2700 workflowContext: DomainWorkflowContext(
2701 workflowID: summary.workflowID,
2702 workflowName: summary.workflowName,
2703 source: "workflow"
2704 )
2705 )
2706 }
2707 }
2708
2709 func reports(for domains: [TrackedDomain]) -> [DomainReport] {
2710 let latestEntries = latestSnapshots(for: domains)
2711
2712 return domains.map { trackedDomain in
2713 if let entry = latestEntries.first(where: {
2714 $0.trackedDomainID == trackedDomain.id ||
2715 $0.domain.caseInsensitiveCompare(trackedDomain.domain) == .orderedSame
2716 }) {
2717 return report(for: entry)
2718 }
2719
2720 return reportBuilder.build(from: placeholderSnapshot(for: trackedDomain))
2721 }
2722 }
2723
2724 func timelineReports(for domain: String) -> [DomainReport] {
2725 historyEntries(for: domain).map { report(for: $0) }
2726 }
2727
2728 private func report(for entry: HistoryEntry, workflowContext: DomainWorkflowContext? = nil) -> DomainReport {
2729 reportBuilder.build(
2730 from: entry,
2731 previousSnapshot: comparisonSnapshot(for: entry),
2732 workflowContext: workflowContext,
2733 historyEntries: historyEntries(for: entry.domain)
2734 )
2735 }
2736
2737 private var activeWorkflowContext: DomainWorkflowContext? {
2738 guard batchLookupSource == .workflow, let activeWorkflowRunID, let activeWorkflowRunName else {
2739 return nil
2740 }
2741 return DomainWorkflowContext(
2742 workflowID: activeWorkflowRunID,
2743 workflowName: activeWorkflowRunName,
2744 source: "workflow"
2745 )
2746 }
2747
2748 private static var defaultAuditReviewer: String {
2749 let reviewer = NSFullUserName().trimmingCharacters(in: .whitespacesAndNewlines)
2750 return reviewer.isEmpty ? "Local Reviewer" : reviewer
2751 }
2752
2753 private func snapshotEvidenceAssets(from report: DomainReport) -> [AuditEvidenceAsset] {
2754 var assets: [AuditEvidenceAsset] = []
2755 if let finalURL = report.web.finalURL {
2756 assets.append(AuditEvidenceAsset(title: "Final URL", kind: .document, reference: finalURL))
2757 }
2758 if let registrar = report.ownership?.registrar {
2759 assets.append(AuditEvidenceAsset(title: "Registrar", kind: .document, reference: registrar))
2760 }
2761 if let primaryIP = report.dns.primaryIP {
2762 assets.append(AuditEvidenceAsset(title: "Primary IP", kind: .document, reference: primaryIP))
2763 }
2764 if !report.web.redirectChain.isEmpty {
2765 assets.append(
2766 AuditEvidenceAsset(
2767 title: "Redirect Chain",
2768 kind: .document,
2769 reference: report.web.redirectChain.map { "\($0.statusCode) \($0.url)" }.joined(separator: " | ")
2770 )
2771 )
2772 }
2773 if !report.web.headers.isEmpty {
2774 assets.append(
2775 AuditEvidenceAsset(
2776 title: "Observed Headers",
2777 kind: .document,
2778 reference: report.web.headers.prefix(6).map { "\($0.name): \($0.value)" }.joined(separator: " | ")
2779 )
2780 )
2781 }
2782 return assets
2783 }
2784
2785 private func placeholderSnapshot(for trackedDomain: TrackedDomain) -> LookupSnapshot {
2786 LookupSnapshot(
2787 historyEntryID: trackedDomain.lastSnapshotID,
2788 domain: trackedDomain.domain,
2789 timestamp: trackedDomain.updatedAt,
2790 trackedDomainID: trackedDomain.id,
2791 note: trackedDomain.note,
2792 appVersion: AppVersion.current,
2793 resolverDisplayName: resolverDisplayName,
2794 resolverURLString: resolverURLString,
2795 dataSources: [],
2796 provenanceBySection: [:],
2797 availabilityConfidence: nil,
2798 ownershipConfidence: nil,
2799 subdomainConfidence: nil,
2800 emailSecurityConfidence: nil,
2801 geolocationConfidence: nil,
2802 errorDetails: [:],
2803 isPartialSnapshot: true,
2804 validationIssues: ["No stored snapshot data available"],
2805 totalLookupDurationMs: nil,
2806 snapshotIndex: nil,
2807 previousSnapshotID: nil,
2808 changeCount: 0,
2809 severitySummary: trackedDomain.lastChangeSeverity,
2810 dnsSections: [],
2811 dnsError: nil,
2812 availabilityResult: DomainAvailabilityResult(domain: trackedDomain.domain, status: trackedDomain.lastKnownAvailability ?? .unknown),
2813 suggestions: [],
2814 sslInfo: nil,
2815 sslError: nil,
2816 hstsPreloaded: nil,
2817 httpHeaders: [],
2818 httpSecurityGrade: nil,
2819 httpStatusCode: nil,
2820 httpResponseTimeMs: nil,
2821 httpProtocol: nil,
2822 http3Advertised: false,
2823 httpHeadersError: nil,
2824 reachabilityResults: [],
2825 reachabilityError: nil,
2826 ipGeolocation: nil,
2827 ipGeolocationError: nil,
2828 emailSecurity: nil,
2829 emailSecurityError: nil,
2830 ownership: nil,
2831 ownershipError: nil,
2832 ownershipHistory: [],
2833 ownershipHistoryError: nil,
2834 inferredProvider: nil,
2835 priorProviders: [],
2836 domainClassification: nil,
2837 ownershipTransitions: [],
2838 hostingTransitions: [],
2839 subdomainHistory: [],
2840 riskSignals: [],
2841 intelligenceTimeline: [],
2842 ptrRecord: nil,
2843 ptrError: nil,
2844 redirectChain: [],
2845 redirectChainError: nil,
2846 subdomains: [],
2847 subdomainsError: nil,
2848 extendedSubdomains: [],
2849 extendedSubdomainsError: nil,
2850 dnsHistory: [],
2851 dnsHistoryError: nil,
2852 domainPricing: nil,
2853 domainPricingError: nil,
2854 reputation: nil,
2855 reputationError: nil,
2856 portScanResults: [],
2857 portScanError: nil,
2858 changeSummary: trackedDomain.lastChangeSummary,
2859 resultSource: .snapshot,
2860 cachedSections: [],
2861 statusMessage: nil
2862 )
2863 }
2864
2865 private static func loadHistoryEntries(
2866 defaults: UserDefaults,
2867 historyLocation: HistoryFileStore.Location
2868 ) -> [HistoryEntry] {
2869 DataMigrationService.migrateIfNeeded(defaults: defaults, historyLocation: historyLocation)
2870 return DomainDataPortabilityService.loadHistoryEntries(
2871 defaults: defaults,
2872 historyLocation: historyLocation
2873 )
2874 }
2875
2876 private static func loadHistoryAutoPruneOption(defaults: UserDefaults) -> HistoryAutoPruneOption {
2877 guard let rawValue = defaults.string(forKey: historyAutoPruneKey),
2878 let option = HistoryAutoPruneOption(rawValue: rawValue) else {
2879 return .unlimited
2880 }
2881 return option
2882 }
2883
2884 private static func loadTrackedDomains(
2885 defaults: UserDefaults,
2886 historyLocation: HistoryFileStore.Location
2887 ) -> [TrackedDomain] {
2888 DataMigrationService.migrateIfNeeded(defaults: defaults, historyLocation: historyLocation)
2889 return DomainDataPortabilityService.loadTrackedDomains(defaults: defaults)
2890 }
2891
2892 func persistWorkflows() {
2893 DomainDataPortabilityService.saveWorkflows(workflows, defaults: defaults)
2894 CloudSyncService.shared.scheduleSyncIfNeeded()
2895 refreshDataLifecycleSummary()
2896 }
2897
2898 static func loadWorkflows(
2899 defaults: UserDefaults,
2900 historyLocation: HistoryFileStore.Location
2901 ) -> [DomainWorkflow] {
2902 DataMigrationService.migrateIfNeeded(defaults: defaults, historyLocation: historyLocation)
2903 return DomainDataPortabilityService.loadWorkflows(defaults: defaults)
2904 }
2905
2906 private static func deduplicatedTrackedDomains(_ domains: [TrackedDomain]) -> [TrackedDomain] {
2907 var seen = Set<String>()
2908 return domains.filter { domain in
2909 let key = domain.domain.lowercased()
2910 return seen.insert(key).inserted
2911 }
2912 }
2913
2914 func normalizedDomains(_ domains: [String]) -> [String] {
2915 var seen = Set<String>()
2916 return domains
2917 .map(normalizedDomain)
2918 .filter { !$0.isEmpty }
2919 .filter { seen.insert($0).inserted }
2920 }
2921
2922 private func historySortPredicate(lhs: HistoryEntry, rhs: HistoryEntry) -> Bool {
2923 switch historySortOption {
2924 case .newest:
2925 return lhs.timestamp > rhs.timestamp
2926 case .oldest:
2927 return lhs.timestamp < rhs.timestamp
2928 case .domain:
2929 let domainOrder = lhs.domain.localizedCaseInsensitiveCompare(rhs.domain)
2930 if domainOrder != .orderedSame {
2931 return domainOrder == .orderedAscending
2932 }
2933 return lhs.timestamp > rhs.timestamp
2934 }
2935 }
2936
2937 private func sortedTrackedDomains(from domains: [TrackedDomain], using sortOption: WatchlistSortOption) -> [TrackedDomain] {
2938 domains.sorted { lhs, rhs in
2939 switch sortOption {
2940 case .pinned:
2941 if lhs.isPinned != rhs.isPinned {
2942 return lhs.isPinned && !rhs.isPinned
2943 }
2944 if lhs.updatedAt != rhs.updatedAt {
2945 return lhs.updatedAt > rhs.updatedAt
2946 }
2947 return lhs.domain.localizedCaseInsensitiveCompare(rhs.domain) == .orderedAscending
2948 case .recentlyUpdated:
2949 if lhs.updatedAt != rhs.updatedAt {
2950 return lhs.updatedAt > rhs.updatedAt
2951 }
2952 return lhs.domain.localizedCaseInsensitiveCompare(rhs.domain) == .orderedAscending
2953 case .alphabetical:
2954 let domainOrder = lhs.domain.localizedCaseInsensitiveCompare(rhs.domain)
2955 if domainOrder != .orderedSame {
2956 return domainOrder == .orderedAscending
2957 }
2958 return lhs.updatedAt > rhs.updatedAt
2959 }
2960 }
2961 }
2962
2963 static func summaryFields(from snapshot: LookupSnapshot) -> [SummaryFieldViewData] {
2964 [
2965 SummaryFieldViewData(label: "Domain", value: snapshot.domain.nilIfEmpty ?? "Unavailable", tone: .primary),
2966 SummaryFieldViewData(label: "Observed IP", value: primaryIPAddress(from: snapshot) ?? "Unavailable", tone: .primary),
2967 SummaryFieldViewData(label: "Observed Redirect", value: finalRedirectTarget(from: snapshot) ?? "Unavailable", tone: .secondary),
2968 SummaryFieldViewData(label: "Inference", value: availabilityInference(from: snapshot), tone: availabilityTone(snapshot.availabilityResult?.status)),
2969 SummaryFieldViewData(label: "Observed TLS", value: httpsSummary(from: snapshot), tone: httpsSummaryTone(from: snapshot)),
2970 SummaryFieldViewData(label: "Certificate", value: certificateStatusLabel(from: snapshot), tone: certificateStatusTone(from: snapshot)),
2971 SummaryFieldViewData(label: "Source", value: snapshot.statusMessage ?? snapshot.resultSource.label, tone: sourceTone(for: snapshot))
2972 ]
2973 }
2974
2975 static func domainRows(from snapshot: LookupSnapshot) -> [InfoRowViewData] {
2976 var rows = [
2977 InfoRowViewData(label: "Domain", value: snapshot.domain, tone: .primary),
2978 InfoRowViewData(label: "Resolver", value: snapshot.resolverDisplayName, tone: .secondary),
2979 InfoRowViewData(label: "Collected", value: snapshot.timestamp.formatted(date: .abbreviated, time: .shortened), tone: .secondary),
2980 InfoRowViewData(label: snapshot.statusMessage == nil ? "Result" : "Snapshot", value: snapshot.statusMessage ?? snapshot.resultSource.label, tone: sourceTone(for: snapshot)),
2981 InfoRowViewData(label: "Lookup Duration", value: durationLabel(snapshot.totalLookupDurationMs), tone: .secondary)
2982 ]
2983 rows.insert(
2984 InfoRowViewData(
2985 label: "Observed Availability",
2986 value: snapshot.availabilityResult?.status == .unknown ? "No direct registration proof" : "Status collected",
2987 tone: .secondary
2988 ),
2989 at: 1
2990 )
2991 rows.insert(
2992 InfoRowViewData(
2993 label: "Inference",
2994 value: availabilityInference(from: snapshot),
2995 tone: availabilityTone(snapshot.availabilityResult?.status)
2996 ),
2997 at: 2
2998 )
2999 if let confidence = snapshot.availabilityConfidence {
3000 rows.insert(
3001 InfoRowViewData(label: "Confidence", value: confidence.title, tone: .secondary),
3002 at: 3
3003 )
3004 }
3005 if let pricing = snapshot.domainPricing {
3006 rows += pricingRows(pricing)
3007 }
3008 if let reputation = snapshot.reputation {
3009 rows.append(reputationRow(reputation))
3010 }
3011 if let certificateStatus = certificateBadgeLabel(from: snapshot) {
3012 rows.insert(
3013 InfoRowViewData(
3014 label: "Certificate",
3015 value: certificateStatus,
3016 tone: certificateStatusTone(from: snapshot)
3017 ),
3018 at: 2
3019 )
3020 }
3021 return rows
3022 }
3023
3024 private static func pricingRows(_ pricing: DomainPricingInsight) -> [InfoRowViewData] {
3025 var rows = [InfoRowViewData(label: "External Price", value: pricing.estimatedPrice ?? "Unavailable", tone: .secondary)]
3026 if let premiumIndicator = pricing.premiumIndicator {
3027 rows.append(
3028 InfoRowViewData(
3029 label: "Premium",
3030 value: premiumIndicator ? "Yes" : "No",
3031 tone: premiumIndicator ? .warning : .secondary
3032 )
3033 )
3034 }
3035 if let resaleSignal = pricing.resaleSignal {
3036 rows.append(InfoRowViewData(label: "Resale", value: resaleSignal, tone: .secondary))
3037 }
3038 if let auctionSignal = pricing.auctionSignal {
3039 rows.append(InfoRowViewData(label: "Auction", value: auctionSignal, tone: .secondary))
3040 }
3041 return rows
3042 }
3043
3044 private static func reputationRow(_ reputation: DomainReputationResult) -> InfoRowViewData {
3045 let tone: ResultTone
3046 switch reputation.status {
3047 case .clean: tone = .success
3048 case .listed: tone = .failure
3049 case .unknown: tone = .secondary
3050 }
3051 let value = reputation.status == .listed && !reputation.listedSources.isEmpty
3052 ? "\(reputation.status.title) (\(reputation.listedSources.joined(separator: ", ")))"
3053 : reputation.status.title
3054 return InfoRowViewData(label: "Reputation", value: value, tone: tone)
3055 }
3056
3057 static func suggestionRows(from snapshot: LookupSnapshot) -> [DomainSuggestionViewData] {
3058 snapshot.suggestions.map {
3059 DomainSuggestionViewData(
3060 id: $0.id,
3061 domain: $0.domain,
3062 availabilityStatus: $0.status,
3063 status: availabilityLabel($0.status),
3064 tone: availabilityTone($0.status)
3065 )
3066 }
3067 }
3068
3069 static func subdomainRows(from subdomains: [DiscoveredSubdomain]) -> [SubdomainRowViewData] {
3070 subdomains.map { subdomain in
3071 SubdomainRowViewData(
3072 hostname: subdomain.hostname,
3073 isInteresting: subdomain.isExtended || isInterestingSubdomain(subdomain.hostname)
3074 )
3075 }
3076 }
3077
3078 static func dnsRows(from snapshot: LookupSnapshot) -> [DNSRecordSectionViewData] {
3079 snapshot.dnsSections.map { section in
3080 DNSRecordSectionViewData(
3081 title: section.recordType.rawValue,
3082 rows: section.records.map { InfoRowViewData(label: "TTL \($0.ttl)", value: $0.value, tone: .primary, speechStyle: .technical) },
3083 wildcardRows: section.wildcardRecords.map { InfoRowViewData(label: "TTL \($0.ttl)", value: $0.value, tone: .primary, speechStyle: .technical) },
3084 wildcardTitle: section.wildcardRecords.isEmpty ? nil : "*.\(snapshot.domain)",
3085 message: section.error.map { SectionMessageViewData(text: $0, isError: true) } ??
3086 ((section.records.isEmpty && section.wildcardRecords.isEmpty) ? SectionMessageViewData(text: "No records found", isError: false) : nil)
3087 )
3088 }
3089 }
3090
3091 static func dnssecLabel(from snapshot: LookupSnapshot) -> String? {
3092 guard let signed = snapshot.dnsSections.compactMap(\.dnssecSigned).first else { return nil }
3093 return "Resolver-reported DNSSEC (not full validation): \(signed ? "Yes" : "No")"
3094 }
3095
3096 static func ptrMessage(from snapshot: LookupSnapshot) -> SectionMessageViewData? {
3097 if let ptrRecord = snapshot.ptrRecord {
3098 return SectionMessageViewData(text: ptrRecord, isError: false)
3099 }
3100 if let ptrError = snapshot.ptrError {
3101 return SectionMessageViewData(text: ptrError, isError: ptrError != "No A record available" && ptrError != "No PTR record found")
3102 }
3103 return nil
3104 }
3105
3106 static func webCertificateRows(from snapshot: LookupSnapshot) -> [InfoRowViewData] {
3107 guard let sslInfo = snapshot.sslInfo else { return [] }
3108 var rows = [
3109 InfoRowViewData(label: "Common Name", value: sslInfo.commonName, tone: .primary),
3110 InfoRowViewData(label: "Issuer", value: sslInfo.issuer, tone: .primary),
3111 InfoRowViewData(label: "Valid From", value: certificateDateFormatter.string(from: sslInfo.validFrom), tone: .secondary),
3112 InfoRowViewData(label: "Valid Until", value: certificateDateFormatter.string(from: sslInfo.validUntil), tone: .secondary),
3113 InfoRowViewData(label: "Days Until Expiry", value: "\(sslInfo.daysUntilExpiry)", tone: certificateTone(daysRemaining: sslInfo.daysUntilExpiry)),
3114 InfoRowViewData(label: "Chain Depth", value: "\(sslInfo.chainDepth)", tone: .secondary)
3115 ]
3116 if let tlsVersion = sslInfo.tlsVersion {
3117 rows.append(InfoRowViewData(label: "TLS Version", value: tlsVersion, tone: .secondary))
3118 }
3119 if let cipherSuite = sslInfo.cipherSuite {
3120 rows.append(InfoRowViewData(label: "Cipher Suite", value: cipherSuite, tone: .secondary, speechStyle: .technical))
3121 }
3122 if let hstsPreloaded = snapshot.hstsPreloaded {
3123 rows.append(InfoRowViewData(label: "HSTS Preload", value: hstsPreloaded ? "Preloaded" : "Not preloaded", tone: hstsPreloaded ? .success : .secondary))
3124 }
3125 return rows
3126 }
3127
3128 static func webResponseRows(from snapshot: LookupSnapshot) -> [InfoRowViewData] {
3129 var rows: [InfoRowViewData] = []
3130 if let httpStatusCode = snapshot.httpStatusCode {
3131 rows.append(InfoRowViewData(label: "Status", value: "\(httpStatusCode)", tone: .primary))
3132 }
3133 if let httpResponseTimeMs = snapshot.httpResponseTimeMs {
3134 rows.append(InfoRowViewData(label: "Response Time", value: "\(httpResponseTimeMs) ms", tone: .secondary))
3135 }
3136 if let httpProtocol = snapshot.httpProtocol {
3137 rows.append(InfoRowViewData(label: "Protocol", value: httpProtocol, tone: .secondary))
3138 }
3139 if let httpSecurityGrade = snapshot.httpSecurityGrade {
3140 rows.append(InfoRowViewData(label: "Security Grade", value: httpSecurityGrade, tone: securityGradeTone(httpSecurityGrade)))
3141 }
3142 if snapshot.http3Advertised {
3143 rows.append(InfoRowViewData(label: "HTTP/3", value: "Advertised", tone: .secondary))
3144 }
3145 return rows
3146 }
3147
3148 static func redirectRows(from snapshot: LookupSnapshot) -> [RedirectHopViewData] {
3149 snapshot.redirectChain.map {
3150 RedirectHopViewData(
3151 stepLabel: "\($0.stepNumber)",
3152 statusCode: "\($0.statusCode)",
3153 url: $0.url,
3154 isFinal: $0.isFinal
3155 )
3156 }
3157 }
3158
3159 static func emailRows(from snapshot: LookupSnapshot) -> [EmailRowViewData] {
3160 guard let emailSecurity = snapshot.emailSecurity else { return [] }
3161 return [
3162 EmailRowViewData(label: "SPF", status: emailSecurity.spf.found ? "Present" : "Missing", statusTone: emailSecurity.spf.found ? .success : .warning, detail: emailSecurity.spf.value ?? "No record found", auxiliaryDetail: nil),
3163 EmailRowViewData(label: "DMARC", status: emailSecurity.dmarc.found ? "Present" : "Missing", statusTone: emailSecurity.dmarc.found ? .success : .warning, detail: emailSecurity.dmarc.value ?? "No record found", auxiliaryDetail: nil),
3164 EmailRowViewData(label: "DKIM", status: emailSecurity.dkim.found ? "Present" : "Missing", statusTone: emailSecurity.dkim.found ? .success : .warning, detail: emailSecurity.dkim.value ?? "No record found", auxiliaryDetail: emailSecurity.dkim.matchedSelector.map { "Selector: \($0)" }),
3165 EmailRowViewData(label: "MTA-STS", status: emailSecurity.mtaSts?.txtFound == true ? "Present" : "Missing", statusTone: emailSecurity.mtaSts?.txtFound == true ? .success : .warning, detail: emailSecurity.mtaSts?.policyMode ?? (emailSecurity.mtaSts?.txtFound == true ? "Policy unavailable" : "No record found"), auxiliaryDetail: nil),
3166 EmailRowViewData(label: "BIMI", status: emailSecurity.bimi.found ? "Present" : "Missing", statusTone: emailSecurity.bimi.found ? .success : .warning, detail: emailSecurity.bimi.value ?? "No record found", auxiliaryDetail: nil)
3167 ]
3168 }
3169
3170 static func ownershipRows(from snapshot: LookupSnapshot) -> [InfoRowViewData] {
3171 let ownership = snapshot.ownership
3172
3173 return [
3174 InfoRowViewData(label: "Registrar", value: ownership?.registrar ?? "Unavailable", tone: ownership?.registrar == nil ? .secondary : .primary),
3175 InfoRowViewData(label: "Registered", value: ownership?.createdDate.map(ownershipDateFormatter.string(from:)) ?? "Unavailable", tone: ownership?.createdDate == nil ? .secondary : .primary),
3176 InfoRowViewData(label: "Expires", value: ownership?.expirationDate.map(ownershipDateFormatter.string(from:)) ?? "Unavailable", tone: ownership?.expirationDate == nil ? .secondary : .primary),
3177 InfoRowViewData(label: "Status", value: ownership?.status.nilIfEmpty?.joined(separator: ", ") ?? "Unavailable", tone: ownership?.status.isEmpty == false ? .primary : .secondary),
3178 InfoRowViewData(label: "Nameservers", value: ownership?.nameservers.nilIfEmpty?.joined(separator: ", ") ?? "Unavailable", tone: ownership?.nameservers.isEmpty == false ? .primary : .secondary),
3179 InfoRowViewData(label: "Abuse Contact", value: ownership?.abuseEmail ?? "Unavailable", tone: ownership?.abuseEmail == nil ? .secondary : .primary)
3180 ]
3181 }
3182
3183 static func subdomainRows(from snapshot: LookupSnapshot) -> [SubdomainRowViewData] {
3184 snapshot.subdomains.map { subdomain in
3185 SubdomainRowViewData(
3186 hostname: subdomain.hostname,
3187 isInteresting: isInterestingSubdomain(subdomain.hostname)
3188 )
3189 }
3190 }
3191
3192 static func reachabilityRows(from snapshot: LookupSnapshot) -> [ReachabilityRowViewData] {
3193 snapshot.reachabilityResults.map {
3194 ReachabilityRowViewData(
3195 portLabel: "Port \($0.port)",
3196 latencyLabel: $0.latencyMs.map { "\($0) ms" } ?? "—",
3197 statusLabel: $0.reachable ? "Reachable" : "Unreachable",
3198 statusTone: $0.reachable ? .success : .failure
3199 )
3200 }
3201 }
3202
3203 static func locationRows(from snapshot: LookupSnapshot) -> [InfoRowViewData] {
3204 guard let ipGeolocation = snapshot.ipGeolocation else { return [] }
3205 var rows = [InfoRowViewData(label: "IP", value: ipGeolocation.ip, tone: .primary)]
3206 if let org = ipGeolocation.org {
3207 rows.append(InfoRowViewData(label: "Org / ISP", value: org, tone: .secondary))
3208 }
3209 let location = [ipGeolocation.city, ipGeolocation.region, ipGeolocation.countryName].compactMap { $0 }.joined(separator: ", ")
3210 if !location.isEmpty {
3211 rows.append(InfoRowViewData(label: "Location", value: location, tone: .secondary))
3212 }
3213 if let latitude = ipGeolocation.latitude, let longitude = ipGeolocation.longitude {
3214 rows.append(InfoRowViewData(label: "Coordinates", value: "\(latitude), \(longitude)", tone: .secondary))
3215 }
3216 return rows
3217 }
3218
3219 static func portRows(from snapshot: LookupSnapshot, kind: PortScanKind) -> [PortScanRowViewData] {
3220 snapshot.portScanResults
3221 .filter { $0.kind == kind }
3222 .map {
3223 PortScanRowViewData(
3224 portLabel: "\($0.port)",
3225 service: $0.service,
3226 statusLabel: $0.open ? "Open" : "Closed",
3227 statusTone: $0.open ? .success : .secondary,
3228 banner: $0.banner,
3229 durationLabel: $0.durationMs.map { "\($0) ms" }
3230 )
3231 }
3232 }
3233
3234 static func primaryIPAddress(from snapshot: LookupSnapshot) -> String? {
3235 snapshot.dnsSections.first(where: { $0.recordType == .A })?.records.first?.value
3236 }
3237
3238 static func finalRedirectTarget(from snapshot: LookupSnapshot) -> String? {
3239 snapshot.redirectChain.last?.url
3240 }
3241
3242 static func httpsSummary(from snapshot: LookupSnapshot) -> String {
3243 if snapshot.sslInfo != nil {
3244 return "Valid"
3245 }
3246 if let sslError = snapshot.sslError {
3247 return sslError.localizedCaseInsensitiveContains("certificate") ? "Invalid" : "Failed"
3248 }
3249 return "Unavailable"
3250 }
3251
3252 private static func httpsSummaryTone(from snapshot: LookupSnapshot) -> ResultTone {
3253 if snapshot.sslInfo != nil {
3254 return .success
3255 }
3256 return snapshot.sslError == nil ? .secondary : .failure
3257 }
3258
3259 static func emailSummary(from snapshot: LookupSnapshot) -> String {
3260 guard let emailSecurity = snapshot.emailSecurity else {
3261 return snapshot.emailSecurityError ?? "Unavailable"
3262 }
3263 return "SPF \(emailSecurity.spf.found ? "Yes" : "No") / DMARC \(emailSecurity.dmarc.found ? "Yes" : "No")"
3264 }
3265
3266 private static func certificateStatusLabel(from snapshot: LookupSnapshot) -> String {
3267 guard let sslInfo = snapshot.sslInfo else {
3268 return snapshot.sslError ?? "Unavailable"
3269 }
3270
3271 switch DomainDiffService.certificateWarningLevel(for: snapshot) {
3272 case .critical:
3273 return "Critical (\(sslInfo.daysUntilExpiry)d)"
3274 case .warning:
3275 return "Warning (\(sslInfo.daysUntilExpiry)d)"
3276 case .none:
3277 return "Healthy (\(sslInfo.daysUntilExpiry)d)"
3278 }
3279 }
3280
3281 private static func certificateBadgeLabel(from snapshot: LookupSnapshot) -> String? {
3282 guard snapshot.sslInfo != nil else { return nil }
3283 return certificateStatusLabel(from: snapshot)
3284 }
3285
3286 private static func certificateStatusTone(from snapshot: LookupSnapshot) -> ResultTone {
3287 guard let daysRemaining = snapshot.sslInfo?.daysUntilExpiry else {
3288 return snapshot.sslError == nil ? .secondary : .failure
3289 }
3290 return certificateTone(daysRemaining: daysRemaining)
3291 }
3292
3293 private static func certificateTone(daysRemaining: Int) -> ResultTone {
3294 if daysRemaining < 14 {
3295 return .failure
3296 }
3297 if daysRemaining < 30 {
3298 return .warning
3299 }
3300 return .success
3301 }
3302
3303 static func availabilityLabel(_ status: DomainAvailabilityStatus?) -> String {
3304 switch status {
3305 case .available:
3306 return "Available"
3307 case .registered:
3308 return "Registered"
3309 case .unknown, .none:
3310 return "Unknown"
3311 }
3312 }
3313
3314 private static func availabilityInference(from snapshot: LookupSnapshot) -> String {
3315 switch snapshot.availabilityResult?.status {
3316 case .registered:
3317 return "Likely registered"
3318 case .available:
3319 return "Possibly available"
3320 case .unknown, .none:
3321 return "Unclear"
3322 }
3323 }
3324
3325 private static func availabilityTone(_ status: DomainAvailabilityStatus?) -> ResultTone {
3326 switch status {
3327 case .available:
3328 return .success
3329 case .registered:
3330 return .warning
3331 case .unknown, .none:
3332 return .secondary
3333 }
3334 }
3335
3336 private static func sourceTone(for snapshot: LookupSnapshot) -> ResultTone {
3337 if snapshot.statusMessage != nil {
3338 return .warning
3339 }
3340
3341 switch snapshot.resultSource {
3342 case .live:
3343 return .success
3344 case .cached:
3345 return .secondary
3346 case .mixed:
3347 return .warning
3348 case .snapshot:
3349 return .warning
3350 }
3351 }
3352
3353 private static func securityGradeTone(_ grade: String) -> ResultTone {
3354 switch grade {
3355 case "A", "B":
3356 return .success
3357 case "C":
3358 return .warning
3359 case "D", "F":
3360 return .failure
3361 default:
3362 return .secondary
3363 }
3364 }
3365
3366 static func durationLabel(_ durationMs: Int?) -> String {
3367 durationMs.map { "\($0) ms" } ?? "Unavailable"
3368 }
3369
3370 private static let certificateDateFormatter: DateFormatter = {
3371 let formatter = DateFormatter()
3372 formatter.dateStyle = .medium
3373 formatter.timeStyle = .short
3374 return formatter
3375 }()
3376
3377 private static let ownershipDateFormatter: DateFormatter = {
3378 let formatter = DateFormatter()
3379 formatter.dateStyle = .medium
3380 formatter.timeStyle = .none
3381 return formatter
3382 }()
3383
3384 private func conciseExternalMessage(_ message: String, fallback: String) -> String {
3385 let trimmed = message.trimmingCharacters(in: .whitespacesAndNewlines)
3386 if trimmed.isEmpty {
3387 return fallback
3388 }
3389 if trimmed.localizedCaseInsensitiveContains("rate") {
3390 return "Rate limited. Try again later."
3391 }
3392 if trimmed.localizedCaseInsensitiveContains("invalid") {
3393 return "External data was invalid."
3394 }
3395 if trimmed.localizedCaseInsensitiveContains("network") {
3396 return "External data is offline."
3397 }
3398 return trimmed
3399 }
3400
3401 private static func isInterestingSubdomain(_ hostname: String) -> Bool {
3402 let keywords = ["admin", "api", "dev", "staging", "test", "internal"]
3403 let labels = hostname.lowercased().split(separator: ".").map(String.init)
3404 return labels.contains { label in
3405 keywords.contains(where: { label.contains($0) })
3406 }
3407 }
3408}
3409