@finos_sdk/sdk-ekyc 1.4.9 → 1.5.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -92,97 +92,154 @@ class EKYCModule(reactContext: ReactApplicationContext) : ReactContextBaseJavaMo
92
92
  private var exitSheetResolvedViaButton = false
93
93
 
94
94
  private fun getTrueCurrentActivity(): Activity? {
95
- // Try React Native's currentActivity first
95
+ // Try React Native's currentActivity first as a baseline
96
96
  val rnActivity = currentActivity
97
- if (rnActivity != null && rnActivity.javaClass.simpleName != "MainActivity") {
97
+
98
+ Log.d(TAG, "🔍 getTrueCurrentActivity check: rnActivity=${rnActivity?.javaClass?.simpleName}")
99
+
100
+ // If rnActivity is already an SDK activity, we can likely trust it
101
+ if (rnActivity != null && rnActivity.javaClass.name.startsWith("finos.sdk.")) {
102
+ Log.d(TAG, "✅ Current activity is already an SDK activity: ${rnActivity.javaClass.simpleName}")
98
103
  return rnActivity
99
104
  }
100
105
 
101
- // If RN gives us MainActivity or null, but we know an SDK is showing,
102
- // we must find the actual top activity via reflection or ActivityThread
106
+ // Use reflection to find the absolute top resumed activity.
107
+ // This is crucial when the SDK is running in a native Activity on top of the RN Activity,
108
+ // and currentActivity might still point to the background Activity.
109
+ try {
110
+ val topActivity = findTopActivityViaReflection()
111
+ if (topActivity != null) {
112
+ Log.d(TAG, "✅ Found top activity via reflection: ${topActivity.javaClass.simpleName}")
113
+ return topActivity
114
+ }
115
+ } catch (e: Exception) {
116
+ Log.e(TAG, "Failed to find top activity via reflection", e)
117
+ }
118
+
119
+ Log.d(TAG, "⚠️ Fallback to rnActivity: ${rnActivity?.javaClass?.simpleName}")
120
+ return rnActivity
121
+ }
122
+
123
+ /**
124
+ * Finds the top-most resumed activity using ActivityThread's internal records.
125
+ */
126
+ private fun findTopActivityViaReflection(): Activity? {
103
127
  try {
104
128
  val activityThreadClass = Class.forName("android.app.ActivityThread")
105
- val activityThread = activityThreadClass.getMethod("currentActivityThread").invoke(null)
129
+ val activityThread = activityThreadClass.getMethod("currentActivityThread").invoke(null) ?: return null
106
130
  val activitiesField = activityThreadClass.getDeclaredField("mActivities")
107
131
  activitiesField.isAccessible = true
108
132
 
109
- val activities = activitiesField.get(activityThread) as Map<Any, Any>
110
- Log.d(TAG, "🔍 Scanning ${activities.size} activities...")
111
-
112
- var topActivity: Activity? = null
133
+ val activities = activitiesField.get(activityThread) as? Map<*, *> ?: return null
134
+ Log.d(TAG, "🔍 Scanning ${activities.size} activities via reflection...")
113
135
 
136
+ var bestCandidate: Activity? = null
137
+ var highestPriority = -1
138
+
114
139
  for (activityRecord in activities.values) {
115
- val activityRecordClass = activityRecord.javaClass
116
-
117
- val activityField = activityRecordClass.getDeclaredField("activity")
118
- activityField.isAccessible = true
119
- val activity = activityField.get(activityRecord) as Activity
120
-
121
- val pausedField = activityRecordClass.getDeclaredField("paused")
122
- pausedField.isAccessible = true
123
- val isPaused = pausedField.get(activityRecord) as Boolean
124
-
125
- val stoppedField = activityRecordClass.getDeclaredField("stopped")
126
- stoppedField.isAccessible = true
127
- val isStopped = stoppedField.get(activityRecord) as Boolean
128
-
129
- Log.d(TAG, " - Found: ${activity.javaClass.simpleName} (Paused: $isPaused, Stopped: $isStopped, Finishing: ${activity.isFinishing})")
130
-
131
- if (!activity.isFinishing && !isStopped) {
132
- topActivity = activity
133
- if (!isPaused) break // Found the resumed one
140
+ if (activityRecord == null) continue
141
+ try {
142
+ val activityRecordClass = activityRecord.javaClass
143
+ val activityField = activityRecordClass.getDeclaredField("activity")
144
+ activityField.isAccessible = true
145
+ val activity = activityField.get(activityRecord) as? Activity ?: continue
146
+
147
+ if (activity.isFinishing) continue
148
+
149
+ val pausedField = activityRecordClass.getDeclaredField("paused")
150
+ pausedField.isAccessible = true
151
+ val isPaused = pausedField.get(activityRecord) as Boolean
152
+
153
+ val stoppedField = activityRecordClass.getDeclaredField("stopped")
154
+ stoppedField.isAccessible = true
155
+ val isStopped = stoppedField.get(activityRecord) as Boolean
156
+
157
+ if (isStopped) continue
158
+
159
+ // Identity check: prioritize known SDK activity patterns
160
+ val className = activity.javaClass.name
161
+ val isSDK = className.startsWith("finos.sdk.") ||
162
+ className.contains("EKYC", ignoreCase = true) ||
163
+ className.contains("Liveness", ignoreCase = true) ||
164
+ className.contains("OCR", ignoreCase = true) ||
165
+ className.contains("NFC", ignoreCase = true)
166
+
167
+ // Priority scoring:
168
+ // 3: Resumed SDK Activity
169
+ // 2: Resumed App Activity
170
+ // 1: Paused SDK Activity
171
+ // 0: Paused App Activity
172
+ val currentPriority = (if (isSDK) 1 else 0) + (if (!isPaused) 2 else 0)
173
+
174
+ Log.v(TAG, " [Audit] ${activity.javaClass.simpleName} -> Prio: $currentPriority (SDK=$isSDK, Paused=$isPaused)")
175
+
176
+ if (currentPriority > highestPriority) {
177
+ highestPriority = currentPriority
178
+ bestCandidate = activity
179
+ }
180
+
181
+ // Optimization: Found the absolute best target
182
+ if (highestPriority == 3) break
183
+
184
+ } catch (e: Exception) {
185
+ // Silently continue for individual activity record failures
134
186
  }
135
187
  }
136
- return topActivity ?: rnActivity
188
+
189
+ if (bestCandidate != null) {
190
+ Log.d(TAG, "✅ Best candidate found: ${bestCandidate.javaClass.simpleName} (Prio: $highestPriority)")
191
+ }
192
+
193
+ return bestCandidate
137
194
  } catch (e: Exception) {
138
- Log.e(TAG, "Error finding true current activity", e)
195
+ Log.e(TAG, " Critical error in findTopActivityViaReflection", e)
196
+ return null
139
197
  }
140
-
141
- return rnActivity
142
198
  }
143
199
 
144
200
  @ReactMethod
145
201
  fun showRNExitSheet(bundleName: String, initialProps: ReadableMap, promise: Promise) {
146
- val activity = getTrueCurrentActivity() ?: run {
147
- Log.e(TAG, "❌ showRNExitSheet failed: No visible activity found")
148
- promise.reject("NO_ACTIVITY", "No visible activity found")
149
- return
150
- }
151
-
152
- if (activity.isFinishing || activity.isDestroyed) {
153
- Log.e(TAG, "❌ showRNExitSheet failed: Activity is finishing/destroyed")
154
- promise.reject("ACTIVITY_INVALID", "Activity is finishing or destroyed")
155
- return
156
- }
202
+ // Fix: Move activity detection to UI thread to avoid race conditions and ensure correct window attachment
203
+ Handler(Looper.getMainLooper()).post {
204
+ val activity = getTrueCurrentActivity() ?: run {
205
+ Log.e(TAG, "❌ showRNExitSheet failed: No visible activity found")
206
+ promise.reject("NO_ACTIVITY", "No visible activity found")
207
+ return@post
208
+ }
157
209
 
158
- // Guard chống double-resolve/reject promise ( nhiều entry point: sync error, async listener, exception)
159
- val promiseSettled = java.util.concurrent.atomic.AtomicBoolean(false)
160
- fun safeResolve(value: Any?) {
161
- if (promiseSettled.compareAndSet(false, true)) promise.resolve(value)
162
- }
163
- fun safeReject(code: String, msg: String, e: Throwable? = null) {
164
- if (promiseSettled.compareAndSet(false, true)) {
165
- if (e != null) promise.reject(code, msg, e) else promise.reject(code, msg)
210
+ if (activity.isFinishing || (android.os.Build.VERSION.SDK_INT >= 17 && activity.isDestroyed)) {
211
+ Log.e(TAG, "❌ showRNExitSheet failed: Activity is finishing or destroyed")
212
+ promise.reject("ACTIVITY_INVALID", "Activity is finishing or destroyed")
213
+ return@post
166
214
  }
167
- }
168
215
 
169
- activity.runOnUiThread {
216
+ // Guard chống double-resolve/reject promise
217
+ val promiseSettled = java.util.concurrent.atomic.AtomicBoolean(false)
218
+ fun safeResolve(value: Any?) {
219
+ if (promiseSettled.compareAndSet(false, true)) promise.resolve(value)
220
+ }
221
+ fun safeReject(code: String, msg: String, e: Throwable? = null) {
222
+ if (promiseSettled.compareAndSet(false, true)) {
223
+ if (e != null) promise.reject(code, msg, e) else promise.reject(code, msg)
224
+ }
225
+ }
170
226
  try {
171
227
  val activityName = activity.javaClass.simpleName
172
228
  Log.d(TAG, "▶️ showRNExitSheet: Top Activity=$activityName, bundle=$bundleName")
173
229
 
174
230
  val reactApplication = activity.application as? ReactApplication
175
231
  if (reactApplication == null) {
176
- Log.e(TAG, "❌ Application does not implement ReactApplication")
232
+ Log.e(TAG, "❌ showRNExitSheet failed: Application class (${activity.application.javaClass.name}) does not implement ReactApplication. Please ensure your Application class implements ReactApplication or provide a way for the SDK to access the ReactInstanceManager.")
177
233
  safeReject("NO_REACT_APP", "Application does not implement ReactApplication")
178
- return@runOnUiThread
234
+ return@post
179
235
  }
180
236
  val reactInstanceManager = reactApplication.reactNativeHost.reactInstanceManager
181
237
 
182
238
  if (reactInstanceManager.currentReactContext != null) {
239
+ Log.d(TAG, "✅ ReactContext is ready, presenting sheet...")
183
240
  presentRNBottomSheet(activity, reactInstanceManager, bundleName, initialProps,
184
241
  ::safeResolve, ::safeReject)
185
- return@runOnUiThread
242
+ return@post
186
243
  }
187
244
 
188
245
  // Context chưa sẵn sàng: chờ listener
@@ -212,7 +269,7 @@ class EKYCModule(reactContext: ReactApplicationContext) : ReactContextBaseJavaMo
212
269
  Log.d(TAG, "✅ ReactContext init xong giữa lúc add listener — present luôn")
213
270
  presentRNBottomSheet(activity, reactInstanceManager, bundleName, initialProps,
214
271
  ::safeResolve, ::safeReject)
215
- return@runOnUiThread
272
+ return@post
216
273
  }
217
274
 
218
275
  // Chỉ trigger background create nếu chưa start (tránh IllegalStateException)
@@ -250,12 +307,17 @@ class EKYCModule(reactContext: ReactApplicationContext) : ReactContextBaseJavaMo
250
307
  safeReject: (String, String, Throwable?) -> Unit
251
308
  ) {
252
309
  try {
310
+ val minHeightPx = (400 * activity.resources.displayMetrics.density).toInt()
253
311
  val container = LinearLayout(activity).apply {
254
312
  orientation = LinearLayout.VERTICAL
255
313
  setBackgroundColor(Color.TRANSPARENT)
314
+ minimumHeight = minHeightPx
256
315
  }
257
316
 
258
317
  val rootView = ReactRootView(activity)
318
+ // Hardening: Set a minimum height to ensure the sheet is visible even before RN finishes layout
319
+ rootView.minimumHeight = minHeightPx
320
+
259
321
  rootView.layoutParams = LinearLayout.LayoutParams(
260
322
  LinearLayout.LayoutParams.MATCH_PARENT,
261
323
  LinearLayout.LayoutParams.WRAP_CONTENT
@@ -328,7 +390,7 @@ class EKYCModule(reactContext: ReactApplicationContext) : ReactContextBaseJavaMo
328
390
 
329
391
  bottomSheetDialog.show()
330
392
 
331
- Log.d(TAG, "✅ showRNExitSheet: BottomSheetDialog shown (wrap content), bundle=$bundleName")
393
+ Log.d(TAG, "✅ showRNExitSheet: BottomSheetDialog shown on ${activity.javaClass.simpleName}, bundle=$bundleName")
332
394
  safeResolve(true)
333
395
  } catch (e: Exception) {
334
396
  Log.e(TAG, "❌ Exception in presentRNBottomSheet", e)
@@ -903,12 +965,7 @@ class EKYCModule(reactContext: ReactApplicationContext) : ReactContextBaseJavaMo
903
965
  isActiveLiveness = isActiveLiveness ?: false,
904
966
  isActiveLivenessColor = isActiveLivenessColor ?: false,
905
967
  isShowCameraFont = isShowCameraFont ?: true,
906
- // Custom actions từ checkboxes (nếu có chọn)
907
- // Nếu có actions được chọn → sử dụng customActions
908
- // Nếu không có actions nào được chọn → sử dụng random actions với activeActionCount
909
968
  customActions = customActions,
910
- // Number of random actions (1-10), only used when customActions = null
911
- // activeActionCount = 2 → 2 random actions + STRAIGHT
912
969
  activeActionCount = activeActionCount ?: 2,
913
970
  forceCaptureTimeout = (forceCaptureTimeout ?: 0.0).toLong(),
914
971
  selfieImage = imageFile,
@@ -2645,15 +2702,16 @@ class EKYCModule(reactContext: ReactApplicationContext) : ReactContextBaseJavaMo
2645
2702
 
2646
2703
  @ReactMethod
2647
2704
  fun setExitSheetHeight(heightDp: Float) {
2648
- val activity = getTrueCurrentActivity() ?: return
2649
- val heightPx = (heightDp * activity.resources.displayMetrics.density).toInt()
2650
- Log.d(TAG, "▶️ setExitSheetHeight: ${heightDp}dp ${heightPx}px")
2651
- activity.runOnUiThread {
2652
- val sheet = currentExitSheet ?: return@runOnUiThread
2653
- if (!sheet.isShowing) return@runOnUiThread
2705
+ Handler(Looper.getMainLooper()).post {
2706
+ val activity = getTrueCurrentActivity() ?: return@post
2707
+ val heightPx = (heightDp * activity.resources.displayMetrics.density).toInt()
2708
+ Log.d(TAG, "▶️ setExitSheetHeight: ${heightDp}dp → ${heightPx}px")
2709
+
2710
+ val sheet = currentExitSheet ?: return@post
2711
+ if (!sheet.isShowing) return@post
2654
2712
  val bs = sheet.findViewById<View>(com.google.android.material.R.id.design_bottom_sheet)
2655
- ?: return@runOnUiThread
2656
- val lp = bs.layoutParams ?: return@runOnUiThread
2713
+ ?: return@post
2714
+ val lp = bs.layoutParams ?: return@post
2657
2715
  lp.height = heightPx
2658
2716
  bs.layoutParams = lp
2659
2717
  val behavior = com.google.android.material.bottomsheet.BottomSheetBehavior.from(bs)
package/dist/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@finos_sdk/sdk-ekyc",
3
- "version": "1.4.9",
3
+ "version": "1.5.0",
4
4
  "description": "React Native SDK for eKYC - Vietnamese CCCD NFC reading, OCR, Liveness detection, Face matching, and C06, eSign, SmsOTP residence verification",
5
5
  "main": "dist/index.js",
6
6
  "types": "dist/index.d.ts",
@@ -826,7 +826,11 @@ const isMethod = (prop) => {
826
826
  prop === 'checkC06' ||
827
827
  prop === 'startOcr' ||
828
828
  prop === 'startLiveness' ||
829
- prop === 'startFaceCompare';
829
+ prop === 'startFaceCompare' ||
830
+ prop === 'registerExitHandler' ||
831
+ prop === 'resolveExit' ||
832
+ prop === 'showRNExitSheet' ||
833
+ prop === 'setExitSheetComponent';
830
834
  };
831
835
  // Create a comprehensive stub object with all methods to prevent undefined errors
832
836
  const createFinosEKYCStub = () => {
@@ -856,6 +860,7 @@ const createFinosEKYCStub = () => {
856
860
  'startEkycUI', 'sendOtp', 'verifyOtp', 'resendOtp', 'initializeESign', 'openSessionId',
857
861
  'registerDevice', 'listCerts', 'verifyCert', 'listSignRequest', 'confirmSign',
858
862
  'registerRemoteSigning', 'signPdf', 'sendConfirmationDocument',
863
+ 'registerExitHandler', 'resolveExit', 'showRNExitSheet', 'setExitSheetComponent',
859
864
  'onResume', 'onPause', 'isSDKReady', 'getSDKInfo'
860
865
  ];
861
866
  otherMethods.forEach(method => {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@finos_sdk/sdk-ekyc",
3
- "version": "1.4.9",
3
+ "version": "1.5.0",
4
4
  "description": "React Native SDK for eKYC - Vietnamese CCCD NFC reading, OCR, Liveness detection, Face matching, and C06, eSign, SmsOTP residence verification",
5
5
  "main": "dist/index.js",
6
6
  "types": "dist/index.d.ts",
@@ -1001,7 +1001,11 @@ const isMethod = (prop: string | symbol): boolean => {
1001
1001
  prop === 'checkC06' ||
1002
1002
  prop === 'startOcr' ||
1003
1003
  prop === 'startLiveness' ||
1004
- prop === 'startFaceCompare';
1004
+ prop === 'startFaceCompare' ||
1005
+ prop === 'registerExitHandler' ||
1006
+ prop === 'resolveExit' ||
1007
+ prop === 'showRNExitSheet' ||
1008
+ prop === 'setExitSheetComponent';
1005
1009
  };
1006
1010
 
1007
1011
  // Create a comprehensive stub object with all methods to prevent undefined errors
@@ -1035,6 +1039,7 @@ const createFinosEKYCStub = (): FinosEKYCModule => {
1035
1039
  'startEkycUI', 'sendOtp', 'verifyOtp', 'resendOtp', 'initializeESign', 'openSessionId',
1036
1040
  'registerDevice', 'listCerts', 'verifyCert', 'listSignRequest', 'confirmSign',
1037
1041
  'registerRemoteSigning', 'signPdf', 'sendConfirmationDocument',
1042
+ 'registerExitHandler', 'resolveExit', 'showRNExitSheet', 'setExitSheetComponent',
1038
1043
  'onResume', 'onPause', 'isSDKReady', 'getSDKInfo'
1039
1044
  ];
1040
1045