@app-swiss-knife/react-native-sdk 0.5.1 → 0.6.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 (36) hide show
  1. package/CHANGELOG.md +77 -2
  2. package/README.md +19 -8
  3. package/android/vendor/java/com/appswissknife/context/DeviceContext.kt +1 -1
  4. package/android/vendor/java/com/appswissknife/net/IngestClient.kt +1 -1
  5. package/ios/SwissKnifePurchases.swift +9 -1
  6. package/ios/vendor/SwissKnifeiOS/Context/DeviceContext.swift +1 -1
  7. package/ios/vendor/SwissKnifeiOS/Identity/Identity.swift +7 -0
  8. package/ios/vendor/SwissKnifeiOS/Net/IngestClient.swift +2 -3
  9. package/ios/vendor/SwissKnifeiOS/Services/EntitlementSync.swift +104 -0
  10. package/ios/vendor/SwissKnifeiOS/Services/IntroEligibility.swift +137 -0
  11. package/ios/vendor/SwissKnifeiOS/Services/PurchaseService.swift +368 -52
  12. package/ios/vendor/SwissKnifeiOS/Services/TransactionEvents.swift +371 -0
  13. package/ios/vendor/SwissKnifeiOS/SwissKnife.swift +73 -8
  14. package/ios-notification-service/SwissKnifeNotificationService.podspec +1 -1
  15. package/lib/commonjs/internal/config.js +3 -0
  16. package/lib/commonjs/internal/config.js.map +1 -1
  17. package/lib/commonjs/native/spec.js.map +1 -1
  18. package/lib/commonjs/types.js.map +1 -1
  19. package/lib/module/internal/config.js +3 -0
  20. package/lib/module/internal/config.js.map +1 -1
  21. package/lib/module/native/spec.js.map +1 -1
  22. package/lib/module/types.js.map +1 -1
  23. package/lib/typescript/commonjs/internal/config.d.ts.map +1 -1
  24. package/lib/typescript/commonjs/native/spec.d.ts +2 -0
  25. package/lib/typescript/commonjs/native/spec.d.ts.map +1 -1
  26. package/lib/typescript/commonjs/types.d.ts +13 -0
  27. package/lib/typescript/commonjs/types.d.ts.map +1 -1
  28. package/lib/typescript/module/internal/config.d.ts.map +1 -1
  29. package/lib/typescript/module/native/spec.d.ts +2 -0
  30. package/lib/typescript/module/native/spec.d.ts.map +1 -1
  31. package/lib/typescript/module/types.d.ts +13 -0
  32. package/lib/typescript/module/types.d.ts.map +1 -1
  33. package/package.json +1 -1
  34. package/src/internal/config.ts +3 -0
  35. package/src/native/spec.ts +4 -0
  36. package/src/types.ts +13 -0
@@ -29,6 +29,26 @@
29
29
  // We intentionally do NOT tear it down on logout — Apple recommends a single
30
30
  // observer per process to avoid missing updates that arrive during the
31
31
  // re-init gap.
32
+ //
33
+ // Silent sync
34
+ // -----------
35
+ // `syncCurrentEntitlements()` posts the verified `Transaction.currentEntitlements`
36
+ // the backend has not yet accepted for the current subject (a fingerprint
37
+ // ledger on disk remembers which it has), WITHOUT `AppStore.sync()`, so it
38
+ // never shows UI. It runs by itself, debounced and throttled, after configure
39
+ // and after `Identity.logIn` (`PurchasesConfiguration.syncEntitlementsAutomatically`).
40
+ // Every sync post carries `silent_sync: true`: the backend records what is
41
+ // the current user's and never moves (or shares) a purchase it holds for
42
+ // another user, whatever the app's transfer setting, answering
43
+ // `owned_elsewhere` instead. Only `restorePurchases()` (and a purchase) posts
44
+ // without it, so only a Restore button applies the transfer setting.
45
+ //
46
+ // Transaction events
47
+ // ------------------
48
+ // Every transaction this service posts is reported to
49
+ // `SwissKnife.addTransactionObserver` / `transactionEvents` once the backend
50
+ // answered (see `TransactionEvents.swift`), after `finish()` and without
51
+ // waiting for the observers.
32
52
 
33
53
  import Foundation
34
54
  import StoreKit
