@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,201 @@
1
+ // packages/swiss-knife-android/src/main/java/com/appswissknife/crashreporting/SKScreenshot.kt
2
+ //
3
+ // Masked screenshot capture for error-event attachments (wave-2 contract C1).
4
+ //
5
+ // Semantics (binding — the RN bridge and SDK jest mocks assume exactly this):
6
+ // - Callback receives a base64-encoded JPEG (NO `data:` prefix), longest
7
+ // side <= 1600px, quality ~0.7 — or null on ANY failure/timeout. The
8
+ // callback fires exactly once and never throws out of this object.
9
+ // - MASKED BY DEFAULT, non-configurable in v1: an opaque black rectangle is
10
+ // drawn over every EditText subclass (which covers RN's ReactEditText).
11
+ // TextViews/labels intentionally stay visible.
12
+ // - Must be invoked on the main thread (the view tree is walked and, on the
13
+ // PixelCopy path, the result is delivered on a main-looper Handler).
14
+ // - Budget: a ~150ms timeout races the capture; on overrun the callback
15
+ // fires with null and any late capture result is dropped.
16
+ //
17
+ // Capture strategy: PixelCopy.request(Window, ...) on API 26+ (captures the
18
+ // real composited surface, including SurfaceView content), falling back to
19
+ // View#draw on a software canvas when PixelCopy is unavailable or fails.
20
+
21
+ package com.appswissknife.crashreporting
22
+
23
+ import android.app.Activity
24
+ import android.graphics.Bitmap
25
+ import android.graphics.Canvas
26
+ import android.graphics.Color
27
+ import android.graphics.Paint
28
+ import android.graphics.Rect
29
+ import android.os.Build
30
+ import android.os.Handler
31
+ import android.os.Looper
32
+ import android.util.Base64
33
+ import android.view.PixelCopy
34
+ import android.view.View
35
+ import android.view.ViewGroup
36
+ import android.widget.EditText
37
+ import java.io.ByteArrayOutputStream
38
+ import java.util.concurrent.atomic.AtomicBoolean
39
+
40
+ object SKScreenshot {
41
+
42
+ /** Longest encoded side, in pixels. Contract C1 fixes this at 1600. */
43
+ const val MAX_LONGEST_SIDE_PX = 1600
44
+
45
+ /** JPEG compression quality (0-100). Contract C1 fixes this at ~0.7. */
46
+ const val JPEG_QUALITY = 70
47
+
48
+ /** Capture budget — on overrun the callback fires with null. */
49
+ private const val CAPTURE_TIMEOUT_MS = 150L
50
+
51
+ /**
52
+ * Capture a masked screenshot of [activity]'s window.
53
+ *
54
+ * Main thread only. Invokes [callback] exactly once — with the base64
55
+ * JPEG string, or null on any failure — and never lets an exception
56
+ * escape to the caller.
57
+ */
58
+ @JvmStatic
59
+ fun captureMasked(activity: Activity, callback: (String?) -> Unit) {
60
+ val done = AtomicBoolean(false)
61
+ fun finishOnce(value: String?) {
62
+ if (done.compareAndSet(false, true)) callback(value)
63
+ }
64
+ try {
65
+ val handler = Handler(Looper.getMainLooper())
66
+ handler.postDelayed({ finishOnce(null) }, CAPTURE_TIMEOUT_MS)
67
+
68
+ val window = activity.window
69
+ val decor = window?.decorView
70
+ if (window == null || decor == null || decor.width <= 0 || decor.height <= 0) {
71
+ finishOnce(null)
72
+ return
73
+ }
74
+
75
+ // Collect mask frames BEFORE the async copy so the rects describe
76
+ // the same view state the pixels do.
77
+ val maskRects = collectMaskRects(decor)
78
+
79
+ if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
80
+ val bitmap = Bitmap.createBitmap(decor.width, decor.height, Bitmap.Config.ARGB_8888)
81
+ try {
82
+ PixelCopy.request(
83
+ window,
84
+ bitmap,
85
+ { result ->
86
+ if (result == PixelCopy.SUCCESS) {
87
+ // encodeMaskedJpeg consumes (recycles) bitmap.
88
+ finishOnce(encodeMaskedJpeg(bitmap, maskRects))
89
+ } else {
90
+ bitmap.recycle()
91
+ finishOnce(drawFallback(decor, maskRects))
92
+ }
93
+ },
94
+ handler,
95
+ )
96
+ } catch (t: Throwable) {
97
+ // PixelCopy throws IllegalArgumentException for windows
98
+ // with no backing surface (e.g. mid-teardown).
99
+ bitmap.recycle()
100
+ finishOnce(drawFallback(decor, maskRects))
101
+ }
102
+ } else {
103
+ finishOnce(drawFallback(decor, maskRects))
104
+ }
105
+ } catch (t: Throwable) {
106
+ finishOnce(null)
107
+ }
108
+ }
109
+
110
+ // MARK: - Mask collection
111
+
112
+ /**
113
+ * Window-relative frames of every visible EditText under [root]
114
+ * (RN text inputs are EditText subclasses).
115
+ */
116
+ internal fun collectMaskRects(root: View): List<Rect> {
117
+ val rects = ArrayList<Rect>()
118
+ val rootLocation = IntArray(2)
119
+ root.getLocationInWindow(rootLocation)
120
+ appendMaskRects(root, rootLocation, rects)
121
+ return rects
122
+ }
123
+
124
+ private fun appendMaskRects(view: View, rootLocation: IntArray, out: MutableList<Rect>) {
125
+ // Invisible subtrees contribute no pixels — nothing to mask.
126
+ if (view.visibility != View.VISIBLE || view.width <= 0 || view.height <= 0) return
127
+
128
+ if (view is EditText) {
129
+ val location = IntArray(2)
130
+ view.getLocationInWindow(location)
131
+ val left = location[0] - rootLocation[0]
132
+ val top = location[1] - rootLocation[1]
133
+ out.add(Rect(left, top, left + view.width, top + view.height))
134
+ // The whole view is covered by one opaque rect; no need to descend.
135
+ return
136
+ }
137
+
138
+ if (view is ViewGroup) {
139
+ for (i in 0 until view.childCount) {
140
+ appendMaskRects(view.getChildAt(i), rootLocation, out)
141
+ }
142
+ }
143
+ }
144
+
145
+ // MARK: - Encode
146
+
147
+ /** View#draw fallback when PixelCopy is unavailable or failed. */
148
+ private fun drawFallback(decor: View, maskRects: List<Rect>): String? = try {
149
+ val bitmap = Bitmap.createBitmap(decor.width, decor.height, Bitmap.Config.ARGB_8888)
150
+ decor.draw(Canvas(bitmap))
151
+ encodeMaskedJpeg(bitmap, maskRects)
152
+ } catch (t: Throwable) {
153
+ null
154
+ }
155
+
156
+ /**
157
+ * Black out [maskRects] on [bitmap] (full-resolution window coords),
158
+ * downscale so the longest side is <= [MAX_LONGEST_SIDE_PX], JPEG-encode,
159
+ * and base64 the bytes. Consumes (recycles) [bitmap]. Returns null on any
160
+ * failure.
161
+ */
162
+ private fun encodeMaskedJpeg(bitmap: Bitmap, maskRects: List<Rect>): String? = try {
163
+ val canvas = Canvas(bitmap)
164
+ val paint = Paint().apply {
165
+ color = Color.BLACK
166
+ style = Paint.Style.FILL
167
+ }
168
+ for (rect in maskRects) canvas.drawRect(rect, paint)
169
+
170
+ val (targetWidth, targetHeight) = targetSize(bitmap.width, bitmap.height, MAX_LONGEST_SIDE_PX)
171
+ val scaled = if (targetWidth == bitmap.width && targetHeight == bitmap.height) {
172
+ bitmap
173
+ } else {
174
+ Bitmap.createScaledBitmap(bitmap, targetWidth, targetHeight, true)
175
+ }
176
+
177
+ val bytes = ByteArrayOutputStream()
178
+ val compressed = scaled.compress(Bitmap.CompressFormat.JPEG, JPEG_QUALITY, bytes)
179
+ if (scaled !== bitmap) scaled.recycle()
180
+ bitmap.recycle()
181
+ if (compressed) Base64.encodeToString(bytes.toByteArray(), Base64.NO_WRAP) else null
182
+ } catch (t: Throwable) {
183
+ null
184
+ }
185
+
186
+ /**
187
+ * Pure downscale math (unit-tested on the JVM): the largest (w, h) with
188
+ * preserved aspect ratio whose longest side is <= [maxLongest]. Never
189
+ * upscales; degenerate input is returned unchanged (callers already
190
+ * reject non-positive dimensions before capture).
191
+ */
192
+ internal fun targetSize(width: Int, height: Int, maxLongest: Int): Pair<Int, Int> {
193
+ val longest = maxOf(width, height)
194
+ if (longest <= maxLongest || longest <= 0) return Pair(width, height)
195
+ val ratio = maxLongest.toFloat() / longest.toFloat()
196
+ return Pair(
197
+ maxOf(1, Math.round(width * ratio)),
198
+ maxOf(1, Math.round(height * ratio)),
199
+ )
200
+ }
201
+ }
@@ -0,0 +1,172 @@
1
+ // packages/swiss-knife-android/src/main/java/com/appswissknife/device/DeviceID.kt
2
+ //
3
+ // Persistent per-install device identifier for the Swiss Knife SDK.
4
+ //
5
+ // The ID must:
6
+ // - survive process restart (so user-level analytics stays coherent across
7
+ // app launches) — was previously a process-scoped UUID generated at class
8
+ // init, which fragmented every user's timeline on every cold start.
9
+ // - NOT survive Auto Backup → restore on a new device. Carrying the same
10
+ // device_id to a different physical device would silently merge two users'
11
+ // analytics streams. The XML resource at
12
+ // res/xml/swissknife_data_extraction_rules.xml excludes our SharedPreferences
13
+ // file from both cloud-backup and device-transfer flows.
14
+ //
15
+ // Storage strategy:
16
+ // 1. Primary: EncryptedSharedPreferences (Tink-backed AES-256-GCM via
17
+ // androidx.security:security-crypto). Keys live in the Android Keystore,
18
+ // so the ciphertext is bound to this install/device.
19
+ // 2. Fallback: plain SharedPreferences on the same file name and key. Tink +
20
+ // Keystore initialization has known failure modes on some old/quirky
21
+ // OEM devices (corrupted KeyStore, missing strongbox provider, Tink
22
+ // key-set version mismatch after host-app downgrade, etc.). When that
23
+ // happens, generating a fresh in-memory UUID every launch is worse for
24
+ // analytics than persisting an unencrypted UUID — there's no PII in a
25
+ // random UUIDv4, the threat model is "survive process restart", not
26
+ // "defend against device compromise". So we fall back, log a single
27
+ // warning, and continue.
28
+ //
29
+ // Why we DON'T set android:allowBackup="false" on this library's <application>:
30
+ // This is a library — the host app's manifest wins (and SHOULD win) for
31
+ // global backup policy. Forcing allowBackup=false on every consumer is
32
+ // user-hostile. The per-file exclusion via dataExtractionRules achieves
33
+ // the same goal (our SP file is never backed up / transferred) without
34
+ // overriding the host app's decision for its own data.
35
+
36
+ package com.appswissknife.device
37
+
38
+ import android.content.Context
39
+ import android.content.SharedPreferences
40
+ import android.util.Log
41
+ import androidx.annotation.VisibleForTesting
42
+ import androidx.security.crypto.EncryptedSharedPreferences
43
+ import androidx.security.crypto.MasterKey
44
+ import java.util.UUID
45
+
46
+ /**
47
+ * Persistent install-scoped device identifier.
48
+ *
49
+ * Use [get] to read (and lazily generate) the ID. Subsequent calls within the
50
+ * same process return the cached value without touching disk.
51
+ *
52
+ * Not part of the public SDK surface — internal use by [com.appswissknife.analytics.SKAnalytics]
53
+ * and (eventually) the swap-in Play Billing v8 implementation only.
54
+ */
55
+ internal object DeviceID {
56
+
57
+ @VisibleForTesting
58
+ internal const val FILE_NAME = "swissknife_device"
59
+
60
+ @VisibleForTesting
61
+ internal const val KEY = "device_id"
62
+
63
+ private const val TAG = "SwissKnife.DeviceID"
64
+
65
+ private val lock = Any()
66
+
67
+ @Volatile
68
+ private var cached: String? = null
69
+
70
+ /**
71
+ * Return the persistent device ID. Generates and persists a new UUIDv4 on
72
+ * first call. Thread-safe. Always returns a non-empty, well-formed UUID
73
+ * string — corrupted persisted values are silently regenerated.
74
+ */
75
+ fun get(context: Context): String {
76
+ cached?.let { return it }
77
+ synchronized(lock) {
78
+ cached?.let { return it }
79
+ val appContext = context.applicationContext ?: context
80
+ val prefs = openPrefs(appContext)
81
+ val existing = runCatching { prefs.getString(KEY, null) }.getOrNull()
82
+ val id = if (existing.isValidUuid()) {
83
+ existing!!
84
+ } else {
85
+ val fresh = UUID.randomUUID().toString()
86
+ // Best-effort write; if commit fails we still hand back the UUID
87
+ // for this process — next launch will retry.
88
+ runCatching { prefs.edit().putString(KEY, fresh).apply() }
89
+ fresh
90
+ }
91
+ cached = id
92
+ return id
93
+ }
94
+ }
95
+
96
+ /**
97
+ * Open the primary EncryptedSharedPreferences, falling back to plain
98
+ * SharedPreferences on any failure during MasterKey / EncryptedSharedPreferences
99
+ * setup. Wrapped via a function seam so tests can override.
100
+ */
101
+ private fun openPrefs(appContext: Context): SharedPreferences {
102
+ return createEncryptedPrefsOrNull(appContext)
103
+ ?: appContext.getSharedPreferences(FILE_NAME, Context.MODE_PRIVATE)
104
+ }
105
+
106
+ @VisibleForTesting
107
+ internal var createEncryptedPrefsForTesting: ((Context) -> SharedPreferences?)? = null
108
+
109
+ private fun createEncryptedPrefsOrNull(appContext: Context): SharedPreferences? {
110
+ createEncryptedPrefsForTesting?.let { override ->
111
+ return try {
112
+ override(appContext)
113
+ } catch (t: Throwable) {
114
+ Log.w(TAG, "EncryptedSharedPreferences unavailable (test override threw); using plain SharedPreferences fallback", t)
115
+ null
116
+ }
117
+ }
118
+ return try {
119
+ val masterKey = MasterKey.Builder(appContext)
120
+ .setKeyScheme(MasterKey.KeyScheme.AES256_GCM)
121
+ .build()
122
+ EncryptedSharedPreferences.create(
123
+ appContext,
124
+ FILE_NAME,
125
+ masterKey,
126
+ EncryptedSharedPreferences.PrefKeyEncryptionScheme.AES256_SIV,
127
+ EncryptedSharedPreferences.PrefValueEncryptionScheme.AES256_GCM,
128
+ )
129
+ } catch (t: Throwable) {
130
+ Log.w(TAG, "EncryptedSharedPreferences unavailable; using plain SharedPreferences fallback", t)
131
+ null
132
+ }
133
+ }
134
+
135
+ private fun String?.isValidUuid(): Boolean {
136
+ if (this.isNullOrEmpty()) return false
137
+ return try {
138
+ // UUID.fromString accepts some malformed inputs that round-trip
139
+ // differently — require an exact round-trip to reject those.
140
+ UUID.fromString(this).toString() == this
141
+ } catch (_: IllegalArgumentException) {
142
+ false
143
+ }
144
+ }
145
+
146
+ /**
147
+ * Test-only: drop the in-memory cache so the next [get] call re-reads from
148
+ * disk. Simulates a process restart.
149
+ */
150
+ @VisibleForTesting
151
+ internal fun resetCacheForTesting() {
152
+ synchronized(lock) { cached = null }
153
+ }
154
+
155
+ /**
156
+ * Clear both the in-memory cache and the persisted SharedPreferences
157
+ * entry. Called by `Identity.wipe(context)` for GDPR-delete /
158
+ * test-build cleanup. Next [get] generates and persists a fresh
159
+ * UUID.
160
+ *
161
+ * Internal-only; production code other than `Identity.wipe` must
162
+ * not call this — a fresh device id breaks analytics continuity.
163
+ */
164
+ internal fun wipe(context: Context) {
165
+ synchronized(lock) {
166
+ cached = null
167
+ val appContext = context.applicationContext ?: context
168
+ val prefs = openPrefs(appContext)
169
+ runCatching { prefs.edit().remove(KEY).apply() }
170
+ }
171
+ }
172
+ }
@@ -0,0 +1,97 @@
1
+ // packages/swiss-knife-android/src/main/java/com/appswissknife/diagnostics/SKLog.kt
2
+ //
3
+ // Wave 4 — unified diagnostics. Closes the audit finding that
4
+ // `SwissKnife.setLogLevel(...)` on Android did NOTHING in production:
5
+ // the level value flowed into `BillingClientGateway.setLogLevel(...)`,
6
+ // where the implementation was a literal no-op ("Play Billing doesn't
7
+ // expose a log-level knob"). Meanwhile every other module logged with
8
+ // hard-coded `Log.d/i/w/e` calls that ignored the user's threshold.
9
+ //
10
+ // Now `SKLog.{debug, info, warn, error}` is the one entry point. Each
11
+ // call:
12
+ //
13
+ // 1. Compares the call-site severity to the current
14
+ // `SwissKnife.resolvedLogLevel()`. Below the threshold → return
15
+ // without doing anything.
16
+ // 2. Routes the message through `android.util.Log` with a unified
17
+ // `TAG = "SwissKnife"` plus the caller-supplied category as a
18
+ // message prefix.
19
+ //
20
+ // Thread safety: log-level read goes through a single AtomicReference.
21
+ // Each call is a non-blocking volatile read.
22
+
23
+ package com.appswissknife.diagnostics
24
+
25
+ import android.util.Log
26
+ import androidx.annotation.VisibleForTesting
27
+ import com.appswissknife.models.LogLevel
28
+ import java.util.concurrent.atomic.AtomicReference
29
+
30
+ object SKLog {
31
+
32
+ private val TAG = "SwissKnife"
33
+
34
+ /** Current threshold. `SwissKnife.setLogLevel(...)` writes here. */
35
+ private val level = AtomicReference(LogLevel.WARN)
36
+
37
+ /** Test sink. Production routes to `android.util.Log`. */
38
+ @Volatile
39
+ @VisibleForTesting
40
+ internal var sink: (LogLevel, String, String) -> Unit = { lvl, category, msg ->
41
+ val tag = "$TAG/$category"
42
+ when (lvl) {
43
+ LogLevel.VERBOSE, LogLevel.DEBUG -> Log.d(tag, msg)
44
+ LogLevel.INFO -> Log.i(tag, msg)
45
+ LogLevel.WARN -> Log.w(tag, msg)
46
+ LogLevel.ERROR -> Log.e(tag, msg)
47
+ }
48
+ }
49
+
50
+ fun setLevel(level: LogLevel) {
51
+ this.level.set(level)
52
+ }
53
+
54
+ fun getLevel(): LogLevel = level.get()
55
+
56
+ fun debug(category: String, message: () -> String) {
57
+ if (rank(LogLevel.DEBUG) < rank(level.get())) return
58
+ sink(LogLevel.DEBUG, category, message())
59
+ }
60
+
61
+ fun info(category: String, message: () -> String) {
62
+ if (rank(LogLevel.INFO) < rank(level.get())) return
63
+ sink(LogLevel.INFO, category, message())
64
+ }
65
+
66
+ fun warn(category: String, message: () -> String) {
67
+ if (rank(LogLevel.WARN) < rank(level.get())) return
68
+ sink(LogLevel.WARN, category, message())
69
+ }
70
+
71
+ fun error(category: String, message: () -> String) {
72
+ if (rank(LogLevel.ERROR) < rank(level.get())) return
73
+ sink(LogLevel.ERROR, category, message())
74
+ }
75
+
76
+ private fun rank(level: LogLevel): Int = when (level) {
77
+ LogLevel.VERBOSE -> 0
78
+ LogLevel.DEBUG -> 1
79
+ LogLevel.INFO -> 2
80
+ LogLevel.WARN -> 3
81
+ LogLevel.ERROR -> 4
82
+ }
83
+
84
+ @VisibleForTesting
85
+ internal fun _resetForTesting() {
86
+ level.set(LogLevel.WARN)
87
+ sink = { lvl, category, msg ->
88
+ val tag = "$TAG/$category"
89
+ when (lvl) {
90
+ LogLevel.VERBOSE, LogLevel.DEBUG -> Log.d(tag, msg)
91
+ LogLevel.INFO -> Log.i(tag, msg)
92
+ LogLevel.WARN -> Log.w(tag, msg)
93
+ LogLevel.ERROR -> Log.e(tag, msg)
94
+ }
95
+ }
96
+ }
97
+ }