@app-swiss-knife/react-native-sdk 0.3.2 → 0.5.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 (177) hide show
  1. package/CHANGELOG.md +465 -0
  2. package/LICENSE +21 -0
  3. package/README.md +229 -42
  4. package/SwissKnifePurchases.podspec +1 -1
  5. package/android/build.gradle +24 -2
  6. package/android/consumer-rules.pro +12 -0
  7. package/android/src/main/AndroidManifest.xml +15 -1
  8. package/android/src/main/java/com/swissknife/crashreporting/SKCrashReportingModule.kt +5 -4
  9. package/android/src/main/java/com/swissknife/purchases/SwissKnifeJson.kt +7 -2
  10. package/android/src/main/java/com/swissknife/purchases/SwissKnifePurchasesModule.kt +168 -6
  11. package/android/src/play/java/com/swissknife/purchases/StoreIntentHandler.kt +7 -0
  12. package/android/src/rustore/java/com/swissknife/purchases/StoreIntentHandler.kt +9 -0
  13. package/android/vendor/java/com/appswissknife/SwissKnife.kt +107 -38
  14. package/android/vendor/java/com/appswissknife/analytics/SKAnalytics.kt +180 -115
  15. package/android/vendor/java/com/appswissknife/attributes/AttributesClient.kt +16 -18
  16. package/android/vendor/java/com/appswissknife/attributes/SetAttributesWorker.kt +13 -13
  17. package/android/vendor/java/com/appswissknife/attribution/Attribution.kt +56 -25
  18. package/android/vendor/java/com/appswissknife/context/DeviceContext.kt +1 -1
  19. package/android/vendor/java/com/appswissknife/crashreporting/SKCrashReporting.kt +641 -208
  20. package/android/vendor/java/com/appswissknife/entitlements/EntitlementsRepository.kt +195 -26
  21. package/android/vendor/java/com/appswissknife/identity/Identity.kt +31 -6
  22. package/android/vendor/java/com/appswissknife/models/PurchasesError.kt +5 -0
  23. package/android/vendor/java/com/appswissknife/net/BackendHttpClient.kt +69 -35
  24. package/android/vendor/java/com/appswissknife/net/IngestClient.kt +756 -98
  25. package/android/vendor/java/com/appswissknife/net/OfflineQueueStore.kt +214 -30
  26. package/android/vendor/java/com/appswissknife/notifications/NotificationRenderer.kt +195 -0
  27. package/android/vendor/java/com/appswissknife/notifications/PermissionRequestActivity.kt +60 -0
  28. package/android/vendor/java/com/appswissknife/notifications/PermissionStatus.kt +41 -0
  29. package/android/vendor/java/com/appswissknife/notifications/PushEventQueue.kt +143 -0
  30. package/android/vendor/java/com/appswissknife/notifications/PushPayload.kt +72 -0
  31. package/android/vendor/java/com/appswissknife/notifications/PushRegistration.kt +89 -0
  32. package/android/vendor/java/com/appswissknife/notifications/SwissKnifeMessagingService.kt +57 -0
  33. package/android/vendor/java/com/appswissknife/notifications/SwissKnifeNotifications.kt +438 -0
  34. package/android/vendor/java/com/appswissknife/offerings/OfferingsRepository.kt +266 -64
  35. package/android/vendor/java/com/appswissknife/performance/SKPerformance.kt +1 -0
  36. package/android/vendor/java/com/appswissknife/purchases/BillingClientGateway.kt +545 -88
  37. package/android/vendor/java/com/appswissknife/purchases/PlayPriceEnrichmentProvider.kt +55 -24
  38. package/android/vendor/java/com/appswissknife/purchases/ProductKindHint.kt +21 -0
  39. package/android/vendor/java/com/appswissknife/purchases/PurchasesGateway.kt +14 -0
  40. package/android/vendor-rustore/AndroidManifest.xml +59 -0
  41. package/android/vendor-rustore/java/com/appswissknife/rustore/RuStoreGateway.kt +428 -0
  42. package/android/vendor-rustore/java/com/appswissknife/rustore/RuStoreInitProvider.kt +43 -0
  43. package/android/vendor-rustore/java/com/appswissknife/rustore/RuStorePriceEnrichmentProvider.kt +85 -0
  44. package/app.plugin.js +287 -0
  45. package/ios/SwissKnifePurchases.m +20 -0
  46. package/ios/SwissKnifePurchases.swift +97 -3
  47. package/ios/SwissKnifePushBootstrap.m +34 -0
  48. package/ios/vendor/SwissKnifeiOS/Analytics/SKAnalytics.swift +138 -89
  49. package/ios/vendor/SwissKnifeiOS/Context/DeviceContext.swift +1 -1
  50. package/ios/vendor/SwissKnifeiOS/CrashReporting/SKCrashReporting.swift +531 -100
  51. package/ios/vendor/SwissKnifeiOS/Net/BackendBackoffGate.swift +43 -2
  52. package/ios/vendor/SwissKnifeiOS/Net/IngestClient.swift +495 -16
  53. package/ios/vendor/SwissKnifeiOS/Net/OfflineQueueStore.swift +231 -23
  54. package/ios/vendor/SwissKnifeiOS/Notifications/PushPayload.swift +87 -0
  55. package/ios/vendor/SwissKnifeiOS/Notifications/PushRegistrar.swift +322 -0
  56. package/ios/vendor/SwissKnifeiOS/Notifications/SwissKnife+Notifications.swift +403 -0
  57. package/ios/vendor/SwissKnifeiOS/Performance/SKPerformance.swift +1 -0
  58. package/ios/vendor/SwissKnifeiOS/Services/EntitlementsService.swift +11 -7
  59. package/ios/vendor/SwissKnifeiOS/Services/PurchaseService.swift +38 -7
  60. package/ios/vendor/SwissKnifeiOS/SwissKnife.swift +34 -6
  61. package/lib/commonjs/attribution.js +4 -3
  62. package/lib/commonjs/attribution.js.map +1 -1
  63. package/lib/commonjs/identity.js +12 -11
  64. package/lib/commonjs/identity.js.map +1 -1
  65. package/lib/commonjs/index.js +16 -5
  66. package/lib/commonjs/index.js.map +1 -1
  67. package/lib/commonjs/internal/config.js +105 -8
  68. package/lib/commonjs/internal/config.js.map +1 -1
  69. package/lib/commonjs/internal/telemetry-context.js +70 -0
  70. package/lib/commonjs/internal/telemetry-context.js.map +1 -0
  71. package/lib/commonjs/modules/analytics.js +18 -25
  72. package/lib/commonjs/modules/analytics.js.map +1 -1
  73. package/lib/commonjs/modules/crash-reporting.js +353 -31
  74. package/lib/commonjs/modules/crash-reporting.js.map +1 -1
  75. package/lib/commonjs/modules/log.js +1 -1
  76. package/lib/commonjs/modules/notifications.js +500 -0
  77. package/lib/commonjs/modules/notifications.js.map +1 -0
  78. package/lib/commonjs/modules/performance.js +57 -8
  79. package/lib/commonjs/modules/performance.js.map +1 -1
  80. package/lib/commonjs/native/module.js +6 -0
  81. package/lib/commonjs/native/module.js.map +1 -1
  82. package/lib/commonjs/native/spec.js +12 -5
  83. package/lib/commonjs/native/spec.js.map +1 -1
  84. package/lib/commonjs/purchases.js +4 -4
  85. package/lib/commonjs/types.js +12 -15
  86. package/lib/commonjs/types.js.map +1 -1
  87. package/lib/module/attribution.js +4 -3
  88. package/lib/module/attribution.js.map +1 -1
  89. package/lib/module/identity.js +12 -11
  90. package/lib/module/identity.js.map +1 -1
  91. package/lib/module/index.js +8 -4
  92. package/lib/module/index.js.map +1 -1
  93. package/lib/module/internal/config.js +103 -8
  94. package/lib/module/internal/config.js.map +1 -1
  95. package/lib/module/internal/telemetry-context.js +63 -0
  96. package/lib/module/internal/telemetry-context.js.map +1 -0
  97. package/lib/module/modules/analytics.js +18 -25
  98. package/lib/module/modules/analytics.js.map +1 -1
  99. package/lib/module/modules/crash-reporting.js +353 -31
  100. package/lib/module/modules/crash-reporting.js.map +1 -1
  101. package/lib/module/modules/log.js +1 -1
  102. package/lib/module/modules/notifications.js +491 -0
  103. package/lib/module/modules/notifications.js.map +1 -0
  104. package/lib/module/modules/performance.js +57 -8
  105. package/lib/module/modules/performance.js.map +1 -1
  106. package/lib/module/native/module.js +6 -1
  107. package/lib/module/native/module.js.map +1 -1
  108. package/lib/module/native/spec.js +11 -4
  109. package/lib/module/native/spec.js.map +1 -1
  110. package/lib/module/purchases.js +4 -4
  111. package/lib/module/types.js +12 -15
  112. package/lib/module/types.js.map +1 -1
  113. package/lib/typescript/commonjs/attribution.d.ts +3 -2
  114. package/lib/typescript/commonjs/attribution.d.ts.map +1 -1
  115. package/lib/typescript/commonjs/identity.d.ts.map +1 -1
  116. package/lib/typescript/commonjs/index.d.ts +3 -1
  117. package/lib/typescript/commonjs/index.d.ts.map +1 -1
  118. package/lib/typescript/commonjs/internal/config.d.ts +16 -2
  119. package/lib/typescript/commonjs/internal/config.d.ts.map +1 -1
  120. package/lib/typescript/commonjs/internal/telemetry-context.d.ts +22 -0
  121. package/lib/typescript/commonjs/internal/telemetry-context.d.ts.map +1 -0
  122. package/lib/typescript/commonjs/modules/analytics.d.ts +8 -11
  123. package/lib/typescript/commonjs/modules/analytics.d.ts.map +1 -1
  124. package/lib/typescript/commonjs/modules/crash-reporting.d.ts +50 -12
  125. package/lib/typescript/commonjs/modules/crash-reporting.d.ts.map +1 -1
  126. package/lib/typescript/commonjs/modules/notifications.d.ts +110 -0
  127. package/lib/typescript/commonjs/modules/notifications.d.ts.map +1 -0
  128. package/lib/typescript/commonjs/modules/performance.d.ts +13 -0
  129. package/lib/typescript/commonjs/modules/performance.d.ts.map +1 -1
  130. package/lib/typescript/commonjs/native/module.d.ts +2 -0
  131. package/lib/typescript/commonjs/native/module.d.ts.map +1 -1
  132. package/lib/typescript/commonjs/native/spec.d.ts +33 -4
  133. package/lib/typescript/commonjs/native/spec.d.ts.map +1 -1
  134. package/lib/typescript/commonjs/purchases.d.ts +4 -4
  135. package/lib/typescript/commonjs/types.d.ts +4 -5
  136. package/lib/typescript/commonjs/types.d.ts.map +1 -1
  137. package/lib/typescript/module/attribution.d.ts +3 -2
  138. package/lib/typescript/module/attribution.d.ts.map +1 -1
  139. package/lib/typescript/module/identity.d.ts.map +1 -1
  140. package/lib/typescript/module/index.d.ts +3 -1
  141. package/lib/typescript/module/index.d.ts.map +1 -1
  142. package/lib/typescript/module/internal/config.d.ts +16 -2
  143. package/lib/typescript/module/internal/config.d.ts.map +1 -1
  144. package/lib/typescript/module/internal/telemetry-context.d.ts +22 -0
  145. package/lib/typescript/module/internal/telemetry-context.d.ts.map +1 -0
  146. package/lib/typescript/module/modules/analytics.d.ts +8 -11
  147. package/lib/typescript/module/modules/analytics.d.ts.map +1 -1
  148. package/lib/typescript/module/modules/crash-reporting.d.ts +50 -12
  149. package/lib/typescript/module/modules/crash-reporting.d.ts.map +1 -1
  150. package/lib/typescript/module/modules/notifications.d.ts +110 -0
  151. package/lib/typescript/module/modules/notifications.d.ts.map +1 -0
  152. package/lib/typescript/module/modules/performance.d.ts +13 -0
  153. package/lib/typescript/module/modules/performance.d.ts.map +1 -1
  154. package/lib/typescript/module/native/module.d.ts +2 -0
  155. package/lib/typescript/module/native/module.d.ts.map +1 -1
  156. package/lib/typescript/module/native/spec.d.ts +33 -4
  157. package/lib/typescript/module/native/spec.d.ts.map +1 -1
  158. package/lib/typescript/module/purchases.d.ts +4 -4
  159. package/lib/typescript/module/types.d.ts +4 -5
  160. package/lib/typescript/module/types.d.ts.map +1 -1
  161. package/package.json +13 -4
  162. package/src/attribution.ts +4 -3
  163. package/src/identity.ts +12 -11
  164. package/src/index.ts +18 -4
  165. package/src/internal/config.ts +113 -8
  166. package/src/internal/telemetry-context.ts +76 -0
  167. package/src/modules/analytics.ts +24 -33
  168. package/src/modules/crash-reporting.ts +476 -67
  169. package/src/modules/log.ts +1 -1
  170. package/src/modules/notifications.ts +557 -0
  171. package/src/modules/performance.ts +94 -14
  172. package/src/native/module.ts +6 -0
  173. package/src/native/spec.ts +45 -10
  174. package/src/purchases.ts +4 -4
  175. package/src/types.ts +12 -15
  176. package/android/vendor/java/com/appswissknife/analytics/EventQueueStore.kt +0 -326
  177. package/android/vendor/java/com/appswissknife/analytics/FlushEventsWorker.kt +0 -296
