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 {
2626
2727struct FeatureMetadataSnapshot: Codable {
2828 let cachedEntitlement: PurchaseService.CachedEntitlement?
29 let usageCredits: UsageCreditsSnapshot?
30}
31
32struct UsageCreditsSnapshot: Codable {
33 let appVersion: String
34 let remainingByFeature: [UsageCreditFeature: Int]
3529}
3630
3731struct TrackedDomainsExport: Codable {
@@ -565,7 +559,6 @@ enum DomainDataPortabilityService {
565559 static let appDensity = AppDensity.userDefaultsKey
566560 static let resolverURL = DNSResolverOption.userDefaultsKey
567561 static let purchaseCache = "purchase.cachedEntitlement"
568 static let usageCredits = "usageCredits.ledger"
569562 }
570563
571564 static func loadRecentSearches(defaults: UserDefaults = .standard) -> [String] {
@@ -727,14 +720,7 @@ enum DomainDataPortabilityService {
727720 cachedEntitlement = nil
728721 }
729722
730 let usageCredits: UsageCreditsSnapshot?
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)
723 return FeatureMetadataSnapshot(cachedEntitlement: cachedEntitlement)
738724 }
739725
740726 static func saveFeatureMetadata(_ featureMetadata: FeatureMetadataSnapshot?, defaults: UserDefaults = .standard) {
@@ -742,11 +728,6 @@ enum DomainDataPortabilityService {
742728 let data = try? JSONEncoder().encode(cachedEntitlement) {
743729 defaults.set(data, forKey: StorageKey.purchaseCache)
744730 }
745
746 if let usageCredits = featureMetadata?.usageCredits,
747 let data = try? JSONEncoder().encode(usageCredits) {
748 defaults.set(data, forKey: StorageKey.usageCredits)
749 }
750731 }
751732
752733 static func currentBackup(defaults: UserDefaults = .standard) -> DomainDigBackup {
@@ -885,7 +866,6 @@ enum DomainDataPortabilityService {
885866 let cachedItems = appSettings.recentSearches.count
886867 + appSettings.savedDomains.count
887868 + (featureMetadata.cachedEntitlement == nil ? 0 : 1)
888 + (featureMetadata.usageCredits == nil ? 0 : 1)
889869
890870 return DataLifecycleSummary(
891871 trackedDomains: loadTrackedDomains(defaults: defaults).count,
@@ -1095,7 +1075,7 @@ enum DomainDataPortabilityService {
10951075 historySnapshots: backup.historyEntries.count,
10961076 auditSessions: backup.auditSessions?.count ?? 0,
10971077 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),
10991079 monitoringLogs: backup.monitoringLogs.count
11001080 )
11011081 }
@@ -1297,27 +1277,8 @@ enum DomainDataPortabilityService {
12971277 private static func mergeFeatureMetadata(existing: FeatureMetadataSnapshot, incoming: FeatureMetadataSnapshot?) -> FeatureMetadataSnapshot {
12981278 guard let incoming else { return existing }
12991279
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
13181280 return FeatureMetadataSnapshot(
1319 cachedEntitlement: incoming.cachedEntitlement ?? existing.cachedEntitlement,
1320 usageCredits: mergedUsageCredits
1281 cachedEntitlement: incoming.cachedEntitlement ?? existing.cachedEntitlement
13211282 )
13221283 }
13231284
DomainDig.xcodeproj/project.pbxproj +4
@@ -27,6 +27,7 @@
2727 C7CA9E02B0DC2708DE7A8563 /* DomainDataPortabilityServiceTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = CC948A02EC0184228BC4630E /* DomainDataPortabilityServiceTests.swift */; };
2828 E959C4D24DAAB3CB80D854B2 /* DiffServiceTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 15A25DF2B8BB52589D49986B /* DiffServiceTests.swift */; };
2929 A1B2C3D40000000000000202 /* InspectionInputTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = A1B2C3D40000000000000201 /* InspectionInputTests.swift */; };
30 A1B2C3D40000000000000602 /* FeatureAccessTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = A1B2C3D40000000000000601 /* FeatureAccessTests.swift */; };
3031 A1B2C3D40000000000000302 /* AvailabilityTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = A1B2C3D40000000000000301 /* AvailabilityTests.swift */; };
3132 A1B2C3D40000000000000402 /* CloudSyncMergeTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = A1B2C3D40000000000000401 /* CloudSyncMergeTests.swift */; };
3233 A1B2C3D40000000000000502 /* DomainNameTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = A1B2C3D40000000000000501 /* DomainNameTests.swift */; };
@@ -101,6 +102,7 @@
101102 8BF9DA842F9B13FB00EF41D5 /* DomainDataPortabilityService.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = DomainDataPortabilityService.swift; sourceTree = "<group>"; };
102103 A1B2C3D40000000000000101 /* HistoryEntryCodableTests.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; path = HistoryEntryCodableTests.swift; sourceTree = "<group>"; };
103104 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>"; };
104106 A1B2C3D40000000000000301 /* AvailabilityTests.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; path = AvailabilityTests.swift; sourceTree = "<group>"; };
105107 A1B2C3D40000000000000401 /* CloudSyncMergeTests.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; path = CloudSyncMergeTests.swift; sourceTree = "<group>"; };
106108 A1B2C3D40000000000000501 /* DomainNameTests.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; path = DomainNameTests.swift; sourceTree = "<group>"; };
@@ -242,6 +244,7 @@
242244 499B99A1866999A38AC475F5 /* AppInfoTests.swift */,
243245 A1B2C3D40000000000000101 /* HistoryEntryCodableTests.swift */,
244246 A1B2C3D40000000000000201 /* InspectionInputTests.swift */,
247 A1B2C3D40000000000000601 /* FeatureAccessTests.swift */,
245248 A1B2C3D40000000000000301 /* AvailabilityTests.swift */,
246249 A1B2C3D40000000000000401 /* CloudSyncMergeTests.swift */,
247250 A1B2C3D40000000000000501 /* DomainNameTests.swift */,
@@ -506,6 +509,7 @@
506509 4F96CEB875EC3501E784CE39 /* DataMigrationServiceTests.swift in Sources */,
507510 99024E91EED2275FD80E83A9 /* AppInfoTests.swift in Sources */,
508511 A1B2C3D40000000000000202 /* InspectionInputTests.swift in Sources */,
512 A1B2C3D40000000000000602 /* FeatureAccessTests.swift in Sources */,
509513 A1B2C3D40000000000000302 /* AvailabilityTests.swift in Sources */,
510514 A1B2C3D40000000000000402 /* CloudSyncMergeTests.swift in Sources */,
511515 A1B2C3D40000000000000502 /* DomainNameTests.swift in Sources */,
DomainDig/ContentView.swift +1 −9
@@ -191,7 +191,6 @@ struct ContentView: View {
191191 }
192192 }
193193 .task {
194 await viewModel.refreshUsageCredits()
195194 }
196195 .onChange(of: viewModel.searchedDomain) { _, _ in
197196 collapsedSections = defaultCollapsedSections
@@ -408,9 +407,7 @@ struct ContentView: View {
408407 trackedDomain: trackedDomain,
409408 workflows: workflows,
410409 trackingLimitMessage: viewModel.trackingLimitMessage,
411 pricingLoading: viewModel.domainPricingLoading,
412 pricingError: viewModel.domainPricingError,
413 showsPricingPlaceholder: !DataAccessService.hasAccess(to: .domainPricing),
410
414411 onTrack: {
415412 _ = viewModel.trackCurrentDomain()
416413 },
@@ -451,11 +448,9 @@ struct ContentView: View {
451448 error: viewModel.ownershipError,
452449 provenance: viewModel.currentSnapshot.provenanceBySection[.ownership],
453450 confidence: viewModel.currentSnapshot.ownershipConfidence,
454 showsHistoryPlaceholder: !DataAccessService.hasAccess(to: .ownershipHistory),
455451 history: viewModel.ownershipHistory,
456452 historyLoading: viewModel.ownershipHistoryLoading,
457453 historyError: viewModel.ownershipHistoryError,
458 historyCreditStatus: viewModel.ownershipHistoryCreditStatus,
459454 onLoadHistory: {
460455 Task {
461456 await viewModel.loadOwnershipHistory()
@@ -477,7 +472,6 @@ struct ContentView: View {
477472 extendedCount: viewModel.extendedSubdomains.count,
478473 extendedLoading: viewModel.extendedSubdomainsLoading,
479474 extendedError: viewModel.extendedSubdomainsError,
480 extendedCreditStatus: viewModel.extendedSubdomainsCreditStatus,
481475 onLoadExtended: {
482476 Task {
483477 await viewModel.loadExtendedSubdomains()
@@ -500,8 +494,6 @@ struct ContentView: View {
500494 history: viewModel.dnsHistory,
501495 historyLoading: viewModel.dnsHistoryLoading,
502496 historyError: viewModel.dnsHistoryError,
503 showsHistoryPlaceholder: !DataAccessService.hasAccess(to: .dnsHistory),
504 historyCreditStatus: viewModel.dnsHistoryCreditStatus,
505497 onLoadHistory: {
506498 Task {
507499 await viewModel.loadDNSHistory()
DomainDig/DataAccessService.swift −4
@@ -10,11 +10,7 @@ extension DataCapability {
1010 /// The plan feature that unlocks this data.
1111 var feature: FeatureCapability {
1212 switch self {
13 case .ownershipHistory: .ownershipHistory
14 case .dnsHistory: .dnsHistory
1513 case .extendedSubdomains: .extendedSubdomains
16 case .domainPricing: .domainPricing
17 case .reputation: .reputation
1814 }
1915 }
2016}
DomainDig/DataResetService.swift −1
@@ -24,7 +24,6 @@ enum DataResetService {
2424
2525 await LookupRuntime.shared.clearCache()
2626 await LocalNotificationService.shared.clearAllNotifications()
27 await UsageCreditService.shared.resetForCurrentVersion()
2827
2928 await MainActor.run {
3029 IntegrationService.shared.resetAfterLocalWipe()
DomainDig/DomainViewModel.swift +16 −94
@@ -242,7 +242,6 @@ final class DomainViewModel {
242242 var reputation: DomainReputationResult?
243243 var reputationLoading = false
244244 var reputationError: String?
245 var usageCredits: [UsageCreditFeature: UsageCreditStatus] = DomainViewModel.defaultUsageCredits()
246245
247246 var portScanResults: [PortScanResult] = []
248247 var portScanLoading = false
@@ -698,18 +697,6 @@ final class DomainViewModel {
698697 currentReport?.web
699698 }
700699
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
713700 var combinedSubdomains: [DiscoveredSubdomain] {
714701 let existingHosts = Set(subdomains.map { $0.hostname.lowercased() })
715702 return subdomains + extendedSubdomains.filter { !existingHosts.contains($0.hostname.lowercased()) }
@@ -1090,7 +1077,6 @@ final class DomainViewModel {
10901077 latestWorkflowRunSummary = nil
10911078 historyAutoPruneOption = Self.loadHistoryAutoPruneOption()
10921079 refreshDataLifecycleSummary()
1093 await refreshUsageCredits()
10941080 await refreshMonitoringAuthorizationStatus()
10951081 }
10961082
@@ -1255,6 +1241,14 @@ final class DomainViewModel {
12551241 .lowercased() ?? domain.lowercased()
12561242 guard !normalizedDomain.isEmpty else { return nil }
12571243
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
12581252 let previous = historyEntries(for: normalizedDomain).first?.snapshot
12591253 let snapshot = await inspectionService.inspectSnapshot(domain: normalizedDomain, previousSnapshot: previous)
12601254 guard let entry = saveHistoryEntry(
@@ -1291,7 +1285,7 @@ final class DomainViewModel {
12911285 }
12921286
12931287 func loadOwnershipHistory() async {
1294 await loadLookup(.ownershipHistory, into: \.ownershipHistory, loading: \.ownershipHistoryLoading, error: \.ownershipHistoryError,
1288 await loadLookup(into: \.ownershipHistory, loading: \.ownershipHistoryLoading, error: \.ownershipHistoryError,
12951289 fallback: "Ownership history unavailable") {
12961290 await ExternalDataService.shared.ownershipHistory(
12971291 domain: searchedDomain,
@@ -1302,7 +1296,7 @@ final class DomainViewModel {
13021296 }
13031297
13041298 func loadDNSHistory() async {
1305 await loadLookup(.dnsHistory, into: \.dnsHistory, loading: \.dnsHistoryLoading, error: \.dnsHistoryError,
1299 await loadLookup(into: \.dnsHistory, loading: \.dnsHistoryLoading, error: \.dnsHistoryError,
13061300 fallback: "DNS history unavailable") {
13071301 await ExternalDataService.shared.dnsHistory(
13081302 domain: searchedDomain,
@@ -1322,10 +1316,11 @@ final class DomainViewModel {
13221316 }
13231317 }
13241318
1325 /// Loads `capability`'s 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.
1319 /// Loads a lookup for the searched domain into `items`, unless it is loaded
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.
13271322 private func loadLookup<Item>(
1328 _ capability: DataCapability,
1323 _ capability: DataCapability? = nil,
13291324 into items: ReferenceWritableKeyPath<DomainViewModel, [Item]>,
13301325 loading: ReferenceWritableKeyPath<DomainViewModel, Bool>,
13311326 error: ReferenceWritableKeyPath<DomainViewModel, String?>,
@@ -1333,7 +1328,7 @@ final class DomainViewModel {
13331328 fetch: () async -> ServiceResult<[Item]>
13341329 ) async {
13351330 guard !searchedDomain.isEmpty else { return }
1336 guard DataAccessService.hasAccess(to: capability) else {
1331 if let capability, !DataAccessService.hasAccess(to: capability) {
13371332 upgradePrompt = FeatureAccessService.upgradePrompt(for: capability.feature)
13381333 return
13391334 }
@@ -1360,11 +1355,6 @@ final class DomainViewModel {
13601355 }
13611356 }
13621357
1363 func refreshUsageCredits() async {
1364 let statuses = await UsageCreditService.shared.allStatuses()
1365 usageCredits = Dictionary(uniqueKeysWithValues: statuses.map { ($0.feature, $0) })
1366 }
1367
13681358 private func performLookup(domain: String, lookupID: UUID) async -> HistoryEntry? {
13691359 let lookupStartedAt = DomainDebugLog.signpostStart("DomainViewModel.performLookup", domain: domain)
13701360 let previous = previousSnapshot(
@@ -1383,16 +1373,6 @@ final class DomainViewModel {
13831373 lastLookupDurationMs = snapshot.totalLookupDurationMs
13841374 refreshingTrackedDomainID = nil
13851375
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
13961376 guard snapshot.statusMessage == nil else {
13971377 return history.first(where: { $0.id == snapshot.historyEntryID })
13981378 }
@@ -3582,9 +3562,6 @@ final class DomainViewModel {
35823562 if let ownershipError = snapshot.ownershipError, snapshot.ownership == nil {
35833563 lines.append(" Source: \(ownershipError)")
35843564 }
3585 if !DataAccessService.hasAccess(to: .ownershipHistory) {
3586 lines.append(" Ownership history (coming soon)")
3587 }
35883565 return lines
35893566 }
35903567
@@ -3600,7 +3577,7 @@ final class DomainViewModel {
36003577 }
36013578 }
36023579 if !DataAccessService.hasAccess(to: .extendedSubdomains) {
3603 lines.append(" Extended subdomain discovery (Pro+)")
3580 lines.append(" Extended subdomain discovery (Pro)")
36043581 }
36053582 return lines
36063583 }
@@ -3910,46 +3887,6 @@ final class DomainViewModel {
39103887 return formatter
39113888 }()
39123889
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
39533890 private func conciseExternalMessage(_ message: String, fallback: String) -> String {
39543891 let trimmed = message.trimmingCharacters(in: .whitespacesAndNewlines)
39553892 if trimmed.isEmpty {
@@ -3967,21 +3904,6 @@ final class DomainViewModel {
39673904 return trimmed
39683905 }
39693906
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
39853907 private static func csvEscaped(_ value: String) -> String {
39863908 let escaped = value.replacingOccurrences(of: "\"", with: "\"\"")
39873909 return "\"\(escaped)\""
DomainDig/ExternalDataService.swift +1 −95
@@ -7,15 +7,11 @@ actor ExternalDataService {
77 case ownershipHistory(String)
88 case dnsHistory(String)
99 case extendedSubdomains(String)
10 case pricing(String)
11 case reputation(String)
1210 }
1311
1412 private enum RateLimitBucket: Hashable {
1513 case history
1614 case subdomains
17 case pricing
18 case reputation
1915
2016 var minimumSpacing: TimeInterval {
2117 switch self {
@@ -23,10 +19,6 @@ actor ExternalDataService {
2319 return 1.0
2420 case .subdomains:
2521 return 1.5
26 case .pricing:
27 return 1.0
28 case .reputation:
29 return 1.0
3022 }
3123 }
3224 }
@@ -35,8 +27,6 @@ actor ExternalDataService {
3527 case ownershipHistory(ServiceResult<[DomainOwnershipHistoryEvent]>)
3628 case dnsHistory(ServiceResult<[DNSHistoryEvent]>)
3729 case extendedSubdomains(ServiceResult<[DiscoveredSubdomain]>)
38 case pricing(ServiceResult<DomainPricingInsight>)
39 case reputation(ServiceResult<DomainReputationResult>)
4030 }
4131
4232 private struct CacheEntry {
@@ -48,8 +38,6 @@ actor ExternalDataService {
4838 let ownershipHistoryURL: String?
4939 let dnsHistoryURL: String?
5040 let extendedSubdomainsURL: String?
51 let pricingURL: String?
52 let reputationURL: String?
5341 }
5442
5543 private let ttl: TimeInterval = 900
@@ -152,40 +140,6 @@ actor ExternalDataService {
152140 )
153141 }
154142
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
189143 private func execute<T>(
190144 key: RequestKey,
191145 rateLimitBucket: RateLimitBucket,
@@ -236,11 +190,7 @@ actor ExternalDataService {
236190 dnsHistoryURL: defaults.string(forKey: "externalData.dnsHistoryURL")
237191 ?? Bundle.main.object(forInfoDictionaryKey: "ExternalDNSHistoryURL") as? String,
238192 extendedSubdomainsURL: defaults.string(forKey: "externalData.extendedSubdomainsURL")
239 ?? 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
193 ?? Bundle.main.object(forInfoDictionaryKey: "ExternalExtendedSubdomainsURL") as? String
244194 )
245195 }
246196
@@ -295,50 +245,6 @@ actor ExternalDataService {
295245 }
296246 }
297247
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
342248 private func requestData(url: URL) async -> ServiceResult<Data> {
343249 for attempt in 0..<2 {
344250 do {
DomainDig/FeatureAccessService.swift +30 −21
@@ -28,11 +28,9 @@ enum FeatureCapability: String, CaseIterable, Identifiable {
2828 case automatedMonitoring
2929 case localAlerts
3030 case advancedExports
31 case ownershipHistory
32 case dnsHistory
3331 case extendedSubdomains
34 case domainPricing
35 case reputation
32 case sharedPortfolios
33 case auditDepth
3634
3735 var id: String { rawValue }
3836
@@ -54,16 +52,12 @@ enum FeatureCapability: String, CaseIterable, Identifiable {
5452 return "Local alerts"
5553 case .advancedExports:
5654 return "Advanced exports"
57 case .ownershipHistory:
58 return "Ownership history"
59 case .dnsHistory:
60 return "DNS history"
6155 case .extendedSubdomains:
6256 return "Extended subdomains"
63 case .domainPricing:
64 return "Domain pricing"
65 case .reputation:
66 return "Domain reputation"
57 case .sharedPortfolios:
58 return "Shared portfolios"
59 case .auditDepth:
60 return "Unlimited audits"
6761 }
6862 }
6963}
@@ -74,6 +68,8 @@ struct FeatureEntitlements: Equatable {
7468 let trackedDomainLimit: Int
7569 let workflowLimit: Int?
7670 let batchSizeLimit: Int?
71 /// Concurrently open audit sessions; nil is unlimited.
72 let activeAuditSessionLimit: Int?
7773}
7874
7975struct UpgradePromptContext: Identifiable, Equatable {
@@ -91,14 +87,19 @@ enum FeatureAccessService {
9187 }
9288
9389 static var entitlements: FeatureEntitlements {
94 switch currentTier {
90 entitlements(for: currentTier)
91 }
92
93 static func entitlements(for tier: FeatureTier) -> FeatureEntitlements {
94 switch tier {
9595 case .free:
9696 return FeatureEntitlements(
9797 tier: .free,
9898 capabilities: [.singleLookup, .basicHistory, .limitedTracking, .workflows, .batchOperations],
9999 trackedDomainLimit: 5,
100100 workflowLimit: 1,
101 batchSizeLimit: 10
101 batchSizeLimit: 10,
102 activeAuditSessionLimit: 1
102103 )
103104 case .pro:
104105 return FeatureEntitlements(
@@ -111,11 +112,13 @@ enum FeatureAccessService {
111112 .batchOperations,
112113 .automatedMonitoring,
113114 .localAlerts,
114 .advancedExports
115 .advancedExports,
116 .extendedSubdomains
115117 ],
116118 trackedDomainLimit: effectivelyUnlimitedTrackedDomains,
117119 workflowLimit: nil,
118 batchSizeLimit: nil
120 batchSizeLimit: nil,
121 activeAuditSessionLimit: nil
119122 )
120123 case .proPlus:
121124 return FeatureEntitlements(
@@ -123,7 +126,8 @@ enum FeatureAccessService {
123126 capabilities: Set(FeatureCapability.allCases),
124127 trackedDomainLimit: effectivelyUnlimitedTrackedDomains,
125128 workflowLimit: nil,
126 batchSizeLimit: nil
129 batchSizeLimit: nil,
130 activeAuditSessionLimit: nil
127131 )
128132 }
129133 }
@@ -133,7 +137,11 @@ enum FeatureAccessService {
133137 }
134138
135139 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
137145 }
138146
139147 static func trackedDomainLimitMessage(currentCount: Int) -> String? {
@@ -158,9 +166,10 @@ enum FeatureAccessService {
158166
159167 static func upgradeMessage(for capability: FeatureCapability) -> String {
160168 switch capability {
161 case .workflows, .batchOperations, .automatedMonitoring, .localAlerts, .advancedExports:
169 case .workflows, .batchOperations, .automatedMonitoring, .localAlerts, .advancedExports,
170 .extendedSubdomains:
162171 return "Available in Pro"
163 case .ownershipHistory, .dnsHistory, .extendedSubdomains, .domainPricing, .reputation:
172 case .sharedPortfolios, .auditDepth:
164173 return "Available in Pro+"
165174 case .limitedTracking:
166175 return "Tracking is limited on Free"
@@ -222,7 +231,7 @@ enum FeatureAccessService {
222231 static func upgradePrompt(for capability: FeatureCapability) -> UpgradePromptContext {
223232 let title: String
224233 switch capability {
225 case .ownershipHistory, .dnsHistory, .extendedSubdomains, .domainPricing, .reputation:
234 case .sharedPortfolios, .auditDepth:
226235 title = "Available in Pro+"
227236 default:
228237 title = "Available in Pro"
DomainDig/HistoryView.swift +1 −5
@@ -199,9 +199,6 @@ struct HistoryDetailView: View {
199199 trackedDomain: trackedDomain,
200200 workflows: viewModel.workflowsContaining(domain: entry.domain),
201201 trackingLimitMessage: nil,
202 pricingLoading: false,
203 pricingError: snapshot.domainPricingError,
204 showsPricingPlaceholder: !DataAccessService.hasAccess(to: .domainPricing),
205202 onTrack: {
206203 _ = viewModel.trackDomain(domain: entry.domain, availabilityStatus: entry.availabilityResult?.status)
207204 },
@@ -221,8 +218,7 @@ struct HistoryDetailView: View {
221218 loading: false,
222219 error: snapshot.ownershipError,
223220 provenance: snapshot.provenanceBySection[.ownership],
224 confidence: snapshot.ownershipConfidence,
225 showsHistoryPlaceholder: !DataAccessService.hasAccess(to: .ownershipHistory)
221 confidence: snapshot.ownershipConfidence
226222 )
227223 .padding(.top, appDensity.metrics.sectionSpacing)
228224 SubdomainsSectionView(
DomainDig/Models.swift +3 −47
@@ -392,55 +392,11 @@ struct WorkflowRunSummary: Identifiable, Equatable {
392392 let generatedAt: Date
393393}
394394
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.
395398enum DataCapability: String, Codable {
396 case ownershipHistory
397 case dnsHistory
398399 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 }
444400}
445401
446402struct DomainOwnershipHistoryEvent: Identifiable, Codable, Equatable, Sendable {
DomainDig/PaywallView.swift +4 −5
@@ -10,7 +10,7 @@ struct PaywallView: View {
1010 NavigationStack {
1111 List {
1212 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.")
1414 .font(appDensity.font(.body, design: .default))
1515 .foregroundStyle(Color(.appTextSecondary))
1616 .fixedSize(horizontal: false, vertical: true)
@@ -23,13 +23,12 @@ struct PaywallView: View {
2323 featureRow("Background monitoring")
2424 featureRow("Local alerts")
2525 featureRow("Advanced exports")
26 featureRow("Extended subdomain discovery")
2627 }
2728
2829 Section("What Pro+ Unlocks") {
29 featureRow("Ownership history")
30 featureRow("DNS history")
31 featureRow("Extended subdomains")
32 featureRow("External pricing signals")
30 featureRow("Shared portfolios")
31 featureRow("Unlimited audit sessions")
3332 }
3433
3534 Section("Subscription") {
DomainDig/ResultSectionViews.swift +2 −35
@@ -21,9 +21,6 @@ struct DomainSectionView: View {
2121 let trackedDomain: TrackedDomain?
2222 let workflows: [DomainWorkflow]
2323 let trackingLimitMessage: String?
24 let pricingLoading: Bool
25 let pricingError: String?
26 let showsPricingPlaceholder: Bool
2724 let onTrack: () -> Void
2825 let onTogglePinned: () -> Void
2926 let onEditNote: (() -> Void)?
@@ -160,17 +157,6 @@ struct DomainSectionView: View {
160157 }
161158 }
162159 }
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 }
174160 }
175161 }
176162 }
@@ -184,11 +170,9 @@ struct OwnershipSectionView: View {
184170 let error: String?
185171 let provenance: SectionProvenance?
186172 let confidence: ConfidenceLevel?
187 let showsHistoryPlaceholder: Bool
188173 let history: [DomainOwnershipHistoryEvent]
189174 let historyLoading: Bool
190175 let historyError: String?
191 let historyCreditStatus: UsageCreditStatus?
192176 let onLoadHistory: (() -> Void)?
193177
194178 init(
@@ -198,11 +182,9 @@ struct OwnershipSectionView: View {
198182 error: String?,
199183 provenance: SectionProvenance?,
200184 confidence: ConfidenceLevel?,
201 showsHistoryPlaceholder: Bool,
202185 history: [DomainOwnershipHistoryEvent] = [],
203186 historyLoading: Bool = false,
204187 historyError: String? = nil,
205 historyCreditStatus: UsageCreditStatus? = nil,
206188 onLoadHistory: (() -> Void)? = nil
207189 ) {
208190 _isCollapsed = isCollapsed
@@ -211,11 +193,9 @@ struct OwnershipSectionView: View {
211193 self.error = error
212194 self.provenance = provenance
213195 self.confidence = confidence
214 self.showsHistoryPlaceholder = showsHistoryPlaceholder
215196 self.history = history
216197 self.historyLoading = historyLoading
217198 self.historyError = historyError
218 self.historyCreditStatus = historyCreditStatus
219199 self.onLoadHistory = onLoadHistory
220200 }
221201
@@ -248,7 +228,7 @@ struct OwnershipSectionView: View {
248228 .font(appDensity.font(.caption))
249229 .foregroundStyle(Color(.appTextSecondary))
250230 Spacer()
251 if let onLoadHistory, history.isEmpty, !historyLoading, !showsHistoryPlaceholder {
231 if let onLoadHistory, history.isEmpty, !historyLoading {
252232 Button("Load") {
253233 onLoadHistory()
254234 }
@@ -274,8 +254,6 @@ struct OwnershipSectionView: View {
274254 }
275255 } else if let historyError {
276256 MessageRowView(text: historyError, isError: false)
277 } else if showsHistoryPlaceholder {
278 MessageRowView(text: "Ownership history available in Pro+", isError: false)
279257 }
280258 }
281259 }
@@ -414,7 +392,6 @@ struct SubdomainsSectionView: View {
414392 let extendedCount: Int
415393 let extendedLoading: Bool
416394 let extendedError: String?
417 let extendedCreditStatus: UsageCreditStatus?
418395 let onLoadExtended: (() -> Void)?
419396
420397 init(
@@ -429,7 +406,6 @@ struct SubdomainsSectionView: View {
429406 extendedCount: Int = 0,
430407 extendedLoading: Bool = false,
431408 extendedError: String? = nil,
432 extendedCreditStatus: UsageCreditStatus? = nil,
433409 onLoadExtended: (() -> Void)? = nil
434410 ) {
435411 _isCollapsed = isCollapsed
@@ -443,7 +419,6 @@ struct SubdomainsSectionView: View {
443419 self.extendedCount = extendedCount
444420 self.extendedLoading = extendedLoading
445421 self.extendedError = extendedError
446 self.extendedCreditStatus = extendedCreditStatus
447422 self.onLoadExtended = onLoadExtended
448423 }
449424
@@ -551,8 +526,6 @@ struct DNSSectionView: View {
551526 let history: [DNSHistoryEvent]
552527 let historyLoading: Bool
553528 let historyError: String?
554 let showsHistoryPlaceholder: Bool
555 let historyCreditStatus: UsageCreditStatus?
556529 let onLoadHistory: (() -> Void)?
557530
558531 init(
@@ -568,8 +541,6 @@ struct DNSSectionView: View {
568541 history: [DNSHistoryEvent] = [],
569542 historyLoading: Bool = false,
570543 historyError: String? = nil,
571 showsHistoryPlaceholder: Bool = false,
572 historyCreditStatus: UsageCreditStatus? = nil,
573544 onLoadHistory: (() -> Void)? = nil
574545 ) {
575546 _isCollapsed = isCollapsed
@@ -584,8 +555,6 @@ struct DNSSectionView: View {
584555 self.history = history
585556 self.historyLoading = historyLoading
586557 self.historyError = historyError
587 self.showsHistoryPlaceholder = showsHistoryPlaceholder
588 self.historyCreditStatus = historyCreditStatus
589558 self.onLoadHistory = onLoadHistory
590559 }
591560
@@ -641,7 +610,7 @@ struct DNSSectionView: View {
641610 .font(appDensity.font(.subheadline, weight: .semibold))
642611 .foregroundStyle(Color(.statusInfo))
643612 Spacer()
644 if let onLoadHistory, history.isEmpty, !historyLoading, !showsHistoryPlaceholder {
613 if let onLoadHistory, history.isEmpty, !historyLoading {
645614 Button("Load") {
646615 onLoadHistory()
647616 }
@@ -682,8 +651,6 @@ struct DNSSectionView: View {
682651 }
683652 } else if let historyError {
684653 MessageRowView(text: historyError, isError: false)
685 } else if showsHistoryPlaceholder {
686 MessageRowView(text: "DNS history available in Pro+", isError: false)
687654 }
688655 }
689656
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 {
668668 .disabled(!viewModel.canEdit(liveTrackedDomain))
669669
670670 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 }
671678 shareEntity = .trackedDomain(liveTrackedDomain.domain)
672679 } label: {
673680 Label(liveTrackedDomain.collaboration?.isShared == true ? "Manage Share" : "Share Domain", systemImage: "person.2")
DomainDig/WorkflowsView.swift +5
@@ -229,6 +229,11 @@ struct WorkflowDetailView: View {
229229 .disabled(!viewModel.canEdit(workflow))
230230
231231 Button {
232 guard workflow.collaboration?.isShared == true
233 || FeatureAccessService.hasAccess(to: .sharedPortfolios) else {
234 viewModel.upgradePrompt = FeatureAccessService.upgradePrompt(for: .sharedPortfolios)
235 return
236 }
232237 shareEntity = .workflow(workflow.id)
233238 } label: {
234239 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}