@app-swiss-knife/react-native-sdk 0.2.1 → 0.2.4

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 (26) hide show
  1. package/android/src/main/java/com/swissknife/crashreporting/SKCrashReportingModule.kt +9 -3
  2. package/android/vendor/java/com/appswissknife/context/DeviceContext.kt +1 -1
  3. package/android/vendor/java/com/appswissknife/net/IngestClient.kt +1 -1
  4. package/android/vendor/java/com/appswissknife/purchases/BillingClientGateway.kt +106 -16
  5. package/ios/SwissKnifeCrashReporting.swift +19 -3
  6. package/ios/vendor/SwissKnifeiOS/Context/DeviceContext.swift +1 -1
  7. package/ios/vendor/SwissKnifeiOS/CrashReporting/SKCrashReporting.swift +153 -6
  8. package/lib/commonjs/modules/crash-reporting.js +199 -15
  9. package/lib/commonjs/modules/crash-reporting.js.map +1 -1
  10. package/lib/commonjs/purchases.js +60 -6
  11. package/lib/commonjs/purchases.js.map +1 -1
  12. package/lib/module/modules/crash-reporting.js +199 -15
  13. package/lib/module/modules/crash-reporting.js.map +1 -1
  14. package/lib/module/purchases.js +60 -7
  15. package/lib/module/purchases.js.map +1 -1
  16. package/lib/typescript/commonjs/modules/crash-reporting.d.ts +89 -0
  17. package/lib/typescript/commonjs/modules/crash-reporting.d.ts.map +1 -1
  18. package/lib/typescript/commonjs/purchases.d.ts +32 -1
  19. package/lib/typescript/commonjs/purchases.d.ts.map +1 -1
  20. package/lib/typescript/module/modules/crash-reporting.d.ts +89 -0
  21. package/lib/typescript/module/modules/crash-reporting.d.ts.map +1 -1
  22. package/lib/typescript/module/purchases.d.ts +32 -1
  23. package/lib/typescript/module/purchases.d.ts.map +1 -1
  24. package/package.json +1 -1
  25. package/src/modules/crash-reporting.ts +297 -25
  26. package/src/purchases.ts +65 -7