@@ -1,9 +1,9 @@
1
1
  // packages/swiss-knife-android/src/main/java/com/appswissknife/entitlements/EntitlementsRepository.kt
2
2
  //
3
- // Phase 6 commit 2 — disk-cached CustomerInfo + backend-authoritative
4
- // entitlement state. Replaces PHC's in-process cache; the backend at
5
- // /api/sdk/entitlements/check is the source of truth per the user-locked
6
- // decision (backend, not PHC, owns entitlements).
3
+ // Disk-cached CustomerInfo + backend-authoritative entitlement state. The
4
+ // backend is the source of truth: refresh() reads the user's whole entitlement
5
+ // set from /api/sdk/entitlements/list (iOS reads the same route), or asks
6
+ // /api/sdk/entitlements/check about each key a host names.
7
7
  //
8
8
  // Storage pattern mirrors Phase 2.2's EventQueueStore: atomic write-then-
9
9
  // rename + tolerant parse on read. We use cacheDir (not filesDir) because
@@ -38,11 +38,15 @@ import com.appswissknife.models.OwnershipType
38
38
  import com.appswissknife.models.PeriodType
39
39
  import com.appswissknife.models.Store
40
40
  import com.appswissknife.models.VerificationResult
41
+ import org.json.JSONException
41
42
  import org.json.JSONObject