@@ -41,12 +61,15 @@ public final class PurchaseService {
41
61
  public static let shared = PurchaseService()
42
62
 
43
63
  private let log = OSLog(subsystem: "com.swissknife", category: "purchase")
64
+ private static let staticLog = OSLog(subsystem: "com.swissknife", category: "purchase")
44
65
  private let queue = DispatchQueue(label: "com.swissknife.purchase")
45
66
 
46
67
  // MARK: Configuration
47
68
 
48
69
  private var serverURL: String?
49
70
  private var apiKey: String?
71
+ private var settings = SwissKnife.PurchasesConfiguration()
72
+ private var engineConfigured = false
50
73
 
51
74
  // MARK: Network seam
52
75
 
@@ -72,6 +95,51 @@ public final class PurchaseService {
72
95
  }
73
96
  }
74
97
 
98
+ /// The verified `Transaction.currentEntitlements`, as restore and sync
99
+ /// post them. Tests replace it (StoreKit transactions cannot be built
100
+ /// outside a StoreKit session).
101
+ internal var currentEntitlementsSource: () async -> [EntitlementCandidate] =
102
+ PurchaseService.defaultCurrentEntitlements
103
+
104
+ private static let defaultCurrentEntitlements: () async -> [EntitlementCandidate] = {
105
+ guard #available(iOS 15.0, macOS 12.0, *) else { return [] }
106
+ var candidates: [EntitlementCandidate] = []
107
+ for await result in StoreKit.Transaction.currentEntitlements {
108
+ switch result {
109
+ case .verified(let transaction):
110
+ candidates.append(EntitlementCandidate(
111
+ facts: TransactionFacts(transaction),
112
+ jws: result.jwsRepresentation
113
+ ))
114
+ case .unverified(let transaction, let error):
115
+ os_log(
116
+ "PurchaseService: skipping unverified transaction productId=%{public}@ (%{public}@)",
117
+ log: PurchaseService.staticLog,
118
+ type: .info,
119
+ transaction.productID,
120
+ String(describing: error)
121
+ )
122
+ }
123
+ }
124
+ return candidates
125
+ }
126
+
127
+ /// Which transactions the backend already accepted for which subject.
128
+ internal var ledger = SyncedTransactionLedger()
129
+
130
+ // MARK: Automatic sync state (guarded by `queue`)
131
+
132
+ /// Debounce before an automatic sync runs: a configure followed at once
133
+ /// by a `logIn` syncs for the signed-in user only.
134
+ internal var automaticSyncDelay: TimeInterval = 1.0
135
+ /// An automatic sync for the same subject runs at most this often.
136
+ internal var automaticSyncMinimumInterval: TimeInterval = 60
137
+ private var pendingAutomaticSync: Task<Void, Never>?
138
+ private var lastAutomaticSync: [String: Date] = [:]
139
+ private var automaticSyncRuns = 0
140
+ /// The sync in flight, so overlapping syncs run one after another.
141
+ private var syncTail: Task<SyncOutcome, Never>?
142
+
75
143
  // MARK: Transaction.updates observer
76
144
 
77
145
  private var observerTask: Task<Void, Never>?
@@ -102,12 +170,23 @@ public final class PurchaseService {
102
170
  queue.sync { observerTask != nil }
103
171
  }
104
172
 
173
+ /// Automatic syncs that actually ran (past the debounce and throttle).
174
+ internal var automaticSyncRunCountForTesting: Int {
175
+ queue.sync { automaticSyncRuns }
176
+ }
177
+
105
178
  // MARK: Configure
106
179
 
107
- internal func configure(serverURL: String?, apiKey: String) {
180
+ internal func configure(
181
+ serverURL: String?,
182
+ apiKey: String,
183
+ settings: SwissKnife.PurchasesConfiguration = .init()
184
+ ) {
108
185
  queue.sync {
109
186
  self.serverURL = (serverURL?.isEmpty == true) ? nil : serverURL
110
187
  self.apiKey = apiKey
188
+ self.settings = settings
189
+ self.engineConfigured = true
111
190
  }
112
191
  startObservingTransactionUpdates()
113
192
  }
@@ -140,8 +219,19 @@ public final class PurchaseService {
140
219
  observerStartCount = 0
141
220
  serverURL = nil
142
221
  apiKey = nil
222
+ settings = SwissKnife.PurchasesConfiguration()
223
+ engineConfigured = false
143
224
  http = BackendHttpClient.shared
144
225
  syncWithAppStore = PurchaseService.defaultAppStoreSync
226
+ currentEntitlementsSource = PurchaseService.defaultCurrentEntitlements
227
+ ledger = SyncedTransactionLedger()
228
+ pendingAutomaticSync?.cancel()
229
+ pendingAutomaticSync = nil
230
+ lastAutomaticSync = [:]
231
+ automaticSyncRuns = 0
232
+ automaticSyncDelay = 1.0
233
+ automaticSyncMinimumInterval = 60
234
+ syncTail = nil
145
235
  }
146
236
  }
