@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.
Files changed (218) hide show
  1. package/README.md +182 -0
  2. package/SwissKnifePurchases.podspec +40 -0
  3. package/android/build.gradle +89 -0
  4. package/android/gradle.properties +3 -0
  5. package/android/src/main/AndroidManifest.xml +26 -0
  6. package/android/src/main/java/com/swissknife/crashreporting/SKCrashReportingModule.kt +216 -0
  7. package/android/src/main/java/com/swissknife/crashreporting/SKCrashReportingPackage.kt +17 -0
  8. package/android/src/main/java/com/swissknife/purchases/Conversions.kt +15 -0
  9. package/android/src/main/java/com/swissknife/purchases/SwissKnifeJson.kt +371 -0
  10. package/android/src/main/java/com/swissknife/purchases/SwissKnifePurchasesModule.kt +497 -0
  11. package/android/src/main/java/com/swissknife/purchases/SwissKnifePurchasesPackage.kt +25 -0
  12. package/android/vendor/GENERATED.md +10 -0
  13. package/android/vendor/java/com/appswissknife/SwissKnife.kt +533 -0
  14. package/android/vendor/java/com/appswissknife/analytics/EventQueueStore.kt +326 -0
  15. package/android/vendor/java/com/appswissknife/analytics/FlushEventsWorker.kt +296 -0
  16. package/android/vendor/java/com/appswissknife/analytics/SKAnalytics.kt +503 -0
  17. package/android/vendor/java/com/appswissknife/attributes/AttributesClient.kt +188 -0
  18. package/android/vendor/java/com/appswissknife/attributes/SetAttributesWorker.kt +204 -0
  19. package/android/vendor/java/com/appswissknife/attribution/Attribution.kt +447 -0
  20. package/android/vendor/java/com/appswissknife/context/AppLifecycle.kt +120 -0
  21. package/android/vendor/java/com/appswissknife/context/Clock.kt +70 -0
  22. package/android/vendor/java/com/appswissknife/context/DeviceContext.kt +138 -0
  23. package/android/vendor/java/com/appswissknife/context/IDs.kt +55 -0
  24. package/android/vendor/java/com/appswissknife/context/Reachability.kt +145 -0
  25. package/android/vendor/java/com/appswissknife/context/Session.kt +192 -0
  26. package/android/vendor/java/com/appswissknife/crashreporting/SKCrashReporting.kt +945 -0
  27. package/android/vendor/java/com/appswissknife/crashreporting/SKScreenshot.kt +201 -0
  28. package/android/vendor/java/com/appswissknife/device/DeviceID.kt +172 -0
  29. package/android/vendor/java/com/appswissknife/diagnostics/SKLog.kt +97 -0
  30. package/android/vendor/java/com/appswissknife/entitlements/EntitlementsRepository.kt +495 -0
  31. package/android/vendor/java/com/appswissknife/identity/Identity.kt +522 -0
  32. package/android/vendor/java/com/appswissknife/models/CustomerInfo.kt +67 -0
  33. package/android/vendor/java/com/appswissknife/models/Enums.kt +35 -0
  34. package/android/vendor/java/com/appswissknife/models/Offerings.kt +80 -0
  35. package/android/vendor/java/com/appswissknife/models/PurchasesError.kt +89 -0
  36. package/android/vendor/java/com/appswissknife/models/StoreTransaction.kt +17 -0
  37. package/android/vendor/java/com/appswissknife/net/BackendHttpClient.kt +507 -0
  38. package/android/vendor/java/com/appswissknife/net/ExponentialBackoff.kt +69 -0
  39. package/android/vendor/java/com/appswissknife/net/IngestClient.kt +582 -0
  40. package/android/vendor/java/com/appswissknife/net/OfflineQueueStore.kt +320 -0
  41. package/android/vendor/java/com/appswissknife/offerings/OfferingsRepository.kt +219 -0
  42. package/android/vendor/java/com/appswissknife/performance/SKFrameTracker.kt +94 -0
  43. package/android/vendor/java/com/appswissknife/performance/SKPerformance.kt +428 -0
  44. package/android/vendor/java/com/appswissknife/purchases/BillingClientGateway.kt +560 -0
  45. package/android/vendor/java/com/appswissknife/purchases/PlayPriceEnrichmentProvider.kt +100 -0
  46. package/android/vendor/java/com/appswissknife/purchases/PriceEnrichmentProvider.kt +36 -0
  47. package/android/vendor/java/com/appswissknife/purchases/PurchasesGateway.kt +120 -0
  48. package/android/vendor/res/xml/swissknife_data_extraction_rules.xml +20 -0
  49. package/ios/SwissKnifeCrashReporting.m +32 -0
  50. package/ios/SwissKnifeCrashReporting.swift +186 -0
  51. package/ios/SwissKnifeJSON.swift +347 -0
  52. package/ios/SwissKnifePurchases.m +124 -0
  53. package/ios/SwissKnifePurchases.swift +523 -0
  54. package/ios/vendor/GENERATED.md +10 -0
  55. package/ios/vendor/SwissKnifeiOS/Analytics/SKAnalytics.swift +488 -0
  56. package/ios/vendor/SwissKnifeiOS/AttributesClient.swift +460 -0
  57. package/ios/vendor/SwissKnifeiOS/Attribution/Attribution.swift +307 -0
  58. package/ios/vendor/SwissKnifeiOS/Attribution/AttributionNetwork.swift +92 -0
  59. package/ios/vendor/SwissKnifeiOS/Attribution/AttributionState.swift +141 -0
  60. package/ios/vendor/SwissKnifeiOS/Context/AppLifecycle.swift +130 -0
  61. package/ios/vendor/SwissKnifeiOS/Context/Clock.swift +100 -0
  62. package/ios/vendor/SwissKnifeiOS/Context/DeviceContext.swift +190 -0
  63. package/ios/vendor/SwissKnifeiOS/Context/IDs.swift +64 -0
  64. package/ios/vendor/SwissKnifeiOS/Context/Reachability.swift +121 -0
  65. package/ios/vendor/SwissKnifeiOS/Context/Session.swift +223 -0
  66. package/ios/vendor/SwissKnifeiOS/CrashReporting/SKCrashReporting.swift +1287 -0
  67. package/ios/vendor/SwissKnifeiOS/CrashReporting/SKScreenshot.swift +175 -0
  68. package/ios/vendor/SwissKnifeiOS/DeviceID.swift +161 -0
  69. package/ios/vendor/SwissKnifeiOS/Diagnostics/SKLog.swift +128 -0
  70. package/ios/vendor/SwissKnifeiOS/Identity/Identity.swift +323 -0
  71. package/ios/vendor/SwissKnifeiOS/Identity/IdentityNetwork.swift +70 -0
  72. package/ios/vendor/SwissKnifeiOS/Net/BackendHttpClient.swift +329 -0
  73. package/ios/vendor/SwissKnifeiOS/Net/ExponentialBackoff.swift +87 -0
  74. package/ios/vendor/SwissKnifeiOS/Net/IngestClient.swift +681 -0
  75. package/ios/vendor/SwissKnifeiOS/Net/OfflineQueueStore.swift +409 -0
  76. package/ios/vendor/SwissKnifeiOS/Performance/SKFrameTracker.swift +89 -0
  77. package/ios/vendor/SwissKnifeiOS/Performance/SKPerformance.swift +440 -0
  78. package/ios/vendor/SwissKnifeiOS/Performance/SKURLSessionDelegate.swift +87 -0
  79. package/ios/vendor/SwissKnifeiOS/Services/EntitlementsService.swift +646 -0
  80. package/ios/vendor/SwissKnifeiOS/Services/OfferingsService.swift +458 -0
  81. package/ios/vendor/SwissKnifeiOS/Services/PurchaseService.swift +374 -0
  82. package/ios/vendor/SwissKnifeiOS/SwissKnife+Analytics.swift +46 -0
  83. package/ios/vendor/SwissKnifeiOS/SwissKnife+DeviceID.swift +30 -0
  84. package/ios/vendor/SwissKnifeiOS/SwissKnife+Session.swift +47 -0
  85. package/ios/vendor/SwissKnifeiOS/SwissKnife.swift +417 -0
  86. package/ios/vendor/SwissKnifeiOS/Types.swift +496 -0
  87. package/lib/commonjs/attribution.js +55 -0
  88. package/lib/commonjs/attribution.js.map +1 -0
  89. package/lib/commonjs/identity.js +126 -0
  90. package/lib/commonjs/identity.js.map +1 -0
  91. package/lib/commonjs/index.js +118 -0
  92. package/lib/commonjs/index.js.map +1 -0
  93. package/lib/commonjs/modules/analytics.js +646 -0
  94. package/lib/commonjs/modules/analytics.js.map +1 -0
  95. package/lib/commonjs/modules/attachments.js +169 -0
  96. package/lib/commonjs/modules/attachments.js.map +1 -0
  97. package/lib/commonjs/modules/crash-reporting.js +1327 -0
  98. package/lib/commonjs/modules/crash-reporting.js.map +1 -0
  99. package/lib/commonjs/modules/ids.js +50 -0
  100. package/lib/commonjs/modules/ids.js.map +1 -0
  101. package/lib/commonjs/modules/log.js +59 -0
  102. package/lib/commonjs/modules/log.js.map +1 -0
  103. package/lib/commonjs/modules/offline-store.js +44 -0
  104. package/lib/commonjs/modules/offline-store.js.map +1 -0
  105. package/lib/commonjs/modules/performance.js +494 -0
  106. package/lib/commonjs/modules/performance.js.map +1 -0
  107. package/lib/commonjs/native/module.js +41 -0
  108. package/lib/commonjs/native/module.js.map +1 -0
  109. package/lib/commonjs/native/spec.js +26 -0
  110. package/lib/commonjs/native/spec.js.map +1 -0
  111. package/lib/commonjs/package.json +1 -0
  112. package/lib/commonjs/purchases.js +194 -0
  113. package/lib/commonjs/purchases.js.map +1 -0
  114. package/lib/commonjs/types.js +236 -0
  115. package/lib/commonjs/types.js.map +1 -0
  116. package/lib/module/attribution.js +51 -0
  117. package/lib/module/attribution.js.map +1 -0
  118. package/lib/module/identity.js +122 -0
  119. package/lib/module/identity.js.map +1 -0
  120. package/lib/module/index.js +36 -0
  121. package/lib/module/index.js.map +1 -0
  122. package/lib/module/modules/analytics.js +642 -0
  123. package/lib/module/modules/analytics.js.map +1 -0
  124. package/lib/module/modules/attachments.js +162 -0
  125. package/lib/module/modules/attachments.js.map +1 -0
  126. package/lib/module/modules/crash-reporting.js +1320 -0
  127. package/lib/module/modules/crash-reporting.js.map +1 -0
  128. package/lib/module/modules/ids.js +44 -0
  129. package/lib/module/modules/ids.js.map +1 -0
  130. package/lib/module/modules/log.js +54 -0
  131. package/lib/module/modules/log.js.map +1 -0
  132. package/lib/module/modules/offline-store.js +39 -0
  133. package/lib/module/modules/offline-store.js.map +1 -0
  134. package/lib/module/modules/performance.js +491 -0
  135. package/lib/module/modules/performance.js.map +1 -0
  136. package/lib/module/native/module.js +34 -0
  137. package/lib/module/native/module.js.map +1 -0
  138. package/lib/module/native/spec.js +22 -0
  139. package/lib/module/native/spec.js.map +1 -0
  140. package/lib/module/package.json +1 -0
  141. package/lib/module/purchases.js +187 -0
  142. package/lib/module/purchases.js.map +1 -0
  143. package/lib/module/types.js +230 -0
  144. package/lib/module/types.js.map +1 -0
  145. package/lib/typescript/commonjs/attribution.d.ts +24 -0
  146. package/lib/typescript/commonjs/attribution.d.ts.map +1 -0
  147. package/lib/typescript/commonjs/identity.d.ts +37 -0
  148. package/lib/typescript/commonjs/identity.d.ts.map +1 -0
  149. package/lib/typescript/commonjs/index.d.ts +15 -0
  150. package/lib/typescript/commonjs/index.d.ts.map +1 -0
  151. package/lib/typescript/commonjs/modules/analytics.d.ts +127 -0
  152. package/lib/typescript/commonjs/modules/analytics.d.ts.map +1 -0
  153. package/lib/typescript/commonjs/modules/attachments.d.ts +50 -0
  154. package/lib/typescript/commonjs/modules/attachments.d.ts.map +1 -0
  155. package/lib/typescript/commonjs/modules/crash-reporting.d.ts +175 -0
  156. package/lib/typescript/commonjs/modules/crash-reporting.d.ts.map +1 -0
  157. package/lib/typescript/commonjs/modules/ids.d.ts +17 -0
  158. package/lib/typescript/commonjs/modules/ids.d.ts.map +1 -0
  159. package/lib/typescript/commonjs/modules/log.d.ts +12 -0
  160. package/lib/typescript/commonjs/modules/log.d.ts.map +1 -0
  161. package/lib/typescript/commonjs/modules/offline-store.d.ts +9 -0
  162. package/lib/typescript/commonjs/modules/offline-store.d.ts.map +1 -0
  163. package/lib/typescript/commonjs/modules/performance.d.ts +75 -0
  164. package/lib/typescript/commonjs/modules/performance.d.ts.map +1 -0
  165. package/lib/typescript/commonjs/native/module.d.ts +6 -0
  166. package/lib/typescript/commonjs/native/module.d.ts.map +1 -0
  167. package/lib/typescript/commonjs/native/spec.d.ts +119 -0
  168. package/lib/typescript/commonjs/native/spec.d.ts.map +1 -0
  169. package/lib/typescript/commonjs/package.json +1 -0
  170. package/lib/typescript/commonjs/purchases.d.ts +68 -0
  171. package/lib/typescript/commonjs/purchases.d.ts.map +1 -0
  172. package/lib/typescript/commonjs/types.d.ts +384 -0
  173. package/lib/typescript/commonjs/types.d.ts.map +1 -0
  174. package/lib/typescript/module/attribution.d.ts +24 -0
  175. package/lib/typescript/module/attribution.d.ts.map +1 -0
  176. package/lib/typescript/module/identity.d.ts +37 -0
  177. package/lib/typescript/module/identity.d.ts.map +1 -0
  178. package/lib/typescript/module/index.d.ts +15 -0
  179. package/lib/typescript/module/index.d.ts.map +1 -0
  180. package/lib/typescript/module/modules/analytics.d.ts +127 -0
  181. package/lib/typescript/module/modules/analytics.d.ts.map +1 -0
  182. package/lib/typescript/module/modules/attachments.d.ts +50 -0
  183. package/lib/typescript/module/modules/attachments.d.ts.map +1 -0
  184. package/lib/typescript/module/modules/crash-reporting.d.ts +175 -0
  185. package/lib/typescript/module/modules/crash-reporting.d.ts.map +1 -0
  186. package/lib/typescript/module/modules/ids.d.ts +17 -0
  187. package/lib/typescript/module/modules/ids.d.ts.map +1 -0
  188. package/lib/typescript/module/modules/log.d.ts +12 -0
  189. package/lib/typescript/module/modules/log.d.ts.map +1 -0
  190. package/lib/typescript/module/modules/offline-store.d.ts +9 -0
  191. package/lib/typescript/module/modules/offline-store.d.ts.map +1 -0
  192. package/lib/typescript/module/modules/performance.d.ts +75 -0
  193. package/lib/typescript/module/modules/performance.d.ts.map +1 -0
  194. package/lib/typescript/module/native/module.d.ts +6 -0
  195. package/lib/typescript/module/native/module.d.ts.map +1 -0
  196. package/lib/typescript/module/native/spec.d.ts +119 -0
  197. package/lib/typescript/module/native/spec.d.ts.map +1 -0
  198. package/lib/typescript/module/package.json +1 -0
  199. package/lib/typescript/module/purchases.d.ts +68 -0
  200. package/lib/typescript/module/purchases.d.ts.map +1 -0
  201. package/lib/typescript/module/types.d.ts +384 -0
  202. package/lib/typescript/module/types.d.ts.map +1 -0
  203. package/package.json +115 -0
  204. package/react-native.config.js +23 -0
  205. package/src/attribution.ts +56 -0
  206. package/src/identity.ts +133 -0
  207. package/src/index.ts +54 -0
  208. package/src/modules/analytics.ts +689 -0
  209. package/src/modules/attachments.ts +222 -0
  210. package/src/modules/crash-reporting.ts +1577 -0
  211. package/src/modules/ids.ts +41 -0
  212. package/src/modules/log.ts +56 -0
  213. package/src/modules/offline-store.ts +51 -0
  214. package/src/modules/performance.ts +589 -0
  215. package/src/native/module.ts +47 -0
  216. package/src/native/spec.ts +183 -0
  217. package/src/purchases.ts +214 -0
  218. package/src/types.ts +470 -0
