Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@
package com.pingidentity.rnbinding

import androidx.annotation.VisibleForTesting
import com.facebook.react.bridge.Arguments
import com.facebook.react.bridge.Promise
import com.facebook.react.bridge.ReactApplicationContext
import com.facebook.react.bridge.ReadableMap
Expand All @@ -19,11 +20,11 @@ import com.pingidentity.logger.NONE
import com.pingidentity.logger.Logger
import com.pingidentity.rncore.CoreRuntime
import com.pingidentity.rncore.error.ErrorType
import com.pingidentity.rncore.utils.launchBridge
import kotlinx.coroutines.CompletableDeferred
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.SupervisorJob
import kotlinx.coroutines.launch
import java.lang.ref.WeakReference

/**
Expand Down Expand Up @@ -113,41 +114,32 @@ object RNPingBindingCommon {
"No foreground activity is available for Journey device binding.")
return
}
scope.launch {
try {
val index = parseCallbackIndex(options)
val callback = resolveDeviceBindingCallback(journeyId, index)
if (callback == null) {
rejectWithError(promise, BindingErrorCodes.BINDING_CALLBACK_NOT_FOUND,
"No active DeviceBindingCallback found for journey $journeyId at index $index.",
ErrorType.STATE_ERROR)
return@launch
}
val jsDeviceName = parseStringOption(options, "deviceName")
val jsSigningAlgorithm = parseStringOption(options, "signingAlgorithm")
callback.bind {
logger = resolvedLogger ?: Logger.NONE
jsDeviceName?.let { deviceName = it }
jsSigningAlgorithm?.let { signingAlgorithm = it }
applyCommonBindingConfig(this, options, callConfig.userKeyStorageId)
if (callConfig.hasPinCollector) {
appPinConfig { pinCollector { prompt -> bridgePinCollector(reactContext, prompt) } }
}
}.fold(
onSuccess = { promise.resolve(createJourneyResultPayload("success")) },
onFailure = { error ->
rejectWithError(promise, resolveBindingErrorCode(error, BindingErrorCodes.BINDING_BIND_ERROR),
error.localizedMessage ?: "Journey device binding callback execution failed.", throwable = error)
}
)
} catch (error: IllegalArgumentException) {
rejectWithError(promise, BindingErrorCodes.BINDING_BIND_ERROR,
error.localizedMessage ?: "Invalid Journey device binding options payload.",
ErrorType.ARGUMENT_ERROR, error)
} catch (error: Throwable) {
rejectWithError(promise, BindingErrorCodes.BINDING_BIND_ERROR,
error.localizedMessage ?: "Journey device binding callback execution failed.", throwable = error)
scope.launchBridge(promise, BindingErrorCodes.BINDING_BIND_ERROR) {
val index = parseCallbackIndex(options)
val callback = resolveDeviceBindingCallback(journeyId, index)
if (callback == null) {
rejectWithError(promise, BindingErrorCodes.BINDING_CALLBACK_NOT_FOUND,
"No active DeviceBindingCallback found for journey $journeyId at index $index.",
ErrorType.STATE_ERROR)
return@launchBridge
}
val jsDeviceName = parseStringOption(options, "deviceName")
val jsSigningAlgorithm = parseStringOption(options, "signingAlgorithm")
callback.bind {
logger = resolvedLogger ?: Logger.NONE
jsDeviceName?.let { deviceName = it }
jsSigningAlgorithm?.let { signingAlgorithm = it }
applyCommonBindingConfig(this, options, callConfig.userKeyStorageId)
if (callConfig.hasPinCollector) {
appPinConfig { pinCollector { prompt -> bridgePinCollector(reactContext, prompt) } }
}
}.fold(
onSuccess = { promise.resolve(createJourneyResultPayload("success")) },
onFailure = { error ->
rejectWithError(promise, resolveBindingErrorCode(error, BindingErrorCodes.BINDING_BIND_ERROR),
error.localizedMessage ?: "Journey device binding callback execution failed.", throwable = error)
}
)
}
}

Expand All @@ -171,44 +163,35 @@ object RNPingBindingCommon {
"No foreground activity is available for Journey device signing.")
return
}
scope.launch {
try {
val index = parseCallbackIndex(options)
val callback = resolveDeviceSigningVerifierCallback(journeyId, index)
if (callback == null) {
rejectWithError(promise, BindingErrorCodes.BINDING_CALLBACK_NOT_FOUND,
"No active DeviceSigningVerifierCallback found for journey $journeyId at index $index.",
ErrorType.STATE_ERROR)
return@launch
}
val jsSigningAlgorithm = parseStringOption(options, "signingAlgorithm")
val jsClaims = parseClaims(options)
callback.sign {
logger = resolvedLogger ?: Logger.NONE
jsSigningAlgorithm?.let { signingAlgorithm = it }
if (jsClaims.isNotEmpty()) { claims { putAll(jsClaims) } }
applyCommonBindingConfig(this, options, callConfig.userKeyStorageId)
if (callConfig.hasPinCollector) {
appPinConfig { pinCollector { prompt -> bridgePinCollector(reactContext, prompt) } }
}
if (callConfig.hasUserKeySelector) {
userKeySelector { keys -> bridgeUserKeySelector(reactContext, keys) }
}
}.fold(
onSuccess = { promise.resolve(createJourneyResultPayload("success")) },
onFailure = { error ->
rejectWithError(promise, resolveBindingErrorCode(error, BindingErrorCodes.BINDING_SIGN_ERROR),
error.localizedMessage ?: "Journey device signing callback execution failed.", throwable = error)
}
)
} catch (error: IllegalArgumentException) {
rejectWithError(promise, BindingErrorCodes.BINDING_SIGN_ERROR,
error.localizedMessage ?: "Invalid Journey device signing options payload.",
ErrorType.ARGUMENT_ERROR, error)
} catch (error: Throwable) {
rejectWithError(promise, BindingErrorCodes.BINDING_SIGN_ERROR,
error.localizedMessage ?: "Journey device signing callback execution failed.", throwable = error)
scope.launchBridge(promise, BindingErrorCodes.BINDING_SIGN_ERROR) {
val index = parseCallbackIndex(options)
val callback = resolveDeviceSigningVerifierCallback(journeyId, index)
if (callback == null) {
rejectWithError(promise, BindingErrorCodes.BINDING_CALLBACK_NOT_FOUND,
"No active DeviceSigningVerifierCallback found for journey $journeyId at index $index.",
ErrorType.STATE_ERROR)
return@launchBridge
}
val jsSigningAlgorithm = parseStringOption(options, "signingAlgorithm")
val jsClaims = parseClaims(options)
callback.sign {
logger = resolvedLogger ?: Logger.NONE
jsSigningAlgorithm?.let { signingAlgorithm = it }
if (jsClaims.isNotEmpty()) { claims { putAll(jsClaims) } }
applyCommonBindingConfig(this, options, callConfig.userKeyStorageId)
if (callConfig.hasPinCollector) {
appPinConfig { pinCollector { prompt -> bridgePinCollector(reactContext, prompt) } }
}
if (callConfig.hasUserKeySelector) {
userKeySelector { keys -> bridgeUserKeySelector(reactContext, keys) }
}
}.fold(
onSuccess = { promise.resolve(createJourneyResultPayload("success")) },
onFailure = { error ->
rejectWithError(promise, resolveBindingErrorCode(error, BindingErrorCodes.BINDING_SIGN_ERROR),
error.localizedMessage ?: "Journey device signing callback execution failed.", throwable = error)
}
)
}
}

Expand All @@ -217,71 +200,56 @@ object RNPingBindingCommon {
/** Returns all registered device binding keys from [UserKeysStorage] as a JS array. */
@JvmStatic
fun getAllKeys(promise: Promise) {
scope.launch {
try {
val storage = userKeysStorage
val result = com.facebook.react.bridge.Arguments.createArray().apply {
storage.findAll().forEach { key ->
pushMap(com.facebook.react.bridge.Arguments.createMap().apply {
putString("id", key.id)
putString("userId", key.userId)
putString("username", key.userName)
putString("authenticationType", key.authType.name)
})
}
scope.launchBridge(promise, BindingErrorCodes.BINDING_ERROR) {
val storage = userKeysStorage
val result = Arguments.createArray().apply {
storage.findAll().forEach { key ->
pushMap(Arguments.createMap().apply {
putString("id", key.id)
putString("userId", key.userId)
putString("username", key.userName)
putString("authenticationType", key.authType.name)
})
}
promise.resolve(result)
} catch (error: Throwable) {
rejectWithError(promise, BindingErrorCodes.BINDING_ERROR,
error.localizedMessage ?: "Failed to retrieve binding keys.", throwable = error)
}
promise.resolve(result)
}
}

/** Deletes the key identified by [userId] and [keyId], including its KeyStore material. */
@JvmStatic
fun deleteKey(userId: String, keyId: String, promise: Promise) {
scope.launch {
try {
val storage = userKeysStorage
val key = storage.findAll().firstOrNull { it.id == keyId && it.userId == userId }
if (key == null) {
rejectWithError(promise, BindingErrorCodes.BINDING_KEY_DELETE_ERROR,
"No binding key found.", ErrorType.STATE_ERROR)
return@launch
}
deleteKeyMaterial(key)
storage.delete(key)
promise.resolve(null)
} catch (error: Throwable) {
scope.launchBridge(promise, BindingErrorCodes.BINDING_KEY_DELETE_ERROR) {
val storage = userKeysStorage
val key = storage.findAll().firstOrNull { it.id == keyId && it.userId == userId }
if (key == null) {
rejectWithError(promise, BindingErrorCodes.BINDING_KEY_DELETE_ERROR,
error.localizedMessage ?: "Failed to delete binding key.", throwable = error)
"No binding key found.", ErrorType.STATE_ERROR)
return@launchBridge
}
deleteKeyMaterial(key)
storage.delete(key)
promise.resolve(null)
}
}

/** Deletes all registered device binding keys, including their KeyStore material. */
@JvmStatic
fun deleteAllKeys(promise: Promise) {
scope.launch {
try {
val storage = userKeysStorage
val errors = mutableListOf<String>()
storage.findAll().forEach { key ->
runCatching {
deleteKeyMaterial(key)
storage.delete(key)
}.onFailure { errors.add(it.localizedMessage ?: "Failed to delete key.") }
}
if (errors.isEmpty()) {
promise.resolve(null)
} else {
rejectWithError(promise, BindingErrorCodes.BINDING_KEY_DELETE_ERROR,
errors.joinToString("; "))
}
} catch (error: Throwable) {
scope.launchBridge(promise, BindingErrorCodes.BINDING_KEY_DELETE_ERROR) {
val storage = userKeysStorage
val errors = mutableListOf<String>()
storage.findAll().forEach { key ->
runCatching {
deleteKeyMaterial(key)
storage.delete(key)
}.onFailure { errors.add(it.localizedMessage ?: "Failed to delete key.") }
}
if (errors.isEmpty()) {
promise.resolve(null)
} else {
rejectWithError(promise, BindingErrorCodes.BINDING_KEY_DELETE_ERROR,
error.localizedMessage ?: "Failed to delete all binding keys.", throwable = error)
errors.joinToString("; "))
}
}
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -34,7 +34,7 @@ import kotlinx.coroutines.CancellationException
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.SupervisorJob
import kotlinx.coroutines.launch
import com.pingidentity.rncore.utils.launchBridge

/**
* Common utilities for the Ping Browser module.
Expand Down Expand Up @@ -188,7 +188,7 @@ object RNPingBrowserCommon {
null
}

scope.launch {
scope.launchBridge(promise, BrowserErrorCodes.BROWSER_OPEN_ERROR) {
val launchUrl = try {
parseLaunchUrl(url)
} catch (e: MalformedURLException) {
Expand All @@ -200,12 +200,14 @@ object RNPingBrowserCommon {
),
e
)
return@launch
return@launchBridge
}

val result = try {
val resolvedRedirectUri = redirectUri?.toUri() ?: browserLauncher.redirectUri
browserLauncher.launch(launchUrl, resolvedRedirectUri)
} catch (e: CancellationException) {
throw e
} catch (e: Exception) {
Result.failure(e)
}
Expand All @@ -216,22 +218,22 @@ object RNPingBrowserCommon {
val payload = mapFactory()
payload.putString("type", "cancel")
promise.resolve(payload)
return@launch
return@launchBridge
}

val payload = mapFactory()
payload.putString("type", "success")
payload.putString("url", uri.toString())
promise.resolve(payload)
return@launch
return@launchBridge
}

val error = result.exceptionOrNull()
if (error is BrowserCanceledException || error is CancellationException) {
if (error is BrowserCanceledException) {
val payload = mapFactory()
payload.putString("type", "cancel")
promise.resolve(payload)
return@launch
return@launchBridge

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

CancellationException is swallowed and resolved as a {type:"cancel"} payload here (the if (error is BrowserCanceledException || error is CancellationException) at line 230), defeating the migration's purpose.

The inner catch (e: Exception) { Result.failure(e) } (~line 211) captures coroutine CancellationException into the Result, and this branch then resolves {type:"cancel"} for it. launchBridge exists precisely to re-throw CancellationException so scope cancellation propagates without settling the promise — this site subverts that.

Inconsistent with iOS: packages/browser/ios/RNPingBrowserCommon.swift resolves {type:"cancel"} only for BrowserError.externalUserAgentCancelled / ASWebAuthenticationSessionError.canceledLogin, and lets Swift CancellationError reject through the generic catch. BrowserCanceledException (Android's genuine user-cancel) is a plain RuntimeException, unrelated to kotlinx.coroutines.CancellationException, and is returned via normal suspend completion — not via coroutine cancellation.

Suggested fix: drop the || error is CancellationException disjunct at line 230, and stop catching CancellationException in the inner catch (e: Exception) (re-throw it). Keep BrowserCanceledException -> {type:"cancel"}. Genuine user cancels are unaffected; structured-concurrency cancellation then propagates per the launchBridge contract and matches iOS.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed. Added catch (e: CancellationException) { throw e } before catch (e: Exception) so CancellationException is never boxed into Result.failure, and dropped the || error is CancellationException disjunct from the result.exceptionOrNull() check. The kotlinx.coroutines.CancellationException import is still needed for the rethrow clause. BrowserCanceledException to {type:"cancel"} is unchanged.

}

// Map native errors to the shared JS contract from RNPingCore.
Expand Down
1 change: 1 addition & 0 deletions packages/core/android/build.gradle
Original file line number Diff line number Diff line change
Expand Up @@ -86,4 +86,5 @@ dependencies {
implementation "org.jetbrains.kotlin:kotlin-stdlib:$kotlin_version"
implementation "org.jetbrains.kotlinx:kotlinx-serialization-json:1.9.0"
testImplementation "junit:junit:4.13.2"
testImplementation "org.robolectric:robolectric:4.11.1"
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,50 @@
/*
* Copyright (c) 2026 Ping Identity Corporation. All rights reserved.
*
* This software may be modified and distributed under the terms
* of the MIT license. See the LICENSE file for details.
*/

package com.pingidentity.rncore.utils

import com.facebook.react.bridge.Promise
import com.pingidentity.rncore.error.mapThrowableToGenericError
import com.pingidentity.rncore.error.reject
import kotlinx.coroutines.CancellationException
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Job
import kotlinx.coroutines.launch
import kotlin.coroutines.CoroutineContext
import kotlin.coroutines.EmptyCoroutineContext

/**
* Launches a coroutine that automatically handles promise rejection on failure.
*
* [CancellationException] is re-thrown so that structured-concurrency scope cancellation
* propagates correctly without settling the promise. All other [Throwable] instances are
* mapped to a [com.pingidentity.rncore.error.GenericError] via
* [mapThrowableToGenericError] and the promise is rejected with the resulting error.
*
* @param promise The React Native promise to reject on failure. Success settlement
* (`resolve`) is the caller's responsibility inside [block].
* @param errorCode The module-specific error code passed to [mapThrowableToGenericError].
* @param context Additional [CoroutineContext] elements merged into the launch context.
* Defaults to [EmptyCoroutineContext] so the receiver scope's dispatcher is preserved.
* @param block The suspend body to execute inside the coroutine.
* @return The [Job] for the launched coroutine.
*/
@JvmSynthetic
fun CoroutineScope.launchBridge(
promise: Promise,
errorCode: String,
context: CoroutineContext = EmptyCoroutineContext,
block: suspend CoroutineScope.() -> Unit
): Job = launch(context) {
try {
block()
} catch (e: CancellationException) {
throw e
} catch (e: Throwable) {
promise.reject(mapThrowableToGenericError(e, errorCode), e)
}
}
Loading
Loading