147
237
 
@@ -150,16 +240,29 @@ public final class PurchaseService {
150
240
  /// Purchase a package (i.e. a Product behind a specific offering). The
151
241
  /// flow is: look up the underlying StoreKit `Product`, call `purchase()`,
152
242
  /// validate the resulting JWS with our backend, refresh the cache.
243
+ ///
244
+ /// `appAccountToken` is attached to the StoreKit purchase. When nil, the
245
+ /// current app user id is used if it is a UUID (see
246
+ /// `PurchasesConfiguration.automaticAppAccountToken`).
153
247
  @available(iOS 15.0, macOS 12.0, *)
154
- public func purchase(package: Package) async throws -> SwissKnife.PurchaseResult {
155
- try await purchase(productIdentifier: package.storeProduct.productIdentifier)
248
+ public func purchase(
249
+ package: Package,
250
+ appAccountToken: UUID? = nil
251
+ ) async throws -> SwissKnife.PurchaseResult {
252
+ try await purchase(
253
+ productIdentifier: package.storeProduct.productIdentifier,
254
+ appAccountToken: appAccountToken
255
+ )
156
256
  }
157
257
 
158
258
  /// Purchase a single product by identifier. Used by the package-based and
159
259
  /// product-based paths alike — the package layer is just a paywall-grouping
160
260
  /// concern on top of a `StoreProduct`.
161
261
  @available(iOS 15.0, macOS 12.0, *)
162
- public func purchase(productIdentifier: String) async throws -> SwissKnife.PurchaseResult {
262
+ public func purchase(
263
+ productIdentifier: String,
264
+ appAccountToken: UUID? = nil
265
+ ) async throws -> SwissKnife.PurchaseResult {
163
266
  // 1) Resolve the StoreKit Product. `Product.products(for:)` returns
164
267
  // empty on unknown IDs rather than throwing; we surface the
165
268
  // typed PurchasesError so callers don't have to special-case.
@@ -168,11 +271,16 @@ public final class PurchaseService {
168
271
  throw PurchasesError.productNotAvailable
169
272
  }
170
273
 
274
+ var options: Set<Product.PurchaseOption> = []
275
+ if let token = resolveAppAccountToken(explicit: appAccountToken) {
276
+ options.insert(.appAccountToken(token))
277
+ }
278
+
171
279
  // 2) Kick off StoreKit's purchase sheet. The sheet itself is OS-
172
280
  // owned; we await whatever it returns.
173
281
  let result: Product.PurchaseResult
174
282
  do {
175
- result = try await product.purchase()
283
+ result = try await product.purchase(options: options)
176
284
  } catch {
177
285
  throw mapStoreKitPurchaseError(error)
178
286
  }
@@ -189,6 +297,14 @@ public final class PurchaseService {
189
297
  }
190
298
  }
191
299
 
300
+ /// The `appAccountToken` a purchase carries: the caller's, else the
301
+ /// current user id when it is a UUID and automatic tokens are on.
302
+ internal func resolveAppAccountToken(explicit: UUID?) -> UUID? {
303
+ if let explicit { return explicit }
304
+ let automatic = queue.sync { settings.automaticAppAccountToken }
305
+ return automatic ? SwissKnife.defaultAppAccountToken() : nil
306
+ }
307
+
192
308
  /// Restore prior purchases. Asks the App Store to sync first (a new
193
309
  /// device or a changed Apple ID may not have the transactions locally
194
310
  /// yet), then iterates `Transaction.currentEntitlements`, POSTs each
@@ -198,33 +314,21 @@ public final class PurchaseService {
198
314
  @available(iOS 15.0, macOS 12.0, *)
199
315
  public func restorePurchases() async throws -> CustomerInfo {
200
316
  await syncWithAppStore()
201
- var anyValidated = false
202
- for await result in StoreKit.Transaction.currentEntitlements {
203
- let jws = result.jwsRepresentation
204
- switch result {
205
- case .verified(let transaction):
206
- do {
207
- try await validateTransactionWithBackend(transaction, jws: jws)
208
- anyValidated = true
209
- } catch {
210
- os_log(
211
- "PurchaseService: backend validation failed during restore for productId=%{public}@: %{public}@",
212
- log: log,
213
- type: .error,
214
- transaction.productID,
215
- String(describing: error)
216
- )
217
- // Continue with the rest — one failure should not
218
- // abort the whole restore.
219
- }
220
- case .unverified(let transaction, let error):
317
+ for candidate in await currentEntitlementsSource() {
318
+ do {
319
+ try await post(candidate.facts, jws: candidate.jws)
320
+ emit(candidate.facts.event(kind: .restore, serverConfirmed: true))
321
+ } catch {
221
322
  os_log(
222
- "PurchaseService: skipping unverified transaction productId=%{public}@ (%{public}@)",
323
+ "PurchaseService: backend validation failed during restore for productId=%{public}@: %{public}@",
223
324
  log: log,
224
- type: .info,
225
- transaction.productID,
325
+ type: .error,
326
+ candidate.facts.productId,
226
327
  String(describing: error)
227
328
  )
329
+ emit(candidate.facts.event(kind: .restore, serverConfirmed: false))
330
+ // Continue with the rest — one failure should not
331
+ // abort the whole restore.
228
332
  }
229
333
  }
230
334
  // Always end with a refresh so the cache reflects whatever the
@@ -232,16 +336,147 @@ public final class PurchaseService {
232
336
  // to validate, we want to surface the latest server-side state.
233
337
  // No invalidate() first: refresh() replaces the snapshot only on
234
338
  // success, so a restore on a bad connection keeps the entitlements
235
- // the user already had instead of wiping them.
236
- if anyValidated {
237
- return try await EntitlementsService.shared.refresh()
339
+ // the user already had instead of wiping them. With nothing to
340
+ // restore this matches RC's "restore returns CustomerInfo even when
341
+ // empty" shape, and a refresh error bubbles up.
342
+ return try await EntitlementsService.shared.refresh()
343
+ }
344
+
345
+ // MARK: Public API — silent sync
346
+
347
+ /// Post the device's current entitlements that the backend has not
348
+ /// accepted for the current user yet, and return `CustomerInfo`.
349
+ ///
350
+ /// Never calls `AppStore.sync()`, so it never shows the Apple ID sheet;
351
+ /// keep `restorePurchases()` for a Restore button. With nothing new it
352
+ /// sends no transaction and answers from the cache (refreshing only when
353
+ /// there is none). A transaction the backend could not accept is
354
+ /// reported (`TransactionEvent.serverConfirmed == false`) and posted
355
+ /// again by the next sync. A purchase the backend holds for another user
356
+ /// stays with them (the sync never moves one) and is reported with
357
+ /// `TransactionEvent.ownedByAnotherUser`.
358
+ @available(iOS 15.0, macOS 12.0, *)
359
+ public func syncCurrentEntitlements() async throws -> CustomerInfo {
360
+ let outcome = await runSync(automatic: false)
361
+ if outcome.accepted == 0, let cached = EntitlementsService.shared.current() {
362
+ return cached
238
363
  }
239
- // No transactions to restore — fall back to whatever the cache /
240
- // refresh says. We let the cache's own error path bubble up; that
241
- // matches RC's "restore returns CustomerInfo even when empty" shape.
242
364
  return try await EntitlementsService.shared.refresh()
243
365
  }
244
366
 
367
+ /// Schedule the automatic sync (configure, logIn). A newer trigger
368
+ /// replaces one still waiting out the debounce; a subject synced within
369
+ /// `automaticSyncMinimumInterval` is skipped.
370
+ internal func scheduleAutomaticSync(trigger: AutomaticSyncTrigger) {
371
+ queue.sync {
372
+ guard engineConfigured, settings.syncEntitlementsAutomatically else { return }
373
+ pendingAutomaticSync?.cancel()
374
+ let delay = automaticSyncDelay
375
+ pendingAutomaticSync = Task { [weak self] in
376
+ if delay > 0 {
377
+ try? await Task.sleep(nanoseconds: UInt64(delay * 1_000_000_000))
378
+ }
379
+ guard !Task.isCancelled, let self else { return }
380
+ // A login still resolving will sync for its user when it
381
+ // lands; syncing the anonymous subject now would only post
382
+ // what is about to move.
383
+ if trigger == .configure, SwissKnife.Identity._hasLogInInFlight { return }
384
+ guard self.claimAutomaticSync(subject: SwissKnife.backendSubjectId()) else { return }
385
+ if #available(iOS 15.0, macOS 12.0, *) {
386
+ let outcome = await self.runSync(automatic: true)
387
+ if outcome.accepted > 0 {
388
+ _ = try? await EntitlementsService.shared.refresh()
389
+ }
390
+ }
391
+ }
392
+ }
393
+ }
394
+
395
+ internal enum AutomaticSyncTrigger { case configure, logIn }
396
+
397
+ /// Throttle bookkeeping: true (and recorded) when `subject` may sync now.
398
+ private func claimAutomaticSync(subject: String) -> Bool {
399
+ queue.sync {
400
+ let now = Date()
401
+ if let last = lastAutomaticSync[subject],
402
+ now.timeIntervalSince(last) < automaticSyncMinimumInterval {
403
+ return false
404
+ }
405
+ lastAutomaticSync[subject] = now
406
+ automaticSyncRuns += 1
407
+ return true
408
+ }
409
+ }
410
+
411
+ internal struct SyncOutcome: Sendable {
412
+ var accepted = 0
413
+ var failed = 0
414
+ var skipped = 0
415
+ /// Transactions the backend holds for another user and left there.
416
+ var ownedByOtherUsers: [String] = []
417
+ }
418
+
419
+ /// One sync pass, after any pass already in flight (so two overlapping
420
+ /// syncs never post the same transaction twice).
421
+ @available(iOS 15.0, macOS 12.0, *)
422
+ internal func runSync(automatic: Bool) async -> SyncOutcome {
423
+ let task: Task<SyncOutcome, Never> = queue.sync {
424
+ let previous = syncTail
425
+ let next = Task { [weak self] () -> SyncOutcome in
426
+ _ = await previous?.value
427
+ guard let self else { return SyncOutcome() }
428
+ return await self.syncPass(automatic: automatic)
429
+ }
430
+ syncTail = next
431
+ return next
432
+ }
433
+ return await task.value
434
+ }
435
+
436
+ @available(iOS 15.0, macOS 12.0, *)
437
+ private func syncPass(automatic: Bool) async -> SyncOutcome {
438
+ var outcome = SyncOutcome()
439
+ let subject = SwissKnife.backendSubjectId()
440
+ let automaticTokens = queue.sync { settings.automaticAppAccountToken }
441
+ let ownToken = automatic && automaticTokens ? SwissKnife.defaultAppAccountToken() : nil
442
+ for candidate in await currentEntitlementsSource() {
443
+ let facts = candidate.facts
444
+ if ledger.contains(fingerprint(subject: subject, transactionId: facts.transactionId)) {
445
+ continue
446
+ }
447
+ // Bought by another account of this app on this Apple ID: an
448
+ // automatic sync does not post it for whoever is signed in now
449
+ // (the backend would leave a recorded one where it is anyway).
450
+ if let ownToken, let token = facts.appAccountToken, token != ownToken {
451
+ outcome.skipped += 1
452
+ continue
453
+ }
454
+ do {
455
+ switch try await post(facts, jws: candidate.jws, subject: subject, silentSync: true) {
456
+ case .recorded:
457
+ outcome.accepted += 1
458
+ emit(facts.event(kind: .sync, serverConfirmed: true))
459
+ case .ownedByAnotherUser:
460
+ // Not remembered: the next sync asks again, in case the
461
+ // purchase has changed hands since.
462
+ outcome.ownedByOtherUsers.append(facts.transactionId)
463
+ emit(facts.event(kind: .sync, serverConfirmed: false, ownedByAnotherUser: true))
464
+ }
465
+ } catch {
466
+ outcome.failed += 1
467
+ os_log(
468
+ "PurchaseService: sync could not post productId=%{public}@: %{public}@",
469
+ log: log,
470
+ type: .error,
471
+ facts.productId,
472
+ String(describing: error)
473
+ )
474
+ emit(facts.event(kind: .sync, serverConfirmed: false))
475
+ }
476
+ }
477
+ return outcome
478
+ }
479
+
245
480
  // MARK: Internals
246
481
 
247
482
  /// Final stage of a purchase: extract the verified transaction, POST
@@ -258,12 +493,19 @@ public final class PurchaseService {
258
493
  let jws = verification.jwsRepresentation
259
494
  switch verification {
260
495
  case .verified(let transaction):
496
+ let facts = TransactionFacts(transaction)
261
497
  // Validate against backend first. If the backend rejects the
262
498
  // receipt, we DO NOT finish the transaction — that gives Apple
263
499
  // a chance to redeliver on the next launch, and the user a
264
500
  // chance to retry. Only finish on validated success.
265
- try await validateTransactionWithBackend(transaction, jws: jws)
501
+ do {
502
+ try await post(facts, jws: jws)
503
+ } catch {
504
+ emit(facts.event(kind: .purchase, serverConfirmed: false))
505
+ throw error
506
+ }
266
507
  await transaction.finish()
508
+ emit(facts.event(kind: .purchase, serverConfirmed: true))
267
509
 
268
510
  let info = try await EntitlementsService.shared.refresh()
269
511
  let storeTx = StoreTransaction(
@@ -290,9 +532,11 @@ public final class PurchaseService {
290
532
  let jws = result.jwsRepresentation
291
533
  switch result {
292
534
  case .verified(let transaction):
535
+ let facts = TransactionFacts(transaction)
293
536
  do {
294
- try await validateTransactionWithBackend(transaction, jws: jws)
537
+ try await post(facts, jws: jws)
295
538
  await transaction.finish()
539
+ emit(facts.event(kind: facts.updateKind, serverConfirmed: true))
296
540
  await refreshEntitlementsAfterTransactionUpdate()
297
541
  } catch {
298
542
  os_log(
@@ -302,6 +546,8 @@ public final class PurchaseService {
302
546
  transaction.productID,
303
547
  String(describing: error)
304
548
  )
549
+ // Left unfinished, as before: StoreKit redelivers it.
550
+ emit(facts.event(kind: facts.updateKind, serverConfirmed: false))
305
551
  }
306
552
  case .unverified(let transaction, let error):
307
553
  os_log(
@@ -314,6 +560,11 @@ public final class PurchaseService {
314
560
  }
315
561
  }
316
562
 
563
+ /// Hand an event to the observers without waiting for them.
564
+ private func emit(_ event: SwissKnife.TransactionEvent) {
565
+ TransactionEventHub.shared.emit(event)
566
+ }
567
+
317
568
  /// Re-read entitlements after the backend accepted a `Transaction.updates`
318
569
  /// delivery (a renewal, a refund, a purchase from another device).
319
570
  ///
@@ -325,6 +576,46 @@ public final class PurchaseService {
325
576
  _ = try? await EntitlementsService.shared.refresh()
326
577
  }
327
578
 
579
+ private func fingerprint(subject: String, transactionId: String) -> String {
580
+ SyncedTransactionLedger.fingerprint(
581
+ apiKey: queue.sync { apiKey ?? "" },
582
+ subject: subject,
583
+ transactionId: transactionId
584
+ )
585
+ }
586
+
587
+ /// What the backend did with a posted transaction.
588
+ internal enum PostOutcome: Equatable {
589
+ /// Recorded for the subject (or already theirs).
590
+ case recorded
591
+ /// Silent sync only: held for another user and left with them.
592
+ case ownedByAnotherUser
593
+ }
594
+
595
+ /// POST one transaction and, once the backend recorded it for `subject`,
596
+ /// remember it so a sync does not send it again. `silentSync` marks a
597
+ /// sync's post: the backend then never moves a purchase another user
598
+ /// holds (`.ownedByAnotherUser`, not remembered).
599
+ @discardableResult
600
+ internal func post(
601
+ _ facts: TransactionFacts,
602
+ jws: String,
603
+ subject: String = SwissKnife.backendSubjectId(),
604
+ silentSync: Bool = false
605
+ ) async throws -> PostOutcome {
606
+ let outcome = try await validateTransactionWithBackend(
607
+ transactionId: facts.transactionId,
608
+ productId: facts.productId,
609
+ jws: jws,
610
+ userId: subject,
611
+ silentSync: silentSync
612
+ )
613
+ if outcome == .recorded {
614
+ ledger.insert(fingerprint(subject: subject, transactionId: facts.transactionId))
615
+ }
616
+ return outcome
617
+ }
618
+
328
619
  /// POST the JWS to our backend for receipt validation via
329
620
  /// `BackendHttpClient`. The client handles X-API-Key injection,
330
621
  /// 4xx-vs-5xx classification (backendRejected vs backendUnavailable),
@@ -333,20 +624,22 @@ public final class PurchaseService {
333
624
  /// We use `postRaw` because the validate body is hand-assembled from a
334
625
  /// `[String: Any]` (Mixed shapes — JWS string + ints + plain strings —
335
626
  /// don't model cleanly as a single Codable struct without a lossy
336
- /// intermediate). The response body is discarded; the caller only
337
- /// branches on success vs the typed errors.
338
- @available(iOS 15.0, macOS 12.0, *)
627
+ /// intermediate). Of the response only a silent sync's `owned_elsewhere`
628
+ /// is read; otherwise the caller branches on success vs the typed errors.
629
+ ///
630
+ /// `userId` is the effective subject id — single source of truth, shared
631
+ /// with EntitlementsService. NEVER the bare device id: see
632
+ /// `SwissKnife.backendSubjectId()` for why, and for why the previous
633
+ /// `appUserIDOrNil() ?? DeviceID.get()` shape leaked it on the
634
+ /// `configurePurchases`-without-`configureCore` path.
339
635
  private func validateTransactionWithBackend(
340
- _ transaction: StoreKit.Transaction,
341
- jws: String
342
- ) async throws {
343
- // Effective subject id — single source of truth, shared with
344
- // EntitlementsService. NEVER the bare device id: see
345
- // `SwissKnife.backendSubjectId()` for why, and for why the previous
346
- // `appUserIDOrNil() ?? DeviceID.get()` shape leaked it on the
347
- // `configurePurchases`-without-`configureCore` path.
348
- let userId = SwissKnife.backendSubjectId()
349
- let body: [String: Any] = [
636
+ transactionId: String,
637
+ productId: String,
638
+ jws: String,
639
+ userId: String,
640
+ silentSync: Bool
641
+ ) async throws -> PostOutcome {
642
+ var body: [String: Any] = [
350
643
  "user_id": userId,
351
644
  "platform": "ios",
352
645
  // The backend's `/api/sdk/subscriptions/validate` accepts
@@ -354,12 +647,28 @@ public final class PurchaseService {
354
647
  // the JWS IS the receipt — we send it through here, and the
355
648
  // store-validation layer treats it accordingly.
356
649
  "receipt_data": jws,
357
- "transaction_id": String(transaction.id),
358
- "product_id": transaction.productID,
650
+ "transaction_id": transactionId,
651
+ "product_id": productId,
359
652
  "jws": jws,
360
653
  ]
654
+ // Only a sync sends it: a purchase and a Restore button keep the
655
+ // app's transfer setting.
656
+ if silentSync { body["silent_sync"] = true }
361
657
  let data = try JSONSerialization.data(withJSONObject: body, options: [])
362
- _ = try await http.postRaw(path: "/api/sdk/subscriptions/validate", body: data)
658
+ let response = try await http.postRaw(path: "/api/sdk/subscriptions/validate", body: data)
659
+ guard silentSync else { return .recorded }
660
+ return Self.ownedElsewhere(in: response) ? .ownedByAnotherUser : .recorded
661
+ }
662
+
663
+ /// Whether a silent sync's answer says the posted transaction is held
664
+ /// for another user: `owned_elsewhere.count > 0`.
665
+ internal static func ownedElsewhere(in response: Data) -> Bool {
666
+ guard
667
+ let json = (try? JSONSerialization.jsonObject(with: response)) as? [String: Any],
668
+ let report = json["owned_elsewhere"] as? [String: Any],
669
+ let count = report["count"] as? Int
670
+ else { return false }
671
+ return count > 0
363
672
  }
364
673
 
365
674
  /// Map StoreKit's purchase-time error types to PurchasesError. SK2 uses
@@ -402,6 +711,13 @@ public final class PurchaseService {
402
711
  }
403
712
  }
404
713
 
714
+ /// A verified transaction from `Transaction.currentEntitlements`: what restore
715
+ /// and sync post.
716
+ internal struct EntitlementCandidate: Sendable {
717
+ var facts: TransactionFacts
718
+ var jws: String
719
+ }
720
+
405
721
  // MARK: - Bridge for StoreKit.VerificationResult
406
722
  //
407
723
  // `StoreKit.VerificationResult` collides with our public `VerificationResult`