Commit f82d4efc9c

f82d4efc9c225e89c2c7e0326313a94dd1240af8

parent: 1c232d563b

Verified · cmc

cmc <hello@cleberg.net> · 2026-10-24 05:07 UTC

Stop selling capabilities that cannot return data

Pro+ promised five capabilities and four of them could not produce anything in
a shipping build: pricing and reputation resolved to .empty with no endpoint
configured, and ownership and DNS history returned only events re-derived from
the user's own stored snapshots. Those five were also Pro+'s entire difference
from Pro, so deleting them without replacement would have left a tier that
grants nothing.

The new table: ownership and DNS history are ungated, being local derivations;
pricing and reputation are deleted, having no local derivation and no provider;
extended subdomains moves down to Pro, since its crt.sh query at limit 100 does
return data the base lookup's 25 does not; and Pro+ gains sharedPortfolios and
auditDepth, both of which were already built and given away.

Creating a share now needs Pro+ while managing an existing one does not, and
free keeps one audit session open at a time. Limits gate adding, not holding, so
a lapsed subscriber loses access to nothing they already have.

The usage meter is deleted outright. It was never enforced — canUse and consume
had no callers — and never displayed either: the three status values reached
view initialisers, were stored, and were read by no view body. Its backup field
was Optional, so old backups still decode; the orphaned usageCredits.ledger key
remains in UserDefaults until a reset.

DomainReport keeps its domainPricing and reputation fields and the CSV keeps its
seven columns, always empty, so the Local API v1 shape is unchanged.

141 tests pass on iOS 18.6 and iOS 27.0.

Layout: unified · split