42
43
  import java.io.File
43
44
  import java.io.IOException
45
+ import java.text.SimpleDateFormat
44
46
  import java.util.Collections
45
47
  import java.util.Date
48
+ import java.util.Locale
49
+ import java.util.TimeZone
46
50
  import java.util.concurrent.ExecutorService
47
51
  import java.util.concurrent.Executors
48
52
  import java.util.concurrent.locks.ReentrantLock
@@ -83,24 +87,48 @@ class EntitlementsRepository internal constructor(
83
87
  * have nothing yet. Within the 24h grace window the result is trustworthy
84
88
  * for read-only purposes (entitlement gating). Past the window the gateway
85
89
  * should call [refresh] before relying on it.
90
+ *
91
+ * Only the current user's: a snapshot read for another subject (the app was
92
+ * configured with a different appUserID on a later launch, or a logIn or
93
+ * logOut changed the user) counts as no cache, as iOS drops it, so one
94
+ * user's entitlements are never shown to another.
86
95
  */
87
- fun current(): CustomerInfo? = cached?.customerInfo
96
+ fun current(): CustomerInfo? = currentUsersSnapshot()?.customerInfo
88
97
 
89
- /** True if the cached snapshot is within the 24h offline grace window. */
98
+ /** True if the current user's cached snapshot is within the 24h offline grace window. */
90
99
  fun isFresh(): Boolean {
91
- val snap = cached ?: return false
100
+ val snap = currentUsersSnapshot() ?: return false
92
101
  return clock() - snap.fetchedAt <= GRACE_MILLIS
93
102
  }
94
103
 
95
104
  /**
96
- * Replace the cached snapshot. Called by the gateway after a successful
97
- * purchase (which already roundtripped through /api/sdk/subscriptions/validate
98
- * and so reflects authoritative state), to avoid an immediate redundant
99
- * refresh() round-trip.
105
+ * Replace the cached snapshot with [info], which belongs to
106
+ * [CustomerInfo.originalAppUserId]. Ignored when that is not the current
107
+ * user.
100
108
  */
