@app-swiss-knife/react-native-sdk 0.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +182 -0
- package/SwissKnifePurchases.podspec +40 -0
- package/android/build.gradle +89 -0
- package/android/gradle.properties +3 -0
- package/android/src/main/AndroidManifest.xml +26 -0
- package/android/src/main/java/com/swissknife/crashreporting/SKCrashReportingModule.kt +216 -0
- package/android/src/main/java/com/swissknife/crashreporting/SKCrashReportingPackage.kt +17 -0
- package/android/src/main/java/com/swissknife/purchases/Conversions.kt +15 -0
- package/android/src/main/java/com/swissknife/purchases/SwissKnifeJson.kt +371 -0
- package/android/src/main/java/com/swissknife/purchases/SwissKnifePurchasesModule.kt +497 -0
- package/android/src/main/java/com/swissknife/purchases/SwissKnifePurchasesPackage.kt +25 -0
- package/android/vendor/GENERATED.md +10 -0
- package/android/vendor/java/com/appswissknife/SwissKnife.kt +533 -0
- package/android/vendor/java/com/appswissknife/analytics/EventQueueStore.kt +326 -0
- package/android/vendor/java/com/appswissknife/analytics/FlushEventsWorker.kt +296 -0
- package/android/vendor/java/com/appswissknife/analytics/SKAnalytics.kt +503 -0
- package/android/vendor/java/com/appswissknife/attributes/AttributesClient.kt +188 -0
- package/android/vendor/java/com/appswissknife/attributes/SetAttributesWorker.kt +204 -0
- package/android/vendor/java/com/appswissknife/attribution/Attribution.kt +447 -0
- package/android/vendor/java/com/appswissknife/context/AppLifecycle.kt +120 -0
- package/android/vendor/java/com/appswissknife/context/Clock.kt +70 -0
- package/android/vendor/java/com/appswissknife/context/DeviceContext.kt +138 -0
- package/android/vendor/java/com/appswissknife/context/IDs.kt +55 -0
- package/android/vendor/java/com/appswissknife/context/Reachability.kt +145 -0
- package/android/vendor/java/com/appswissknife/context/Session.kt +192 -0
- package/android/vendor/java/com/appswissknife/crashreporting/SKCrashReporting.kt +945 -0
- package/android/vendor/java/com/appswissknife/crashreporting/SKScreenshot.kt +201 -0
- package/android/vendor/java/com/appswissknife/device/DeviceID.kt +172 -0
- package/android/vendor/java/com/appswissknife/diagnostics/SKLog.kt +97 -0
- package/android/vendor/java/com/appswissknife/entitlements/EntitlementsRepository.kt +495 -0
- package/android/vendor/java/com/appswissknife/identity/Identity.kt +522 -0
- package/android/vendor/java/com/appswissknife/models/CustomerInfo.kt +67 -0
- package/android/vendor/java/com/appswissknife/models/Enums.kt +35 -0
- package/android/vendor/java/com/appswissknife/models/Offerings.kt +80 -0
- package/android/vendor/java/com/appswissknife/models/PurchasesError.kt +89 -0
- package/android/vendor/java/com/appswissknife/models/StoreTransaction.kt +17 -0
- package/android/vendor/java/com/appswissknife/net/BackendHttpClient.kt +507 -0
- package/android/vendor/java/com/appswissknife/net/ExponentialBackoff.kt +69 -0
- package/android/vendor/java/com/appswissknife/net/IngestClient.kt +582 -0
- package/android/vendor/java/com/appswissknife/net/OfflineQueueStore.kt +320 -0
- package/android/vendor/java/com/appswissknife/offerings/OfferingsRepository.kt +219 -0
- package/android/vendor/java/com/appswissknife/performance/SKFrameTracker.kt +94 -0
- package/android/vendor/java/com/appswissknife/performance/SKPerformance.kt +428 -0
- package/android/vendor/java/com/appswissknife/purchases/BillingClientGateway.kt +560 -0
- package/android/vendor/java/com/appswissknife/purchases/PlayPriceEnrichmentProvider.kt +100 -0
- package/android/vendor/java/com/appswissknife/purchases/PriceEnrichmentProvider.kt +36 -0
- package/android/vendor/java/com/appswissknife/purchases/PurchasesGateway.kt +120 -0
- package/android/vendor/res/xml/swissknife_data_extraction_rules.xml +20 -0
- package/ios/SwissKnifeCrashReporting.m +32 -0
- package/ios/SwissKnifeCrashReporting.swift +186 -0
- package/ios/SwissKnifeJSON.swift +347 -0
- package/ios/SwissKnifePurchases.m +124 -0
- package/ios/SwissKnifePurchases.swift +523 -0
- package/ios/vendor/GENERATED.md +10 -0
- package/ios/vendor/SwissKnifeiOS/Analytics/SKAnalytics.swift +488 -0
- package/ios/vendor/SwissKnifeiOS/AttributesClient.swift +460 -0
- package/ios/vendor/SwissKnifeiOS/Attribution/Attribution.swift +307 -0
- package/ios/vendor/SwissKnifeiOS/Attribution/AttributionNetwork.swift +92 -0
- package/ios/vendor/SwissKnifeiOS/Attribution/AttributionState.swift +141 -0
- package/ios/vendor/SwissKnifeiOS/Context/AppLifecycle.swift +130 -0
- package/ios/vendor/SwissKnifeiOS/Context/Clock.swift +100 -0
- package/ios/vendor/SwissKnifeiOS/Context/DeviceContext.swift +190 -0
- package/ios/vendor/SwissKnifeiOS/Context/IDs.swift +64 -0
- package/ios/vendor/SwissKnifeiOS/Context/Reachability.swift +121 -0
- package/ios/vendor/SwissKnifeiOS/Context/Session.swift +223 -0
- package/ios/vendor/SwissKnifeiOS/CrashReporting/SKCrashReporting.swift +1287 -0
- package/ios/vendor/SwissKnifeiOS/CrashReporting/SKScreenshot.swift +175 -0
- package/ios/vendor/SwissKnifeiOS/DeviceID.swift +161 -0
- package/ios/vendor/SwissKnifeiOS/Diagnostics/SKLog.swift +128 -0
- package/ios/vendor/SwissKnifeiOS/Identity/Identity.swift +323 -0
- package/ios/vendor/SwissKnifeiOS/Identity/IdentityNetwork.swift +70 -0
- package/ios/vendor/SwissKnifeiOS/Net/BackendHttpClient.swift +329 -0
- package/ios/vendor/SwissKnifeiOS/Net/ExponentialBackoff.swift +87 -0
- package/ios/vendor/SwissKnifeiOS/Net/IngestClient.swift +681 -0
- package/ios/vendor/SwissKnifeiOS/Net/OfflineQueueStore.swift +409 -0
- package/ios/vendor/SwissKnifeiOS/Performance/SKFrameTracker.swift +89 -0
- package/ios/vendor/SwissKnifeiOS/Performance/SKPerformance.swift +440 -0
- package/ios/vendor/SwissKnifeiOS/Performance/SKURLSessionDelegate.swift +87 -0
- package/ios/vendor/SwissKnifeiOS/Services/EntitlementsService.swift +646 -0
- package/ios/vendor/SwissKnifeiOS/Services/OfferingsService.swift +458 -0
- package/ios/vendor/SwissKnifeiOS/Services/PurchaseService.swift +374 -0
- package/ios/vendor/SwissKnifeiOS/SwissKnife+Analytics.swift +46 -0
- package/ios/vendor/SwissKnifeiOS/SwissKnife+DeviceID.swift +30 -0
- package/ios/vendor/SwissKnifeiOS/SwissKnife+Session.swift +47 -0
- package/ios/vendor/SwissKnifeiOS/SwissKnife.swift +417 -0
- package/ios/vendor/SwissKnifeiOS/Types.swift +496 -0
- package/lib/commonjs/attribution.js +55 -0
- package/lib/commonjs/attribution.js.map +1 -0
- package/lib/commonjs/identity.js +126 -0
- package/lib/commonjs/identity.js.map +1 -0
- package/lib/commonjs/index.js +118 -0
- package/lib/commonjs/index.js.map +1 -0
- package/lib/commonjs/modules/analytics.js +646 -0
- package/lib/commonjs/modules/analytics.js.map +1 -0
- package/lib/commonjs/modules/attachments.js +169 -0
- package/lib/commonjs/modules/attachments.js.map +1 -0
- package/lib/commonjs/modules/crash-reporting.js +1327 -0
- package/lib/commonjs/modules/crash-reporting.js.map +1 -0
- package/lib/commonjs/modules/ids.js +50 -0
- package/lib/commonjs/modules/ids.js.map +1 -0
- package/lib/commonjs/modules/log.js +59 -0
- package/lib/commonjs/modules/log.js.map +1 -0
- package/lib/commonjs/modules/offline-store.js +44 -0
- package/lib/commonjs/modules/offline-store.js.map +1 -0
- package/lib/commonjs/modules/performance.js +494 -0
- package/lib/commonjs/modules/performance.js.map +1 -0
- package/lib/commonjs/native/module.js +41 -0
- package/lib/commonjs/native/module.js.map +1 -0
- package/lib/commonjs/native/spec.js +26 -0
- package/lib/commonjs/native/spec.js.map +1 -0
- package/lib/commonjs/package.json +1 -0
- package/lib/commonjs/purchases.js +194 -0
- package/lib/commonjs/purchases.js.map +1 -0
- package/lib/commonjs/types.js +236 -0
- package/lib/commonjs/types.js.map +1 -0
- package/lib/module/attribution.js +51 -0
- package/lib/module/attribution.js.map +1 -0
- package/lib/module/identity.js +122 -0
- package/lib/module/identity.js.map +1 -0
- package/lib/module/index.js +36 -0
- package/lib/module/index.js.map +1 -0
- package/lib/module/modules/analytics.js +642 -0
- package/lib/module/modules/analytics.js.map +1 -0
- package/lib/module/modules/attachments.js +162 -0
- package/lib/module/modules/attachments.js.map +1 -0
- package/lib/module/modules/crash-reporting.js +1320 -0
- package/lib/module/modules/crash-reporting.js.map +1 -0
- package/lib/module/modules/ids.js +44 -0
- package/lib/module/modules/ids.js.map +1 -0
- package/lib/module/modules/log.js +54 -0
- package/lib/module/modules/log.js.map +1 -0
- package/lib/module/modules/offline-store.js +39 -0
- package/lib/module/modules/offline-store.js.map +1 -0
- package/lib/module/modules/performance.js +491 -0
- package/lib/module/modules/performance.js.map +1 -0
- package/lib/module/native/module.js +34 -0
- package/lib/module/native/module.js.map +1 -0
- package/lib/module/native/spec.js +22 -0
- package/lib/module/native/spec.js.map +1 -0
- package/lib/module/package.json +1 -0
- package/lib/module/purchases.js +187 -0
- package/lib/module/purchases.js.map +1 -0
- package/lib/module/types.js +230 -0
- package/lib/module/types.js.map +1 -0
- package/lib/typescript/commonjs/attribution.d.ts +24 -0
- package/lib/typescript/commonjs/attribution.d.ts.map +1 -0
- package/lib/typescript/commonjs/identity.d.ts +37 -0
- package/lib/typescript/commonjs/identity.d.ts.map +1 -0
- package/lib/typescript/commonjs/index.d.ts +15 -0
- package/lib/typescript/commonjs/index.d.ts.map +1 -0
- package/lib/typescript/commonjs/modules/analytics.d.ts +127 -0
- package/lib/typescript/commonjs/modules/analytics.d.ts.map +1 -0
- package/lib/typescript/commonjs/modules/attachments.d.ts +50 -0
- package/lib/typescript/commonjs/modules/attachments.d.ts.map +1 -0
- package/lib/typescript/commonjs/modules/crash-reporting.d.ts +175 -0
- package/lib/typescript/commonjs/modules/crash-reporting.d.ts.map +1 -0
- package/lib/typescript/commonjs/modules/ids.d.ts +17 -0
- package/lib/typescript/commonjs/modules/ids.d.ts.map +1 -0
- package/lib/typescript/commonjs/modules/log.d.ts +12 -0
- package/lib/typescript/commonjs/modules/log.d.ts.map +1 -0
- package/lib/typescript/commonjs/modules/offline-store.d.ts +9 -0
- package/lib/typescript/commonjs/modules/offline-store.d.ts.map +1 -0
- package/lib/typescript/commonjs/modules/performance.d.ts +75 -0
- package/lib/typescript/commonjs/modules/performance.d.ts.map +1 -0
- package/lib/typescript/commonjs/native/module.d.ts +6 -0
- package/lib/typescript/commonjs/native/module.d.ts.map +1 -0
- package/lib/typescript/commonjs/native/spec.d.ts +119 -0
- package/lib/typescript/commonjs/native/spec.d.ts.map +1 -0
- package/lib/typescript/commonjs/package.json +1 -0
- package/lib/typescript/commonjs/purchases.d.ts +68 -0
- package/lib/typescript/commonjs/purchases.d.ts.map +1 -0
- package/lib/typescript/commonjs/types.d.ts +384 -0
- package/lib/typescript/commonjs/types.d.ts.map +1 -0
- package/lib/typescript/module/attribution.d.ts +24 -0
- package/lib/typescript/module/attribution.d.ts.map +1 -0
- package/lib/typescript/module/identity.d.ts +37 -0
- package/lib/typescript/module/identity.d.ts.map +1 -0
- package/lib/typescript/module/index.d.ts +15 -0
- package/lib/typescript/module/index.d.ts.map +1 -0
- package/lib/typescript/module/modules/analytics.d.ts +127 -0
- package/lib/typescript/module/modules/analytics.d.ts.map +1 -0
- package/lib/typescript/module/modules/attachments.d.ts +50 -0
- package/lib/typescript/module/modules/attachments.d.ts.map +1 -0
- package/lib/typescript/module/modules/crash-reporting.d.ts +175 -0
- package/lib/typescript/module/modules/crash-reporting.d.ts.map +1 -0
- package/lib/typescript/module/modules/ids.d.ts +17 -0
- package/lib/typescript/module/modules/ids.d.ts.map +1 -0
- package/lib/typescript/module/modules/log.d.ts +12 -0
- package/lib/typescript/module/modules/log.d.ts.map +1 -0
- package/lib/typescript/module/modules/offline-store.d.ts +9 -0
- package/lib/typescript/module/modules/offline-store.d.ts.map +1 -0
- package/lib/typescript/module/modules/performance.d.ts +75 -0
- package/lib/typescript/module/modules/performance.d.ts.map +1 -0
- package/lib/typescript/module/native/module.d.ts +6 -0
- package/lib/typescript/module/native/module.d.ts.map +1 -0
- package/lib/typescript/module/native/spec.d.ts +119 -0
- package/lib/typescript/module/native/spec.d.ts.map +1 -0
- package/lib/typescript/module/package.json +1 -0
- package/lib/typescript/module/purchases.d.ts +68 -0
- package/lib/typescript/module/purchases.d.ts.map +1 -0
- package/lib/typescript/module/types.d.ts +384 -0
- package/lib/typescript/module/types.d.ts.map +1 -0
- package/package.json +115 -0
- package/react-native.config.js +23 -0
- package/src/attribution.ts +56 -0
- package/src/identity.ts +133 -0
- package/src/index.ts +54 -0
- package/src/modules/analytics.ts +689 -0
- package/src/modules/attachments.ts +222 -0
- package/src/modules/crash-reporting.ts +1577 -0
- package/src/modules/ids.ts +41 -0
- package/src/modules/log.ts +56 -0
- package/src/modules/offline-store.ts +51 -0
- package/src/modules/performance.ts +589 -0
- package/src/native/module.ts +47 -0
- package/src/native/spec.ts +183 -0
- package/src/purchases.ts +214 -0
- package/src/types.ts +470 -0
|
@@ -0,0 +1,374 @@
|
|
|
1
|
+
// packages/swiss-knife-ios/Sources/SwissKnifeiOS/Services/PurchaseService.swift
|
|
2
|
+
//
|
|
3
|
+
// Phase 5 step 3 — own purchase service backed by StoreKit 2. Replaces RC's
|
|
4
|
+
// purchase / restore / transaction-observation paths with direct calls to
|
|
5
|
+
// `Product.purchase()`, `Transaction.currentEntitlements`, and
|
|
6
|
+
// `Transaction.updates`. Every verified transaction is POSTed to our backend
|
|
7
|
+
// at `POST /api/sdk/subscriptions/validate` (existing endpoint, see
|
|
8
|
+
// `apps/web/src/app/api/sdk/subscriptions/validate/route.ts`) which validates
|
|
9
|
+
// the JWS against Apple, writes the subscription row, and returns the
|
|
10
|
+
// authoritative state. The backend response then triggers an
|
|
11
|
+
// `EntitlementsService.refresh()` so the in-memory + on-disk cache reflects
|
|
12
|
+
// the new entitlement immediately.
|
|
13
|
+
//
|
|
14
|
+
// Why StoreKit 2 (not StoreKit 1 + receipt URL)
|
|
15
|
+
// ---------------------------------------------
|
|
16
|
+
// - StoreKit 2 ships JWS-signed transactions out of the box; we don't need
|
|
17
|
+
// to ship the entire receipt and trust Apple to parse it server-side.
|
|
18
|
+
// - `Transaction.updates` is a single typed AsyncSequence covering renewals,
|
|
19
|
+
// refunds, and billing-retry state changes from any device. That replaces
|
|
20
|
+
// RC's PurchasesDelegate fan-out for the multi-device sync case.
|
|
21
|
+
// - StoreKit 2's `Product` type carries localized prices, intro offer
|
|
22
|
+
// metadata, and subscription period information directly — `StoreProduct`
|
|
23
|
+
// in `Types.swift` is a 1:1 mirror of what we need from it.
|
|
24
|
+
//
|
|
25
|
+
// Lifecycle
|
|
26
|
+
// ---------
|
|
27
|
+
// The `Transaction.updates` listener is started by `startObservingTransactionUpdates()`
|
|
28
|
+
// from `SwissKnife.configure(...)` and runs for the lifetime of the process.
|
|
29
|
+
// We intentionally do NOT tear it down on logout — Apple recommends a single
|
|
30
|
+
// observer per process to avoid missing updates that arrive during the
|
|
31
|
+
// re-init gap.
|
|
32
|
+
|
|
33
|
+
import Foundation
|
|
34
|
+
import StoreKit
|
|
35
|
+
import os.log
|
|
36
|
+
|
|
37
|
+
/// Process-wide owner of the StoreKit 2 purchase + restore + transaction
|
|
38
|
+
/// observation pipeline.
|
|
39
|
+
public final class PurchaseService {
|
|
40
|
+
|
|
41
|
+
public static let shared = PurchaseService()
|
|
42
|
+
|
|
43
|
+
private let log = OSLog(subsystem: "com.swissknife", category: "purchase")
|
|
44
|
+
private let queue = DispatchQueue(label: "com.swissknife.purchase")
|
|
45
|
+
|
|
46
|
+
// MARK: Configuration
|
|
47
|
+
|
|
48
|
+
private var serverURL: String?
|
|
49
|
+
private var apiKey: String?
|
|
50
|
+
|
|
51
|
+
// MARK: Network seam
|
|
52
|
+
|
|
53
|
+
/// BackendHttpClient seam — production wires the shared singleton;
|
|
54
|
+
/// tests inject a custom instance backed by a `ScriptedTransport` to
|
|
55
|
+
/// assert the validate POST without touching the network. The legacy
|
|
56
|
+
/// `PurchaseValidationTransport` is gone; BackendHttpClient handles
|
|
57
|
+
/// X-API-Key, retry, and Date-header Clock sync uniformly.
|
|
58
|
+
internal var http: BackendHttpClient = BackendHttpClient.shared
|
|
59
|
+
|
|
60
|
+
// MARK: Transaction.updates observer
|
|
61
|
+
|
|
62
|
+
private var observerTask: Task<Void, Never>?
|
|
63
|
+
|
|
64
|
+
private init() {}
|
|
65
|
+
|
|
66
|
+
// MARK: Configure
|
|
67
|
+
|
|
68
|
+
internal func configure(serverURL: String?, apiKey: String) {
|
|
69
|
+
queue.sync {
|
|
70
|
+
self.serverURL = (serverURL?.isEmpty == true) ? nil : serverURL
|
|
71
|
+
self.apiKey = apiKey
|
|
72
|
+
}
|
|
73
|
+
startObservingTransactionUpdates()
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
/// Stop and restart the StoreKit `Transaction.updates` listener. Idempotent
|
|
77
|
+
/// — safe to call repeatedly from `configure(...)`.
|
|
78
|
+
internal func startObservingTransactionUpdates() {
|
|
79
|
+
queue.sync {
|
|
80
|
+
observerTask?.cancel()
|
|
81
|
+
observerTask = Task { [weak self] in
|
|
82
|
+
if #available(iOS 15.0, macOS 12.0, *) {
|
|
83
|
+
for await update in StoreKit.Transaction.updates {
|
|
84
|
+
await self?.handleTransactionUpdate(update)
|
|
85
|
+
}
|
|
86
|
+
}
|
|
87
|
+
}
|
|
88
|
+
}
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
// MARK: Test seams
|
|
92
|
+
|
|
93
|
+
/// Reset to a known state between tests. Cancels the observer task,
|
|
94
|
+
/// drops configuration, and swaps the BackendHttpClient back to the
|
|
95
|
+
/// shared production instance.
|
|
96
|
+
internal func _resetForTesting() {
|
|
97
|
+
queue.sync {
|
|
98
|
+
observerTask?.cancel()
|
|
99
|
+
observerTask = nil
|
|
100
|
+
serverURL = nil
|
|
101
|
+
apiKey = nil
|
|
102
|
+
http = BackendHttpClient.shared
|
|
103
|
+
}
|
|
104
|
+
}
|
|
105
|
+
|
|
106
|
+
// MARK: Public API — purchase
|
|
107
|
+
|
|
108
|
+
/// Purchase a package (i.e. a Product behind a specific offering). The
|
|
109
|
+
/// flow is: look up the underlying StoreKit `Product`, call `purchase()`,
|
|
110
|
+
/// validate the resulting JWS with our backend, refresh the cache.
|
|
111
|
+
@available(iOS 15.0, macOS 12.0, *)
|
|
112
|
+
public func purchase(package: Package) async throws -> SwissKnife.PurchaseResult {
|
|
113
|
+
try await purchase(productIdentifier: package.storeProduct.productIdentifier)
|
|
114
|
+
}
|
|
115
|
+
|
|
116
|
+
/// Purchase a single product by identifier. Used by the package-based and
|
|
117
|
+
/// product-based paths alike — the package layer is just a paywall-grouping
|
|
118
|
+
/// concern on top of a `StoreProduct`.
|
|
119
|
+
@available(iOS 15.0, macOS 12.0, *)
|
|
120
|
+
public func purchase(productIdentifier: String) async throws -> SwissKnife.PurchaseResult {
|
|
121
|
+
// 1) Resolve the StoreKit Product. `Product.products(for:)` returns
|
|
122
|
+
// empty on unknown IDs rather than throwing; we surface the
|
|
123
|
+
// typed PurchasesError so callers don't have to special-case.
|
|
124
|
+
let products = try await Product.products(for: [productIdentifier])
|
|
125
|
+
guard let product = products.first else {
|
|
126
|
+
throw PurchasesError.productNotAvailable
|
|
127
|
+
}
|
|
128
|
+
|
|
129
|
+
// 2) Kick off StoreKit's purchase sheet. The sheet itself is OS-
|
|
130
|
+
// owned; we await whatever it returns.
|
|
131
|
+
let result: Product.PurchaseResult
|
|
132
|
+
do {
|
|
133
|
+
result = try await product.purchase()
|
|
134
|
+
} catch {
|
|
135
|
+
throw mapStoreKitPurchaseError(error)
|
|
136
|
+
}
|
|
137
|
+
|
|
138
|
+
switch result {
|
|
139
|
+
case .success(let verification):
|
|
140
|
+
return try await completePurchase(verification: verification, productIdentifier: productIdentifier)
|
|
141
|
+
case .userCancelled:
|
|
142
|
+
throw PurchasesError.purchaseCancelled
|
|
143
|
+
case .pending:
|
|
144
|
+
throw PurchasesError.paymentPending
|
|
145
|
+
@unknown default:
|
|
146
|
+
throw PurchasesError.unknown(message: "Unknown StoreKit purchase result")
|
|
147
|
+
}
|
|
148
|
+
}
|
|
149
|
+
|
|
150
|
+
/// Restore prior purchases. Iterates `Transaction.currentEntitlements`,
|
|
151
|
+
/// POSTs each verified JWS to the backend, refreshes the cache, and
|
|
152
|
+
/// returns the resulting CustomerInfo. Empty entitlements + no error is
|
|
153
|
+
/// the "restore-on-fresh-install with nothing to restore" path.
|
|
154
|
+
@available(iOS 15.0, macOS 12.0, *)
|
|
155
|
+
public func restorePurchases() async throws -> CustomerInfo {
|
|
156
|
+
var anyValidated = false
|
|
157
|
+
for await result in StoreKit.Transaction.currentEntitlements {
|
|
158
|
+
let jws = result.jwsRepresentation
|
|
159
|
+
switch result {
|
|
160
|
+
case .verified(let transaction):
|
|
161
|
+
do {
|
|
162
|
+
try await validateTransactionWithBackend(transaction, jws: jws)
|
|
163
|
+
anyValidated = true
|
|
164
|
+
} catch {
|
|
165
|
+
os_log(
|
|
166
|
+
"PurchaseService: backend validation failed during restore for productId=%{public}@: %{public}@",
|
|
167
|
+
log: log,
|
|
168
|
+
type: .error,
|
|
169
|
+
transaction.productID,
|
|
170
|
+
String(describing: error)
|
|
171
|
+
)
|
|
172
|
+
// Continue with the rest — one failure should not
|
|
173
|
+
// abort the whole restore.
|
|
174
|
+
}
|
|
175
|
+
case .unverified(let transaction, let error):
|
|
176
|
+
os_log(
|
|
177
|
+
"PurchaseService: skipping unverified transaction productId=%{public}@ (%{public}@)",
|
|
178
|
+
log: log,
|
|
179
|
+
type: .info,
|
|
180
|
+
transaction.productID,
|
|
181
|
+
String(describing: error)
|
|
182
|
+
)
|
|
183
|
+
}
|
|
184
|
+
}
|
|
185
|
+
// Always end with a refresh so the cache reflects whatever the
|
|
186
|
+
// backend believes the user now owns — even when there was nothing
|
|
187
|
+
// to validate, we want to surface the latest server-side state.
|
|
188
|
+
EntitlementsService.shared.invalidate()
|
|
189
|
+
if anyValidated {
|
|
190
|
+
return try await EntitlementsService.shared.refresh()
|
|
191
|
+
}
|
|
192
|
+
// No transactions to restore — fall back to whatever the cache /
|
|
193
|
+
// refresh says. We let the cache's own error path bubble up; that
|
|
194
|
+
// matches RC's "restore returns CustomerInfo even when empty" shape.
|
|
195
|
+
return try await EntitlementsService.shared.refresh()
|
|
196
|
+
}
|
|
197
|
+
|
|
198
|
+
// MARK: Internals
|
|
199
|
+
|
|
200
|
+
/// Final stage of a purchase: extract the verified transaction, POST
|
|
201
|
+
/// its JWS to the backend for validation, finish the transaction on
|
|
202
|
+
/// success, refresh the cache.
|
|
203
|
+
@available(iOS 15.0, macOS 12.0, *)
|
|
204
|
+
private func completePurchase(
|
|
205
|
+
verification: VerificationResult2,
|
|
206
|
+
productIdentifier: String
|
|
207
|
+
) async throws -> SwissKnife.PurchaseResult {
|
|
208
|
+
// StoreKit 2 exposes the JWS on the VerificationResult, NOT on the
|
|
209
|
+
// unwrapped Transaction value — that's deliberate: the JWS is the
|
|
210
|
+
// verification source. We pull it before unwrapping.
|
|
211
|
+
let jws = verification.jwsRepresentation
|
|
212
|
+
switch verification {
|
|
213
|
+
case .verified(let transaction):
|
|
214
|
+
// Validate against backend first. If the backend rejects the
|
|
215
|
+
// receipt, we DO NOT finish the transaction — that gives Apple
|
|
216
|
+
// a chance to redeliver on the next launch, and the user a
|
|
217
|
+
// chance to retry. Only finish on validated success.
|
|
218
|
+
try await validateTransactionWithBackend(transaction, jws: jws)
|
|
219
|
+
await transaction.finish()
|
|
220
|
+
|
|
221
|
+
let info = try await EntitlementsService.shared.refresh()
|
|
222
|
+
let storeTx = StoreTransaction(
|
|
223
|
+
productIdentifier: transaction.productID,
|
|
224
|
+
transactionIdentifier: String(transaction.id),
|
|
225
|
+
purchaseDate: transaction.purchaseDate,
|
|
226
|
+
jwsRepresentation: jws,
|
|
227
|
+
quantity: transaction.purchasedQuantity
|
|
228
|
+
)
|
|
229
|
+
return SwissKnife.PurchaseResult(transaction: storeTx, customerInfo: info)
|
|
230
|
+
|
|
231
|
+
case .unverified(_, let error):
|
|
232
|
+
throw PurchasesError.verificationFailed(reason: String(describing: error))
|
|
233
|
+
}
|
|
234
|
+
}
|
|
235
|
+
|
|
236
|
+
/// Handler for `Transaction.updates` — fires for renewals, refunds, and
|
|
237
|
+
/// any state change that lands from another device (or a delayed
|
|
238
|
+
/// validation). We forward every verified update to the backend so the
|
|
239
|
+
/// server-side row stays in sync; the SDK consumer then sees the change
|
|
240
|
+
/// via `EntitlementsService.customerInfoStream`.
|
|
241
|
+
@available(iOS 15.0, macOS 12.0, *)
|
|
242
|
+
private func handleTransactionUpdate(_ result: VerificationResult2) async {
|
|
243
|
+
let jws = result.jwsRepresentation
|
|
244
|
+
switch result {
|
|
245
|
+
case .verified(let transaction):
|
|
246
|
+
do {
|
|
247
|
+
try await validateTransactionWithBackend(transaction, jws: jws)
|
|
248
|
+
await transaction.finish()
|
|
249
|
+
EntitlementsService.shared.invalidate()
|
|
250
|
+
_ = try? await EntitlementsService.shared.refresh()
|
|
251
|
+
} catch {
|
|
252
|
+
os_log(
|
|
253
|
+
"PurchaseService: backend validation failed for incoming transaction productId=%{public}@: %{public}@",
|
|
254
|
+
log: log,
|
|
255
|
+
type: .error,
|
|
256
|
+
transaction.productID,
|
|
257
|
+
String(describing: error)
|
|
258
|
+
)
|
|
259
|
+
}
|
|
260
|
+
case .unverified(let transaction, let error):
|
|
261
|
+
os_log(
|
|
262
|
+
"PurchaseService: skipping unverified Transaction.update productId=%{public}@ (%{public}@)",
|
|
263
|
+
log: log,
|
|
264
|
+
type: .info,
|
|
265
|
+
transaction.productID,
|
|
266
|
+
String(describing: error)
|
|
267
|
+
)
|
|
268
|
+
}
|
|
269
|
+
}
|
|
270
|
+
|
|
271
|
+
/// POST the JWS to our backend for receipt validation via
|
|
272
|
+
/// `BackendHttpClient`. The client handles X-API-Key injection,
|
|
273
|
+
/// 4xx-vs-5xx classification (backendRejected vs backendUnavailable),
|
|
274
|
+
/// retry on 5xx + 429 + transport errors, and Date-header Clock sync.
|
|
275
|
+
///
|
|
276
|
+
/// We use `postRaw` because the validate body is hand-assembled from a
|
|
277
|
+
/// `[String: Any]` (Mixed shapes — JWS string + ints + plain strings —
|
|
278
|
+
/// don't model cleanly as a single Codable struct without a lossy
|
|
279
|
+
/// intermediate). The response body is discarded; the caller only
|
|
280
|
+
/// branches on success vs the typed errors.
|
|
281
|
+
@available(iOS 15.0, macOS 12.0, *)
|
|
282
|
+
private func validateTransactionWithBackend(
|
|
283
|
+
_ transaction: StoreKit.Transaction,
|
|
284
|
+
jws: String
|
|
285
|
+
) async throws {
|
|
286
|
+
// Effective user id — same fallback logic as EntitlementsService.
|
|
287
|
+
let userId: String = {
|
|
288
|
+
let configured = SwissKnife.appUserIDOrNil()
|
|
289
|
+
return (configured?.isEmpty == false) ? configured! : DeviceID.get()
|
|
290
|
+
}()
|
|
291
|
+
let body: [String: Any] = [
|
|
292
|
+
"user_id": userId,
|
|
293
|
+
"platform": "ios",
|
|
294
|
+
// The backend's `/api/sdk/subscriptions/validate` accepts
|
|
295
|
+
// `receipt_data` as the raw payload to validate. For StoreKit 2
|
|
296
|
+
// the JWS IS the receipt — we send it through here, and the
|
|
297
|
+
// store-validation layer treats it accordingly.
|
|
298
|
+
"receipt_data": jws,
|
|
299
|
+
"transaction_id": String(transaction.id),
|
|
300
|
+
"product_id": transaction.productID,
|
|
301
|
+
"jws": jws,
|
|
302
|
+
]
|
|
303
|
+
let data = try JSONSerialization.data(withJSONObject: body, options: [])
|
|
304
|
+
_ = try await http.postRaw(path: "/api/sdk/subscriptions/validate", body: data)
|
|
305
|
+
}
|
|
306
|
+
|
|
307
|
+
/// Map StoreKit's purchase-time error types to PurchasesError. SK2 uses
|
|
308
|
+
/// `Product.PurchaseError` for some failures and `StoreKitError` for
|
|
309
|
+
/// transport / system issues — we keep the cases tight.
|
|
310
|
+
@available(iOS 15.0, macOS 12.0, *)
|
|
311
|
+
private func mapStoreKitPurchaseError(_ error: Error) -> PurchasesError {
|
|
312
|
+
if let purchaseError = error as? Product.PurchaseError {
|
|
313
|
+
switch purchaseError {
|
|
314
|
+
case .productUnavailable: return .productNotAvailable
|
|
315
|
+
case .purchaseNotAllowed: return .unknown(message: "Purchases not allowed (e.g. parental controls)")
|
|
316
|
+
case .ineligibleForOffer: return .unknown(message: "Ineligible for the requested offer")
|
|
317
|
+
case .invalidOfferIdentifier, .invalidOfferPrice, .invalidOfferSignature:
|
|
318
|
+
return .verificationFailed(reason: String(describing: purchaseError))
|
|
319
|
+
case .missingOfferParameters:
|
|
320
|
+
return .unknown(message: "Missing offer parameters")
|
|
321
|
+
default:
|
|
322
|
+
// `.invalidQuantity` (iOS ≥17) and any future cases — treat
|
|
323
|
+
// as a generic unknown so the SDK keeps building against
|
|
324
|
+
// newer SDKs without source churn here.
|
|
325
|
+
return .unknown(message: String(describing: purchaseError))
|
|
326
|
+
}
|
|
327
|
+
}
|
|
328
|
+
if let skError = error as? StoreKitError {
|
|
329
|
+
switch skError {
|
|
330
|
+
case .userCancelled: return .purchaseCancelled
|
|
331
|
+
case .networkError: return .networkError(underlying: String(describing: skError))
|
|
332
|
+
case .systemError: return .unknown(message: "StoreKit system error")
|
|
333
|
+
case .notAvailableInStorefront: return .productNotAvailable
|
|
334
|
+
case .notEntitled: return .productNotAvailable
|
|
335
|
+
case .unknown: return .unknown(message: "StoreKit unknown error")
|
|
336
|
+
default:
|
|
337
|
+
// `.unsupported` (iOS ≥17.4) and any future cases — closest
|
|
338
|
+
// typed mapping is `productNotAvailable` since the user-
|
|
339
|
+
// visible result is "this product cannot be purchased here".
|
|
340
|
+
return .productNotAvailable
|
|
341
|
+
}
|
|
342
|
+
}
|
|
343
|
+
return .unknown(message: error.localizedDescription)
|
|
344
|
+
}
|
|
345
|
+
}
|
|
346
|
+
|
|
347
|
+
// MARK: - Bridge for StoreKit.VerificationResult
|
|
348
|
+
//
|
|
349
|
+
// `StoreKit.VerificationResult` collides with our public `VerificationResult`
|
|
350
|
+
// enum (different shapes — ours is a Codable string enum surfaced to consumers,
|
|
351
|
+
// StoreKit's wraps the verified payload). We aliased it locally to avoid the
|
|
352
|
+
// confusion when reading the purchase flow above.
|
|
353
|
+
@available(iOS 15.0, macOS 12.0, *)
|
|
354
|
+
internal typealias VerificationResult2 = StoreKit.VerificationResult<StoreKit.Transaction>
|
|
355
|
+
|
|
356
|
+
// MARK: - SwissKnife appUserID accessor for the service layer
|
|
357
|
+
//
|
|
358
|
+
// `SwissKnife.appUserID` currently still routes through RC (commit 5 swaps
|
|
359
|
+
// it). We want to read it from the service layer without taking a hard
|
|
360
|
+
// dependency on RC being configured — `appUserIDOrNil()` returns nil when
|
|
361
|
+
// the SDK isn't configured yet, which the validate call falls back from to
|
|
362
|
+
// the device id.
|
|
363
|
+
|
|
364
|
+
internal extension SwissKnife {
|
|
365
|
+
static func appUserIDOrNil() -> String? {
|
|
366
|
+
guard isConfigured else { return nil }
|
|
367
|
+
// Wave 1: route through the Identity snapshot. `userId` is the
|
|
368
|
+
// identified id when known, else the anonymous id. Falling back
|
|
369
|
+
// to the anonymous id matches the prior facade behaviour where
|
|
370
|
+
// `SwissKnife.appUserID` returned whichever was currently active.
|
|
371
|
+
let snapshot = Identity.current
|
|
372
|
+
return snapshot.userId ?? snapshot.anonymousId
|
|
373
|
+
}
|
|
374
|
+
}
|
|
@@ -0,0 +1,46 @@
|
|
|
1
|
+
// packages/swiss-knife-ios/Sources/SwissKnifeiOS/SwissKnife+Analytics.swift
|
|
2
|
+
//
|
|
3
|
+
// Public facade that exposes the persistent event queue to the React Native
|
|
4
|
+
// bridge (`packages/react-native-sdk/ios/SwissKnifePurchases.swift`).
|
|
5
|
+
//
|
|
6
|
+
// Why this exists
|
|
7
|
+
// ---------------
|
|
8
|
+
// Phase 2.3 of the RC rip-and-replace makes RN Analytics a thin pass-through
|
|
9
|
+
// to native: the JS layer builds events client-side (event_id, device_id,
|
|
10
|
+
// super properties, timed events, identify merges) and hands them to native
|
|
11
|
+
// for disk-backed persistence + back-off retry + dead-letter — guarantees JS
|
|
12
|
+
// can't provide. The two methods below are the bridge entry points.
|
|
13
|
+
//
|
|
14
|
+
// We intentionally keep `SKAnalytics` itself (and its internal store /
|
|
15
|
+
// transport / back-off types) as the implementation detail; only these two
|
|
16
|
+
// passthrough wrappers are public. Native-iOS consumers should keep using
|
|
17
|
+
// `SKAnalytics.shared.track(...)` directly.
|
|
18
|
+
|
|
19
|
+
import Foundation
|
|
20
|
+
|
|
21
|
+
public extension SwissKnife {
|
|
22
|
+
/// Enqueue a pre-built analytics event onto the disk-backed queue.
|
|
23
|
+
///
|
|
24
|
+
/// **For the React Native bridge only.** The JS layer constructs the full
|
|
25
|
+
/// event payload (including `event_id`, `device_id`, super properties,
|
|
26
|
+
/// timed-event duration, identify merges) and passes it here. Native owns
|
|
27
|
+
/// the queue; JS owns the payload shape.
|
|
28
|
+
///
|
|
29
|
+
/// Synchronous on the calling thread up to the disk write — once this
|
|
30
|
+
/// returns, the event has hit disk and survives a process kill.
|
|
31
|
+
static func trackEvent(_ event: [String: Any]) {
|
|
32
|
+
SKAnalytics.shared.trackPreBuiltEvent(event)
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
/// Kick off a flush of the disk-backed queue. Fire-and-forget — the
|
|
36
|
+
/// flush itself runs asynchronously on `SKAnalytics`'s internal queue
|
|
37
|
+
/// with exponential back-off and dead-letter on permanent failure.
|
|
38
|
+
///
|
|
39
|
+
/// `async` is structural rather than load-bearing — the underlying
|
|
40
|
+
/// `flush()` returns immediately after enqueueing the flush job. We use
|
|
41
|
+
/// the `async` shape so the RN bridge can adopt Swift Concurrency for
|
|
42
|
+
/// future flush-with-completion variants without breaking the call site.
|
|
43
|
+
static func flushEvents() async {
|
|
44
|
+
SKAnalytics.shared.flush()
|
|
45
|
+
}
|
|
46
|
+
}
|
|
@@ -0,0 +1,30 @@
|
|
|
1
|
+
// packages/swiss-knife-ios/Sources/SwissKnifeiOS/SwissKnife+DeviceID.swift
|
|
2
|
+
//
|
|
3
|
+
// Public facade that exposes the persistent device identifier to the React
|
|
4
|
+
// Native bridge (`packages/react-native-sdk/ios/SwissKnifePurchases.swift`).
|
|
5
|
+
//
|
|
6
|
+
// The underlying `DeviceID` type stays `internal` by design — the keychain-
|
|
7
|
+
// backed UUID is an SDK implementation detail, not a general consumer API.
|
|
8
|
+
// Native-iOS consumers should not depend on a device-scoped ID directly; if
|
|
9
|
+
// they need analytics identity they go through `SKAnalytics` (which already
|
|
10
|
+
// reads this value via the internal `DeviceID.get()` accessor).
|
|
11
|
+
//
|
|
12
|
+
// This facade exists solely because the RN bridge lives in a separate Swift
|
|
13
|
+
// module (`SwissKnifePurchases` inside the RN SDK pod) and cannot reach into
|
|
14
|
+
// our package's `internal` symbols. A single-line passthrough is the smallest
|
|
15
|
+
// surface that unblocks the RN bridge without leaking the type itself.
|
|
16
|
+
|
|
17
|
+
import Foundation
|
|
18
|
+
|
|
19
|
+
public extension SwissKnife {
|
|
20
|
+
/// Persistent per-device identifier, backed by the iOS Keychain.
|
|
21
|
+
///
|
|
22
|
+
/// **For the React Native bridge only.** Native-iOS consumers should not
|
|
23
|
+
/// call this directly — use `SKAnalytics` for analytics identity. The
|
|
24
|
+
/// value survives app restart and reinstall (Keychain outlives the app
|
|
25
|
+
/// sandbox) and never leaves the device (`ThisDeviceOnly` accessibility +
|
|
26
|
+
/// `synchronizable=false`). See `DeviceID.swift` for the full rationale.
|
|
27
|
+
static func getDeviceId() -> String {
|
|
28
|
+
DeviceID.get()
|
|
29
|
+
}
|
|
30
|
+
}
|
|
@@ -0,0 +1,47 @@
|
|
|
1
|
+
// packages/swiss-knife-ios/Sources/SwissKnifeiOS/SwissKnife+Session.swift
|
|
2
|
+
//
|
|
3
|
+
// Public facade that exposes the canonical Session snapshot to the React
|
|
4
|
+
// Native bridge (`packages/react-native-sdk/ios/SwissKnifePurchases.swift`).
|
|
5
|
+
//
|
|
6
|
+
// The underlying `Session` / `SessionSnapshot` types stay `internal` by
|
|
7
|
+
// design — the session-rotation policy is an SDK implementation detail.
|
|
8
|
+
// This single-method facade exists so the RN bridge can derive its
|
|
9
|
+
// JS-side `session_id` from the same primitive the envelope stamps
|
|
10
|
+
// (closes the post-#136 audit divergence where JS used `Date.now()`).
|
|
11
|
+
|
|
12
|
+
import Foundation
|
|
13
|
+
|
|
14
|
+
public extension SwissKnife {
|
|
15
|
+
/// Plain-data shape of the current session snapshot, exposed for the
|
|
16
|
+
/// React Native bridge. Mirrors `SessionSnapshot` but stripped of any
|
|
17
|
+
/// internal types so a separate Swift module can read it.
|
|
18
|
+
///
|
|
19
|
+
/// **For the React Native bridge only.** Native-iOS consumers should
|
|
20
|
+
/// not depend on this; production paths read `Session.shared.current`
|
|
21
|
+
/// directly inside the package.
|
|
22
|
+
struct SessionInfo: Equatable {
|
|
23
|
+
public let id: String
|
|
24
|
+
public let sessionNumber: Int
|
|
25
|
+
/// Unix-millis epoch when the current session was minted.
|
|
26
|
+
public let startedAtMillis: Int64
|
|
27
|
+
|
|
28
|
+
public init(id: String, sessionNumber: Int, startedAtMillis: Int64) {
|
|
29
|
+
self.id = id
|
|
30
|
+
self.sessionNumber = sessionNumber
|
|
31
|
+
self.startedAtMillis = startedAtMillis
|
|
32
|
+
}
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
/// Current session snapshot from `Session.shared` — the same source
|
|
36
|
+
/// that stamps envelope-level `ContextSnapshot.session_id`. Read by
|
|
37
|
+
/// the RN bridge so JS-side analytics' legacy `session_id` field
|
|
38
|
+
/// agrees with the envelope. Replaces the JS `Date.now()` fallback.
|
|
39
|
+
static func currentSession() -> SessionInfo {
|
|
40
|
+
let snapshot = Session.shared.current
|
|
41
|
+
return SessionInfo(
|
|
42
|
+
id: snapshot.id,
|
|
43
|
+
sessionNumber: snapshot.sessionNumber,
|
|
44
|
+
startedAtMillis: Int64(snapshot.startedAt.timeIntervalSince1970 * 1000)
|
|
45
|
+
)
|
|
46
|
+
}
|
|
47
|
+
}
|