DomainDataPortabilityService.swift +3 −42
@@ -26,12 +26,6 @@ struct AppSettingsSnapshot: Codable {
26 26
27struct FeatureMetadataSnapshot: Codable { 27struct FeatureMetadataSnapshot: Codable {
28 let cachedEntitlement: PurchaseService.CachedEntitlement? 28 let cachedEntitlement: PurchaseService.CachedEntitlement?
29 let usageCredits: UsageCreditsSnapshot?
30}
31
32struct UsageCreditsSnapshot: Codable {
33 let appVersion: String
34 let remainingByFeature: [UsageCreditFeature: Int]
35} 29}
36 30
37struct TrackedDomainsExport: Codable { 31struct TrackedDomainsExport: Codable {
@@ -565,7 +559,6 @@ enum DomainDataPortabilityService {
565 static let appDensity = AppDensity.userDefaultsKey 559 static let appDensity = AppDensity.userDefaultsKey
566 static let resolverURL = DNSResolverOption.userDefaultsKey 560 static let resolverURL = DNSResolverOption.userDefaultsKey
567 static let purchaseCache = "purchase.cachedEntitlement" 561 static let purchaseCache = "purchase.cachedEntitlement"
568 static let usageCredits = "usageCredits.ledger"
569 } 562 }
570 563
571 static func loadRecentSearches(defaults: UserDefaults = .standard) -> [String] { 564 static func loadRecentSearches(defaults: UserDefaults = .standard) -> [String] {
@@ -727,14 +720,7 @@ enum DomainDataPortabilityService {
727 cachedEntitlement = nil 720 cachedEntitlement = nil
728 } 721 }
729 722
730 let usageCredits: UsageCreditsSnapshot? 723 return FeatureMetadataSnapshot(cachedEntitlement: cachedEntitlement)
731 if let data = defaults.data(forKey: StorageKey.usageCredits) {
732 usageCredits = try? JSONDecoder().decode(UsageCreditsSnapshot.self, from: data)
733 } else {
734 usageCredits = nil
735 }
736
737 return FeatureMetadataSnapshot(cachedEntitlement: cachedEntitlement, usageCredits: usageCredits)
738 } 724 }
739 725
740 static func saveFeatureMetadata(_ featureMetadata: FeatureMetadataSnapshot?, defaults: UserDefaults = .standard) { 726 static func saveFeatureMetadata(_ featureMetadata: FeatureMetadataSnapshot?, defaults: UserDefaults = .standard) {
@@ -742,11 +728,6 @@ enum DomainDataPortabilityService {
742 let data = try? JSONEncoder().encode(cachedEntitlement) { 728 let data = try? JSONEncoder().encode(cachedEntitlement) {
743 defaults.set(data, forKey: StorageKey.purchaseCache) 729 defaults.set(data, forKey: StorageKey.purchaseCache)
744 } 730 }
745
746 if let usageCredits = featureMetadata?.usageCredits,
747 let data = try? JSONEncoder().encode(usageCredits) {
748 defaults.set(data, forKey: StorageKey.usageCredits)
749 }
750 } 731 }
751 732
752 static func currentBackup(defaults: UserDefaults = .standard) -> DomainDigBackup { 733 static func currentBackup(defaults: UserDefaults = .standard) -> DomainDigBackup {
@@ -885,7 +866,6 @@ enum DomainDataPortabilityService {
885 let cachedItems = appSettings.recentSearches.count 866 let cachedItems = appSettings.recentSearches.count
886 + appSettings.savedDomains.count 867 + appSettings.savedDomains.count
887 + (featureMetadata.cachedEntitlement == nil ? 0 : 1) 868 + (featureMetadata.cachedEntitlement == nil ? 0 : 1)
888 + (featureMetadata.usageCredits == nil ? 0 : 1)
889 869
890 return DataLifecycleSummary( 870 return DataLifecycleSummary(
891 trackedDomains: loadTrackedDomains(defaults: defaults).count, 871 trackedDomains: loadTrackedDomains(defaults: defaults).count,
@@ -1095,7 +1075,7 @@ enum DomainDataPortabilityService {
1095 historySnapshots: backup.historyEntries.count, 1075 historySnapshots: backup.historyEntries.count,
1096 auditSessions: backup.auditSessions?.count ?? 0, 1076 auditSessions: backup.auditSessions?.count ?? 0,
1097 workflows: backup.workflows.count, 1077 workflows: backup.workflows.count,
1098 cachedItems: backup.appSettings.recentSearches.count + backup.appSettings.savedDomains.count + ((backup.featureMetadata?.cachedEntitlement == nil ? 0 : 1) + (backup.featureMetadata?.usageCredits == nil ? 0 : 1)), 1078 cachedItems: backup.appSettings.recentSearches.count + backup.appSettings.savedDomains.count + (backup.featureMetadata?.cachedEntitlement == nil ? 0 : 1),
1099 monitoringLogs: backup.monitoringLogs.count 1079 monitoringLogs: backup.monitoringLogs.count
1100 ) 1080 )
1101 } 1081 }
@@ -1297,27 +1277,8 @@ enum DomainDataPortabilityService {
1297 private static func mergeFeatureMetadata(existing: FeatureMetadataSnapshot, incoming: FeatureMetadataSnapshot?) -> FeatureMetadataSnapshot { 1277 private static func mergeFeatureMetadata(existing: FeatureMetadataSnapshot, incoming: FeatureMetadataSnapshot?) -> FeatureMetadataSnapshot {
1298 guard let incoming else { return existing } 1278 guard let incoming else { return existing }
1299 1279
1300 let mergedUsageCredits: UsageCreditsSnapshot?
1301 switch (existing.usageCredits, incoming.usageCredits) {
1302 case let (.some(lhs), .some(rhs)):
1303 let mergedRemaining = Dictionary(uniqueKeysWithValues: UsageCreditFeature.allCases.map { feature in
1304 (feature, max(lhs.remainingByFeature[feature] ?? 0, rhs.remainingByFeature[feature] ?? 0))
1305 })
1306 mergedUsageCredits = UsageCreditsSnapshot(
1307 appVersion: rhs.appVersion,
1308 remainingByFeature: mergedRemaining
1309 )
1310 case (.some(let lhs), nil):
1311 mergedUsageCredits = lhs
1312 case (nil, .some(let rhs)):
1313 mergedUsageCredits = rhs
1314 case (nil, nil):
1315 mergedUsageCredits = nil
1316 }
1317
1318 return FeatureMetadataSnapshot( 1280 return FeatureMetadataSnapshot(
1319 cachedEntitlement: incoming.cachedEntitlement ?? existing.cachedEntitlement, 1281 cachedEntitlement: incoming.cachedEntitlement ?? existing.cachedEntitlement
1320 usageCredits: mergedUsageCredits
1321 ) 1282 )
1322 } 1283 }
1323 1284
DomainDig.xcodeproj/project.pbxproj +4
@@ -27,6 +27,7 @@
27 C7CA9E02B0DC2708DE7A8563 /* DomainDataPortabilityServiceTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = CC948A02EC0184228BC4630E /* DomainDataPortabilityServiceTests.swift */; }; 27 C7CA9E02B0DC2708DE7A8563 /* DomainDataPortabilityServiceTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = CC948A02EC0184228BC4630E /* DomainDataPortabilityServiceTests.swift */; };
28 E959C4D24DAAB3CB80D854B2 /* DiffServiceTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 15A25DF2B8BB52589D49986B /* DiffServiceTests.swift */; }; 28 E959C4D24DAAB3CB80D854B2 /* DiffServiceTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 15A25DF2B8BB52589D49986B /* DiffServiceTests.swift */; };
29 A1B2C3D40000000000000202 /* InspectionInputTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = A1B2C3D40000000000000201 /* InspectionInputTests.swift */; }; 29 A1B2C3D40000000000000202 /* InspectionInputTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = A1B2C3D40000000000000201 /* InspectionInputTests.swift */; };
30 A1B2C3D40000000000000602 /* FeatureAccessTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = A1B2C3D40000000000000601 /* FeatureAccessTests.swift */; };
30 A1B2C3D40000000000000302 /* AvailabilityTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = A1B2C3D40000000000000301 /* AvailabilityTests.swift */; }; 31 A1B2C3D40000000000000302 /* AvailabilityTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = A1B2C3D40000000000000301 /* AvailabilityTests.swift */; };
31 A1B2C3D40000000000000402 /* CloudSyncMergeTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = A1B2C3D40000000000000401 /* CloudSyncMergeTests.swift */; }; 32 A1B2C3D40000000000000402 /* CloudSyncMergeTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = A1B2C3D40000000000000401 /* CloudSyncMergeTests.swift */; };
32 A1B2C3D40000000000000502 /* DomainNameTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = A1B2C3D40000000000000501 /* DomainNameTests.swift */; }; 33 A1B2C3D40000000000000502 /* DomainNameTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = A1B2C3D40000000000000501 /* DomainNameTests.swift */; };
@@ -101,6 +102,7 @@
101 8BF9DA842F9B13FB00EF41D5 /* DomainDataPortabilityService.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = DomainDataPortabilityService.swift; sourceTree = "<group>"; }; 102 8BF9DA842F9B13FB00EF41D5 /* DomainDataPortabilityService.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = DomainDataPortabilityService.swift; sourceTree = "<group>"; };
102 A1B2C3D40000000000000101 /* HistoryEntryCodableTests.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; path = HistoryEntryCodableTests.swift; sourceTree = "<group>"; }; 103 A1B2C3D40000000000000101 /* HistoryEntryCodableTests.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; path = HistoryEntryCodableTests.swift; sourceTree = "<group>"; };
103 A1B2C3D40000000000000201 /* InspectionInputTests.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; path = InspectionInputTests.swift; sourceTree = "<group>"; }; 104 A1B2C3D40000000000000201 /* InspectionInputTests.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; path = InspectionInputTests.swift; sourceTree = "<group>"; };
105 A1B2C3D40000000000000601 /* FeatureAccessTests.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; path = FeatureAccessTests.swift; sourceTree = "<group>"; };
104 A1B2C3D40000000000000301 /* AvailabilityTests.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; path = AvailabilityTests.swift; sourceTree = "<group>"; }; 106 A1B2C3D40000000000000301 /* AvailabilityTests.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; path = AvailabilityTests.swift; sourceTree = "<group>"; };
105 A1B2C3D40000000000000401 /* CloudSyncMergeTests.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; path = CloudSyncMergeTests.swift; sourceTree = "<group>"; }; 107 A1B2C3D40000000000000401 /* CloudSyncMergeTests.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; path = CloudSyncMergeTests.swift; sourceTree = "<group>"; };
106 A1B2C3D40000000000000501 /* DomainNameTests.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; path = DomainNameTests.swift; sourceTree = "<group>"; }; 108 A1B2C3D40000000000000501 /* DomainNameTests.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; path = DomainNameTests.swift; sourceTree = "<group>"; };
@@ -242,6 +244,7 @@
242 499B99A1866999A38AC475F5 /* AppInfoTests.swift */, 244 499B99A1866999A38AC475F5 /* AppInfoTests.swift */,
243 A1B2C3D40000000000000101 /* HistoryEntryCodableTests.swift */, 245 A1B2C3D40000000000000101 /* HistoryEntryCodableTests.swift */,
244 A1B2C3D40000000000000201 /* InspectionInputTests.swift */, 246 A1B2C3D40000000000000201 /* InspectionInputTests.swift */,
247 A1B2C3D40000000000000601 /* FeatureAccessTests.swift */,
245 A1B2C3D40000000000000301 /* AvailabilityTests.swift */, 248 A1B2C3D40000000000000301 /* AvailabilityTests.swift */,
246 A1B2C3D40000000000000401 /* CloudSyncMergeTests.swift */, 249 A1B2C3D40000000000000401 /* CloudSyncMergeTests.swift */,
247 A1B2C3D40000000000000501 /* DomainNameTests.swift */, 250 A1B2C3D40000000000000501 /* DomainNameTests.swift */,
@@ -506,6 +509,7 @@
506 4F96CEB875EC3501E784CE39 /* DataMigrationServiceTests.swift in Sources */, 509 4F96CEB875EC3501E784CE39 /* DataMigrationServiceTests.swift in Sources */,
507 99024E91EED2275FD80E83A9 /* AppInfoTests.swift in Sources */, 510 99024E91EED2275FD80E83A9 /* AppInfoTests.swift in Sources */,
508 A1B2C3D40000000000000202 /* InspectionInputTests.swift in Sources */, 511 A1B2C3D40000000000000202 /* InspectionInputTests.swift in Sources */,
512 A1B2C3D40000000000000602 /* FeatureAccessTests.swift in Sources */,
509 A1B2C3D40000000000000302 /* AvailabilityTests.swift in Sources */, 513 A1B2C3D40000000000000302 /* AvailabilityTests.swift in Sources */,
510 A1B2C3D40000000000000402 /* CloudSyncMergeTests.swift in Sources */, 514 A1B2C3D40000000000000402 /* CloudSyncMergeTests.swift in Sources */,
511 A1B2C3D40000000000000502 /* DomainNameTests.swift in Sources */, 515 A1B2C3D40000000000000502 /* DomainNameTests.swift in Sources */,
DomainDig/ContentView.swift +1 −9
@@ -191,7 +191,6 @@ struct ContentView: View {
191 } 191 }
192 } 192 }
193 .task { 193 .task {
194 await viewModel.refreshUsageCredits()
195 } 194 }
196 .onChange(of: viewModel.searchedDomain) { _, _ in 195 .onChange(of: viewModel.searchedDomain) { _, _ in
197 collapsedSections = defaultCollapsedSections 196 collapsedSections = defaultCollapsedSections
@@ -408,9 +407,7 @@ struct ContentView: View {
408 trackedDomain: trackedDomain, 407 trackedDomain: trackedDomain,
409 workflows: workflows, 408 workflows: workflows,
410 trackingLimitMessage: viewModel.trackingLimitMessage, 409 trackingLimitMessage: viewModel.trackingLimitMessage,
411 pricingLoading: viewModel.domainPricingLoading, 410
412 pricingError: viewModel.domainPricingError,
413 showsPricingPlaceholder: !DataAccessService.hasAccess(to: .domainPricing),
414 onTrack: { 411 onTrack: {
415 _ = viewModel.trackCurrentDomain() 412 _ = viewModel.trackCurrentDomain()
416 }, 413 },
@@ -451,11 +448,9 @@ struct ContentView: View {
451 error: viewModel.ownershipError, 448 error: viewModel.ownershipError,
452 provenance: viewModel.currentSnapshot.provenanceBySection[.ownership], 449 provenance: viewModel.currentSnapshot.provenanceBySection[.ownership],
453 confidence: viewModel.currentSnapshot.ownershipConfidence, 450 confidence: viewModel.currentSnapshot.ownershipConfidence,
454 showsHistoryPlaceholder: !DataAccessService.hasAccess(to: .ownershipHistory),
455 history: viewModel.ownershipHistory, 451 history: viewModel.ownershipHistory,
456 historyLoading: viewModel.ownershipHistoryLoading, 452 historyLoading: viewModel.ownershipHistoryLoading,
457 historyError: viewModel.ownershipHistoryError, 453 historyError: viewModel.ownershipHistoryError,
458 historyCreditStatus: viewModel.ownershipHistoryCreditStatus,
459 onLoadHistory: { 454 onLoadHistory: {
460 Task { 455 Task {
461 await viewModel.loadOwnershipHistory() 456 await viewModel.loadOwnershipHistory()
@@ -477,7 +472,6 @@ struct ContentView: View {
477 extendedCount: viewModel.extendedSubdomains.count, 472 extendedCount: viewModel.extendedSubdomains.count,
478 extendedLoading: viewModel.extendedSubdomainsLoading, 473 extendedLoading: viewModel.extendedSubdomainsLoading,
479 extendedError: viewModel.extendedSubdomainsError, 474 extendedError: viewModel.extendedSubdomainsError,
480 extendedCreditStatus: viewModel.extendedSubdomainsCreditStatus,
481 onLoadExtended: { 475 onLoadExtended: {
482 Task { 476 Task {
483 await viewModel.loadExtendedSubdomains() 477 await viewModel.loadExtendedSubdomains()
@@ -500,8 +494,6 @@ struct ContentView: View {
500 history: viewModel.dnsHistory, 494 history: viewModel.dnsHistory,
501 historyLoading: viewModel.dnsHistoryLoading, 495 historyLoading: viewModel.dnsHistoryLoading,
502 historyError: viewModel.dnsHistoryError, 496 historyError: viewModel.dnsHistoryError,
503 showsHistoryPlaceholder: !DataAccessService.hasAccess(to: .dnsHistory),
504 historyCreditStatus: viewModel.dnsHistoryCreditStatus,
505 onLoadHistory: { 497 onLoadHistory: {
506 Task { 498 Task {
507 await viewModel.loadDNSHistory() 499 await viewModel.loadDNSHistory()
DomainDig/DataAccessService.swift −4
@@ -10,11 +10,7 @@ extension DataCapability {
10 /// The plan feature that unlocks this data. 10 /// The plan feature that unlocks this data.
11 var feature: FeatureCapability { 11 var feature: FeatureCapability {
12 switch self { 12 switch self {
13 case .ownershipHistory: .ownershipHistory
14 case .dnsHistory: .dnsHistory
15 case .extendedSubdomains: .extendedSubdomains 13 case .extendedSubdomains: .extendedSubdomains
16 case .domainPricing: .domainPricing
17 case .reputation: .reputation
18 } 14 }
19 } 15 }
20} 16}
DomainDig/DataResetService.swift −1
@@ -24,7 +24,6 @@ enum DataResetService {
24 24
25 await LookupRuntime.shared.clearCache() 25 await LookupRuntime.shared.clearCache()
26 await LocalNotificationService.shared.clearAllNotifications() 26 await LocalNotificationService.shared.clearAllNotifications()
27 await UsageCreditService.shared.resetForCurrentVersion()
28 27
29 await MainActor.run { 28 await MainActor.run {
30 IntegrationService.shared.resetAfterLocalWipe() 29 IntegrationService.shared.resetAfterLocalWipe()
DomainDig/DomainViewModel.swift +16 −94
@@ -242,7 +242,6 @@ final class DomainViewModel {
242 var reputation: DomainReputationResult? 242 var reputation: DomainReputationResult?
243 var reputationLoading = false 243 var reputationLoading = false
244 var reputationError: String? 244 var reputationError: String?
245 var usageCredits: [UsageCreditFeature: UsageCreditStatus] = DomainViewModel.defaultUsageCredits()
246 245
247 var portScanResults: [PortScanResult] = [] 246 var portScanResults: [PortScanResult] = []
248 var portScanLoading = false 247 var portScanLoading = false
@@ -698,18 +697,6 @@ final class DomainViewModel {
698 currentReport?.web 697 currentReport?.web
699 } 698 }
700 699
701 var ownershipHistoryCreditStatus: UsageCreditStatus {
702 usageCredits[.ownershipHistory] ?? Self.fallbackCreditStatus(for: .ownershipHistory)
703 }
704
705 var dnsHistoryCreditStatus: UsageCreditStatus {
706 usageCredits[.dnsHistory] ?? Self.fallbackCreditStatus(for: .dnsHistory)
707 }
708
709 var extendedSubdomainsCreditStatus: UsageCreditStatus {
710 usageCredits[.extendedSubdomains] ?? Self.fallbackCreditStatus(for: .extendedSubdomains)
711 }
712
713 var combinedSubdomains: [DiscoveredSubdomain] { 700 var combinedSubdomains: [DiscoveredSubdomain] {
714 let existingHosts = Set(subdomains.map { $0.hostname.lowercased() }) 701 let existingHosts = Set(subdomains.map { $0.hostname.lowercased() })
715 return subdomains + extendedSubdomains.filter { !existingHosts.contains($0.hostname.lowercased()) } 702 return subdomains + extendedSubdomains.filter { !existingHosts.contains($0.hostname.lowercased()) }
@@ -1090,7 +1077,6 @@ final class DomainViewModel {
1090 latestWorkflowRunSummary = nil 1077 latestWorkflowRunSummary = nil
1091 historyAutoPruneOption = Self.loadHistoryAutoPruneOption() 1078 historyAutoPruneOption = Self.loadHistoryAutoPruneOption()
1092 refreshDataLifecycleSummary() 1079 refreshDataLifecycleSummary()
1093 await refreshUsageCredits()
1094 await refreshMonitoringAuthorizationStatus() 1080 await refreshMonitoringAuthorizationStatus()
1095 } 1081 }
1096 1082
@@ -1255,6 +1241,14 @@ final class DomainViewModel {
1255 .lowercased() ?? domain.lowercased() 1241 .lowercased() ?? domain.lowercased()
1256 guard !normalizedDomain.isEmpty else { return nil } 1242 guard !normalizedDomain.isEmpty else { return nil }
1257 1243
1244 // Free keeps one audit open at a time so the feature stays discoverable;
1245 // finishing one frees the slot. Existing sessions are never closed off.
1246 if let limit = FeatureAccessService.entitlements.activeAuditSessionLimit,
1247 auditSessions.filter({ $0.status != .complete }).count >= limit {
1248 upgradePrompt = FeatureAccessService.upgradePrompt(for: .auditDepth)
1249 return nil
1250 }
1251
1258 let previous = historyEntries(for: normalizedDomain).first?.snapshot 1252 let previous = historyEntries(for: normalizedDomain).first?.snapshot
1259 let snapshot = await inspectionService.inspectSnapshot(domain: normalizedDomain, previousSnapshot: previous) 1253 let snapshot = await inspectionService.inspectSnapshot(domain: normalizedDomain, previousSnapshot: previous)
1260 guard let entry = saveHistoryEntry( 1254 guard let entry = saveHistoryEntry(
@@ -1291,7 +1285,7 @@ final class DomainViewModel {
1291 } 1285 }
1292 1286
1293 func loadOwnershipHistory() async { 1287 func loadOwnershipHistory() async {
1294 await loadLookup(.ownershipHistory, into: \.ownershipHistory, loading: \.ownershipHistoryLoading, error: \.ownershipHistoryError, 1288 await loadLookup(into: \.ownershipHistory, loading: \.ownershipHistoryLoading, error: \.ownershipHistoryError,
1295 fallback: "Ownership history unavailable") { 1289 fallback: "Ownership history unavailable") {
1296 await ExternalDataService.shared.ownershipHistory( 1290 await ExternalDataService.shared.ownershipHistory(
1297 domain: searchedDomain, 1291 domain: searchedDomain,
@@ -1302,7 +1296,7 @@ final class DomainViewModel {
1302 } 1296 }
1303 1297
1304 func loadDNSHistory() async { 1298 func loadDNSHistory() async {
1305 await loadLookup(.dnsHistory, into: \.dnsHistory, loading: \.dnsHistoryLoading, error: \.dnsHistoryError, 1299 await loadLookup(into: \.dnsHistory, loading: \.dnsHistoryLoading, error: \.dnsHistoryError,
1306 fallback: "DNS history unavailable") { 1300 fallback: "DNS history unavailable") {
1307 await ExternalDataService.shared.dnsHistory( 1301 await ExternalDataService.shared.dnsHistory(
1308 domain: searchedDomain, 1302 domain: searchedDomain,
@@ -1322,10 +1316,11 @@ final class DomainViewModel {
1322 } 1316 }
1323 } 1317 }
1324 1318
1325 /// Loads `capability`'s lookup for the searched domain into `items`, unless it is loaded 1319 /// Loads a lookup for the searched domain into `items`, unless it is loaded
1326 /// already, or shows the upgrade prompt when the plan doesn't include it. 1320 /// already. With a `capability`, shows the upgrade prompt when the plan
1321 /// doesn't include it; without one the lookup is open to every tier.
1327 private func loadLookup<Item>( 1322 private func loadLookup<Item>(
1328 _ capability: DataCapability, 1323 _ capability: DataCapability? = nil,
1329 into items: ReferenceWritableKeyPath<DomainViewModel, [Item]>, 1324 into items: ReferenceWritableKeyPath<DomainViewModel, [Item]>,
1330 loading: ReferenceWritableKeyPath<DomainViewModel, Bool>, 1325 loading: ReferenceWritableKeyPath<DomainViewModel, Bool>,
1331 error: ReferenceWritableKeyPath<DomainViewModel, String?>, 1326 error: ReferenceWritableKeyPath<DomainViewModel, String?>,
@@ -1333,7 +1328,7 @@ final class DomainViewModel {
1333 fetch: () async -> ServiceResult<[Item]> 1328 fetch: () async -> ServiceResult<[Item]>
1334 ) async { 1329 ) async {
1335 guard !searchedDomain.isEmpty else { return } 1330 guard !searchedDomain.isEmpty else { return }
1336 guard DataAccessService.hasAccess(to: capability) else { 1331 if let capability, !DataAccessService.hasAccess(to: capability) {
1337 upgradePrompt = FeatureAccessService.upgradePrompt(for: capability.feature) 1332 upgradePrompt = FeatureAccessService.upgradePrompt(for: capability.feature)
1338 return 1333 return
1339 } 1334 }
@@ -1360,11 +1355,6 @@ final class DomainViewModel {
1360 } 1355 }
1361 } 1356 }
1362 1357
1363 func refreshUsageCredits() async {
1364 let statuses = await UsageCreditService.shared.allStatuses()
1365 usageCredits = Dictionary(uniqueKeysWithValues: statuses.map { ($0.feature, $0) })
1366 }
1367
1368 private func performLookup(domain: String, lookupID: UUID) async -> HistoryEntry? { 1358 private func performLookup(domain: String, lookupID: UUID) async -> HistoryEntry? {
1369 let lookupStartedAt = DomainDebugLog.signpostStart("DomainViewModel.performLookup", domain: domain) 1359 let lookupStartedAt = DomainDebugLog.signpostStart("DomainViewModel.performLookup", domain: domain)
1370 let previous = previousSnapshot( 1360 let previous = previousSnapshot(
@@ -1383,16 +1373,6 @@ final class DomainViewModel {
1383 lastLookupDurationMs = snapshot.totalLookupDurationMs 1373 lastLookupDurationMs = snapshot.totalLookupDurationMs
1384 refreshingTrackedDomainID = nil 1374 refreshingTrackedDomainID = nil
1385 1375
1386 if DataAccessService.hasAccess(to: .domainPricing), domainPricing == nil {
1387 DomainDebugLog.debug("DomainViewModel.performLookup loadingPricing domain=\(domain)")
1388 await refreshDomainPricing(for: snapshot.domain, persistAfterFetch: false)
1389 }
1390
1391 if DataAccessService.hasAccess(to: .reputation), reputation == nil {
1392 DomainDebugLog.debug("DomainViewModel.performLookup loadingReputation domain=\(domain)")
1393 await refreshReputation(for: snapshot.domain, persistAfterFetch: false)
1394 }
1395
1396 guard snapshot.statusMessage == nil else { 1376 guard snapshot.statusMessage == nil else {
1397 return history.first(where: { $0.id == snapshot.historyEntryID }) 1377 return history.first(where: { $0.id == snapshot.historyEntryID })
1398 } 1378 }
@@ -3582,9 +3562,6 @@ final class DomainViewModel {
3582 if let ownershipError = snapshot.ownershipError, snapshot.ownership == nil { 3562 if let ownershipError = snapshot.ownershipError, snapshot.ownership == nil {
3583 lines.append(" Source: \(ownershipError)") 3563 lines.append(" Source: \(ownershipError)")
3584 } 3564 }
3585 if !DataAccessService.hasAccess(to: .ownershipHistory) {
3586 lines.append(" Ownership history (coming soon)")
3587 }
3588 return lines 3565 return lines
3589 } 3566 }
3590 3567
@@ -3600,7 +3577,7 @@ final class DomainViewModel {
3600 } 3577 }
3601 } 3578 }
3602 if !DataAccessService.hasAccess(to: .extendedSubdomains) { 3579 if !DataAccessService.hasAccess(to: .extendedSubdomains) {
3603 lines.append(" Extended subdomain discovery (Pro+)") 3580 lines.append(" Extended subdomain discovery (Pro)")
3604 } 3581 }
3605 return lines 3582 return lines
3606 } 3583 }
@@ -3910,46 +3887,6 @@ final class DomainViewModel {
3910 return formatter 3887 return formatter
3911 }() 3888 }()
3912 3889
3913 private func refreshDomainPricing(for domain: String, persistAfterFetch: Bool) async {
3914 domainPricingLoading = true
3915 let outcome = await ExternalDataService.shared.pricing(domain: domain)
3916
3917 switch outcome.value {
3918 case let .success(pricing):
3919 domainPricing = pricing
3920 domainPricingError = nil
3921 case let .empty(message), let .error(message):
3922 domainPricing = nil
3923 domainPricingError = conciseExternalMessage(message, fallback: "External pricing unavailable")
3924 }
3925
3926 domainPricingLoading = false
3927
3928 if persistAfterFetch {
3929 _ = saveHistoryEntry(replaceLatest: true)
3930 }
3931 }
3932
3933 private func refreshReputation(for domain: String, persistAfterFetch: Bool) async {
3934 reputationLoading = true
3935 let outcome = await ExternalDataService.shared.reputation(domain: domain)
3936
3937 switch outcome.value {
3938 case let .success(result):
3939 reputation = result
3940 reputationError = nil
3941 case let .empty(message), let .error(message):
3942 reputation = nil
3943 reputationError = conciseExternalMessage(message, fallback: "Reputation check unavailable")
3944 }
3945
3946 reputationLoading = false
3947
3948 if persistAfterFetch {
3949 _ = saveHistoryEntry(replaceLatest: true)
3950 }
3951 }
3952
3953 private func conciseExternalMessage(_ message: String, fallback: String) -> String { 3890 private func conciseExternalMessage(_ message: String, fallback: String) -> String {
3954 let trimmed = message.trimmingCharacters(in: .whitespacesAndNewlines) 3891 let trimmed = message.trimmingCharacters(in: .whitespacesAndNewlines)
3955 if trimmed.isEmpty { 3892 if trimmed.isEmpty {
@@ -3967,21 +3904,6 @@ final class DomainViewModel {
3967 return trimmed 3904 return trimmed
3968 } 3905 }
3969 3906
3970 private static func defaultUsageCredits() -> [UsageCreditFeature: UsageCreditStatus] {
3971 Dictionary(uniqueKeysWithValues: UsageCreditFeature.allCases.map { feature in
3972 (feature, fallbackCreditStatus(for: feature))
3973 })
3974 }
3975
3976 private static func fallbackCreditStatus(for feature: UsageCreditFeature) -> UsageCreditStatus {
3977 UsageCreditStatus(
3978 feature: feature,
3979 remaining: feature.defaultAllowance,
3980 total: feature.defaultAllowance,
3981 resetContext: "Resets with app version \(AppVersion.current)"
3982 )
3983 }
3984
3985 private static func csvEscaped(_ value: String) -> String { 3907 private static func csvEscaped(_ value: String) -> String {
3986 let escaped = value.replacingOccurrences(of: "\"", with: "\"\"") 3908 let escaped = value.replacingOccurrences(of: "\"", with: "\"\"")
3987 return "\"\(escaped)\"" 3909 return "\"\(escaped)\""
DomainDig/ExternalDataService.swift +1 −95
@@ -7,15 +7,11 @@ actor ExternalDataService {
7 case ownershipHistory(String) 7 case ownershipHistory(String)
8 case dnsHistory(String) 8 case dnsHistory(String)
9 case extendedSubdomains(String) 9 case extendedSubdomains(String)
10 case pricing(String)
11 case reputation(String)
12 } 10 }
13 11
14 private enum RateLimitBucket: Hashable { 12 private enum RateLimitBucket: Hashable {
15 case history 13 case history
16 case subdomains 14 case subdomains
17 case pricing
18 case reputation
19 15
20 var minimumSpacing: TimeInterval { 16 var minimumSpacing: TimeInterval {
21 switch self { 17 switch self {
@@ -23,10 +19,6 @@ actor ExternalDataService {
23 return 1.0 19 return 1.0
24 case .subdomains: 20 case .subdomains:
25 return 1.5 21 return 1.5
26 case .pricing:
27 return 1.0
28 case .reputation:
29 return 1.0
30 } 22 }
31 } 23 }
32 } 24 }
@@ -35,8 +27,6 @@ actor ExternalDataService {
35 case ownershipHistory(ServiceResult<[DomainOwnershipHistoryEvent]>) 27 case ownershipHistory(ServiceResult<[DomainOwnershipHistoryEvent]>)
36 case dnsHistory(ServiceResult<[DNSHistoryEvent]>) 28 case dnsHistory(ServiceResult<[DNSHistoryEvent]>)
37 case extendedSubdomains(ServiceResult<[DiscoveredSubdomain]>) 29 case extendedSubdomains(ServiceResult<[DiscoveredSubdomain]>)
38 case pricing(ServiceResult<DomainPricingInsight>)
39 case reputation(ServiceResult<DomainReputationResult>)
40 } 30 }
41 31
42 private struct CacheEntry { 32 private struct CacheEntry {
@@ -48,8 +38,6 @@ actor ExternalDataService {
48 let ownershipHistoryURL: String? 38 let ownershipHistoryURL: String?
49 let dnsHistoryURL: String? 39 let dnsHistoryURL: String?
50 let extendedSubdomainsURL: String? 40 let extendedSubdomainsURL: String?
51 let pricingURL: String?
52 let reputationURL: String?
53 } 41 }
54 42
55 private let ttl: TimeInterval = 900 43 private let ttl: TimeInterval = 900
@@ -152,40 +140,6 @@ actor ExternalDataService {
152 ) 140 )
153 } 141 }
154 142
155 func pricing(domain: String) async -> CachedLookupResult<ServiceResult<DomainPricingInsight>> {
156 let normalizedDomain = Self.normalize(domain)
157 return await execute(
158 key: .pricing(normalizedDomain),
159 rateLimitBucket: .pricing,
160 extract: { payload in
161 guard case let .pricing(result) = payload else { return nil }
162 return result
163 },
164 operation: { [configuration = configuration()] in
165 .pricing(await self.fetchPricing(domain: normalizedDomain, configuration: configuration))
166 }
167 )
168 }
169
170 /// Checks a domain against a configured blocklist/reputation endpoint. With
171 /// no endpoint configured (the default, since DomainDig ships no bundled
172 /// third-party reputation dependency) this resolves to `.empty` and callers
173 /// treat the result as unavailable rather than "clean".
174 func reputation(domain: String) async -> CachedLookupResult<ServiceResult<DomainReputationResult>> {
175 let normalizedDomain = Self.normalize(domain)
176 return await execute(
177 key: .reputation(normalizedDomain),
178 rateLimitBucket: .reputation,
179 extract: { payload in
180 guard case let .reputation(result) = payload else { return nil }
181 return result
182 },
183 operation: { [configuration = configuration()] in
184 .reputation(await self.fetchReputation(domain: normalizedDomain, configuration: configuration))
185 }
186 )
187 }
188
189 private func execute<T>( 143 private func execute<T>(
190 key: RequestKey, 144 key: RequestKey,
191 rateLimitBucket: RateLimitBucket, 145 rateLimitBucket: RateLimitBucket,
@@ -236,11 +190,7 @@ actor ExternalDataService {
236 dnsHistoryURL: defaults.string(forKey: "externalData.dnsHistoryURL") 190 dnsHistoryURL: defaults.string(forKey: "externalData.dnsHistoryURL")
237 ?? Bundle.main.object(forInfoDictionaryKey: "ExternalDNSHistoryURL") as? String, 191 ?? Bundle.main.object(forInfoDictionaryKey: "ExternalDNSHistoryURL") as? String,
238 extendedSubdomainsURL: defaults.string(forKey: "externalData.extendedSubdomainsURL") 192 extendedSubdomainsURL: defaults.string(forKey: "externalData.extendedSubdomainsURL")
239 ?? Bundle.main.object(forInfoDictionaryKey: "ExternalExtendedSubdomainsURL") as? String, 193 ?? Bundle.main.object(forInfoDictionaryKey: "ExternalExtendedSubdomainsURL") as? String
240 pricingURL: defaults.string(forKey: "externalData.pricingURL")
241 ?? Bundle.main.object(forInfoDictionaryKey: "ExternalPricingURL") as? String,
242 reputationURL: defaults.string(forKey: "externalData.reputationURL")
243 ?? Bundle.main.object(forInfoDictionaryKey: "ExternalReputationURL") as? String
244 ) 194 )
245 } 195 }
246 196
@@ -295,50 +245,6 @@ actor ExternalDataService {
295 } 245 }
296 } 246 }
297 247
298 private func fetchPricing(
299 domain: String,
300 configuration: Configuration
301 ) async -> ServiceResult<DomainPricingInsight> {
302 guard let template = configuration.pricingURL,
303 let url = Self.url(from: template, domain: domain) else {
304 return .empty("External pricing unavailable")
305 }
306
307 switch await requestData(url: url) {
308 case let .success(data):
309 guard let pricing = parsePricing(from: data) else {
310 return .error("Invalid external response")
311 }
312 return .success(pricing)
313 case let .empty(message):
314 return .empty(message)
315 case let .error(message):
316 return .error(message)
317 }
318 }
319
320 private func fetchReputation(
321 domain: String,
322 configuration: Configuration
323 ) async -> ServiceResult<DomainReputationResult> {
324 guard let template = configuration.reputationURL,
325 let url = Self.url(from: template, domain: domain) else {
326 return .empty("No reputation source configured")
327 }
328
329 switch await requestData(url: url) {
330 case let .success(data):
331 guard let reputation = parseReputation(from: data) else {
332 return .error("Invalid external response")
333 }
334 return .success(reputation)
335 case let .empty(message):
336 return .empty(message)
337 case let .error(message):
338 return .error(message)
339 }
340 }
341
342 private func requestData(url: URL) async -> ServiceResult<Data> { 248 private func requestData(url: URL) async -> ServiceResult<Data> {
343 for attempt in 0..<2 { 249 for attempt in 0..<2 {
344 do { 250 do {
DomainDig/FeatureAccessService.swift +30 −21
@@ -28,11 +28,9 @@ enum FeatureCapability: String, CaseIterable, Identifiable {
28 case automatedMonitoring 28 case automatedMonitoring
29 case localAlerts 29 case localAlerts
30 case advancedExports 30 case advancedExports
31 case ownershipHistory
32 case dnsHistory
33 case extendedSubdomains 31 case extendedSubdomains
34 case domainPricing 32 case sharedPortfolios
35 case reputation 33 case auditDepth
36 34
37 var id: String { rawValue } 35 var id: String { rawValue }
38 36
@@ -54,16 +52,12 @@ enum FeatureCapability: String, CaseIterable, Identifiable {
54 return "Local alerts" 52 return "Local alerts"
55 case .advancedExports: 53 case .advancedExports:
56 return "Advanced exports" 54 return "Advanced exports"
57 case .ownershipHistory:
58 return "Ownership history"
59 case .dnsHistory:
60 return "DNS history"
61 case .extendedSubdomains: 55 case .extendedSubdomains:
62 return "Extended subdomains" 56 return "Extended subdomains"
63 case .domainPricing: 57 case .sharedPortfolios:
64 return "Domain pricing" 58 return "Shared portfolios"
65 case .reputation: 59 case .auditDepth:
66 return "Domain reputation" 60 return "Unlimited audits"
67 } 61 }
68 } 62 }
69} 63}
@@ -74,6 +68,8 @@ struct FeatureEntitlements: Equatable {
74 let trackedDomainLimit: Int 68 let trackedDomainLimit: Int
75 let workflowLimit: Int? 69 let workflowLimit: Int?
76 let batchSizeLimit: Int? 70 let batchSizeLimit: Int?
71 /// Concurrently open audit sessions; nil is unlimited.
72 let activeAuditSessionLimit: Int?
77} 73}
78 74
79struct UpgradePromptContext: Identifiable, Equatable { 75struct UpgradePromptContext: Identifiable, Equatable {
@@ -91,14 +87,19 @@ enum FeatureAccessService {
91 } 87 }
92 88
93 static var entitlements: FeatureEntitlements { 89 static var entitlements: FeatureEntitlements {
94 switch currentTier { 90 entitlements(for: currentTier)
91 }
92
93 static func entitlements(for tier: FeatureTier) -> FeatureEntitlements {
94 switch tier {
95 case .free: 95 case .free:
96 return FeatureEntitlements( 96 return FeatureEntitlements(
97 tier: .free, 97 tier: .free,
98 capabilities: [.singleLookup, .basicHistory, .limitedTracking, .workflows, .batchOperations], 98 capabilities: [.singleLookup, .basicHistory, .limitedTracking, .workflows, .batchOperations],
99 trackedDomainLimit: 5, 99 trackedDomainLimit: 5,
100 workflowLimit: 1, 100 workflowLimit: 1,
101 batchSizeLimit: 10 101 batchSizeLimit: 10,
102 activeAuditSessionLimit: 1
102 ) 103 )
103 case .pro: 104 case .pro:
104 return FeatureEntitlements( 105 return FeatureEntitlements(
@@ -111,11 +112,13 @@ enum FeatureAccessService {
111 .batchOperations, 112 .batchOperations,
112 .automatedMonitoring, 113 .automatedMonitoring,
113 .localAlerts, 114 .localAlerts,
114 .advancedExports 115 .advancedExports,
116 .extendedSubdomains
115 ], 117 ],
116 trackedDomainLimit: effectivelyUnlimitedTrackedDomains, 118 trackedDomainLimit: effectivelyUnlimitedTrackedDomains,
117 workflowLimit: nil, 119 workflowLimit: nil,
118 batchSizeLimit: nil 120 batchSizeLimit: nil,
121 activeAuditSessionLimit: nil
119 ) 122 )
120 case .proPlus: 123 case .proPlus:
121 return FeatureEntitlements( 124 return FeatureEntitlements(
@@ -123,7 +126,8 @@ enum FeatureAccessService {
123 capabilities: Set(FeatureCapability.allCases), 126 capabilities: Set(FeatureCapability.allCases),
124 trackedDomainLimit: effectivelyUnlimitedTrackedDomains, 127 trackedDomainLimit: effectivelyUnlimitedTrackedDomains,
125 workflowLimit: nil, 128 workflowLimit: nil,
126 batchSizeLimit: nil 129 batchSizeLimit: nil,
130 activeAuditSessionLimit: nil
127 ) 131 )
128 } 132 }
129 } 133 }
@@ -133,7 +137,11 @@ enum FeatureAccessService {
133 } 137 }
134 138
135 static func canAddTrackedDomain(currentCount: Int) -> Bool { 139 static func canAddTrackedDomain(currentCount: Int) -> Bool {
136 currentCount < entitlements.trackedDomainLimit 140 canAddTrackedDomain(currentCount: currentCount, tier: currentTier)
141 }
142
143 static func canAddTrackedDomain(currentCount: Int, tier: FeatureTier) -> Bool {
144 currentCount < entitlements(for: tier).trackedDomainLimit
137 } 145 }
138 146
139 static func trackedDomainLimitMessage(currentCount: Int) -> String? { 147 static func trackedDomainLimitMessage(currentCount: Int) -> String? {
@@ -158,9 +166,10 @@ enum FeatureAccessService {
158 166
159 static func upgradeMessage(for capability: FeatureCapability) -> String { 167 static func upgradeMessage(for capability: FeatureCapability) -> String {
160 switch capability { 168 switch capability {
161 case .workflows, .batchOperations, .automatedMonitoring, .localAlerts, .advancedExports: 169 case .workflows, .batchOperations, .automatedMonitoring, .localAlerts, .advancedExports,
170 .extendedSubdomains:
162 return "Available in Pro" 171 return "Available in Pro"
163 case .ownershipHistory, .dnsHistory, .extendedSubdomains, .domainPricing, .reputation: 172 case .sharedPortfolios, .auditDepth:
164 return "Available in Pro+" 173 return "Available in Pro+"
165 case .limitedTracking: 174 case .limitedTracking:
166 return "Tracking is limited on Free" 175 return "Tracking is limited on Free"
@@ -222,7 +231,7 @@ enum FeatureAccessService {
222 static func upgradePrompt(for capability: FeatureCapability) -> UpgradePromptContext { 231 static func upgradePrompt(for capability: FeatureCapability) -> UpgradePromptContext {
223 let title: String 232 let title: String
224 switch capability { 233 switch capability {
225 case .ownershipHistory, .dnsHistory, .extendedSubdomains, .domainPricing, .reputation: 234 case .sharedPortfolios, .auditDepth:
226 title = "Available in Pro+" 235 title = "Available in Pro+"
227 default: 236 default:
228 title = "Available in Pro" 237 title = "Available in Pro"
DomainDig/HistoryView.swift +1 −5
@@ -199,9 +199,6 @@ struct HistoryDetailView: View {
199 trackedDomain: trackedDomain, 199 trackedDomain: trackedDomain,
200 workflows: viewModel.workflowsContaining(domain: entry.domain), 200 workflows: viewModel.workflowsContaining(domain: entry.domain),
201 trackingLimitMessage: nil, 201 trackingLimitMessage: nil,
202 pricingLoading: false,
203 pricingError: snapshot.domainPricingError,
204 showsPricingPlaceholder: !DataAccessService.hasAccess(to: .domainPricing),
205 onTrack: { 202 onTrack: {
206 _ = viewModel.trackDomain(domain: entry.domain, availabilityStatus: entry.availabilityResult?.status) 203 _ = viewModel.trackDomain(domain: entry.domain, availabilityStatus: entry.availabilityResult?.status)
207 }, 204 },
@@ -221,8 +218,7 @@ struct HistoryDetailView: View {
221 loading: false, 218 loading: false,
222 error: snapshot.ownershipError, 219 error: snapshot.ownershipError,
223 provenance: snapshot.provenanceBySection[.ownership], 220 provenance: snapshot.provenanceBySection[.ownership],
224 confidence: snapshot.ownershipConfidence, 221 confidence: snapshot.ownershipConfidence
225 showsHistoryPlaceholder: !DataAccessService.hasAccess(to: .ownershipHistory)
226 ) 222 )
227 .padding(.top, appDensity.metrics.sectionSpacing) 223 .padding(.top, appDensity.metrics.sectionSpacing)
228 SubdomainsSectionView( 224 SubdomainsSectionView(
DomainDig/Models.swift +3 −47
@@ -392,55 +392,11 @@ struct WorkflowRunSummary: Identifiable, Equatable {
392 let generatedAt: Date 392 let generatedAt: Date
393} 393}
394 394
395/// Data that a tier gates. Ownership and DNS history derive from the user's own
396/// stored snapshots and are not gated at all; pricing and reputation were
397/// removed, having no local derivation and no configured provider.
395enum DataCapability: String, Codable { 398enum DataCapability: String, Codable {
396 case ownershipHistory
397 case dnsHistory
398 case extendedSubdomains 399 case extendedSubdomains
399 case domainPricing
400 case reputation
401}
402
403enum UsageCreditFeature: String, Codable, CaseIterable, Identifiable, Sendable {
404 case ownershipHistory
405 case dnsHistory
406 case extendedSubdomains
407
408 nonisolated var id: String { rawValue }
409
410 nonisolated var title: String {
411 switch self {
412 case .ownershipHistory:
413 return "Ownership history"
414 case .dnsHistory:
415 return "DNS history"
416 case .extendedSubdomains:
417 return "Extended subdomains"
418 }
419 }
420
421 nonisolated var defaultAllowance: Int {
422 switch self {
423 case .ownershipHistory, .dnsHistory:
424 return 8
425 case .extendedSubdomains:
426 return 12
427 }
428 }
429}
430
431struct UsageCreditStatus: Codable, Equatable, Sendable {
432 let feature: UsageCreditFeature
433 let remaining: Int
434 let total: Int
435 let resetContext: String
436
437 nonisolated var summary: String {
438 "\(remaining) uses remaining"
439 }
440
441 nonisolated var isExhausted: Bool {
442 remaining <= 0
443 }
444} 400}
445 401
446struct DomainOwnershipHistoryEvent: Identifiable, Codable, Equatable, Sendable { 402struct DomainOwnershipHistoryEvent: Identifiable, Codable, Equatable, Sendable {
DomainDig/PaywallView.swift +4 −5
@@ -10,7 +10,7 @@ struct PaywallView: View {
10 NavigationStack { 10 NavigationStack {
11 List { 11 List {
12 Section { 12 Section {
13 Text("Pro unlocks workflows, scale, monitoring automation, and exports. Pro+ adds deeper external intelligence with no additional usage limits.") 13 Text("Pro unlocks scale, background monitoring, alerts, exports, and extended subdomain discovery. Pro+ adds shared portfolios and unlimited audits.")
14 .font(appDensity.font(.body, design: .default)) 14 .font(appDensity.font(.body, design: .default))
15 .foregroundStyle(Color(.appTextSecondary)) 15 .foregroundStyle(Color(.appTextSecondary))
16 .fixedSize(horizontal: false, vertical: true) 16 .fixedSize(horizontal: false, vertical: true)
@@ -23,13 +23,12 @@ struct PaywallView: View {
23 featureRow("Background monitoring") 23 featureRow("Background monitoring")
24 featureRow("Local alerts") 24 featureRow("Local alerts")
25 featureRow("Advanced exports") 25 featureRow("Advanced exports")
26 featureRow("Extended subdomain discovery")
26 } 27 }
27 28
28 Section("What Pro+ Unlocks") { 29 Section("What Pro+ Unlocks") {
29 featureRow("Ownership history") 30 featureRow("Shared portfolios")
30 featureRow("DNS history") 31 featureRow("Unlimited audit sessions")
31 featureRow("Extended subdomains")
32 featureRow("External pricing signals")
33 } 32 }
34 33
35 Section("Subscription") { 34 Section("Subscription") {
DomainDig/ResultSectionViews.swift +2 −35
@@ -21,9 +21,6 @@ struct DomainSectionView: View {
21 let trackedDomain: TrackedDomain? 21 let trackedDomain: TrackedDomain?
22 let workflows: [DomainWorkflow] 22 let workflows: [DomainWorkflow]
23 let trackingLimitMessage: String? 23 let trackingLimitMessage: String?
24 let pricingLoading: Bool
25 let pricingError: String?
26 let showsPricingPlaceholder: Bool
27 let onTrack: () -> Void 24 let onTrack: () -> Void
28 let onTogglePinned: () -> Void 25 let onTogglePinned: () -> Void
29 let onEditNote: (() -> Void)? 26 let onEditNote: (() -> Void)?
@@ -160,17 +157,6 @@ struct DomainSectionView: View {
160 } 157 }
161 } 158 }
162 } 159 }
163 if pricingLoading {
164 ProgressView("Loading external pricing…")
165 .appLoadingStyle()
166 .padding(.top, 4)
167 } else if let pricingError {
168 MessageRowView(text: pricingError, isError: false)
169 .padding(.top, 4)
170 } else if showsPricingPlaceholder {
171 MessageRowView(text: "Pricing signals available in Pro+", isError: false)
172 .padding(.top, 4)
173 }
174 } 160 }
175 } 161 }
176 } 162 }
@@ -184,11 +170,9 @@ struct OwnershipSectionView: View {
184 let error: String? 170 let error: String?
185 let provenance: SectionProvenance? 171 let provenance: SectionProvenance?
186 let confidence: ConfidenceLevel? 172 let confidence: ConfidenceLevel?
187 let showsHistoryPlaceholder: Bool
188 let history: [DomainOwnershipHistoryEvent] 173 let history: [DomainOwnershipHistoryEvent]
189 let historyLoading: Bool 174 let historyLoading: Bool
190 let historyError: String? 175 let historyError: String?
191 let historyCreditStatus: UsageCreditStatus?
192 let onLoadHistory: (() -> Void)? 176 let onLoadHistory: (() -> Void)?
193 177
194 init( 178 init(
@@ -198,11 +182,9 @@ struct OwnershipSectionView: View {
198 error: String?, 182 error: String?,
199 provenance: SectionProvenance?, 183 provenance: SectionProvenance?,
200 confidence: ConfidenceLevel?, 184 confidence: ConfidenceLevel?,
201 showsHistoryPlaceholder: Bool,
202 history: [DomainOwnershipHistoryEvent] = [], 185 history: [DomainOwnershipHistoryEvent] = [],
203 historyLoading: Bool = false, 186 historyLoading: Bool = false,
204 historyError: String? = nil, 187 historyError: String? = nil,
205 historyCreditStatus: UsageCreditStatus? = nil,
206 onLoadHistory: (() -> Void)? = nil 188 onLoadHistory: (() -> Void)? = nil
207 ) { 189 ) {
208 _isCollapsed = isCollapsed 190 _isCollapsed = isCollapsed
@@ -211,11 +193,9 @@ struct OwnershipSectionView: View {
211 self.error = error 193 self.error = error
212 self.provenance = provenance 194 self.provenance = provenance
213 self.confidence = confidence 195 self.confidence = confidence
214 self.showsHistoryPlaceholder = showsHistoryPlaceholder
215 self.history = history 196 self.history = history
216 self.historyLoading = historyLoading 197 self.historyLoading = historyLoading
217 self.historyError = historyError 198 self.historyError = historyError
218 self.historyCreditStatus = historyCreditStatus
219 self.onLoadHistory = onLoadHistory 199 self.onLoadHistory = onLoadHistory
220 } 200 }
221 201
@@ -248,7 +228,7 @@ struct OwnershipSectionView: View {
248 .font(appDensity.font(.caption)) 228 .font(appDensity.font(.caption))
249 .foregroundStyle(Color(.appTextSecondary)) 229 .foregroundStyle(Color(.appTextSecondary))
250 Spacer() 230 Spacer()
251 if let onLoadHistory, history.isEmpty, !historyLoading, !showsHistoryPlaceholder { 231 if let onLoadHistory, history.isEmpty, !historyLoading {
252 Button("Load") { 232 Button("Load") {
253 onLoadHistory() 233 onLoadHistory()
254 } 234 }
@@ -274,8 +254,6 @@ struct OwnershipSectionView: View {
274 } 254 }
275 } else if let historyError { 255 } else if let historyError {
276 MessageRowView(text: historyError, isError: false) 256 MessageRowView(text: historyError, isError: false)
277 } else if showsHistoryPlaceholder {
278 MessageRowView(text: "Ownership history available in Pro+", isError: false)
279 } 257 }
280 } 258 }
281 } 259 }
@@ -414,7 +392,6 @@ struct SubdomainsSectionView: View {
414 let extendedCount: Int 392 let extendedCount: Int
415 let extendedLoading: Bool 393 let extendedLoading: Bool
416 let extendedError: String? 394 let extendedError: String?
417 let extendedCreditStatus: UsageCreditStatus?
418 let onLoadExtended: (() -> Void)? 395 let onLoadExtended: (() -> Void)?
419 396
420 init( 397 init(
@@ -429,7 +406,6 @@ struct SubdomainsSectionView: View {
429 extendedCount: Int = 0, 406 extendedCount: Int = 0,
430 extendedLoading: Bool = false, 407 extendedLoading: Bool = false,
431 extendedError: String? = nil, 408 extendedError: String? = nil,
432 extendedCreditStatus: UsageCreditStatus? = nil,
433 onLoadExtended: (() -> Void)? = nil 409 onLoadExtended: (() -> Void)? = nil
434 ) { 410 ) {
435 _isCollapsed = isCollapsed 411 _isCollapsed = isCollapsed
@@ -443,7 +419,6 @@ struct SubdomainsSectionView: View {
443 self.extendedCount = extendedCount 419 self.extendedCount = extendedCount
444 self.extendedLoading = extendedLoading 420 self.extendedLoading = extendedLoading
445 self.extendedError = extendedError 421 self.extendedError = extendedError
446 self.extendedCreditStatus = extendedCreditStatus
447 self.onLoadExtended = onLoadExtended 422 self.onLoadExtended = onLoadExtended
448 } 423 }
449 424
@@ -551,8 +526,6 @@ struct DNSSectionView: View {
551 let history: [DNSHistoryEvent] 526 let history: [DNSHistoryEvent]
552 let historyLoading: Bool 527 let historyLoading: Bool
553 let historyError: String? 528 let historyError: String?
554 let showsHistoryPlaceholder: Bool
555 let historyCreditStatus: UsageCreditStatus?
556 let onLoadHistory: (() -> Void)? 529 let onLoadHistory: (() -> Void)?
557 530
558 init( 531 init(
@@ -568,8 +541,6 @@ struct DNSSectionView: View {
568 history: [DNSHistoryEvent] = [], 541 history: [DNSHistoryEvent] = [],
569 historyLoading: Bool = false, 542 historyLoading: Bool = false,
570 historyError: String? = nil, 543 historyError: String? = nil,
571 showsHistoryPlaceholder: Bool = false,
572 historyCreditStatus: UsageCreditStatus? = nil,
573 onLoadHistory: (() -> Void)? = nil 544 onLoadHistory: (() -> Void)? = nil
574 ) { 545 ) {
575 _isCollapsed = isCollapsed 546 _isCollapsed = isCollapsed
@@ -584,8 +555,6 @@ struct DNSSectionView: View {
584 self.history = history 555 self.history = history
585 self.historyLoading = historyLoading 556 self.historyLoading = historyLoading
586 self.historyError = historyError 557 self.historyError = historyError
587 self.showsHistoryPlaceholder = showsHistoryPlaceholder
588 self.historyCreditStatus = historyCreditStatus
589 self.onLoadHistory = onLoadHistory 558 self.onLoadHistory = onLoadHistory
590 } 559 }
591 560
@@ -641,7 +610,7 @@ struct DNSSectionView: View {
641 .font(appDensity.font(.subheadline, weight: .semibold)) 610 .font(appDensity.font(.subheadline, weight: .semibold))
642 .foregroundStyle(Color(.statusInfo)) 611 .foregroundStyle(Color(.statusInfo))
643 Spacer() 612 Spacer()
644 if let onLoadHistory, history.isEmpty, !historyLoading, !showsHistoryPlaceholder { 613 if let onLoadHistory, history.isEmpty, !historyLoading {
645 Button("Load") { 614 Button("Load") {
646 onLoadHistory() 615 onLoadHistory()
647 } 616 }
@@ -682,8 +651,6 @@ struct DNSSectionView: View {
682 } 651 }
683 } else if let historyError { 652 } else if let historyError {
684 MessageRowView(text: historyError, isError: false) 653 MessageRowView(text: historyError, isError: false)
685 } else if showsHistoryPlaceholder {
686 MessageRowView(text: "DNS history available in Pro+", isError: false)
687 } 654 }
688 } 655 }
689 656
DomainDig/UsageCreditService.swift deleted −73
@@ -1,73 +0,0 @@
1import Foundation
2
3actor UsageCreditService {
4 static let shared = UsageCreditService()
5
6 private struct CreditLedger: Codable {
7 let appVersion: String
8 var remainingByFeature: [UsageCreditFeature: Int]
9 }
10
11 private let storageKey = "usageCredits.ledger"
12 private var ledger: CreditLedger
13
14 init(defaults: UserDefaults = .standard) {
15 if let data = defaults.data(forKey: storageKey),
16 let decoded = try? JSONDecoder().decode(CreditLedger.self, from: data),
17 decoded.appVersion == AppVersion.current {
18 ledger = decoded
19 } else {
20 ledger = Self.makeLedger()
21 if let data = try? JSONEncoder().encode(ledger) {
22 defaults.set(data, forKey: storageKey)
23 }
24 }
25 }
26
27 func status(for feature: UsageCreditFeature) -> UsageCreditStatus {
28 let total = feature.defaultAllowance
29 let remaining = ledger.remainingByFeature[feature] ?? total
30 return UsageCreditStatus(
31 feature: feature,
32 remaining: remaining,
33 total: total,
34 resetContext: "Resets with app version \(ledger.appVersion)"
35 )
36 }
37
38 func allStatuses() -> [UsageCreditStatus] {
39 UsageCreditFeature.allCases.map { status(for: $0) }
40 }
41
42 func canUse(_ feature: UsageCreditFeature) -> Bool {
43 status(for: feature).remaining > 0
44 }
45
46 @discardableResult
47 func consume(_ feature: UsageCreditFeature) -> UsageCreditStatus {
48 let current = ledger.remainingByFeature[feature] ?? feature.defaultAllowance
49 ledger.remainingByFeature[feature] = max(0, current - 1)
50 persist()
51 return status(for: feature)
52 }
53
54 func resetForCurrentVersion() {
55 ledger = Self.makeLedger()
56 persist()
57 }
58
59 private static func makeLedger() -> CreditLedger {
60 CreditLedger(
61 appVersion: AppVersion.current,
62 remainingByFeature: Dictionary(
63 uniqueKeysWithValues: UsageCreditFeature.allCases.map { ($0, $0.defaultAllowance) }
64 )
65 )
66 }
67
68 private func persist(defaults: UserDefaults = .standard) {
69 if let data = try? JSONEncoder().encode(ledger) {
70 defaults.set(data, forKey: storageKey)
71 }
72 }
73}
DomainDig/WatchlistView.swift +7
@@ -668,6 +668,13 @@ struct TrackedDomainDetailView: View {
668 .disabled(!viewModel.canEdit(liveTrackedDomain)) 668 .disabled(!viewModel.canEdit(liveTrackedDomain))
669 669
670 Button { 670 Button {
671 // Managing a share the user already has stays available on
672 // any tier; only creating a new one needs Pro+.
673 guard liveTrackedDomain.collaboration?.isShared == true
674 || FeatureAccessService.hasAccess(to: .sharedPortfolios) else {
675 viewModel.upgradePrompt = FeatureAccessService.upgradePrompt(for: .sharedPortfolios)
676 return
677 }
671 shareEntity = .trackedDomain(liveTrackedDomain.domain) 678 shareEntity = .trackedDomain(liveTrackedDomain.domain)
672 } label: { 679 } label: {
673 Label(liveTrackedDomain.collaboration?.isShared == true ? "Manage Share" : "Share Domain", systemImage: "person.2") 680 Label(liveTrackedDomain.collaboration?.isShared == true ? "Manage Share" : "Share Domain", systemImage: "person.2")
DomainDig/WorkflowsView.swift +5
@@ -229,6 +229,11 @@ struct WorkflowDetailView: View {
229 .disabled(!viewModel.canEdit(workflow)) 229 .disabled(!viewModel.canEdit(workflow))
230 230
231 Button { 231 Button {
232 guard workflow.collaboration?.isShared == true
233 || FeatureAccessService.hasAccess(to: .sharedPortfolios) else {
234 viewModel.upgradePrompt = FeatureAccessService.upgradePrompt(for: .sharedPortfolios)
235 return
236 }
232 shareEntity = .workflow(workflow.id) 237 shareEntity = .workflow(workflow.id)
233 } label: { 238 } label: {
234 Label(workflow.collaboration?.isShared == true ? "Manage Share" : "Share Workflow", systemImage: "person.2") 239 Label(workflow.collaboration?.isShared == true ? "Manage Share" : "Share Workflow", systemImage: "person.2")
DomainDigTests/FeatureAccessTests.swift added +132
@@ -0,0 +1,132 @@
1import XCTest
2@testable import DomainDig
3
4/// The tier table used to promise five capabilities that could not return data,
5/// and they were Pro+'s only difference from Pro — so making the paywall honest
6/// by deleting them would have left a paid tier granting nothing. These pin the
7/// replacement table and that invariant.
8final class FeatureAccessTests: XCTestCase {
9
10 // MARK: Free
11
12 func testFreeIncludesTheEverydayCapabilities() {
13 let free = FeatureAccessService.entitlements(for: .free)
14
15 XCTAssertTrue(free.capabilities.contains(.singleLookup))
16 XCTAssertTrue(free.capabilities.contains(.basicHistory))
17 XCTAssertTrue(free.capabilities.contains(.limitedTracking))
18 XCTAssertTrue(free.capabilities.contains(.workflows))
19 XCTAssertTrue(free.capabilities.contains(.batchOperations))
20 }
21
22 func testFreeExcludesThePaidCapabilities() {
23 let free = FeatureAccessService.entitlements(for: .free)
24
25 XCTAssertFalse(free.capabilities.contains(.automatedMonitoring))
26 XCTAssertFalse(free.capabilities.contains(.localAlerts))
27 XCTAssertFalse(free.capabilities.contains(.advancedExports))
28 XCTAssertFalse(free.capabilities.contains(.extendedSubdomains))
29 XCTAssertFalse(free.capabilities.contains(.sharedPortfolios))
30 XCTAssertFalse(free.capabilities.contains(.auditDepth))
31 }
32
33 func testFreeKeepsItsAllowances() {
34 let free = FeatureAccessService.entitlements(for: .free)
35
36 XCTAssertEqual(free.trackedDomainLimit, 5)
37 XCTAssertEqual(free.workflowLimit, 1)
38 XCTAssertEqual(free.batchSizeLimit, 10)
39 XCTAssertEqual(free.activeAuditSessionLimit, 1)
40 }
41
42 // MARK: Pro
43
44 /// Extended subdomains moved down from Pro+: unlike the other four, it does
45 /// return data a lower tier does not have — a live crt.sh query at a higher
46 /// limit than the base lookup.
47 func testProAddsMonitoringAlertsExportsAndExtendedSubdomains() {
48 let pro = FeatureAccessService.entitlements(for: .pro)
49
50 XCTAssertTrue(pro.capabilities.contains(.automatedMonitoring))
51 XCTAssertTrue(pro.capabilities.contains(.localAlerts))
52 XCTAssertTrue(pro.capabilities.contains(.advancedExports))
53 XCTAssertTrue(pro.capabilities.contains(.extendedSubdomains))
54 }
55
56 func testProDoesNotIncludeTheProPlusCapabilities() {
57 let pro = FeatureAccessService.entitlements(for: .pro)
58
59 XCTAssertFalse(pro.capabilities.contains(.sharedPortfolios))
60 XCTAssertFalse(pro.capabilities.contains(.auditDepth))
61 }
62
63 func testProLiftsTheAllowances() {
64 let pro = FeatureAccessService.entitlements(for: .pro)
65
66 XCTAssertNil(pro.workflowLimit)
67 XCTAssertNil(pro.batchSizeLimit)
68 XCTAssertNil(pro.activeAuditSessionLimit)
69 XCTAssertGreaterThan(pro.trackedDomainLimit, 1000)
70 }
71
72 // MARK: Pro+
73
74 func testProPlusAddsSharedPortfoliosAndAuditDepth() {
75 let proPlus = FeatureAccessService.entitlements(for: .proPlus)
76
77 XCTAssertTrue(proPlus.capabilities.contains(.sharedPortfolios))
78 XCTAssertTrue(proPlus.capabilities.contains(.auditDepth))
79 }
80
81 /// The finding this table replaces: Pro+ cost twice Pro and its only
82 /// difference was five capabilities that returned nothing. A tier that
83 /// grants no more than the one below it must not be sellable.
84 func testProPlusGrantsStrictlyMoreThanPro() {
85 let pro = FeatureAccessService.entitlements(for: .pro).capabilities
86 let proPlus = FeatureAccessService.entitlements(for: .proPlus).capabilities
87
88 XCTAssertTrue(pro.isSubset(of: proPlus))
89 XCTAssertFalse(proPlus.subtracting(pro).isEmpty)
90 }
91
92 func testEachTierGrantsAtLeastTheOneBelowIt() {
93 let free = FeatureAccessService.entitlements(for: .free).capabilities
94 let pro = FeatureAccessService.entitlements(for: .pro).capabilities
95
96 XCTAssertTrue(free.isSubset(of: pro))
97 }
98
99 // MARK: Nothing claims a capability that cannot produce data
100
101 /// Pricing and reputation had no local fallback and no configured endpoint,
102 /// so they were deleted rather than renamed. Their absence from the
103 /// capability list is what stops the paywall advertising them again.
104 func testNoCapabilityIsNamedForADeletedFeature() {
105 let names = FeatureCapability.allCases.map(\.rawValue)
106
107 XCTAssertFalse(names.contains("domainPricing"))
108 XCTAssertFalse(names.contains("reputation"))
109 }
110
111 /// Ownership and DNS history derive from the user's own stored snapshots, so
112 /// they are free features now and no longer gated at all.
113 func testTheHistoryDerivationsAreNotGated() {
114 let names = FeatureCapability.allCases.map(\.rawValue)
115
116 XCTAssertFalse(names.contains("ownershipHistory"))
117 XCTAssertFalse(names.contains("dnsHistory"))
118 }
119
120 // MARK: Downgrade safety
121
122 /// A lapsed subscriber keeps data above the new ceiling. Nothing may refuse
123 /// to read it: the limits gate adding, not holding.
124 func testFreeTierStillReportsALimitWhenAlreadyOverIt() {
125 let free = FeatureAccessService.entitlements(for: .free)
126
127 XCTAssertFalse(FeatureAccessService.canAddTrackedDomain(currentCount: free.trackedDomainLimit, tier: .free))
128 XCTAssertTrue(FeatureAccessService.canAddTrackedDomain(currentCount: 0, tier: .free))
129 XCTAssertFalse(FeatureAccessService.canAddTrackedDomain(currentCount: 500, tier: .free))
130 XCTAssertTrue(FeatureAccessService.canAddTrackedDomain(currentCount: 500, tier: .pro))
131 }
132}