Skip to content
Open
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 @@ -19,11 +19,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 +113,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 +162,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 +199,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 = 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)
})
}
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,7 +200,7 @@ object RNPingBrowserCommon {
),
e
)
return@launch
return@launchBridge
}

val result = try {
Expand All @@ -216,22 +216,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) {
val payload = mapFactory()
payload.putString("type", "cancel")
promise.resolve(payload)
return@launch
return@launchBridge
}

// 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.7.3"
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,49 @@
/*
* 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 settle on success or failure.
Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

⚠️ Potential issue | 🟡 Minor | ⚡ Quick win

KDoc overstates what launchBridge settles. The function only rejects the promise on non-cancellation failure; success settlement (resolve) is the block's responsibility (as the tests confirm). The @param promise text "to settle on success or failure" can mislead callers into omitting their own resolve.

📝 Suggested wording
- * `@param` promise The React Native promise to settle on success or failure.
+ * `@param` promise The React Native promise rejected on non-cancellation failure.
+ *   On success the promise is left untouched; the [block] is responsible for resolving it.
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
* @param promise The React Native promise to settle on success or failure.
* `@param` promise The React Native promise rejected on non-cancellation failure.
* On success the promise is left untouched; the [block] is responsible for resolving it.
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In
`@packages/core/android/src/main/java/com/pingidentity/rncore/utils/CoroutineBridge.kt`
at line 28, The KDoc for launchBridge incorrectly states that the provided
promise is settled on success or failure; in reality launchBridge only rejects
the promise on non-cancellation failures and does not call resolve for
successful completions. Update the KDoc for the function launchBridge and its
param promise to clarify that callers are responsible for resolving the promise
on success and that launchBridge will only reject the promise on
non-cancellation errors (or leave resolution to the provided block). Refer to
the launchBridge function and the promise parameter in the comment to ensure the
wording matches the implemented behavior.

* @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