@@ -44,9 +44,8 @@ class SKCrashReportingModule(
44
44
  val environment = config.getString("environment") ?: "production"
45
45
  val release = config.getString("release")
46
46
 
47
- // Mirror the iOS bridge (SwissKnifeCrashReporting.swift), which calls
48
- // SwissKnife.configure(apiKey:proxyURL:) before SKCrashReporting.start
49
- // so IngestClient has an api key + base URL. Without this,
47
+ // Seed the observability backend before SKCrashReporting.start so
48
+ // IngestClient has an api key + base URL. Without this,
50
49
  // IngestClient.shared stays null and the Kotlin crash path
51
50
  // (flushEventQueue / sendEventPayload / sendSessionEvent) silently
52
51
  // falls back to the legacy /api/sdk/errors/* HTTP endpoints.
@@ -55,6 +54,13 @@ class SKCrashReportingModule(
55
54
  // BackendHttpClient + IngestClient + Session/Clock/Reachability with
56
55
  // the same apiKey/serverURL params — without dragging in the
57
56
  // purchases/billing engine as a side effect of crash init.
57
+ //
58
+ // The iOS bridge (SwissKnifeCrashReporting.swift) now does the same.
59
+ // It used to call SwissKnife.configure(apiKey:proxyURL:), which also
60
+ // ran configurePurchases and therefore started the process-wide
61
+ // StoreKit.Transaction.updates observer — so on iOS, turning on crash
62
+ // reporting silently took ownership of the store. Keep the two
63
+ // bridges in lockstep: crash init wires CORE only, never purchases.
58
64
  try {
59
65
  SwissKnife.ensureObservabilityBackend(
60
66
  reactApplicationContext.applicationContext,
@@ -42,7 +42,7 @@ internal object DeviceContextProvider {
42
42
  * eventually inject this via `BuildConfig`, but for now keep it in
43
43
  * source so we don't have to thread build settings through every test.
44
44
  */
45
- const val SDK_VERSION: String = "0.2.1"
45
+ const val SDK_VERSION: String = "0.2.4"
46
46
 
47
47
  private val cacheLock = Any()
48
48
 
@@ -208,7 +208,7 @@ internal object IngestPlaceholderDevice {
208
208
  appBuild = "unknown",
209
209
  locale = Locale.getDefault().toString(),
210
210
  timezone = TimeZone.getDefault().id,
211
- sdkVersion = "0.2.1",
211
+ sdkVersion = "0.2.4",
212
212
  bundleIdentifier = null,
213
213
  )
214
214
  }
@@ -378,26 +378,77 @@ class BillingClientGateway(
378
378
  if (purchases.isNullOrEmpty()) {
379
379
  pending?.onError?.invoke(PurchasesError.PurchaseInvalid("Empty purchases list"), false); return
380
380
  }
381
- val purchase = purchases.firstOrNull { p ->
381
+
382
+ // Which purchase (if any) is the one the in-flight call asked for.
383
+ //
384
+ // There is deliberately NO `?: purchases.first()` fallback here. Play's
385
+ // PurchasesUpdatedListener is a single global callback that also delivers
386
+ // purchases we never started — promo-code redemptions, purchases completed
387
+ // on another device or in the Play Store app, deferred purchases that
388
+ // later clear. The old fallback picked an arbitrary entry out of that list
389
+ // and then (a) validated it against the PENDING call's product id, pairing
390
+ // one product's id with another purchase's token, (b) acknowledged it, and
391
+ // (c) reported it back to the caller as the purchase it had requested.
392
+ // Same shape as the StoreKit `finish()` race: acting on a transaction that
393
+ // is not the one in flight.
394
+ val matched = purchases.firstOrNull { p ->
382
395
  pending != null && pending.productId in p.products
383
- } ?: purchases.first()
396
+ }
397
+
384
398
  executor.execute {
385
- try {
386
- validatePurchaseWithBackend(pending?.productId ?: purchase.products.first(), purchase.purchaseToken)
387
- if (!purchase.isAcknowledged) acknowledge(purchase)
388
- val repo = entitlementsRepo
389
- val info = runCatching { repo?.refresh(emptySet()) }.getOrNull()
390
- ?: repo?.current()
391
- ?: emptyCustomerInfo()
392
- pending?.onSuccess?.invoke(
393
- StoreTransactionResult(
394
- transaction = purchase.toStoreTransaction(),
395
- customerInfo = info,
396
- )
399
+ // Every purchase Play just handed us still needs validating and
400
+ // acknowledging with ITS OWN product ids — an unacknowledged Play
401
+ // purchase is auto-refunded after three days, so silently dropping the
402
+ // out-of-band ones would be its own bug. What must never happen is
403
+ // attributing one of them to a request that did not produce it.
404
+ var matchedFailure: Exception? = null
405
+ for (p in purchases) {
406
+ try {
407
+ for (productId in p.products) {
408
+ validatePurchaseWithBackend(productId, p.purchaseToken)
409
+ }
410
+ if (!p.isAcknowledged) acknowledge(p)
411
+ } catch (e: Exception) {
412
+ if (p === matched) {
413
+ matchedFailure = e
414
+ } else {
415
+ // Out-of-band purchase: no caller to surface this to. The backend
416
+ // reconciles via RTDN, and restorePurchases()/the next launch
417
+ // retries. Log rather than hijack the in-flight call's callbacks.
418
+ Log.w(TAG, "validate/acknowledge failed for an out-of-band purchase", e)
419
+ }
420
+ }
421
+ }
422
+
423
+ if (pending == null) return@execute
424
+
425
+ if (matched == null) {
426
+ // Play reported OK with a non-empty list, but nothing in it is the
427
+ // product we launched the flow for. Fail the call instead of handing
428
+ // back somebody else's transaction.
429
+ pending.onError(
430
+ PurchasesError.PurchaseInvalid(
431
+ "Play returned no purchase for ${pending.productId}"
432
+ ),
433
+ false,
397
434
  )
398
- } catch (e: Exception) {
399
- pending?.onError?.invoke(toPurchasesError(e), false)
435
+ return@execute
436
+ }
437
+ if (matchedFailure != null) {
438
+ pending.onError(toPurchasesError(matchedFailure), false)
439
+ return@execute
400
440
  }
441
+
442
+ val repo = entitlementsRepo
443
+ val info = runCatching { repo?.refresh(emptySet()) }.getOrNull()
444
+ ?: repo?.current()
445
+ ?: emptyCustomerInfo()
446
+ pending.onSuccess(
447
+ StoreTransactionResult(
448
+ transaction = matched.toStoreTransaction(),
449
+ customerInfo = info,
450
+ )
451
+ )
401
452
  }
402
453
  }
403
454
 
@@ -462,7 +513,46 @@ class BillingClientGateway(
462
513
  )
463
514
  }
464
515
 
516
+ /**
517
+ * Test seam — records acknowledgements without a live [BillingClient].
518
+ * Production leaves this null and goes through Play. It exists because the
519
+ * "acknowledge only the purchase actually in flight" invariant is otherwise
520
+ * unobservable from a unit test: [acknowledge] is fire-and-forget and
521
+ * returns early when [billingClient] is null.
522
+ */
523
+ @VisibleForTesting
524
+ internal var acknowledgeOverrideForTesting: ((Purchase) -> Unit)? = null
525
+
526
+ /**
527
+ * Test seam — install an in-flight purchase without a live [BillingClient].
528
+ * [purchaseStoreProduct] cannot run off-device (it needs Play to answer
529
+ * queryProductDetailsAsync), so this is the only way to exercise
530
+ * [onPurchasesUpdated]'s routing from a unit test. Sets exactly the same
531
+ * field the production path sets.
532
+ */
533
+ @VisibleForTesting
534
+ internal fun setPendingPurchaseForTesting(
535
+ productId: String,
536
+ onSuccess: (StoreTransactionResult) -> Unit,
537
+ onError: (PurchasesError, Boolean) -> Unit,
538
+ ) {
539
+ pendingPurchase = PendingPurchase(productId, onSuccess, onError)
540
+ }
541
+
542
+ /**
543
+ * Test seam — block until the gateway's single-threaded [executor] has
544
+ * drained. [onPurchasesUpdated] does its work there, so assertions need a
545
+ * join point. Returns false on timeout.
546
+ */
547
+ @VisibleForTesting
548
+ internal fun awaitExecutorForTesting(timeoutMs: Long = 5_000): Boolean {
549
+ val latch = java.util.concurrent.CountDownLatch(1)
550
+ executor.execute { latch.countDown() }
551
+ return latch.await(timeoutMs, java.util.concurrent.TimeUnit.MILLISECONDS)
552
+ }
553
+
465
554
  private fun acknowledge(purchase: Purchase) {
555
+ acknowledgeOverrideForTesting?.let { it(purchase); return }
466
556
  val client = billingClient ?: return
467
557
  val params = AcknowledgePurchaseParams.newBuilder()
468
558
  .setPurchaseToken(purchase.purchaseToken)
@@ -61,11 +61,27 @@ class SwissKnifeCrashReporting: NSObject {
61
61
  let tracesSampleRate = (config["tracesSampleRate"] as? Double) ?? 1.0
62
62
  let enableAutoSessionTracking = (config["enableAutoSessionTracking"] as? Bool) ?? true
63
63
 
64
- // Configure the top-level SDK so IngestClient has an api key + base URL
64
+ // Wire the observability backend so IngestClient has an api key + base URL
65
65
  // for outgoing batches. CrashReporting layers on top of this.
66
- SwissKnife.configure(
66
+ //
67
+ // MUST NOT be `SwissKnife.configure(...)`. That entry point is
68
+ // `configureCore` + `configurePurchases`, and `configurePurchases` starts
69
+ // the process-wide `StoreKit.Transaction.updates` observer whose handler
70
+ // calls `transaction.finish()`. Enabling *crash reporting* would then race
71
+ // the host app's own IAP library (RevenueCat, hand-rolled StoreKit) to
72
+ // finish the same renewal — the exact bug the configureCore /
73
+ // configurePurchases split exists to prevent, re-armed through the back
74
+ // door. `ensureObservabilityBackend` is the public, idempotent entry point
75
+ // that seeds BackendHttpClient + IngestClient + Session/Reachability with
76
+ // the same apiKey/serverURL and marks CORE (not purchases) configured, so
77
+ // `SwissKnife.isConfigured` stays false and no StoreKit observer starts.
78
+ // Pinned by StoreOwnershipSeparationTests.
79
+ //
80
+ // Matches SwissKnifePurchases.configureObservability and the Android
81
+ // bridge (SKCrashReportingModule.kt), which both already do this.
82
+ SwissKnife.ensureObservabilityBackend(
67
83
  apiKey: apiKey,
68
- proxyURL: serverURL.isEmpty ? nil : serverURL
84
+ serverURL: serverURL.isEmpty ? nil : serverURL
69
85
  )
70
86
 
71
87
  let configuration = SKCrashReporting.Configuration(
@@ -99,7 +99,7 @@ internal enum DeviceContextProvider {
99
99
  /// Round A baseline. The build pipeline (`swiss-build`) will eventually
100
100
  /// inject this via `-D` flag, but for now keep it in source so we don't
101
101
  /// have to thread build settings through the SPM Package.swift.
102
- static let sdkVersionConstant: String = "0.2.1"
102
+ static let sdkVersionConstant: String = "0.2.4"
103
103
 
104
104
  private static let cacheLock = DispatchQueue(label: "com.swissknife.context.device")
105
105
  private static var cached: DeviceContext?
@@ -243,6 +243,108 @@ public final class SKCrashReporting {
243
243
  crashDirectory.appendingPathComponent("persisted-context.json")
244
244
  }()
245
245
 
246
+ // MARK: - Handler chaining state
247
+ //
248
+ // We are almost never the only crash reporter in the process. Sentry,
249
+ // Crashlytics, Bugsnag and hand-rolled handlers all install through the
250
+ // same two process-global slots: `NSSetUncaughtExceptionHandler` and
251
+ // `signal()`. Both are last-writer-wins. If we install without capturing
252
+ // and re-invoking what was there, whoever initialises last silently
253
+ // switches the other one off — the host ships two crash reporters and
254
+ // only ever sees crashes from one. Android already chains
255
+ // (`SKCrashReporting.kt` captures `Thread.getDefaultUncaughtExceptionHandler`
256
+ // and re-invokes it) and the RN JS layer chains through
257
+ // `_originalGlobalHandler`; iOS was the odd one out.
258
+ //
259
+ // Install-once is a hard requirement, not a nicety: a second `start(...)`
260
+ // would capture OUR OWN handler as "previous" and chain into infinite
261
+ // recursion at crash time.
262
+
263
+ /// The signals we install handlers for.
264
+ private static let handledSignals: [Int32] = [SIGABRT, SIGBUS, SIGFPE, SIGILL, SIGSEGV, SIGTRAP]
265
+
266
+ /// Slot count for `previousSignalHandlers`. `NSIG` is 32 on Darwin; the
267
+ /// buffer is indexed by raw signal number so it must cover all of them.
268
+ private static let signalSlotCount = 64
269
+
270
+ /// Whatever `NSSetUncaughtExceptionHandler` held before we overwrote it.
271
+ /// `nil` means "nobody else was installed".
272
+ private static var previousUncaughtExceptionHandler:
273
+ (@convention(c) (NSException) -> Void)?
274
+
275
+ /// Previous `signal()` dispositions, indexed by signal number.
276
+ ///
277
+ /// A raw C buffer, NOT a Swift `Array`: the signal handler reads this and
278
+ /// a `UnsafeMutablePointer` load compiles to a plain pointer dereference
279
+ /// with no bounds-check machinery, no retain/release, and no allocation.
280
+ /// Only *real* handler addresses are stored — `SIG_DFL` (0), `SIG_IGN` (1)
281
+ /// and `SIG_ERR` (-1) are sentinels, not callable addresses, and are
282
+ /// filtered out at install time so the handler never has to reason about
283
+ /// them.
284
+ ///
285
+ /// The `static let` itself is lazily initialised via `swift_once`, which
286
+ /// is not formally async-signal-safe. It is forced during
287
+ /// `installSignalHandlers()`, i.e. strictly before any handler can be
288
+ /// entered, so by the time a signal arrives the once-token is already
289
+ /// satisfied and the access degrades to an atomic load + branch.
290
+ private static let previousSignalHandlers: UnsafeMutablePointer<sig_t?> = {
291
+ let buffer = UnsafeMutablePointer<sig_t?>.allocate(capacity: signalSlotCount)
292
+ buffer.initialize(repeating: nil, count: signalSlotCount)
293
+ return buffer
294
+ }()
295
+
296
+ /// Install-once guard for both global handler slots.
297
+ private static var crashHandlersInstalled = false
298
+
299
+ /// Sentinel bit patterns that `signal()` can return but that are not
300
+ /// callable: `SIG_DFL` = 0, `SIG_IGN` = 1, `SIG_ERR` = -1.
301
+ internal static func isCallableSignalHandler(_ handler: sig_t?) -> Bool {
302
+ guard let handler else { return false }
303
+ let raw = unsafeBitCast(handler, to: UInt.self)
304
+ return raw > 1 && raw != UInt.max
305
+ }
306
+
307
+ /// Invoke the handler that was installed for `signum` before us, if any.
308
+ ///
309
+ /// Called from inside the signal handler, AFTER our own async-signal-safe
310
+ /// marker + backtrace writes have completed — we may not get control back.
311
+ /// Whether the incumbent's handler is itself async-signal-safe is its
312
+ /// problem, not ours; not calling it is strictly worse (it reports
313
+ /// nothing at all).
314
+ ///
315
+ /// Split out of the handler body so it is directly testable: a test can
316
+ /// install a recording disposition, run `start(...)`, and call this — no
317
+ /// need to raise a real fatal signal inside the test process.
318
+ @discardableResult
319
+ internal static func chainPreviousSignalHandler(_ signum: Int32) -> Bool {
320
+ guard signum >= 0, Int(signum) < signalSlotCount else { return false }
321
+ guard let previous = previousSignalHandlers[Int(signum)] else { return false }
322
+ previous(signum)
323
+ return true
324
+ }
325
+
326
+ /// Test seam — drops the install-once guard and every captured handler so
327
+ /// a test can re-run `start(...)` from a known state. Production code MUST
328
+ /// NOT call this: it re-arms the self-chaining recursion the guard exists
329
+ /// to prevent.
330
+ internal static func _resetCrashHandlerInstallStateForTesting() {
331
+ crashHandlersInstalled = false
332
+ previousUncaughtExceptionHandler = nil
333
+ for i in 0..<signalSlotCount { previousSignalHandlers[i] = nil }
334
+ }
335
+
336
+ /// Test seam — what we captured for `signum` at install time.
337
+ internal static func _previousSignalHandlerForTesting(_ signum: Int32) -> sig_t? {
338
+ guard signum >= 0, Int(signum) < signalSlotCount else { return nil }
339
+ return previousSignalHandlers[Int(signum)]
340
+ }
341
+
342
+ /// Test seam — what we captured for the NSException slot at install time.
343
+ internal static func _previousUncaughtExceptionHandlerForTesting()
344
+ -> (@convention(c) (NSException) -> Void)? {
345
+ previousUncaughtExceptionHandler
346
+ }
347
+
246
348
  /// Pre-allocated C string path for signal handler (no Swift allocation at crash time)
247
349
  private static var signalMarkerPathCString: [CChar] = []
248
350
  /// Pre-allocated C string path for backtrace binary file (signal handler writes raw addresses here)
@@ -285,9 +387,20 @@ public final class SKCrashReporting {
285
387
  }
286
388
  }
287
389
 
288
- // Install handlers
289
- installUncaughtExceptionHandler()
290
- installSignalHandlers()
390
+ // Install handlers — exactly once per process. A second pass would
391
+ // capture OUR OWN handlers as "previous" and chain into infinite
392
+ // recursion the next time the app crashes. `start(...)` is otherwise
393
+ // safe to call repeatedly (config/breadcrumb capacity are re-applied
394
+ // above, recovery re-runs).
395
+ if !SKCrashReporting.crashHandlersInstalled {
396
+ SKCrashReporting.crashHandlersInstalled = true
397
+ installUncaughtExceptionHandler()
398
+ installSignalHandlers()
399
+ } else {
400
+ // Still refresh the on-disk context — the signal path can only
401
+ // recover what was persisted before the crash.
402
+ queue.async { [weak self] in self?.persistContextToDisk() }
403
+ }
291
404
 
292
405
  // Fix for the signal-path crashed-session gap: session context must
293
406
  // already be ON DISK when a signal fires (the handler is restricted
@@ -810,6 +923,13 @@ public final class SKCrashReporting {
810
923
  // MARK: - Crash Handlers
811
924
 
812
925
  private func installUncaughtExceptionHandler() {
926
+ // Capture the incumbent BEFORE overwriting the slot, so a host that
927
+ // already runs Sentry/Crashlytics keeps reporting NSExceptions. See
928
+ // the "Handler chaining state" block above for why install-once is
929
+ // load-bearing: capturing our own handler as "previous" recurses.
930
+ SKCrashReporting.previousUncaughtExceptionHandler =
931
+ NSGetUncaughtExceptionHandler()
932
+
813
933
  NSSetUncaughtExceptionHandler { exception in
814
934
  let reporting = SKCrashReporting.shared
815
935
  var event = SKErrorEvent(level: .fatal)
@@ -826,6 +946,11 @@ public final class SKCrashReporting {
826
946
  reporting.writeCrashToDisk(event)
827
947
  // Mark session as crashed
828
948
  reporting.sendSessionEvent(status: "crashed")
949
+
950
+ // Chain LAST — our own record is safely on disk first, and the
951
+ // incumbent handler may not return (Crashlytics et al. commonly
952
+ // re-raise or abort from here).
953
+ SKCrashReporting.previousUncaughtExceptionHandler?(exception)
829
954
  }
830
955
  }
831
956
 
@@ -833,13 +958,21 @@ public final class SKCrashReporting {
833
958
  // Persist initial context so there is something on disk for signal recovery
834
959
  queue.async { [weak self] in self?.persistContextToDisk() }
835
960
 
836
- let signals = [SIGABRT, SIGBUS, SIGFPE, SIGILL, SIGSEGV, SIGTRAP]
837
- for sig in signals {
838
- signal(sig) { signum in
961
+ // Force the lazy `static let` allocation now, on a normal thread, so
962
+ // the signal handler's read of it never has to run `swift_once`'s
963
+ // slow path (see the declaration comment).
964
+ _ = SKCrashReporting.previousSignalHandlers
965
+
966
+ for sig in SKCrashReporting.handledSignals {
967
+ let previous = signal(sig) { signum in
839
968
  // ASYNC-SIGNAL-SAFE: only POSIX write(), open(), close(), backtrace().
840
969
  // No Swift objects, no ObjC, no malloc.
841
970
  let path = SKCrashReporting.signalMarkerPathCString
842
971
  guard !path.isEmpty else {
972
+ // Nothing of ours to write, but the incumbent handler
973
+ // still deserves its turn before we fall through to the
974
+ // default disposition.
975
+ SKCrashReporting.chainPreviousSignalHandler(signum)
843
976
  signal(signum, SIG_DFL)
844
977
  raise(signum)
845
978
  return
@@ -907,10 +1040,24 @@ public final class SKCrashReporting {
907
1040
  }
908
1041
  }
909
1042
 
1043
+ // Hand off to whoever owned this signal before us (Sentry,
1044
+ // Crashlytics, a host's own handler) so they still record the
1045
+ // crash. Deliberately after our writes: it may never return.
1046
+ SKCrashReporting.chainPreviousSignalHandler(signum)
1047
+
910
1048
  // Re-raise to allow OS crash reporter to run
911
1049
  signal(signum, SIG_DFL)
912
1050
  raise(signum)
913
1051
  }
1052
+
1053
+ // `signal()` returns the disposition we just displaced. Store only
1054
+ // real, callable addresses — SIG_DFL / SIG_IGN / SIG_ERR are
1055
+ // sentinels, and "default" / "ignore" are exactly what the
1056
+ // `signal(signum, SIG_DFL); raise(signum)` tail already produces.
1057
+ if SKCrashReporting.isCallableSignalHandler(previous),
1058
+ sig >= 0, Int(sig) < SKCrashReporting.signalSlotCount {
1059
+ SKCrashReporting.previousSignalHandlers[Int(sig)] = previous
1060
+ }
914
1061
  }
915
1062
  }
916
1063