101
109
  fun set(info: CustomerInfo) {
102
- val snap = CachedSnapshot(info, clock())
110
+ store(info, subject = info.originalAppUserId)
111
+ }
112
+
113
+ private fun currentUsersSnapshot(): CachedSnapshot? =
114
+ cached?.takeIf { it.subject == userIdProvider() }
115
+
116
+ /**
117
+ * Cache [info], read for [subject], and tell every listener, unless the
118
+ * current user is no longer [subject]: a read that was in flight when a
119
+ * logIn or logOut landed must not become the new user's cache, nor reach
120
+ * the listeners after the switch.
121
+ */
122
+ private fun store(info: CustomerInfo, subject: String) {
123
+ val snap = CachedSnapshot(info, clock(), subject)
103
124
  lock.withLock {
125
+ // Checked under the lock, so a user switch that changes the subject and
126
+ // then invalidates either fails this check or finds the snapshot
127
+ // written and drops it, from memory and disk.
128
+ if (subject != userIdProvider()) {
129
+ Log.i(TAG, "the user changed while their entitlements were read; not caching them")
130
+ return
131
+ }
104
132
  cached = snap
105
133
  runCatching { writeToDisk(snap) }
106
134
  .onFailure { Log.w(TAG, "failed to persist CustomerInfo", it) }
@@ -121,11 +149,22 @@ class EntitlementsRepository internal constructor(
121
149
  }
122
150
 
123
151
  /**
124
- * Fetch fresh state from the backend and update the cache. The supplied
125
- * [entitlementKeys] are the entitlement identifiers the host cares about
126
- * - the backend's `/api/sdk/entitlements/check` is keyed and we need at
127
- * least one key to call it. If empty, [refresh] is a no-op that returns
128
- * the existing cache verbatim.
152
+ * Fetch fresh state from the backend, update the cache and tell every
153
+ * listener.
154
+ *
155
+ * With no [entitlementKeys] (what the SDK itself passes) it reads the user's
156
+ * whole entitlement set from `/api/sdk/entitlements/list`, as iOS does: every
157
+ * entitlement the app defines, active or not, with its product, store,
158
+ * period type and dates, plus the user's active subscriptions and purchase
159
+ * dates. With keys it asks `/api/sdk/entitlements/check` about each one and
160
+ * knows only whether it is active.
161
+ *
162
+ * A failed read throws [IOException] and leaves the cache as it was, so a
163
+ * paying user keeps access through a network error.
164
+ *
165
+ * The answer is cached only while the user it was read for is still the
166
+ * current one; if a logIn or logOut landed meanwhile it is returned to the
167
+ * caller but neither cached nor announced.
129
168
  *
130
169
  * Synchronous + blocking. Callers on the main thread MUST wrap this
131
170
  * (the [BillingClientGateway] schedules it on an Executor; tests run it
@@ -133,12 +172,16 @@ class EntitlementsRepository internal constructor(
133
172
  */
134
173
  @Throws(IOException::class)
135
174
  fun refresh(entitlementKeys: Set<String>): CustomerInfo {
175
+ val userId = userIdProvider()
136
176
  if (entitlementKeys.isEmpty()) {
137
- return current() ?: emptyCustomerInfo(userIdProvider())
177
+ val customerInfo = fetchEntitlementList(userId)
178
+ store(customerInfo, userId)
179
+ return customerInfo
138
180
  }
181
+ val previous = currentUsersSnapshot()?.customerInfo
139
182
  val activeKeys = mutableSetOf<String>()
140
183
  for (key in entitlementKeys) {
141
- if (checkEntitlement(key)) activeKeys.add(key)
184
+ if (checkEntitlement(key, userId)) activeKeys.add(key)
142
185
  }
143
186
  // Rebuild CustomerInfo from the per-key responses. We keep ALL keys
144
187
  // queried in `.all` and the subset that came back has_access=true in
@@ -149,18 +192,18 @@ class EntitlementsRepository internal constructor(
149
192
  backendEntitlement(
150
193
  identifier = k,
151
194
  isActive = k in activeKeys,
152
- latestPurchaseDate = cached?.customerInfo?.entitlements?.all?.get(k)?.latestPurchaseDate,
153
- expirationDate = cached?.customerInfo?.entitlements?.all?.get(k)?.expirationDate,
195
+ latestPurchaseDate = previous?.entitlements?.all?.get(k)?.latestPurchaseDate,
196
+ expirationDate = previous?.entitlements?.all?.get(k)?.expirationDate,
154
197
  )
155
198
  }
156
199
  val activeMap = infos.filterKeys { it in activeKeys }
157
200
  val customerInfo = backendCustomerInfo(
158
- userId = userIdProvider(),
201
+ userId = userId,
159
202
  all = infos,
160
203
  active = activeMap,
161
204
  requestDate = now,
162
205
  )
163
- set(customerInfo)
206
+ store(customerInfo, userId)
164
207
  return customerInfo
165
208
  }
166
209
 
@@ -234,12 +277,12 @@ class EntitlementsRepository internal constructor(
234
277
  * contract.
235
278
  */
236
279
  @Throws(IOException::class)
237
- private fun checkEntitlement(key: String): Boolean {
280
+ private fun checkEntitlement(key: String, userId: String): Boolean {
238
281
  val client = com.appswissknife.net.BackendHttpClient.create(apiKey, serverUrl)
239
282
  val (code, body) = client.simpleGet(
240
283
  path = "/api/sdk/entitlements/check",
241
284
  query = listOf(
242
- "user_id" to userIdProvider(),
285
+ "user_id" to userId,
243
286
  "entitlement" to key,
244
287
  ),
245
288
  allow404 = true,
@@ -249,6 +292,26 @@ class EntitlementsRepository internal constructor(
249
292
  return json.optBoolean("has_access", false)
250
293
  }
251
294
 
295
+ /**
296
+ * Read [userId]'s whole entitlement set from `/api/sdk/entitlements/list`.
297
+ * An empty body means no entitlements. A network error, a non-2xx answer or
298
+ * a body that is not JSON throws [IOException].
299
+ */
300
+ @Throws(IOException::class)
301
+ private fun fetchEntitlementList(userId: String): CustomerInfo {
302
+ val client = com.appswissknife.net.BackendHttpClient.create(apiKey, serverUrl)
303
+ val (_, body) = client.simpleGet(
304
+ path = "/api/sdk/entitlements/list",
305
+ query = listOf("user_id" to userId),
306
+ )
307
+ if (body.isBlank()) return emptyCustomerInfo(userId)
308
+ return try {
309
+ parseEntitlementList(JSONObject(body), userId, Date(clock()))
310
+ } catch (e: JSONException) {
311
+ throw IOException("/api/sdk/entitlements/list returned a body that is not JSON", e)
312
+ }
313
+ }
314
+
252
315
  companion object {
253
316
  private const val TAG = "SwissKnife.Entitlements"
254
317
 
@@ -278,6 +341,7 @@ class EntitlementsRepository internal constructor(
278
341
  val json = JSONObject()
279
342
  json.put("schemaVersion", 1)
280
343
  json.put("fetchedAt", snap.fetchedAt)
344
+ json.put("subject", snap.subject)
281
345
  json.put("originalAppUserId", ci.originalAppUserId)
282
346
  json.put("firstSeen", ci.firstSeen.time)
283
347
  json.put("requestDate", ci.requestDate.time)
@@ -372,7 +436,10 @@ class EntitlementsRepository internal constructor(
372
436
  managementURL = managementURL,
373
437
  requestDate = requestDate,
374
438
  )
375
- return CachedSnapshot(ci, fetchedAt)
439
+ // A cache written before the subject was stored belongs to its
440
+ // CustomerInfo's user, which the SDK always set to the user it read for.
441
+ val subject = json.optString("subject").ifEmpty { originalAppUserId }
442
+ return CachedSnapshot(ci, fetchedAt, subject)
376
443
  }
377
444
 
378
445
  private fun decodeEntitlement(o: JSONObject): EntitlementInfo {
@@ -396,6 +463,106 @@ class EntitlementsRepository internal constructor(
396
463
  )
397
464
  }
398
465
 
466
+ // --- /api/sdk/entitlements/list ----------------------------------------
467
+
468
+ /**
469
+ * The `/api/sdk/entitlements/list` answer as a [CustomerInfo], read the way
470
+ * iOS reads it: a missing field takes a safe default, so a partial answer
471
+ * still gives the entitlements it has. Every entitlement the app defines is
472
+ * in `all`; `active` holds the ones with `is_active`.
473
+ */
474
+ @VisibleForTesting
475
+ internal fun parseEntitlementList(json: JSONObject, userId: String, now: Date): CustomerInfo {
476
+ val all = mutableMapOf<String, EntitlementInfo>()
477
+ json.optJSONObject("entitlements")?.let { obj ->
478
+ val keys = obj.keys()
479
+ while (keys.hasNext()) {
480
+ val key = keys.next()
481
+ val e = obj.optJSONObject(key) ?: continue
482
+ all[key] = SimpleEntitlementInfo(
483
+ identifier = key,
484
+ isActive = e.optBoolean("is_active", false),
485
+ willRenew = e.optBoolean("will_renew", false),
486
+ latestPurchaseDate = parseDate(e.opt("latest_purchase_date")),
487
+ expirationDate = parseDate(e.opt("expiration_date")),
488
+ productIdentifier = e.stringOrNull("product_identifier").orEmpty(),
489
+ productPlanIdentifier = e.stringOrNull("product_plan_identifier"),
490
+ isSandbox = e.optBoolean("is_sandbox", false),
491
+ unsubscribeDetectedAt = parseDate(e.opt("unsubscribe_detected_at")),
492
+ billingIssueDetectedAt = parseDate(e.opt("billing_issue_detected_at")),
493
+ periodType = when (e.stringOrNull("period_type")?.lowercase()) {
494
+ "trial" -> PeriodType.TRIAL
495
+ "intro" -> PeriodType.INTRO
496
+ "prepaid" -> PeriodType.PREPAID
497
+ else -> PeriodType.NORMAL
498
+ },
499
+ store = storeOf(e.stringOrNull("store")),
500
+ ownershipType = when (e.stringOrNull("ownership_type")?.lowercase()) {
501
+ "family_shared", "familyshared" -> OwnershipType.FAMILY_SHARED
502
+ else -> OwnershipType.PURCHASED
503
+ },
504
+ )
505
+ }
506
+ }
507
+ val allPurchaseDates = mutableMapOf<String, Date>()
508
+ json.optJSONObject("all_purchase_dates")?.let { obj ->
509
+ val keys = obj.keys()
510
+ while (keys.hasNext()) {
511
+ val productId = keys.next()
512
+ parseDate(obj.opt(productId))?.let { allPurchaseDates[productId] = it }
513
+ }
514
+ }
515
+ val activeSubscriptions = mutableSetOf<String>()
516
+ json.optJSONArray("active_subscriptions")?.let { arr ->
517
+ for (i in 0 until arr.length()) arr.optString(i).takeIf { it.isNotEmpty() }?.let(activeSubscriptions::add)
518
+ }
519
+ return SimpleCustomerInfo(
520
+ entitlements = SimpleEntitlementInfos(
521
+ all = all,
522
+ active = all.filterValues { it.isActive },
523
+ verification = VerificationResult.NOT_REQUESTED,
524
+ ),
525
+ originalAppUserId = json.stringOrNull("original_app_user_id") ?: userId,
526
+ firstSeen = parseDate(json.opt("first_seen")) ?: now,
527
+ originalPurchaseDate = parseDate(json.opt("original_purchase_date")),
528
+ latestExpirationDate = parseDate(json.opt("latest_expiration_date")),
529
+ allPurchaseDates = allPurchaseDates,
530
+ activeSubscriptions = activeSubscriptions,
531
+ // Everything the user ever bought: a lifetime unlock has a purchase
532
+ // date but is not an active subscription.
533
+ allPurchasedProductIds = allPurchaseDates.keys + activeSubscriptions,
534
+ managementURL = json.stringOrNull("management_url"),
535
+ requestDate = now,
536
+ )
537
+ }
538
+
539
+ private fun storeOf(raw: String?): Store = when (raw?.lowercase()) {
540
+ null -> Store.UNKNOWN_STORE
541
+ "play_store", "playstore" -> Store.PLAY_STORE
542
+ "app_store", "appstore" -> Store.APP_STORE
543
+ else -> runCatching { Store.valueOf(raw.uppercase()) }.getOrDefault(Store.UNKNOWN_STORE)
544
+ }
545
+
546
+ /** An ISO 8601 date (the server's `toISOString()`, with or without millis) or epoch millis. */
547
+ private fun parseDate(raw: Any?): Date? {
548
+ if (raw is Number) return Date(raw.toLong())
549
+ val iso = raw as? String ?: return null
550
+ if (iso.isEmpty()) return null
551
+ for (pattern in ISO_PATTERNS) {
552
+ val format = SimpleDateFormat(pattern, Locale.US).apply {
553
+ timeZone = TimeZone.getTimeZone("UTC")
554
+ isLenient = false
555
+ }
556
+ runCatching { format.parse(iso) }.getOrNull()?.let { return it }
557
+ }
558
+ return null
559
+ }
560
+
561
+ private val ISO_PATTERNS = listOf("yyyy-MM-dd'T'HH:mm:ss.SSSXXX", "yyyy-MM-dd'T'HH:mm:ssXXX")
562
+
563
+ private fun JSONObject.stringOrNull(key: String): String? =
564
+ if (isNull(key)) null else optString(key).takeIf { it.isNotEmpty() }
565
+
399
566
  private fun emptyCustomerInfo(userId: String): CustomerInfo = SimpleCustomerInfo(
400
567
  entitlements = SimpleEntitlementInfos(emptyMap(), emptyMap(), VerificationResult.NOT_REQUESTED),
401
568
  originalAppUserId = userId,
@@ -455,6 +622,8 @@ internal data class CachedSnapshot(
455
622
  val customerInfo: CustomerInfo,
456
623
  /** Wall-clock millis at fetch time - used for 24h grace check. */
457
624
  val fetchedAt: Long,
625
+ /** The user (backend subject) this snapshot was read for; only that user is served it. */
626
+ val subject: String,
458
627
  )
459
628
 
460
629
  /** Concrete CustomerInfo backed by plain data fields. Public so the gateway
@@ -279,6 +279,7 @@ object Identity {
279
279
  explicitUserId = null
280
280
  identityGeneration += 1
281
281
  }
282
+ runCatching { com.appswissknife.notifications.SwissKnifeNotifications.markUserUnlinkPending(ctx) }
282
283
  val newSnapshot = current()
283
284
  executor.execute {
284
285
  SwissKnife.getGateway().logOut(
@@ -287,11 +288,21 @@ object Identity {
287
288
  onSuccess()
288
289
  },
289
290
  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
291
  notifyChange(previousSnapshot, newSnapshot)
294
- onError(err)
292
+ // The gateway is already anonymous (after reset() or
293
+ // wipe(), or no logIn ever happened). Identity is
294
+ // anonymous too, so the logout has nothing left to do:
295
+ // resolve, as iOS does, instead of rejecting with
296
+ // LOG_OUT_ANONYMOUS_USER_ERROR.
297
+ if (err.code == com.appswissknife.models.PurchasesErrorCode.LogOutAnonymousUserError) {
298
+ onSuccess()
299
+ } else {
300
+ // The local snapshot is already anonymous — surface
301
+ // the gateway error but don't roll back. Hosts treat
302
+ // logout failures as recoverable; the SDK state is
303
+ // consistent.
304
+ onError(err)
305
+ }
295
306
  },
296
307
  )
297
308
  }
@@ -299,7 +310,10 @@ object Identity {
299
310
 
300
311
  /**
301
312
  * Rotate in-memory state but keep persistent storage. Matches the
302
- * SKAnalytics-style reset semantic — "switch test user" UX.
313
+ * SKAnalytics-style reset semantic — "switch test user" UX. Purchases go
314
+ * back to the anonymous user too: [SwissKnife.appUserID] is the anonymous
315
+ * id and [SwissKnife.getCustomerInfo] no longer serves the previous user's
316
+ * entitlements.
303
317
  */
304
318
  fun reset() {
305
319
  val previousSnapshot = current()
@@ -308,6 +322,11 @@ object Identity {
308
322
  identityGeneration += 1
309
323
  }
310
324
  entitlementsRepo?.invalidate()
325
+ // The purchases gateway holds the user's id and entitlements too
326
+ // (logIn handed them over): without this, appUserID and
327
+ // getCustomerInfo() kept answering for the user just reset.
328
+ SwissKnife.identityResetLocalState()
329
+ appContext?.let { c -> runCatching { com.appswissknife.notifications.SwissKnifeNotifications.markUserUnlinkPending(c) } }
311
330
  val newSnapshot = current()
312
331
  notifyChange(previousSnapshot, newSnapshot)
313
332
  }
@@ -315,7 +334,8 @@ object Identity {
315
334
  /**
316
335
  * Hard wipe: clears EncryptedSharedPreferences DeviceID, drops the
317
336
  * entitlements cache. GDPR-delete / test-build cleanup. Next
318
- * `current()` regenerates DeviceID.
337
+ * `current()` regenerates DeviceID. Purchases go back to the (new)
338
+ * anonymous user, as with [reset].
319
339
  */
320
340
  fun wipe(context: Context) {
321
341
  val previousSnapshot = current()
@@ -325,6 +345,9 @@ object Identity {
325
345
  }
326
346
  DeviceID.wipe(context)
327
347
  entitlementsRepo?.invalidate()
348
+ // After DeviceID.wipe, so the gateway's anonymous subject is the new id.
349
+ SwissKnife.identityResetLocalState()
350
+ runCatching { com.appswissknife.notifications.SwissKnifeNotifications.markUserUnlinkPending(context) }
328
351
  val newSnapshot = current()
329
352
  notifyChange(previousSnapshot, newSnapshot)
330
353
  }
@@ -387,6 +410,8 @@ object Identity {
387
410
  * [configure] here would reset the identity back to the seed user and
388
411
  * silently undo a `logIn(...)` that landed between the two halves.
389
412
  */
413
+ internal fun entitlementsRepository(): EntitlementsRepository? = entitlementsRepo
414
+
390
415
  internal fun _attachEntitlementsRepository(repository: EntitlementsRepository?) {
391
416
  synchronized(lock) {
392
417
  this.entitlementsRepo = repository
@@ -21,6 +21,11 @@ open class PurchasesError(
21
21
  override val cause: Throwable? = null,
22
22
  ) : Throwable(message, cause) {
23
23
 
24
+ /** Safe backend diagnostics; absent for billing and transport failures. */
25
+ val httpStatus: Int? get() = (cause as? com.appswissknife.net.BillingBackendException)?.httpStatus
26
+ val backendErrorCode: String? get() = (cause as? com.appswissknife.net.BillingBackendException)?.errorCode
27
+ val requestId: String? get() = (cause as? com.appswissknife.net.BillingBackendException)?.requestId
28
+
24
29
  /** Convenience: anything that did not succeed and was NOT a user-cancel. */
25
30
  val underlyingErrorMessage: String? get() = cause?.message
26
31
 
@@ -1,30 +1,29 @@
1
1
  // packages/swiss-knife-android/src/main/java/com/appswissknife/net/BackendHttpClient.kt
2
2
  //
3
- // Round-C/D Android port — single HTTP client for every backend call the
4
- // SDK makes. Mirror of `Sources/SwissKnifeiOS/Net/BackendHttpClient.swift`.
3
+ // The single HTTP client for every backend call the SDK makes. Mirror of
4
+ // `Sources/SwissKnifeiOS/Net/BackendHttpClient.swift`.
5
5
  //
6
- // Collapses every per-feature low-level transport callsite into this
7
- // single file. As of Round D the grep invariant is:
8
- // grep -rn HttpURLConnection packages/swiss-knife-android/src/main/
9
- // matches ONLY this file. Modules that need a one-shot send/receive
10
- // (FlushEventsWorker, SetAttributesWorker, SKCrashReporting fallback,
11
- // SKPerformance fallback, EntitlementsRepository, OfferingsRepository)
12
- // go through `BackendHttpClient.simplePost` / `.simpleGet` (no retries —
13
- // the caller is the retry layer); modules that want the full retry/auth/base-url policy
14
- // (Identity, Attribution, BillingClientGateway.validate) go through
15
- // `BackendHttpClient.shared` (production) or a `BackendHttpClient.create`
16
- // (tests / pre-configure callers).
6
+ // No other file in packages/swiss-knife-android/src/main/ opens an
7
+ // HttpURLConnection to the backend (notifications/NotificationRenderer opens
8
+ // one only to download a notification's image from its own URL).
17
9
  //
18
- // Collapsed callsites:
19
- // - analytics/FlushEventsWorker (events batch — legacy fallback path)
20
- // - crashreporting/SKCrashReporting (5 separate transports — fallback)
21
- // - performance/SKPerformance (transactions + sessions — fallback)
22
- // - purchases/BillingClientGateway.validatePurchaseWithBackend
23
- // - entitlements/EntitlementsRepository
24
- // - offerings/OfferingsRepository
25
- // - attributes/SetAttributesWorker
26
- // - identity/IdentityNetwork
27
- // - attribution/Attribution.registerInstall
10
+ // Telemetry has one pipeline: analytics events, captured errors and crash
11
+ // reports, and performance data are items on IngestClient's durable queue,
12
+ // which drains to `POST /ingest` through `BackendHttpClient.shared`.
13
+ //
14
+ // The other callers:
15
+ // - One-shot send/receive through `simplePost` / `simpleGet` (no retries;
16
+ // the caller is the retry layer): attributes/SetAttributesWorker,
17
+ // crashreporting/SKCrashReporting (user feedback only),
18
+ // performance/SKPerformance (only while IngestClient is not wired),
19
+ // notifications/SwissKnifeNotifications and PushEventQueue (push device
20
+ // registration and push events), entitlements/EntitlementsRepository,
21
+ // offerings/OfferingsRepository.
22
+ // - `postIgnoringResponse` / `postRaw` with a retry budget, on
23
+ // `BackendHttpClient.shared` or a pinned `BackendHttpClient.create(...)`:
24
+ // identity/Identity (identify), attribution/Attribution (install).
25
+ // - [BackendHttpClientAdapter], the `BillingHttpClient` that
26
+ // purchases/BillingClientGateway validates receipts through.
28
27
  //
29
28
  // Design decisions:
30
29
  // - Adds `X-API-Key` automatically using the configResolver lambda.
@@ -153,10 +152,15 @@ internal class BackendRejected(val code: Int, val serverMessage: String?) :
153
152
 
154
153
  /**
155
154
  * Thrown by [BackendHttpClient] after the retry budget is exhausted on
156
- * 5xx / network errors.
155
+ * 429 / 5xx / network errors. [retryAfterMillis] is the server's
156
+ * `Retry-After` on the last attempt, when it sent one.
157
157
  */
158
- internal class BackendUnavailable(val code: Int, val serverMessage: String?, cause: Throwable? = null) :
159
- IOException("backend unavailable ($code): ${serverMessage ?: ""}", cause)
158
+ internal class BackendUnavailable(
159
+ val code: Int,
160
+ val serverMessage: String?,
161
+ cause: Throwable? = null,
162
+ val retryAfterMillis: Long? = null,
163
+ ) : IOException("backend unavailable ($code): ${serverMessage ?: ""}", cause)
160
164
 
161
165
  /**
162
166
  * Thrown when the SDK hasn't been configured (apiKey empty).
@@ -425,7 +429,11 @@ internal class BackendHttpClient(
425
429
  attempt++
426
430
  continue
427
431
  }
428
- throw BackendUnavailable(code, extractMessage(r.body))
432
+ throw BackendUnavailable(
433
+ code,
434
+ extractMessage(r.body),
435
+ retryAfterMillis = r.retryAfterMillis,
436
+ )
429
437
  }
430
438
  // 4xx (other than 429) → terminal.
431
439
  throw BackendRejected(code, extractMessage(r.body))
@@ -442,11 +450,9 @@ internal class BackendHttpClient(
442
450
  }
443
451
 
444
452
  /**
445
- * Round-D — minimal HTTP response shape exposed to per-feature default
446
- * impls (FlushEventsWorker / SetAttributesWorker / SKCrashReporting
447
- * legacy fallbacks). Mirrors the now-deleted per-feature HttpResponse
448
- * data classes so callers can keep their handleResponse(...) branches
449
- * unchanged.
453
+ * What [BackendHttpClient.simplePost] returns: the status code and the
454
+ * server's Retry-After, so the caller that owns the retries
455
+ * (SetAttributesWorker, PushEventQueue, ...) can decide what to do next.
450
456
  */
451
457
  internal data class SimpleHttpResponse(
452
458
  val code: Int,
@@ -468,14 +474,15 @@ internal data class SimpleHttpResponse(
468
474
  * directly. Any future caller MUST do the same; passing `Authorization`
469
475
  * will leave the request unauthenticated.
470
476
  */
471
- internal class BackendHttpClientAdapter : com.appswissknife.purchases.BillingHttpClient {
477
+ internal class BackendHttpClientAdapter(
478
+ private val transport: BackendTransport = UrlConnectionBackendTransport(),
479
+ ) : com.appswissknife.purchases.BillingHttpClient {
472
480
  @Throws(IOException::class)
473
481
  override fun post(url: String, body: String, headers: Map<String, String>): String {
474
482
  val u = java.net.URL(url)
475
483
  val baseUrl = "${u.protocol}://${u.authority}"
476
484
  val pathAndQuery = u.path + (u.query?.let { "?$it" } ?: "")
477
485
  val apiKey = headers["X-API-Key"] ?: ""
478
- val transport = UrlConnectionBackendTransport()
479
486
  val fullHeaders = mapOf(
480
487
  "Content-Type" to (headers["Content-Type"] ?: "application/json"),
481
488
  "Accept" to "application/json",
@@ -484,7 +491,10 @@ internal class BackendHttpClientAdapter : com.appswissknife.purchases.BillingHtt
484
491
  val urlObj = java.net.URL("$baseUrl$pathAndQuery")
485
492
  val r = transport.perform("POST", urlObj, fullHeaders, body.toByteArray(Charsets.UTF_8))
486
493
  if (!r.success) throw IOException(r.error?.message ?: "network error", r.error)
487
- if (r.code !in 200..299) throw IOException("HTTP ${r.code}")
494
+ if (r.code !in 200..299) {
495
+ val json = try { JSONObject(r.body) } catch (_: Exception) { null }
496
+ throw BillingBackendException(r.code, json?.optString("error_code"), json?.optString("request_id"))
497
+ }
488
498
  return r.body
489
499
  }
490
500
  }
@@ -505,3 +515,27 @@ internal object ConfigBridge {
505
515
 
506
516
  fun snapshot(): BackendConfig = supplier()
507
517
  }
518
+
519
+ /** Never retain the raw body: provider errors can echo a receipt or token. */
520
+ internal class BillingBackendException(
521
+ val httpStatus: Int,
522
+ code: String?,
523
+ requestId: String?,
524
+ ) : IOException("HTTP $httpStatus: ${SAFE_MESSAGES[code] ?: "Purchase validation failed"}") {
525
+ val errorCode: String? = code?.takeIf { SAFE_MESSAGES.containsKey(it) }
526
+ val requestId: String? = requestId?.takeIf {
527
+ it.matches(Regex("[a-fA-F0-9]{8}-[a-fA-F0-9]{4}-[a-fA-F0-9]{4}-[a-fA-F0-9]{4}-[a-fA-F0-9]{12}"))
528
+ }
529
+ companion object {
530
+ private val SAFE_MESSAGES = mapOf(
531
+ "missing_required_fields" to "Missing required purchase validation fields",
532
+ "invalid_request" to "Invalid purchase validation request",
533
+ "invalid_platform" to "Invalid purchase platform",
534
+ "android_package_missing" to "Android package is not configured",
535
+ "store_credentials_missing" to "Store credentials are not configured for this app",
536
+ "receipt_invalid" to "The store could not validate this purchase",
537
+ "purchase_ownership_conflict" to "This purchase belongs to another user",
538
+ "validation_unavailable" to "Purchase validation is temporarily unavailable",
539
+ )
540
+ }
541
+ }