@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,175 @@
1
+ // packages/swiss-knife-ios/Sources/SwissKnifeiOS/CrashReporting/SKScreenshot.swift
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
+ // - Returns a base64-encoded JPEG (NO `data:` prefix), longest side ≤ 1600px,
7
+ // quality 0.7 — or nil on ANY failure (no key window, zero-size bounds,
8
+ // encode failure, called off-main). Never throws.
9
+ // - MASKED BY DEFAULT, non-configurable in v1: an opaque black rectangle is
10
+ // drawn over every text-input view — UITextField / UITextView (which covers
11
+ // RN's RCTUITextField / RCTUITextView subclasses) plus any other view whose
12
+ // UITextInputTraits report isSecureTextEntry. UILabels intentionally stay
13
+ // visible.
14
+ // - Must be called on the MAIN thread (UIKit rendering); callers dispatch.
15
+ // The ≤150ms budget is enforced by the caller (the RN bridge races a
16
+ // timeout that resolves null), not here — capture itself is synchronous.
17
+
18
+ import Foundation
19
+ import CoreGraphics
20
+
21
+ #if canImport(UIKit)
22
+ import UIKit
23
+ #endif
24
+
25
+ // MARK: - Pure geometry (platform-neutral, unit-tested via `swift test`)
26
+
27
+ /// Geometry helpers for screenshot capture, kept UIKit-free so they compile
28
+ /// and unit-test on the macOS CLI harness like the rest of the package.
29
+ public enum SKScreenshotGeometry {
30
+
31
+ /// Longest rendered side, in pixels. Contract C1 fixes this at 1600.
32
+ public static let maxLongestSidePixels: CGFloat = 1600
33
+
34
+ /// JPEG compression quality. Contract C1 fixes this at ~0.7.
35
+ public static let jpegQuality: CGFloat = 0.7
36
+
37
+ /// The renderer scale (pixels per point) that keeps the longest side of
38
+ /// `boundsSize` at or under `maxLongestSidePixels` once rendered, without
39
+ /// ever upscaling beyond the screen's native scale.
40
+ ///
41
+ /// Returns nil for degenerate input (empty / non-finite size or scale) —
42
+ /// callers treat that as "cannot capture".
43
+ public static func renderScale(
44
+ boundsSize: CGSize,
45
+ nativeScale: CGFloat,
46
+ maxLongestSidePixels: CGFloat = SKScreenshotGeometry.maxLongestSidePixels
47
+ ) -> CGFloat? {
48
+ let longest = max(boundsSize.width, boundsSize.height)
49
+ guard longest.isFinite, longest > 0,
50
+ nativeScale.isFinite, nativeScale > 0,
51
+ maxLongestSidePixels > 0 else { return nil }
52
+ return min(nativeScale, maxLongestSidePixels / longest)
53
+ }
54
+
55
+ /// Intersect candidate mask rects with the render bounds, dropping empty,
56
+ /// non-finite, and fully-outside rects. The renderer fills exactly what
57
+ /// this returns, so garbage frames (detached views, NaN transforms) must
58
+ /// never survive.
59
+ public static func clampedMaskRects(_ rects: [CGRect], in bounds: CGRect) -> [CGRect] {
60
+ rects.compactMap { rect in
61
+ guard rect.origin.x.isFinite, rect.origin.y.isFinite,
62
+ rect.width.isFinite, rect.height.isFinite else { return nil }
63
+ let clamped = rect.intersection(bounds)
64
+ guard !clamped.isNull, clamped.width > 0, clamped.height > 0 else { return nil }
65
+ return clamped
66
+ }
67
+ }
68
+ }
69
+
70
+ // MARK: - UIKit capture
71
+
72
+ #if canImport(UIKit) && !os(watchOS)
73
+
74
+ public enum SKScreenshot {
75
+
76
+ /// Capture a masked screenshot of the app's key window.
77
+ ///
78
+ /// MAIN THREAD ONLY — returns nil when called off-main instead of
79
+ /// deadlocking or asserting. Never throws; every failure path returns nil.
80
+ public static func captureMaskedBase64() -> String? {
81
+ guard Thread.isMainThread else { return nil }
82
+ guard let window = keyWindow() else { return nil }
83
+
84
+ let bounds = window.bounds
85
+ guard let scale = SKScreenshotGeometry.renderScale(
86
+ boundsSize: bounds.size,
87
+ nativeScale: window.screen.scale
88
+ ) else { return nil }
89
+
90
+ let maskRects = SKScreenshotGeometry.clampedMaskRects(
91
+ collectMaskRects(in: window),
92
+ in: bounds
93
+ )
94
+
95
+ let format = UIGraphicsImageRendererFormat()
96
+ format.scale = scale
97
+ format.opaque = true
98
+ let renderer = UIGraphicsImageRenderer(bounds: bounds, format: format)
99
+
100
+ let image = renderer.image { context in
101
+ // drawHierarchy is the fast snapshot path; afterScreenUpdates:false
102
+ // avoids forcing a layout/commit (we're inside the 150ms budget).
103
+ // It can fail (returns false) for windows that haven't rendered
104
+ // yet — fall back to layer rendering so we still get pixels.
105
+ let drawn = window.drawHierarchy(in: bounds, afterScreenUpdates: false)
106
+ if !drawn {
107
+ window.layer.render(in: context.cgContext)
108
+ }
109
+ UIColor.black.setFill()
110
+ for rect in maskRects {
111
+ context.fill(rect)
112
+ }
113
+ }
114
+
115
+ guard let jpeg = image.jpegData(compressionQuality: SKScreenshotGeometry.jpegQuality) else {
116
+ return nil
117
+ }
118
+ return jpeg.base64EncodedString()
119
+ }
120
+
121
+ // MARK: - Window discovery
122
+
123
+ /// Best-effort key-window lookup that works on scene-based apps (RN apps
124
+ /// included). Prefers the key window of a foreground-active scene, then
125
+ /// any visible window.
126
+ private static func keyWindow() -> UIWindow? {
127
+ let scenes = UIApplication.shared.connectedScenes
128
+ .compactMap { $0 as? UIWindowScene }
129
+ let activeWindows = scenes
130
+ .filter { $0.activationState == .foregroundActive }
131
+ .flatMap { $0.windows }
132
+ let allWindows = scenes.flatMap { $0.windows }
133
+
134
+ return activeWindows.first(where: { $0.isKeyWindow })
135
+ ?? activeWindows.first(where: { !$0.isHidden && $0.alpha > 0 })
136
+ ?? allWindows.first(where: { $0.isKeyWindow })
137
+ ?? allWindows.first(where: { !$0.isHidden && $0.alpha > 0 })
138
+ }
139
+
140
+ // MARK: - Mask collection
141
+
142
+ /// Window-coordinate frames of every view that must be blacked out.
143
+ internal static func collectMaskRects(in window: UIWindow) -> [CGRect] {
144
+ var rects: [CGRect] = []
145
+ appendMaskRects(of: window, window: window, into: &rects)
146
+ return rects
147
+ }
148
+
149
+ private static func appendMaskRects(of view: UIView, window: UIWindow, into rects: inout [CGRect]) {
150
+ // Invisible subtrees contribute no pixels — nothing to mask.
151
+ guard !view.isHidden, view.alpha > 0.01 else { return }
152
+
153
+ if shouldMask(view) {
154
+ rects.append(view.convert(view.bounds, to: window))
155
+ // The whole view is covered by one opaque rect; no need to
156
+ // descend into its subviews.
157
+ return
158
+ }
159
+
160
+ for subview in view.subviews {
161
+ appendMaskRects(of: subview, window: window, into: &rects)
162
+ }
163
+ }
164
+
165
+ /// v1 mask policy (contract C1): UITextField + UITextView — which covers
166
+ /// RN's RCTUITextField / RCTUITextView subclasses via isKindOf — plus any
167
+ /// other view whose text-input traits report secure entry. Labels stay.
168
+ private static func shouldMask(_ view: UIView) -> Bool {
169
+ if view is UITextField || view is UITextView { return true }
170
+ if let traits = view as? UITextInputTraits, traits.isSecureTextEntry == true { return true }
171
+ return false
172
+ }
173
+ }
174
+
175
+ #endif
@@ -0,0 +1,161 @@
1
+ // packages/swiss-knife-ios/Sources/SwissKnifeiOS/DeviceID.swift
2
+ //
3
+ // Persistent per-device identifier for SDK analytics, backed by the iOS
4
+ // Keychain so the ID survives app restarts AND app reinstalls (the Keychain
5
+ // outlives the app's sandbox container — that's the load-bearing property).
6
+ //
7
+ // Accessibility: `kSecAttrAccessibleAfterFirstUnlockThisDeviceOnly`
8
+ // - `AfterFirstUnlock`: usable after the user unlocks the device once
9
+ // post-boot — events triggered before first unlock are extraordinarily
10
+ // rare (background tasks pre-unlock) and `WhenUnlocked` would block
11
+ // normal SDK init flows. `AfterFirstUnlock` is the standard choice.
12
+ // - `ThisDeviceOnly`: never leaves this physical device — does NOT get
13
+ // promoted into the iCloud Keychain backup, even if the user enables
14
+ // Keychain sync. We want a device-scoped analytics ID, not a
15
+ // user/iCloud-scoped one.
16
+ //
17
+ // Synchronizable: false (explicit) — belt-and-braces on top of the
18
+ // `ThisDeviceOnly` accessibility class, so the item never lands in iCloud
19
+ // Keychain regardless of any future Apple changes to the default behavior.
20
+ //
21
+ // Corruption recovery: if the stored item is unreadable as UTF-8 OR is
22
+ // empty, we regenerate a new UUID and overwrite — better to lose one
23
+ // device's continuity than to ship a broken/empty `device_id` in events.
24
+
25
+ import Foundation
26
+ import Security
27
+
28
+ /// Persistent device identifier backed by the iOS Keychain.
29
+ ///
30
+ /// Internal-only by design: the `device_id` is an SDK implementation detail.
31
+ /// Consumers who need to override the value go through
32
+ /// `SKAnalytics.setDeviceId(_:)` (a future API can expose an explicit
33
+ /// override path; today it's the manual setter).
34
+ internal enum DeviceID {
35
+
36
+ /// Production-default Keychain service identifier. Anchored to a stable
37
+ /// reverse-DNS-style name so future SDK upgrades pick up the same record.
38
+ static let productionService = "com.swissknife.deviceid"
39
+
40
+ /// Production-default account identifier. We only ever store one device ID,
41
+ /// so a fixed sentinel account is fine.
42
+ static let defaultAccount = "default"
43
+
44
+ // In-memory cache of (service+account) → resolved UUID string. Reads
45
+ // after the first one are lock-free fast-path; we still guard the cache
46
+ // and Keychain access with a serial lock for correctness under concurrent
47
+ // first-access from multiple threads.
48
+ private static var cache: [String: String] = [:]
49
+ private static let lock = NSLock()
50
+
51
+ /// Production entry point. Returns the persistent device ID, generating
52
+ /// and storing one on first run.
53
+ static func get() -> String {
54
+ get(service: productionService, account: defaultAccount)
55
+ }
56
+
57
+ /// Test-friendly overload — allows passing a unique service per test so
58
+ /// tests don't pollute production Keychain state or each other.
59
+ static func get(service: String, account: String = defaultAccount) -> String {
60
+ let cacheKey = "\(service)::\(account)"
61
+
62
+ lock.lock()
63
+ defer { lock.unlock() }
64
+
65
+ if let cached = cache[cacheKey] {
66
+ return cached
67
+ }
68
+
69
+ // Try to read existing value.
70
+ if let existing = readFromKeychain(service: service, account: account),
71
+ let value = decode(existing),
72
+ !value.isEmpty {
73
+ cache[cacheKey] = value
74
+ return value
75
+ }
76
+
77
+ // Either nothing stored, or stored bytes are corrupted/empty — write
78
+ // a fresh UUID. `writeToKeychain` overwrites (delete-then-add) so
79
+ // corrupted records are replaced cleanly.
80
+ let fresh = UUID().uuidString
81
+ writeToKeychain(service: service, account: account, value: fresh)
82
+ cache[cacheKey] = fresh
83
+ return fresh
84
+ }
85
+
86
+ /// Test-only: clear the in-memory cache so a subsequent `get()` re-reads
87
+ /// from the Keychain. Used to simulate a process restart inside one test
88
+ /// process. Not exposed to consumers.
89
+ static func _resetCache_forTesting() {
90
+ lock.lock()
91
+ cache.removeAll()
92
+ lock.unlock()
93
+ }
94
+
95
+ /// Clear both the in-memory cache and the persisted Keychain item.
96
+ /// Called by `SwissKnife.Identity.wipe()` for GDPR-delete and
97
+ /// test-build cleanup. The next `get()` generates and persists a
98
+ /// fresh UUID. Production code other than `Identity.wipe()` must not
99
+ /// call this — a fresh DeviceID breaks analytics continuity.
100
+ static func wipe() {
101
+ wipe(service: productionService, account: defaultAccount)
102
+ }
103
+
104
+ /// Test-friendly overload — wipes the entry for a specific service.
105
+ static func wipe(service: String, account: String = defaultAccount) {
106
+ lock.lock()
107
+ defer { lock.unlock() }
108
+ cache.removeValue(forKey: "\(service)::\(account)")
109
+ let deleteQuery = baseQuery(service: service, account: account)
110
+ SecItemDelete(deleteQuery as CFDictionary)
111
+ }
112
+
113
+ // MARK: - Keychain primitives
114
+
115
+ private static func baseQuery(service: String, account: String) -> [String: Any] {
116
+ // `kSecAttrSynchronizable: false` is set explicitly even though
117
+ // `ThisDeviceOnly` accessibility already prevents iCloud sync —
118
+ // defense in depth and a clearer signal of intent.
119
+ [
120
+ kSecClass as String: kSecClassGenericPassword,
121
+ kSecAttrService as String: service,
122
+ kSecAttrAccount as String: account,
123
+ kSecAttrSynchronizable as String: kCFBooleanFalse as Any,
124
+ ]
125
+ }
126
+
127
+ private static func readFromKeychain(service: String, account: String) -> Data? {
128
+ var query = baseQuery(service: service, account: account)
129
+ query[kSecReturnData as String] = kCFBooleanTrue as Any
130
+ query[kSecMatchLimit as String] = kSecMatchLimitOne
131
+
132
+ var result: AnyObject?
133
+ let status = SecItemCopyMatching(query as CFDictionary, &result)
134
+ guard status == errSecSuccess else { return nil }
135
+ return result as? Data
136
+ }
137
+
138
+ @discardableResult
139
+ private static func writeToKeychain(service: String, account: String, value: String) -> Bool {
140
+ guard let data = value.data(using: .utf8) else { return false }
141
+
142
+ // Idempotent overwrite: delete any prior record (including corrupted
143
+ // ones), then add fresh. `SecItemUpdate` would also work but the
144
+ // delete-then-add idiom keeps the accessibility/synchronizable
145
+ // attributes consistent on every write.
146
+ let deleteQuery = baseQuery(service: service, account: account)
147
+ SecItemDelete(deleteQuery as CFDictionary)
148
+
149
+ var addQuery = baseQuery(service: service, account: account)
150
+ addQuery[kSecValueData as String] = data
151
+ addQuery[kSecAttrAccessible as String] = kSecAttrAccessibleAfterFirstUnlockThisDeviceOnly
152
+
153
+ let status = SecItemAdd(addQuery as CFDictionary, nil)
154
+ return status == errSecSuccess
155
+ }
156
+
157
+ private static func decode(_ data: Data) -> String? {
158
+ guard !data.isEmpty else { return nil }
159
+ return String(data: data, encoding: .utf8)
160
+ }
161
+ }
@@ -0,0 +1,128 @@
1
+ // packages/swiss-knife-ios/Sources/SwissKnifeiOS/Diagnostics/SKLog.swift
2
+ //
3
+ // Wave 4 — unified diagnostics. Closes the audit finding that
4
+ // `SwissKnife.setLogLevel(.warn)` did NOTHING in production: the level
5
+ // was stored on `SwissKnife.shared.resolvedLogLevel` but no callsite
6
+ // ever checked it. Every `os_log(...)` in the SDK fired at its own
7
+ // hard-coded severity regardless.
8
+ //
9
+ // Now `SKLog.{debug, info, warn, error}` is the one entry point. Each
10
+ // call:
11
+ //
12
+ // 1. Compares the call-site severity to the current
13
+ // `SwissKnife.resolvedLogLevel`. Below the threshold → return
14
+ // without doing anything (no string interpolation, no os_log,
15
+ // no allocation past the format args).
16
+ // 2. Routes the message through `os_log` with the SDK-unified
17
+ // subsystem `com.swissknife` and the caller-supplied category.
18
+ //
19
+ // Migration plan: this commit ships SKLog and switches the heaviest
20
+ // callsites (`SwissKnife.swift`, `AttributesClient.swift`,
21
+ // `EntitlementsService.swift`, `Attribution/*.swift`) to it. Other
22
+ // callsites (Analytics, Offerings, etc.) continue to use ad-hoc
23
+ // `os_log` until they get touched — gradual rollout is fine because
24
+ // the new `SKLog` and existing `os_log` calls share the same
25
+ // subsystem, so log-aggregation tools see the same stream.
26
+ //
27
+ // Thread safety: log-level read goes through `SwissKnife.shared.stateQueue`
28
+ // via `SwissKnife.resolvedLogLevelInternal()`. Each level read takes
29
+ // one queue.sync; for hot paths (per-event analytics flush) callers
30
+ // can hoist the level read outside the loop.
31
+
32
+ import Foundation
33
+ import os.log
34
+
35
+ internal enum SKLog {
36
+
37
+ // MARK: Public entry points
38
+
39
+ static func debug(_ message: @autoclosure () -> String, category: String = "swissknife") {
40
+ log(level: .debug, message: message(), category: category)
41
+ }
42
+
43
+ static func info(_ message: @autoclosure () -> String, category: String = "swissknife") {
44
+ log(level: .info, message: message(), category: category)
45
+ }
46
+
47
+ static func warn(_ message: @autoclosure () -> String, category: String = "swissknife") {
48
+ log(level: .warn, message: message(), category: category)
49
+ }
50
+
51
+ static func error(_ message: @autoclosure () -> String, category: String = "swissknife") {
52
+ log(level: .error, message: message(), category: category)
53
+ }
54
+
55
+ // MARK: Implementation
56
+
57
+ /// Per-category OSLog instance cache. Building an OSLog is cheap but
58
+ /// not free; reusing per category mirrors the pattern existing
59
+ /// services use (`private let log = OSLog(...)`).
60
+ private static let logCache = LogCache()
61
+
62
+ /// Where to route the actual write. Tests override this to capture
63
+ /// emitted messages.
64
+ internal static var sink: (LogLevel, String, String) -> Void = { level, category, message in
65
+ let osLogType: OSLogType = {
66
+ switch level {
67
+ case .verbose, .debug: return .debug
68
+ case .info: return .info
69
+ case .warn: return .default
70
+ case .error: return .error
71
+ }
72
+ }()
73
+ let log = SKLog.logCache.get(category: category)
74
+ os_log("%{public}@", log: log, type: osLogType, message)
75
+ }
76
+
77
+ private static func log(level: LogLevel, message: @autoclosure () -> String, category: String) {
78
+ let threshold = SwissKnife.resolvedLogLevelInternal()
79
+ guard severityRank(level) >= severityRank(threshold) else { return }
80
+ sink(level, category, message())
81
+ }
82
+
83
+ /// Numeric severity ranking matching the spec: verbose < debug <
84
+ /// info < warn < error. `setLogLevel(.warn)` should pass warn +
85
+ /// error and filter info / debug / verbose — matches the LogLevel
86
+ /// raw-value order on RC for parity.
87
+ private static func severityRank(_ level: LogLevel) -> Int {
88
+ switch level {
89
+ case .verbose: return 0
90
+ case .debug: return 1
91
+ case .info: return 2
92
+ case .warn: return 3
93
+ case .error: return 4
94
+ }
95
+ }
96
+
97
+ /// Test seam — reset the sink to the production os_log path.
98
+ internal static func _resetForTesting() {
99
+ sink = { level, category, message in
100
+ let osLogType: OSLogType = {
101
+ switch level {
102
+ case .verbose, .debug: return .debug
103
+ case .info: return .info
104
+ case .warn: return .default
105
+ case .error: return .error
106
+ }
107
+ }()
108
+ let log = SKLog.logCache.get(category: category)
109
+ os_log("%{public}@", log: log, type: osLogType, message)
110
+ }
111
+ }
112
+ }
113
+
114
+ /// Thread-safe map from category-name → OSLog. A serial DispatchQueue
115
+ /// guards the dictionary; reads under the lock are O(1).
116
+ private final class LogCache: @unchecked Sendable {
117
+ private var logs: [String: OSLog] = [:]
118
+ private let queue = DispatchQueue(label: "com.swissknife.sklog.cache")
119
+
120
+ func get(category: String) -> OSLog {
121
+ queue.sync {
122
+ if let existing = logs[category] { return existing }
123
+ let log = OSLog(subsystem: "com.swissknife", category: category)
124
+ logs[category] = log
125
+ return log
126
+ }
127
+ }
128
+ }