@@ -0,0 +1,522 @@
1
+ // packages/swiss-knife-android/src/main/java/com/appswissknife/identity/Identity.kt
2
+ //
3
+ // Wave 1 of the SDK architectural audit — unified `SwissKnife.Identity`
4
+ // surface on Android. Mirror of `SwissKnife.Identity` in
5
+ // packages/swiss-knife-ios/.
6
+ //
7
+ // **Real bug closed here:** the previous `BillingClientGateway.logIn`
8
+ // silently skipped the POST to `/api/sdk/users/identify`. iOS posted, RN
9
+ // went through native, but Android never told the backend "this anonymous
10
+ // id is now this user." Result: anonymous events stayed orphaned after
11
+ // login; the backend's identify-merge case was never triggered from
12
+ // Android.
13
+ //
14
+ // Now `Identity.logIn(...)`:
15
+ // 1. POSTs `/api/sdk/users/identify` with `(anonymous_id, user_id)`.
16
+ // Retries transient failures via `IdentityWorker` (WorkManager) so a
17
+ // flaky network at login time doesn't lose the side-effect.
18
+ // 2. Updates the local snapshot and tells the gateway to rebind store-
19
+ // side state (entitlements cache invalidation + currentUserID).
20
+ // 3. Notifies observers.
21
+ //
22
+ // User-locked decisions:
23
+ // - No auto `$identify` event on `logIn` — decoupled from analytics.
24
+ // - Anonymous prefix unified to `$SKAnonymousID:` (Android previously
25
+ // used `$RCAnonymousID:`).
26
+ // - `reset()` rotates in-memory state but keeps EncryptedSharedPreferences
27
+ // DeviceID; `wipe()` clears DeviceID + entitlements cache.
28
+ //
29
+ // Thread safety: a single `Any` lock guards in-memory state; observers
30
+ // are notified outside the lock so a slow observer can't deadlock the
31
+ // next state mutation.
32
+
33
+ package com.appswissknife.identity
34
+
35
+ import android.content.Context
36
+ import androidx.annotation.VisibleForTesting
37
+ import com.appswissknife.SwissKnife
38
+ import com.appswissknife.device.DeviceID
39
+ import com.appswissknife.entitlements.EntitlementsRepository
40
+ import com.appswissknife.models.CustomerInfo
41
+ import com.appswissknife.models.PurchasesError
42
+ import com.appswissknife.purchases.BillingHttpClient
43
+ import com.appswissknife.net.BackendHttpClientAdapter
44
+ import org.json.JSONObject
45
+ import java.io.IOException
46
+ import java.util.Collections
47
+ import java.util.UUID
48
+ import java.util.concurrent.ConcurrentHashMap
49
+ import java.util.concurrent.ExecutorService
50
+ import java.util.concurrent.Executors
51
+
52
+ /**
53
+ * Universal user-identity surface. Mirrors iOS `SwissKnife.Identity`.
54
+ *
55
+ * Consumers reach this through the deprecated `SwissKnife.logIn/logOut`
56
+ * facades (back-compat) or call `Identity.logIn(...)` directly.
57
+ */
58
+ object Identity {
59
+
60
+ /** Immutable snapshot of the current identity. */
61
+ data class Snapshot(
62
+ val anonymousId: String,
63
+ val userId: String?,
64
+ ) {
65
+ val isAnonymous: Boolean get() = userId == null
66
+ }
67
+
68
+ /** Delivered to observers when the snapshot changes. */
69
+ data class Change(val previous: Snapshot, val current: Snapshot)
70
+
71
+ /** Result of a successful `logIn`. */
72
+ data class LogInResult(val customerInfo: CustomerInfo, val created: Boolean)
73
+
74
+ // ---- Internal state ----------------------------------------------------
75
+
76
+ private val lock = Any()
77
+
78
+ @Volatile
79
+ private var explicitUserId: String? = null
80
+
81
+ /**
82
+ * Monotonically increasing generation counter, bumped on every
83
+ * `logIn`/`logOut`/`reset`/`wipe`. Each background completion captures
84
+ * the generation it was issued under and aborts if a newer mutation has
85
+ * since bumped the counter — closes the Round E TOCTOU race where a
86
+ * fast `logIn → logOut` sequence let an in-flight identify completion
87
+ * land AFTER the logOut and silently re-apply the user.
88
+ */
89
+ @Volatile
90
+ private var identityGeneration: Long = 0L
91
+
92
+ /** App context captured by `configure(...)` — needed for DeviceID + WorkManager. */
93
+ @Volatile
94
+ private var appContext: Context? = null
95
+
96
+ @Volatile
97
+ private var serverUrl: String = ""
98
+
99
+ @Volatile
100
+ private var apiKey: String = ""
101
+
102
+ @Volatile
103
+ private var entitlementsRepo: EntitlementsRepository? = null
104
+
105
+ private val observers: MutableMap<UUID, (Change) -> Unit> = ConcurrentHashMap()
106
+
107
+ /**
108
+ * Pluggable HTTP client for the identify POST. Production uses
109
+ * [BackendHttpClientAdapter] (the unified Round-D transport that
110
+ * also backs BillingClientGateway). Tests inject a fake via
111
+ * `setHttpClientForTesting` (MockWebServer-fronted).
112
+ */
113
+ @Volatile
114
+ @VisibleForTesting
115
+ internal var httpClient: BillingHttpClient = BackendHttpClientAdapter()
116
+
117
+ /**
118
+ * Executor for the identify POST so `logIn(...)` doesn't block the caller.
119
+ * Single-thread because identify is sequential per device.
120
+ */
121
+ @Volatile
122
+ private var executor: ExecutorService = Executors.newSingleThreadExecutor { r ->
123
+ Thread(r, "swissknife-identity").apply { isDaemon = true }
124
+ }
125
+
126
+ // ---- Public surface ----------------------------------------------------
127
+
128
+ /**
129
+ * Current identity snapshot. Reads cheap; the anonymous id is derived
130
+ * from `DeviceID.get(context)` (EncryptedSharedPreferences-backed).
131
+ *
132
+ * The `$SKAnonymousID:` prefix is unified across iOS / Android /
133
+ * RN as of Wave 1; previously Android used `$RCAnonymousID:`.
134
+ */
135
+ fun current(): Snapshot {
136
+ val ctx = appContext
137
+ // Pre-configure callers get a placeholder snapshot. The
138
+ // alternative would be to throw; given how often hosts read
139
+ // `Identity.current()` from `Application.onCreate` and similar
140
+ // wire-up hooks, a benign empty snapshot is friendlier.
141
+ ?: return Snapshot(anonymousId = "", userId = null)
142
+ synchronized(lock) {
143
+ return Snapshot(
144
+ anonymousId = "\$SKAnonymousID:" + DeviceID.get(ctx),
145
+ userId = explicitUserId,
146
+ )
147
+ }
148
+ }
149
+
150
+ /**
151
+ * Identify this device as a known user. POSTs `(anonymous_id, user_id)`
152
+ * to `/api/sdk/users/identify`, asks the gateway to rebind store-side
153
+ * state, and notifies observers.
154
+ *
155
+ * The callback contract mirrors the legacy `SwissKnife.logIn`: the
156
+ * `onSuccess` fires after the backend ack + the gateway's
157
+ * `EntitlementsRepository.invalidate()` + the post-login refresh
158
+ * complete. `onError` fires on any leg failing.
159
+ *
160
+ * Transient backend failures (5xx / IOException) are retried inline
161
+ * once with a fixed 1-second sleep; persistent failures bubble up.
162
+ * The WorkManager-backed long-tail retry is deliberately scoped
163
+ * out — `SetAttributesWorker`-style retry only buys us minutes; for
164
+ * identify the UX cost of "the app appears identified locally but
165
+ * the backend never heard about it" is worse than just surfacing
166
+ * the error.
167
+ */
168
+ fun logIn(
169
+ userId: String,
170
+ onSuccess: (LogInResult) -> Unit,
171
+ onError: (PurchasesError) -> Unit,
172
+ ) {
173
+ require(userId.isNotEmpty()) { "logIn requires a non-empty userId" }
174
+ val ctx = appContext
175
+ if (ctx == null) {
176
+ onError(PurchasesError(
177
+ com.appswissknife.models.PurchasesErrorCode.ConfigurationError,
178
+ "Identity.logIn called before SwissKnife.configure"
179
+ ))
180
+ return
181
+ }
182
+ val previousSnapshot = current()
183
+ val gateway = SwissKnife.getGateway()
184
+ // Bump and capture under the same lock — anything submitted after
185
+ // this point sees a newer generation and our completion checks
186
+ // `gen != identityGeneration` to detect "raced past by logOut/reset".
187
+ val gen: Long
188
+ synchronized(lock) {
189
+ identityGeneration += 1
190
+ gen = identityGeneration
191
+ }
192
+ executor.execute {
193
+ // 1. Backend identify POST — the bug closed in Wave 1. Bounded
194
+ // retry (1 + 1) keeps the login flow snappy.
195
+ val anonymousId = previousSnapshot.anonymousId
196
+ try {
197
+ postIdentifyWithRetry(anonymousId = anonymousId, userId = userId)
198
+ } catch (e: Throwable) {
199
+ // If a logOut/reset/wipe has raced past while we were in
200
+ // flight, do NOT surface this error — the caller has
201
+ // already moved on. Silently drop it.
202
+ if (identityGeneration != gen) return@execute
203
+ onError(toPurchasesError(e))
204
+ return@execute
205
+ }
206
+
207
+ // Round E TOCTOU guard: between issuing the POST and arriving
208
+ // here, a `logOut`/`reset`/`wipe` may have bumped the
209
+ // generation. If so, discard the result — the user's intent
210
+ // (logout) wins.
211
+ if (identityGeneration != gen) {
212
+ return@execute
213
+ }
214
+
215
+ // 2. Local snapshot update + gateway rebind. The gateway's
216
+ // `logIn` no longer owns the backend POST (that just
217
+ // happened); it only does store-side bookkeeping
218
+ // (entitlements cache invalidation + currentUserID).
219
+ val newSnapshot: Snapshot
220
+ synchronized(lock) {
221
+ // Re-check inside the lock to close the last narrow window.
222
+ if (identityGeneration != gen) return@execute
223
+ explicitUserId = userId
224
+ newSnapshot = Snapshot(
225
+ anonymousId = anonymousId,
226
+ userId = userId,
227
+ )
228
+ }
229
+
230
+ // Best-effort gateway rebind. We delegate the
231
+ // entitlements-cache invalidation through the gateway so
232
+ // tests that use FakePurchasesGateway still see the
233
+ // `logIn` recorded call and can canned-up a CustomerInfo.
234
+ gateway.logIn(
235
+ appUserID = userId,
236
+ onSuccess = { info, created ->
237
+ notifyChange(previousSnapshot, newSnapshot)
238
+ onSuccess(LogInResult(info, created))
239
+ },
240
+ onError = { err ->
241
+ // Local rebind failed AFTER the backend got the merge.
242
+ // Snapshot stays — the backend ground-truth is the
243
+ // identified user; the gateway's failure is just a
244
+ // missing CustomerInfo refresh. Surface the error so
245
+ // hosts can show a "we logged you in but couldn't
246
+ // refresh entitlements yet" UX.
247
+ notifyChange(previousSnapshot, newSnapshot)
248
+ onError(err)
249
+ },
250
+ )
251
+ }
252
+ }
253
+
254
+ /**
255
+ * Revert to anonymous. The DeviceID stays — Phase 1 keeps it stable
256
+ * across logout so analytics continuity for the same physical install
257
+ * is preserved. Use `wipe(context)` for a full reset.
258
+ */
259
+ fun logOut(
260
+ onSuccess: () -> Unit,
261
+ onError: (PurchasesError) -> Unit,
262
+ ) {
263
+ val ctx = appContext
264
+ if (ctx == null) {
265
+ onError(PurchasesError(
266
+ com.appswissknife.models.PurchasesErrorCode.ConfigurationError,
267
+ "Identity.logOut called before SwissKnife.configure"
268
+ ))
269
+ return
270
+ }
271
+ // Round E: route through the same single-thread executor as
272
+ // `logIn` so FIFO ordering serializes the two ops. Without this,
273
+ // a fast `logIn → logOut` could let the in-flight identify POST
274
+ // land AFTER logOut and silently re-apply the user. The generation
275
+ // bump is the second line of defence: if anyone has a snapshot of
276
+ // an older generation in flight, their completion is discarded.
277
+ val previousSnapshot = current()
278
+ synchronized(lock) {
279
+ explicitUserId = null
280
+ identityGeneration += 1
281
+ }
282
+ val newSnapshot = current()
283
+ executor.execute {
284
+ SwissKnife.getGateway().logOut(
285
+ onSuccess = {
286
+ notifyChange(previousSnapshot, newSnapshot)
287
+ onSuccess()
288
+ },
289
+ onError = { err ->
290
+ // The local snapshot is already anonymous — surface the
291
+ // gateway error but don't roll back. Hosts treat logout
292
+ // failures as recoverable; the SDK state is consistent.
293
+ notifyChange(previousSnapshot, newSnapshot)
294
+ onError(err)
295
+ },
296
+ )
297
+ }
298
+ }
299
+
300
+ /**
301
+ * Rotate in-memory state but keep persistent storage. Matches the
302
+ * SKAnalytics-style reset semantic — "switch test user" UX.
303
+ */
304
+ fun reset() {
305
+ val previousSnapshot = current()
306
+ synchronized(lock) {
307
+ explicitUserId = null
308
+ identityGeneration += 1
309
+ }
310
+ entitlementsRepo?.invalidate()
311
+ val newSnapshot = current()
312
+ notifyChange(previousSnapshot, newSnapshot)
313
+ }
314
+
315
+ /**
316
+ * Hard wipe: clears EncryptedSharedPreferences DeviceID, drops the
317
+ * entitlements cache. GDPR-delete / test-build cleanup. Next
318
+ * `current()` regenerates DeviceID.
319
+ */
320
+ fun wipe(context: Context) {
321
+ val previousSnapshot = current()
322
+ synchronized(lock) {
323
+ explicitUserId = null
324
+ identityGeneration += 1
325
+ }
326
+ DeviceID.wipe(context)
327
+ entitlementsRepo?.invalidate()
328
+ val newSnapshot = current()
329
+ notifyChange(previousSnapshot, newSnapshot)
330
+ }
331
+
332
+ /** Subscribe to identity changes. Returns an unsubscribe token. */
333
+ fun addObserver(block: (Change) -> Unit): UUID {
334
+ val token = UUID.randomUUID()
335
+ observers[token] = block
336
+ return token
337
+ }
338
+
339
+ fun removeObserver(token: UUID) {
340
+ observers.remove(token)
341
+ }
342
+
343
+ /**
344
+ * Called by the deprecated `SwissKnife.logOut` facade after the
345
+ * gateway has rebound store-side state, so Identity's in-memory
346
+ * snapshot tracks the legacy facade path. New code goes through
347
+ * `Identity.logOut(...)` directly and bypasses this.
348
+ */
349
+ internal fun _syncAnonymousFromFacade(previousSnapshot: Snapshot) {
350
+ synchronized(lock) {
351
+ explicitUserId = null
352
+ identityGeneration += 1
353
+ }
354
+ val newSnapshot = current()
355
+ notifyChange(previousSnapshot, newSnapshot)
356
+ }
357
+
358
+ // ---- Internal: SwissKnife configure-time wiring ------------------------
359
+
360
+ /**
361
+ * Called by `SwissKnife.configure(...)` so Identity captures the app
362
+ * context, backend coordinates, and seed user id in one place.
363
+ * Idempotent — re-configure overwrites.
364
+ */
365
+ internal fun configure(
366
+ context: Context,
367
+ serverUrl: String,
368
+ apiKey: String,
369
+ seedUserId: String?,
370
+ entitlementsRepository: EntitlementsRepository?,
371
+ ) {
372
+ synchronized(lock) {
373
+ this.appContext = context.applicationContext
374
+ this.serverUrl = serverUrl.trimEnd('/')
375
+ this.apiKey = apiKey
376
+ this.entitlementsRepo = entitlementsRepository
377
+ this.explicitUserId = seedUserId?.takeIf { it.isNotEmpty() }
378
+ }
379
+ }
380
+
381
+ /**
382
+ * Whether [configure] has run (an app context is wired). Used by the
383
+ * observability-only init path to avoid clobbering a real configuration
384
+ * (with seed user + entitlements repo) that the purchase `configure()`
385
+ * path already installed.
386
+ */
387
+ internal fun isConfigured(): Boolean = appContext != null
388
+
389
+ // ---- Internal: bug-fixed backend POST ----------------------------------
390
+
391
+ /**
392
+ * POST the `(anonymous_id, user_id)` pair to `/api/sdk/users/identify`.
393
+ * Closes the Wave 1 audit's "Android does not POST" bug.
394
+ *
395
+ * Retry: one inline retry on transient errors. Errors after that
396
+ * bubble up to `logIn`'s `onError`.
397
+ */
398
+ @Throws(IOException::class)
399
+ private fun postIdentifyWithRetry(anonymousId: String, userId: String) {
400
+ val body = JSONObject().apply {
401
+ put("anonymous_id", anonymousId)
402
+ put("user_id", userId)
403
+ }
404
+
405
+ // Round-C/D: when BackendHttpClient.shared is wired (production
406
+ // SwissKnife.configure path), route through it so the X-API-Key
407
+ // header, base URL, and exponential-backoff retry policy come
408
+ // from the unified Net layer. The test seam (`httpClient`) takes
409
+ // precedence so existing IdentityTest's MockWebServer-backed
410
+ // injection points still work.
411
+ val backend = try { com.appswissknife.net.BackendHttpClient.shared } catch (_: Throwable) { null }
412
+ if (backend != null && httpClient is BackendHttpClientAdapter) {
413
+ try {
414
+ backend.postIgnoringResponse(
415
+ path = "/api/sdk/users/identify",
416
+ body = body,
417
+ maxRetries = 1,
418
+ )
419
+ return
420
+ } catch (e: com.appswissknife.net.BackendRejected) {
421
+ throw IOException(e.serverMessage ?: "identify rejected (${e.code})", e)
422
+ } catch (e: com.appswissknife.net.BackendUnavailable) {
423
+ throw IOException(e.serverMessage ?: "identify unavailable (${e.code})", e)
424
+ } catch (_: com.appswissknife.net.BackendNotConfigured) {
425
+ // BackendHttpClient.shared wasn't wired yet — fall through.
426
+ }
427
+ }
428
+
429
+ // Legacy path: kept for the test seam (FakeHttpClient injection)
430
+ // and for callers that haven't gone through SwissKnife.configure.
431
+ val bodyString = body.toString()
432
+ val headers = mapOf(
433
+ "Content-Type" to "application/json",
434
+ "X-API-Key" to apiKey,
435
+ )
436
+ var attempt = 0
437
+ var lastError: Throwable? = null
438
+ while (attempt < 2) {
439
+ try {
440
+ httpClient.post(
441
+ url = "$serverUrl/api/sdk/users/identify",
442
+ body = bodyString,
443
+ headers = headers,
444
+ )
445
+ return
446
+ } catch (e: IOException) {
447
+ lastError = e
448
+ attempt += 1
449
+ if (attempt < 2) {
450
+ try {
451
+ Thread.sleep(1_000)
452
+ } catch (_: InterruptedException) {
453
+ Thread.currentThread().interrupt()
454
+ throw e
455
+ }
456
+ }
457
+ }
458
+ }
459
+ throw IOException(lastError?.message ?: "identify failed", lastError)
460
+ }
461
+
462
+ private fun notifyChange(previous: Snapshot, current: Snapshot) {
463
+ if (previous == current) return
464
+ val change = Change(previous, current)
465
+ // Snapshot the observers to avoid ConcurrentModificationException
466
+ // if a callback adds/removes during dispatch.
467
+ val snapshot = observers.values.toList()
468
+ snapshot.forEach { runCatching { it.invoke(change) } }
469
+ }
470
+
471
+ private fun toPurchasesError(t: Throwable): PurchasesError = when (t) {
472
+ is PurchasesError -> t
473
+ is IOException -> PurchasesError.NetworkError(t.message ?: "Network error", t)
474
+ else -> PurchasesError.Unknown(t.message ?: "Unknown error", t)
475
+ }
476
+
477
+ // ---- Test seams --------------------------------------------------------
478
+
479
+ /** Test seam — drop in-memory state and reset to defaults. */
480
+ @VisibleForTesting
481
+ internal fun _resetForTesting() {
482
+ synchronized(lock) {
483
+ explicitUserId = null
484
+ identityGeneration = 0L
485
+ appContext = null
486
+ serverUrl = ""
487
+ apiKey = ""
488
+ entitlementsRepo = null
489
+ observers.clear()
490
+ httpClient = BackendHttpClientAdapter()
491
+ executor = Executors.newSingleThreadExecutor { r ->
492
+ Thread(r, "swissknife-identity").apply { isDaemon = true }
493
+ }
494
+ }
495
+ }
496
+
497
+ /** Test seam — wait for the background executor to drain. */
498
+ @VisibleForTesting
499
+ internal fun _awaitForTesting() {
500
+ val drainExecutor = executor
501
+ drainExecutor.submit {}.get()
502
+ }
503
+
504
+ /** Test seam — inject a stub HTTP client for the identify POST. */
505
+ @VisibleForTesting
506
+ internal fun _setHttpClientForTesting(client: BillingHttpClient) {
507
+ httpClient = client
508
+ }
509
+
510
+ /** Test-only synchronous executor so assertions don't need to spin. */
511
+ @VisibleForTesting
512
+ internal fun _useDirectExecutorForTesting() {
513
+ executor = object : java.util.concurrent.AbstractExecutorService() {
514
+ override fun shutdown() {}
515
+ override fun shutdownNow(): List<Runnable> = emptyList()
516
+ override fun isShutdown() = false
517
+ override fun isTerminated() = false
518
+ override fun awaitTermination(timeout: Long, unit: java.util.concurrent.TimeUnit) = true
519
+ override fun execute(command: Runnable) { command.run() }
520
+ }
521
+ }
522
+ }
@@ -0,0 +1,67 @@
1
+ // packages/swiss-knife-android/src/main/java/com/appswissknife/models/CustomerInfo.kt
2
+ //
3
+ // Phase 6 of the SDK rip-and-replace: own data classes that REPLACE the
4
+ // `com.revenuecat.purchases.*` types that used to leak through
5
+ // [com.appswissknife.purchases.PurchasesGateway]. PHC is gone after this
6
+ // phase; these types ARE the SDK public model layer now.
7
+ //
8
+ // Shape mirrors RC's public API (same field names, same semantics) per the
9
+ // user-locked decision in the Phase 6 plan, so existing consumers (RN bridge,
10
+ // native Android callers) see no behavior change at the call site.
11
+ //
12
+ // Most of these are **interfaces** (not `data class`) on purpose: the parity
13
+ // test suite mocks them with mockito-kotlin. `data class` would force tests
14
+ // to construct full instances which is the very brittleness the gateway
15
+ // abstraction exists to avoid.
16
+ package com.appswissknife.models
17
+
18
+ import java.util.Date
19
+
20
+ /**
21
+ * Represents the latest known subscriber state — the entitlements they own,
22
+ * which are active, and which products they've purchased. Mirror of
23
+ * RC's [com.revenuecat.purchases.CustomerInfo] public surface.
24
+ */
25
+ interface CustomerInfo {
26
+ val entitlements: EntitlementInfos
27
+ val originalAppUserId: String
28
+ val firstSeen: Date
29
+ val originalPurchaseDate: Date?
30
+ val latestExpirationDate: Date?
31
+ /** Map of product id → most recent purchase date. */
32
+ val allPurchaseDates: Map<String, Date>
33
+ /** Active subscription product identifiers (anything where the entitlement is currently isActive). */
34
+ val activeSubscriptions: Set<String>
35
+ /** Every non-consumable + subscription product the user has ever purchased on this Original Account. */
36
+ val allPurchasedProductIds: Set<String>
37
+ val managementURL: String?
38
+ val requestDate: Date
39
+ }
40
+
41
+ /** Container for [EntitlementInfo] entries. RC parity: `.all` / `.active`. */
42
+ interface EntitlementInfos {
43
+ /** Every entitlement the subscriber has ever owned, keyed by identifier. */
44
+ val all: Map<String, EntitlementInfo>
45
+ /** Only currently-active entitlements. Filter of [all] where [EntitlementInfo.isActive] is true. */
46
+ val active: Map<String, EntitlementInfo>
47
+ /** Signed-response verification status. Phase 6 default: NOT_REQUESTED (we trust our backend). */
48
+ val verification: VerificationResult
49
+ }
50
+
51
+ interface EntitlementInfo {
52
+ val identifier: String
53
+ val isActive: Boolean
54
+ /** True if the underlying subscription is set to auto-renew at expiry. */
55
+ val willRenew: Boolean
56
+ val latestPurchaseDate: Date?
57
+ val expirationDate: Date?
58
+ val productIdentifier: String
59
+ /** Google Play base-plan identifier; iOS leaves this null. */
60
+ val productPlanIdentifier: String?
61
+ val isSandbox: Boolean
62
+ val unsubscribeDetectedAt: Date?
63
+ val billingIssueDetectedAt: Date?
64
+ val periodType: PeriodType
65
+ val store: Store
66
+ val ownershipType: OwnershipType
67
+ }
@@ -0,0 +1,35 @@
1
+ // packages/swiss-knife-android/src/main/java/com/appswissknife/models/Enums.kt
2
+ //
3
+ // Phase 6 — own enums mirroring RC parity.
4
+ package com.appswissknife.models
5
+
6
+ enum class LogLevel { VERBOSE, DEBUG, INFO, WARN, ERROR }
7
+
8
+ /** Signed-response verification status. We do server-side validation only, so
9
+ * Phase 6 emits NOT_REQUESTED unconditionally; reserved for a future signed
10
+ * responses path. */
11
+ enum class VerificationResult { NOT_REQUESTED, VERIFIED, FAILED, VERIFIED_ON_DEVICE }
12
+
13
+ /** Store backing the transaction. RUSTORE is supplied by the optional
14
+ * swiss-knife-android-rustore add-on; the base SDK only needs the enum member
15
+ * so backend-decoded entitlements retain RuStore provenance. */
16
+ enum class Store { PLAY_STORE, APP_STORE, AMAZON, STRIPE, PROMOTIONAL, MAC_APP_STORE, RUSTORE, UNKNOWN_STORE }
17
+
18
+ /** Subscription period type. RC parity: NORMAL / INTRO / TRIAL / PREPAID. */
19
+ enum class PeriodType { NORMAL, INTRO, TRIAL, PREPAID }
20
+
21
+ /** How the subscriber came to own the entitlement. */
22
+ enum class OwnershipType { PURCHASED, FAMILY_SHARED, UNKNOWN }
23
+
24
+ /** Package-type tags. RC parity — these drive paywall layout in the consuming app. */
25
+ enum class PackageType {
26
+ UNKNOWN,
27
+ CUSTOM,
28
+ LIFETIME,
29
+ ANNUAL,
30
+ SIX_MONTH,
31
+ THREE_MONTH,
32
+ TWO_MONTH,
33
+ MONTHLY,
34
+ WEEKLY,
35
+ }