diff --git a/README.md b/README.md index 3679f96..706c6ee 100644 --- a/README.md +++ b/README.md @@ -93,6 +93,59 @@ You do not need to request camera permission in your app code before calling `st Workflows can include a **Bank** step (the person links a bank account) and a **Location** step (the device position is read once, with the person's consent). Both screens are drawn by the native SDKs, so this package needs no new API: they run inside `startVerification()` / `startVerificationWithWorkflow()`, and the outcome comes back as the same `VerificationResult`. +### Bank Link + +Bank Link is the standalone bank product: it opens the connection flow on its own, outside a verification session, and keeps reading balances and transactions for as long as the person allows (or reads once, for a one-time link). Every screen, state and string is native; this package only carries the result and the events, under the same names, events and payload keys as native and the web SDK. + +Bank Link needs the native SDK release that ships it (4.16.0 or later). On a build that links an earlier native release, `presentBankLink` and `resumeBankLink` reject with the code `not_available`. When a presentation cannot open (no screen to present from), the promise rejects with the code `bank_link` and the message `Bank Link presentation was declined.`, on both platforms. + +Create the link on your backend with `POST /v3/bank/links/` and pass its `client_token` (`blt_...`) to the app. **The API key stays on the server: it never reaches your app.** + +```tsx +import { + presentBankLink, + onBankLinkEvent, + type BankLinkResult, +} from '@didit-protocol/sdk-react-native'; + +const stop = onBankLinkEvent(({ name, payload }) => { + console.log(name, payload.link_id); +}); + +try { + const result: BankLinkResult = await presentBankLink(clientToken); + if (result.type === 'success') { + console.log('Linked', result.connectionId); + } else { + console.log('Ended', result.reason, result.step); + } +} finally { + stop(); +} +``` + +Resume after relaunch, when the person was at their bank while the app was closed: + +```tsx +import { resumeBankLink } from '@didit-protocol/sdk-react-native'; + +const resumed = await resumeBankLink(); // null when nothing is pending +if (resumed?.type === 'success') { + console.log('Linked', resumed.connectionId, 'resumed:', resumed.resumed); +} +``` + +If your bank return is an app link or universal link, hand every address the app is opened with to the SDK; it decides whether the address is a link return, and the server decides the screen: + +```tsx +import { handleBankLinkReturn } from '@didit-protocol/sdk-react-native'; + +// onOpenURL / onNewIntent +handleBankLinkReturn(url); +``` + +`presentBankLink` presents from the current view controller or activity, and `resumeBankLink` takes the same single-link slot, so a second call of either while a link is open rejects instead of replacing the first one's result. + ### Bank No setup. The native SDKs open the bank's page (or a page Didit hosts) in the system browser, so there is no permission, URL scheme or deep link to register. @@ -826,6 +879,62 @@ Fetch the current state of a transaction previously submitted with the same toke Returns: `Promise` +### `presentBankLink(token, options?)` + +Open a Bank Link. Every screen, state and string is native. + +| Parameter | Type | Required | Description | +|-----------|------|----------|-------------| +| `token` | `string` | Yes | The link's `client_token` (`blt_...`) from `POST /v3/bank/links/` | +| `options` | `BankLinkOptions` | No | `config` (`DiditConfig`) for language, font and logging | + +Returns: `Promise`, resolved once, as `{ type: 'success', linkId, connectionId?, checkId?, resumed? }` or `{ type: 'exit', reason, step?, resumed? }`. `reason` is one of `closed`, `cancelled`, `bank_unavailable`, `expired`, `failed`. + +Throws: when a link is already open, or when the native result cannot be read. + +### `resumeBankLink()` + +Pick up a link whose bank hop outlived the app, for example after the app was killed in the background. Call it once at start-up. + +Returns: `Promise` - the result with `resumed: true`, or `null` when nothing is pending. + +On Android it waits up to 30 seconds for the host activity when the call arrives before it is attached, then rejects with `no_activity`; it also rejects while a link is already open, so it never replaces the callbacks of a presentation in flight. + +### `onBankLinkEvent(listener)` + +Listen to the events of a Bank Link. Subscribe before `presentBankLink` to see `opened` and every step after it. + +| Parameter | Type | Required | Description | +|-----------|------|----------|-------------| +| `listener` | `(event: BankLinkEvent) => void` | Yes | Called once per event | + +Returns: `() => void` - the unsubscribe function. + +| Event | Payload keys | +|-------|--------------| +| `opened` | `link_id`, `mode`, `access`, `presentation` | +| `consent_shown` | `link_id`, `consent_version` | +| `consent_accepted` | `link_id`, `consent_version` | +| `institution_selected` | `link_id`, `institution_id`, `country` | +| `bank_redirect` | `link_id`, `via` | +| `bank_returned` | `link_id`, `result` | +| `accounts_selected` | `link_id`, `count` | +| `success` | `link_id`, `connection_id?`, `check_id?` | +| `exit` | `link_id`, `reason`, `step` | +| `error` | `link_id`, `code` | + +Every payload includes `link_id`, which is `null` until the ID is known. Replayed terminal events may also carry `resumed`. Payloads carry ids only: never a name, an account number, a token or an email. `success` and `exit` fire at most once each, and never both for one link. + +### `handleBankLinkReturn(url)` + +Hand an address the app was opened with to the SDK, for hosts whose bank return is an app link or universal link. Call it from `onOpenURL`/`onNewIntent` with every address: native decides whether it is a link return. + +| Parameter | Type | Required | Description | +|-----------|------|----------|-------------| +| `url` | `string` | Yes | The address the app was opened with | + +Returns: `void`. + ## Exported Types ```tsx @@ -835,6 +944,10 @@ import { startVerificationWithWorkflow, submitTransaction, getTransaction, + presentBankLink, + resumeBankLink, + onBankLinkEvent, + handleBankLinkReturn, // Enum VerificationStatus, @@ -863,6 +976,16 @@ import { type DiditTransactionResult, type DiditTransactionOptions, type DiditTransactionErrorCode, + type BankLinkOptions, + type BankLinkResult, + type BankLinkSuccess, + type BankLinkExit, + type BankLinkExitReason, + type BankLinkStep, + type BankLinkEvent, + type BankLinkEventName, + type BankLinkEventPayload, + type BankLinkEventListener, } from '@didit-protocol/sdk-react-native'; ``` diff --git a/SdkReactNative.podspec b/SdkReactNative.podspec index 1b036e3..74296b6 100644 --- a/SdkReactNative.podspec +++ b/SdkReactNative.podspec @@ -74,6 +74,15 @@ if package.dig("diditNativeSdkVersions", "source") raise "The pinned native source requires CocoaPods linkage." if didit_sdk_ios_linkage == "spm" end +# Bank Link is only in the native source pin until a released SDK version +# carries it; `diditNativeSdkVersions.bankLink` marks that release. Without +# either, the bridge compiles a stand-in that rejects the calls, because the +# released SDK it links against has no Bank Link API. +didit_sdk_bank_link_enabled = ( + !package.dig("diditNativeSdkVersions", "source").nil? || + package.dig("diditNativeSdkVersions", "bankLink") == true +) + unless ["spm", "cocoapods"].include?(didit_sdk_ios_linkage) raise "Invalid DiditSdk iOS linkage '#{didit_sdk_ios_linkage}'. Set $DiditSdkIosLinkage or DIDIT_SDK_IOS_LINKAGE to one of: spm, cocoapods." end @@ -116,6 +125,10 @@ Pod::Spec.new do |s| ].join(" ") } + if didit_sdk_bank_link_enabled + s.pod_target_xcconfig["SWIFT_ACTIVE_COMPILATION_CONDITIONS"] = "$(inherited) DIDIT_BANK_LINK" + end + if didit_sdk_ios_linkage == "spm" spm_dependency(s, url: "https://github.com/didit-protocol/sdk-ios.git", diff --git a/android/build.gradle b/android/build.gradle index bad45fe..e4d8391 100644 --- a/android/build.gradle +++ b/android/build.gradle @@ -43,6 +43,12 @@ if (nativePins.source && !gradle.ext.has("diditNativeSourceRepository")) { throw new GradleException("Apply the wrapper android/native-source.gradle in settings.gradle to use the pinned native source.") } +// Bank Link is only in the native source pin until a released SDK version +// carries it; `diditNativeSdkVersions.bankLink` marks that release. Without +// either, the module builds against a released SDK that has no Bank Link API, +// so compile the released-only stand-in instead of the native calls. +def bankLinkEnabled = nativePins.source != null || nativePins.bankLink == true + def diditSdkAndroidVariantProperty = ( rootProject.findProperty("diditSdkAndroidVariant") ?: findProperty("diditSdkAndroidVariant") @@ -111,6 +117,12 @@ android { jvmTarget = "17" } + sourceSets { + main { + java.srcDirs += bankLinkEnabled ? "src/bankLink/java" : "src/released/java" + } + } + if (diditSdkAndroidUsesNfc) { configurations.configureEach { exclude group: 'org.bouncycastle', module: 'bcprov-jdk15to18' diff --git a/android/src/bankLink/java/com/sdkreactnative/BankLinkJson.kt b/android/src/bankLink/java/com/sdkreactnative/BankLinkJson.kt new file mode 100644 index 0000000..6fa4c43 --- /dev/null +++ b/android/src/bankLink/java/com/sdkreactnative/BankLinkJson.kt @@ -0,0 +1,85 @@ +package com.sdkreactnative + +import me.didit.sdk.features.bank.link.BankLinkEvent +import me.didit.sdk.features.bank.link.BankLinkResult +import org.json.JSONArray +import org.json.JSONException +import org.json.JSONObject + +/** + * The Bank Link values the TurboModule hands JavaScript. + * + * An event travels as `{ name, payload }`, with the wire name of the link + * contract (`opened`, `consent_shown`, ..., `error`) and its ids-only payload; + * a presentation travels as one result object. JavaScript maps both, so the + * keys here are the ones `src/bankLink.ts` reads and nothing else. + * + * This file, [BankLinkSupport] and the module's three Bank Link overrides are + * the only places that touch the native Bank Link API; they are reconciled + * with that API when the native version that carries it is pinned. + */ +internal object BankLinkJson { + + fun event(event: BankLinkEvent): String = try { + JSONObject() + .put("name", event.name.wire) + .put("payload", payloadJson(event.payload)) + .toString() + } catch (e: JSONException) { + // A payload the JSON writer cannot carry must not throw inside the + // native event callback: the event still arrives, with what is safe. + JSONObject() + .put("name", event.name.wire) + .put("payload", JSONObject().put("link_id", JSONObject.NULL)) + .toString() + } + + /** + * An event payload as JSON. Mirrors the iOS `jsonSafe` guard: strings, + * numbers, booleans, arrays and maps travel; anything else becomes `null` + * instead of throwing inside the callback. + */ + private fun payloadJson(payload: Map): JSONObject { + val json = JSONObject() + for ((key, value) in payload) { + json.put(key, jsonSafe(value)) + } + return json + } + + private fun jsonSafe(value: Any?): Any = when (value) { + null -> JSONObject.NULL + is String, is Boolean -> value + is Double -> if (value.isFinite()) value else JSONObject.NULL + is Float -> if (value.isFinite()) value else JSONObject.NULL + is Number -> value + is Map<*, *> -> JSONObject().also { json -> + for ((key, nested) in value) { + if (key is String) json.put(key, jsonSafe(nested)) + } + } + is Iterable<*> -> JSONArray().also { array -> + for (element in value) array.put(jsonSafe(element)) + } + else -> JSONObject.NULL + } + + fun result(result: BankLinkResult): String = when (result) { + is BankLinkResult.Success -> JSONObject() + .put("type", "success") + .put("linkId", result.success.linkId) + .put("connectionId", result.success.connectionId ?: JSONObject.NULL) + .put("checkId", result.success.checkId ?: JSONObject.NULL) + .put("resumed", result.success.resumed) + .toString() + + is BankLinkResult.Exit -> exit(result.exit.reason.wire, result.exit.step?.wire, result.exit.resumed) + } + + fun exit(reason: String, step: String?, resumed: Boolean): String = JSONObject() + .put("type", "exit") + .put("reason", reason) + .put("step", step ?: JSONObject.NULL) + .put("resumed", resumed) + .toString() +} diff --git a/android/src/bankLink/java/com/sdkreactnative/BankLinkSupport.kt b/android/src/bankLink/java/com/sdkreactnative/BankLinkSupport.kt new file mode 100644 index 0000000..764c3ca --- /dev/null +++ b/android/src/bankLink/java/com/sdkreactnative/BankLinkSupport.kt @@ -0,0 +1,52 @@ +package com.sdkreactnative + +import android.app.Activity +import android.net.Uri +import me.didit.sdk.Configuration +import me.didit.sdk.DiditSdk + +/** + * The native Bank Link calls, compiled only when the pinned native SDK carries + * Bank Link (a source pin, or `diditNativeSdkVersions.bankLink` once released). + * + * The released-only build compiles the counterpart in `src/released` instead, + * so the module keeps building against a native SDK that predates Bank Link. + */ +internal object BankLinkSupport { + + const val available = true + + /** The JSON `null` a resume answers when nothing is pending. */ + const val NONE = "null" + + fun present( + activity: Activity, + token: String, + configuration: Configuration?, + onEvent: (String) -> Unit, + onResult: (String) -> Unit + ) { + val presented = DiditSdk.presentBankLink( + activity = activity, + token = token, + configuration = configuration, + onEvent = { event -> onEvent(BankLinkJson.event(event)) }, + onResult = { result -> onResult(BankLinkJson.result(result)) } + ) + check(presented) { "Bank Link presentation was declined." } + } + + fun resume( + activity: Activity, + onEvent: (String) -> Unit, + onResult: (String) -> Unit + ): Boolean = DiditSdk.resumeBankLink( + activity = activity, + onEvent = { event -> onEvent(BankLinkJson.event(event)) }, + onResult = { result -> onResult(BankLinkJson.result(result)) } + ) + + fun handle(uri: Uri) { + DiditSdk.handleBankLinkReturn(uri) + } +} diff --git a/android/src/main/java/com/sdkreactnative/SdkReactNativeModule.kt b/android/src/main/java/com/sdkreactnative/SdkReactNativeModule.kt index be584b4..949f442 100644 --- a/android/src/main/java/com/sdkreactnative/SdkReactNativeModule.kt +++ b/android/src/main/java/com/sdkreactnative/SdkReactNativeModule.kt @@ -1,5 +1,6 @@ package com.sdkreactnative +import android.net.Uri import com.facebook.react.bridge.Arguments import com.facebook.react.bridge.LifecycleEventListener import com.facebook.react.bridge.Promise @@ -397,6 +398,124 @@ class SdkReactNativeModule(reactContext: ReactApplicationContext) : } } + // ─── Bank Link ─────────────────────────────────────────────────────────── + + override fun presentBankLink(token: String, config: ReadableMap?, promise: Promise) { + val activity = reactApplicationContext.currentActivity + if (activity == null) { + logDebugError("presentBankLink: no active Activity at call time") + promise.reject("no_activity", "No active Activity available to present Bank Link.") + return + } + if (!BankLinkSupport.available) { + promise.reject("not_available", "This native SDK version does not include Bank Link.") + return + } + scope.launch { + try { + BankLinkSupport.present( + activity = activity, + token = token, + configuration = parseConfiguration(config), + onEvent = { eventJson -> emitOnBankLinkEvent(eventJson) }, + onResult = { resultJson -> promise.resolve(resultJson) } + ) + } catch (e: Exception) { + logDebugError("presentBankLink: exception", e) + promise.reject("bank_link", e.message, e) + } + } + } + + override fun resumeBankLink(promise: Promise) { + if (!BankLinkSupport.available) { + promise.reject("not_available", "This native SDK version does not include Bank Link.") + return + } + scope.launch { + // A host calls this once at start-up, before its Activity is + // attached: wait for it, as startVerification waits for the SDK, + // instead of refusing a call that may well have a link pending. + val activity = awaitActivity() + if (activity == null) { + // Never reported as "nothing to resume": a link may well be + // pending, so the host is told the call could not run. + logDebugError("resumeBankLink: no Activity within ${ACTIVITY_TIMEOUT_MS}ms") + promise.reject("no_activity", "No active Activity available to resume Bank Link.") + return@launch + } + try { + val resumed = BankLinkSupport.resume( + activity = activity, + onEvent = { eventJson -> emitOnBankLinkEvent(eventJson) }, + onResult = { resultJson -> promise.resolve(resultJson) } + ) + if (!resumed) { + promise.resolve(BankLinkSupport.NONE) + } + } catch (e: Exception) { + logDebugError("resumeBankLink: exception", e) + promise.reject("bank_link", e.message, e) + } + } + } + + /** + * The Activity a Bank Link is presented from, waiting for the host to + * attach one when the call arrives first (a host calls `resumeBankLink` + * once at start-up). `null` when none arrives within + * [ACTIVITY_TIMEOUT_MS], so the call fails with `no_activity` instead of + * waiting forever. + */ + private suspend fun awaitActivity(): android.app.Activity? { + reactApplicationContext.currentActivity?.let { return it } + + return withTimeoutOrNull(ACTIVITY_TIMEOUT_MS) { + suspendCancellableCoroutine { continuation -> + val listener = object : LifecycleEventListener { + override fun onHostResume() { + val activity = reactApplicationContext.currentActivity + if (activity != null && continuation.isActive) { + reactApplicationContext.removeLifecycleEventListener(this) + continuation.resume(activity) + } + } + + override fun onHostPause() = Unit + + override fun onHostDestroy() { + reactApplicationContext.removeLifecycleEventListener(this) + if (continuation.isActive) continuation.resume(null) + } + } + reactApplicationContext.addLifecycleEventListener(listener) + continuation.invokeOnCancellation { + reactApplicationContext.removeLifecycleEventListener(listener) + } + // The Activity may have appeared between the read above and + // the listener being added. + val activity = reactApplicationContext.currentActivity + if (activity != null && continuation.isActive) { + reactApplicationContext.removeLifecycleEventListener(listener) + continuation.resume(activity) + } + } + } + } + + override fun handleBankLinkReturn(url: String) { + if (!BankLinkSupport.available) { + return + } + // Native decides whether the address is a Bank Link return. The address + // is never parsed here: a resume code arrives in a query parameter and + // contains a dot, so nothing may split or normalise it. + val uri = Uri.parse(url) + reactApplicationContext.runOnUiQueueThread { + BankLinkSupport.handle(uri) + } + } + // ─── Diagnostics ───────────────────────────────────────────────────────── /** @@ -417,5 +536,8 @@ class SdkReactNativeModule(reactContext: ReactApplicationContext) : companion object { const val NAME = NativeSdkReactNativeSpec.NAME private const val TAG = "DiditSdkRN" + + /** How long a Bank Link call waits for the host Activity. */ + private const val ACTIVITY_TIMEOUT_MS = 30_000L } } diff --git a/android/src/released/java/com/sdkreactnative/BankLinkSupport.kt b/android/src/released/java/com/sdkreactnative/BankLinkSupport.kt new file mode 100644 index 0000000..b21a8f2 --- /dev/null +++ b/android/src/released/java/com/sdkreactnative/BankLinkSupport.kt @@ -0,0 +1,36 @@ +package com.sdkreactnative + +import android.app.Activity +import android.net.Uri +import me.didit.sdk.Configuration + +/** + * Bank Link without the native API: the pinned released SDK predates it. + * + * The module checks [available] and rejects `not_available` before calling any + * of these, so a released-only build never presents a flow the native SDK + * cannot run. + */ +internal object BankLinkSupport { + + const val available = false + + /** The JSON `null` a resume answers when nothing is pending. */ + const val NONE = "null" + + fun present( + activity: Activity, + token: String, + configuration: Configuration?, + onEvent: (String) -> Unit, + onResult: (String) -> Unit + ) = Unit + + fun resume( + activity: Activity, + onEvent: (String) -> Unit, + onResult: (String) -> Unit + ): Boolean = false + + fun handle(uri: Uri) = Unit +} diff --git a/example/ios/SdkReactNativeExample/AppDelegate.swift b/example/ios/SdkReactNativeExample/AppDelegate.swift index 98cc40a..22b87ae 100644 --- a/example/ios/SdkReactNativeExample/AppDelegate.swift +++ b/example/ios/SdkReactNativeExample/AppDelegate.swift @@ -10,6 +10,20 @@ class AppDelegate: UIResponder, UIApplicationDelegate { var reactNativeDelegate: ReactNativeDelegate? var reactNativeFactory: RCTReactNativeFactory? + func application( + _ app: UIApplication, open url: URL, + options: [UIApplication.OpenURLOptionsKey: Any] = [:] + ) -> Bool { + RCTLinkingManager.application(app, open: url, options: options) + } + + func application( + _ application: UIApplication, continue userActivity: NSUserActivity, + restorationHandler: @escaping ([UIUserActivityRestoring]?) -> Void + ) -> Bool { + RCTLinkingManager.application(application, continue: userActivity, restorationHandler: restorationHandler) + } + func application( _ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]? = nil diff --git a/example/src/App.tsx b/example/src/App.tsx index 2c639cb..6a64533 100644 --- a/example/src/App.tsx +++ b/example/src/App.tsx @@ -1,5 +1,6 @@ -import { useState, useCallback } from 'react'; +import { useState, useCallback, useEffect } from 'react'; import { + Linking, Text, View, StyleSheet, @@ -15,14 +16,47 @@ import { startVerification, startVerificationWithWorkflow, submitTransaction, + presentBankLink, + resumeBankLink, + handleBankLinkReturn, + onBankLinkEvent, DiditTransactionError, VerificationStatus, type VerificationResult, type DiditTransactionResult, + type BankLinkEvent, + type BankLinkResult, } from '@didit-protocol/sdk-react-native'; const DEMO_WALLET_ADDRESS = '0x71C7656EC7ab88b098defB751B7401B5f6d8976F'; +export function listenForBankReturns( + onResult: (result: BankLinkResult) => void +) { + let mounted = true; + const subscription = Linking.addEventListener('url', ({ url }) => { + handleBankLinkReturn(url); + }); + + async function resumeLaunch() { + try { + const url = await Linking.getInitialURL(); + if (!mounted || !url) return; + handleBankLinkReturn(url); + const result = await resumeBankLink(); + if (mounted && result) onResult(result); + } catch (error) { + if (mounted) Alert.alert('Error', `Bank Link not resumed: ${error}`); + } + } + + resumeLaunch(); + return () => { + mounted = false; + subscription.remove(); + }; +} + export default function App() { const [token, setToken] = useState(''); const [workflowId, setWorkflowId] = useState(''); @@ -32,6 +66,64 @@ export default function App() { ); const [loading, setLoading] = useState(false); const [result, setResult] = useState(null); + const [bankLinkToken, setBankLinkToken] = useState(''); + const [bankLinkEvents, setBankLinkEvents] = useState([]); + const [bankLinkResult, setBankLinkResult] = useState( + null + ); + const [bankLinkLoading, setBankLinkLoading] = useState(false); + + // The live event log is what the manual device matrix compares with native. + useEffect( + () => + onBankLinkEvent((event: BankLinkEvent) => { + setBankLinkEvents((previous) => + [`${event.name} ${JSON.stringify(event.payload)}`, ...previous].slice( + 0, + 20 + ) + ); + }), + [] + ); + + useEffect(() => listenForBankReturns(setBankLinkResult), []); + + const handlePresentBankLink = useCallback(async () => { + if (!bankLinkToken.trim()) { + Alert.alert('Error', 'Please enter a Bank Link client token.'); + return; + } + + setBankLinkLoading(true); + setBankLinkEvents([]); + setBankLinkResult(null); + + try { + setBankLinkResult(await presentBankLink(bankLinkToken.trim())); + } catch (error) { + Alert.alert('Error', `Bank Link not opened: ${error}`); + } finally { + setBankLinkLoading(false); + } + }, [bankLinkToken]); + + const handleResumeBankLink = useCallback(async () => { + setBankLinkLoading(true); + + try { + const resumed = await resumeBankLink(); + if (resumed) { + setBankLinkResult(resumed); + } else { + Alert.alert('Nothing to resume', 'No Bank Link is pending.'); + } + } catch (error) { + Alert.alert('Error', `Bank Link not resumed: ${error}`); + } finally { + setBankLinkLoading(false); + } + }, []); const handleStartWithToken = useCallback(async () => { if (!token.trim()) { @@ -283,6 +375,66 @@ export default function App() { )} + {/* Bank Link */} + + Bank Link + + + {bankLinkLoading ? ( + + ) : ( + Open Bank Link + )} + + + Resume after relaunch + + {bankLinkResult && ( + + + Result:{' '} + + {JSON.stringify(bankLinkResult)} + + + + )} + {bankLinkEvents.length > 0 && ( + + Events + {bankLinkEvents.map((line, index) => ( + + {line} + + ))} + + )} + + {/* Result display */} {result && ( diff --git a/ios/DiditSdkBridge.swift b/ios/DiditSdkBridge.swift index c7fdc37..6abf050 100644 --- a/ios/DiditSdkBridge.swift +++ b/ios/DiditSdkBridge.swift @@ -413,6 +413,213 @@ public class DiditSdkBridge: NSObject, @unchecked Sendable { } } + // MARK: - Bank Link + + /// Whether the native SDK linked into this build has Bank Link. The + /// released-only build compiles the stand-in below, and the TurboModule + /// rejects with `not_available` before calling it. + public var bankLinkAvailable: Bool { +#if DIDIT_BANK_LINK + true +#else + false +#endif + } + +#if DIDIT_BANK_LINK + + /// The error of a presentation that could not open: one code and message + /// on both platforms (Android: `BankLinkSupport.present`). + static let bankLinkDeclinedCode = "bank_link" + static let bankLinkDeclinedMessage = "Bank Link presentation was declined." + + /// Opens a Bank Link with the link's `client_token`. + /// + /// Every screen, state and string is native; the bridge carries the events + /// and the one result to JS, as JSON. The Objective-C++ module resolves the + /// presenting view controller (React Native's `RCTPresentedViewController`) + /// and passes it as `presenter`. With none, native is not called and the + /// promise rejects with the code and message Android uses for a declined + /// presentation, so a presentation that cannot open never leaves the + /// JavaScript promise pending, whichever native release is linked. The + /// native call is not bound to a typed value, so this compiles whether it + /// returns nothing or a discardable `Bool`. + public func presentBankLink( + token: String, + config: NSDictionary?, + presenter: UIViewController?, + onEvent: @escaping @Sendable (String) -> Void, + completion: @escaping @Sendable (String) -> Void, + reject: @escaping @Sendable (String, String) -> Void + ) { + let parsed = ParsedConfig(config) + DispatchQueue.main.async { + MainActor.assumeIsolated { + guard let presenter = presenter else { + reject(Self.bankLinkDeclinedCode, Self.bankLinkDeclinedMessage) + return + } + // Untyped on purpose: native returns nothing in older releases + // and a discardable `Bool` (false: nothing opened) in newer + // ones. Read as `Any`, a `false` rejects, anything else is + // left to the result callback. + let opened = DiditSdk.shared.presentBankLink( + token: token, + from: presenter, + configuration: parsed.toConfiguration(), + onEvent: { event in + onEvent(Self.bankLinkEventJson(event)) + }, + onResult: { result in + completion(Self.bankLinkResultJson(result)) + } + ) + if (opened as Any) as? Bool == false { + reject(Self.bankLinkDeclinedCode, Self.bankLinkDeclinedMessage) + } + } + } + } + + /// Picks up a link whose bank hop outlived the app. Resolves the JSON + /// `null` when native has nothing to resume, and the replayed or continued + /// result otherwise, with `resumed` set. + public func resumeBankLink( + presenter: UIViewController?, + onEvent: @escaping @Sendable (String) -> Void, + completion: @escaping @Sendable (String) -> Void, + reject: @escaping @Sendable (String, String) -> Void + ) { + DispatchQueue.main.async { + MainActor.assumeIsolated { + guard let presenter = presenter else { + reject(Self.bankLinkDeclinedCode, Self.bankLinkDeclinedMessage) + return + } + let resumed = DiditSdk.shared.resumeBankLink( + from: presenter, + onEvent: { event in + onEvent(Self.bankLinkEventJson(event)) + }, + onResult: { result in + completion(Self.bankLinkResultJson(result)) + } + ) + if !resumed { + completion("null") + } + } + } + } + + /// Hands the address the app was opened with to native, which decides + /// whether it is a Bank Link return. The address is never read here: a + /// resume code arrives as a query parameter and contains a dot, so nothing + /// in this bridge may split or normalise it. + public func handleBankLinkReturn(url: String) { + guard let address = URL(string: url) else { return } + DispatchQueue.main.async { + MainActor.assumeIsolated { + _ = DiditSdk.shared.handleBankLinkReturn(address) + } + } + } + + // MARK: - Bank Link JSON Mapping + + /// One event: its wire name and its ids-only payload. + private static func bankLinkEventJson(_ event: BankLinkEvent) -> String { + jsonString([ + "name": event.name.rawValue, + "payload": jsonSafe(event.payload) + ]) + } + + /// The one result of a presentation, in the shape the JS layer maps. + private static func bankLinkResultJson(_ result: BankLinkResult) -> String { + switch result { + case .success(let success): + var json: [String: Any] = [ + "type": "success", + "linkId": success.linkId, + "resumed": success.resumed + ] + if let connectionId = success.connectionId { + json["connectionId"] = connectionId + } + if let checkId = success.checkId { + json["checkId"] = checkId + } + return jsonString(json) + + case .exit(let exit): + return jsonString([ + "type": "exit", + "reason": exit.reason.rawValue, + "step": exit.step?.rawValue ?? NSNull(), + "resumed": exit.resumed + ]) + + @unknown default: + return jsonString([ + "type": "exit", + "reason": "failed", + "step": NSNull(), + "resumed": false + ]) + } + } + + /// Event payloads carry ids, enums and numbers. A value that is not one of + /// those becomes `null` instead of travelling through `String(describing:)`, + /// which could carry a name, a token or an account number to JS. + private static func jsonSafe(_ value: Any) -> Any { + switch value { + case let string as String: + return string + case let number as NSNumber: + return number + case is NSNull: + return NSNull() + case let array as [Any]: + return array.map(jsonSafe) + case let dictionary as [String: Any]: + return dictionary.mapValues(jsonSafe) + default: + return NSNull() + } + } + +#else + + // MARK: - Bank Link stand-in + + /// The pinned released SDK predates Bank Link. These keep the Objective-C + /// bridge compiling; the TurboModule rejects before calling them. + public func presentBankLink( + token: String, + config: NSDictionary?, + presenter: UIViewController?, + onEvent: @escaping @Sendable (String) -> Void, + completion: @escaping @Sendable (String) -> Void, + reject: @escaping @Sendable (String, String) -> Void + ) { + completion("null") + } + + public func resumeBankLink( + presenter: UIViewController?, + onEvent: @escaping @Sendable (String) -> Void, + completion: @escaping @Sendable (String) -> Void, + reject: @escaping @Sendable (String, String) -> Void + ) { + completion("null") + } + + public func handleBankLinkReturn(url: String) {} + +#endif + // MARK: - Transaction JSON Mapping private static func jsonObject(from raw: String) throws -> [String: Any] { diff --git a/ios/SdkReactNative.mm b/ios/SdkReactNative.mm index 827a97b..bf4c41a 100644 --- a/ios/SdkReactNative.mm +++ b/ios/SdkReactNative.mm @@ -1,5 +1,7 @@ #import "SdkReactNative.h" +#import + // Import the Swift-generated header for the bridge class. // The header name follows the pattern: -Swift.h // where ProductModuleName is derived from the CocoaPods pod name (SdkReactNative). @@ -187,6 +189,94 @@ - (void)getTransaction:(NSString *)transactionToken }]; } +// MARK: - Bank Link + +/// The view controller a Bank Link is presented from, resolved on the main +/// queue with React Native's own helper. `nil` when the app has none. +- (UIViewController *)bankLinkPresenter +{ + return RCTPresentedViewController(); +} + +/// Calls `then` on the main queue with the presenter. A host resumes once at +/// start-up, before a window may exist, so the lookup retries for a short, +/// bounded time (as Android waits for its Activity) and then hands `nil` on: +/// the bridge rejects, it never leaves the promise pending. +- (void)withBankLinkPresenterAttempts:(NSInteger)attemptsLeft + then:(void (^)(UIViewController *presenter))then +{ + dispatch_async(dispatch_get_main_queue(), ^{ + UIViewController *presenter = [self bankLinkPresenter]; + if (presenter != nil || attemptsLeft <= 0) { + then(presenter); + return; + } + dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(100 * NSEC_PER_MSEC)), + dispatch_get_main_queue(), ^{ + [self withBankLinkPresenterAttempts:attemptsLeft - 1 then:then]; + }); + }); +} + +- (void)presentBankLink:(NSString *)token + config:(JS::NativeSdkReactNative::VerificationConfig &)config + resolve:(RCTPromiseResolveBlock)resolve + reject:(RCTPromiseRejectBlock)reject +{ + if (!_bridge.bankLinkAvailable) { + reject(@"not_available", @"This native SDK version does not include Bank Link.", nil); + return; + } + NSDictionary *configDict = (&config != nullptr) ? [self configDictFrom:config] : nil; + __weak SdkReactNative *weakSelf = self; + + [self withBankLinkPresenterAttempts:0 then:^(UIViewController *presenter) { + [self->_bridge presentBankLinkWithToken:token + config:configDict + presenter:presenter + onEvent:^(NSString *eventJson) { + [weakSelf emitOnBankLinkEvent:eventJson]; + } + completion:^(NSString *resultJson) { + resolve(resultJson); + } + reject:^(NSString *code, NSString *message) { + reject(code, message, nil); + }]; + }]; +} + +- (void)resumeBankLink:(RCTPromiseResolveBlock)resolve + reject:(RCTPromiseRejectBlock)reject +{ + if (!_bridge.bankLinkAvailable) { + reject(@"not_available", @"This native SDK version does not include Bank Link.", nil); + return; + } + __weak SdkReactNative *weakSelf = self; + + [self withBankLinkPresenterAttempts:50 then:^(UIViewController *presenter) { + [self->_bridge resumeBankLinkWithPresenter:presenter + onEvent:^(NSString *eventJson) { + [weakSelf emitOnBankLinkEvent:eventJson]; + } + completion:^(NSString *resultJson) { + resolve(resultJson); + } + reject:^(NSString *code, NSString *message) { + reject(code, message, nil); + }]; + }]; +} + +- (void)handleBankLinkReturn:(NSString *)url +{ + if (!_bridge.bankLinkAvailable) { + return; + } + [_bridge handleBankLinkReturnWithUrl:url]; +} + // MARK: - TurboModule Registration - (std::shared_ptr)getTurboModule: diff --git a/package.json b/package.json index d4083c7..0e0df88 100644 --- a/package.json +++ b/package.json @@ -3,7 +3,8 @@ "version": "4.15.6", "diditNativeSdkVersions": { "ios": "4.15.6", - "android": "4.15.6" + "android": "4.15.6", + "bankLink": false }, "description": "React Native wrapper for Didit Identity Verification SDK", "main": "./lib/commonjs/index.js", diff --git a/src/NativeSdkReactNative.ts b/src/NativeSdkReactNative.ts index 9568b4c..b4c34b7 100644 --- a/src/NativeSdkReactNative.ts +++ b/src/NativeSdkReactNative.ts @@ -126,6 +126,36 @@ export interface Spec extends TurboModule { optionsJson: string ): Promise; + /** + * Open a Bank Link: the native flow behind the link's `client_token`. + * The resolved value is the result as a JSON string, mapped by the public + * `presentBankLink`; it settles exactly once, with `success` or `exit`. + */ + presentBankLink( + token: string, + config: VerificationConfig | null + ): Promise; + + /** + * Pick up a link whose bank hop outlived the app. The resolved value is the + * result as a JSON string, or the JSON `null` when nothing is pending. + */ + resumeBankLink(): Promise; + + /** + * Hand a Bank Link return address (an app link or universal link) to native, + * called from the host's `onOpenURL`/`onNewIntent`. Native decides whether + * the address is a link return; it is never parsed here. + */ + handleBankLinkReturn(url: string): void; + + /** + * Fired for every Bank Link event. Payload is a JSON string: + * `{ name, payload }`, with the names and snake_case keys of the link + * contract, and ids only. + */ + readonly onBankLinkEvent: EventEmitter; + /** * Fired after an auto-launched action completes and the transaction has * been refreshed. Payload is a JSON string: { callId, result }. diff --git a/src/__tests__/bank-link-formats.test.ts b/src/__tests__/bank-link-formats.test.ts new file mode 100644 index 0000000..d77627c --- /dev/null +++ b/src/__tests__/bank-link-formats.test.ts @@ -0,0 +1,209 @@ +/** + * The identifier formats of the Bank Link contract. + * + * `fixtures/bank-link-formats.json` is a byte-for-byte copy of + * `docs/bank-data/link-contract/formats.json` in the verification service: the + * one file that pins every identifier the backend hands a client. The web SDK + * once rejected a real resume code because its own expression was stricter than + * the backend's and split on the dot, which broke the bank return on staging. + * + * Each example passes unchanged through presentation and return URLs. Only + * the fields defined for an event may reach an event listener. + */ + +jest.mock('../NativeSdkReactNative', () => ({ + __esModule: true, + default: { + startVerification: jest.fn(), + startVerificationWithWorkflow: jest.fn(), + onTransactionUpdated: jest.fn(() => ({ remove: jest.fn() })), + presentBankLink: jest.fn(), + resumeBankLink: jest.fn(), + handleBankLinkReturn: jest.fn(), + onBankLinkEvent: jest.fn(), + }, +})); + +import { readFileSync } from 'fs'; +import { join } from 'path'; +import NativeSdkReactNative from '../NativeSdkReactNative'; +import { + presentBankLink, + onBankLinkEvent, + handleBankLinkReturn, +} from '../index'; + +interface Format { + name: string; + description: string; + travels: string[]; + pattern: string; + example: string; + fields?: string[]; +} + +interface Address { + name: string; + address: string; + where: string; + params: { + name: string; + required: boolean; + format?: string; + pattern?: string; + }[]; +} + +interface Formats { + version: number; + formats: Format[]; + addresses: Address[]; +} + +const contract = JSON.parse( + readFileSync(join(__dirname, 'fixtures', 'bank-link-formats.json'), 'utf8') +) as Formats; + +const present = NativeSdkReactNative.presentBankLink as jest.Mock; +const handleReturn = NativeSdkReactNative.handleBankLinkReturn as jest.Mock; + +const formats = contract.formats.filter( + (format) => typeof format.example === 'string' +); + +/** The address the bank sends the person back to, with the resume code in it. */ +function returnAddress(where: 'query' | 'fragment', code: string): string { + const params = `didit_resume=${encodeURIComponent(code)}`; + return where === 'query' + ? `https://app.example.com/bank/return?${params}` + : `https://app.example.com/bank/return#${params}`; +} + +/** + * The Codegen `EventEmitter` is a function property of the TurboModule, so the + * fake keeps the handler the wrapper registers and the test emits through it. + */ +let nativeHandler: ((raw: string) => void) | null = null; + +beforeEach(() => { + jest.clearAllMocks(); + nativeHandler = null; + (NativeSdkReactNative.onBankLinkEvent as jest.Mock).mockImplementation( + (handler: (raw: string) => void) => { + nativeHandler = handler; + return { + remove: () => { + if (nativeHandler === handler) { + nativeHandler = null; + } + }, + }; + } + ); + present.mockResolvedValue(JSON.stringify({ type: 'exit', reason: 'closed' })); +}); + +describe('the copied contract file', () => { + it('pins the formats the issue names', () => { + expect(contract.version).toBe(1); + expect(contract.formats.map((format) => format.name)).toEqual( + expect.arrayContaining([ + 'link_id', + 'url_token', + 'client_token', + 'resume_code', + 'state', + 'link_ref', + 'instance_id', + 'error_code', + ]) + ); + }); + + it('keeps the dot in the resume code, and the address it travels in', () => { + const resumeCode = contract.formats.find( + (format) => format.name === 'resume_code' + ) as Format; + + expect(resumeCode.example).toContain('.'); + expect(resumeCode.travels).toEqual( + expect.arrayContaining(['query', 'fragment']) + ); + expect(contract.addresses.map((address) => address.name)).toEqual([ + 'sdk_handoff', + 'hosted_return', + ]); + }); + + it('gives the full-page handoff its resume code and instance id', () => { + const handoff = contract.addresses.find( + (address) => address.name === 'sdk_handoff' + ) as Address; + const hostedReturn = contract.addresses.find( + (address) => address.name === 'hosted_return' + ) as Address; + + expect(handoff.params.map((param) => param.name)).toEqual( + expect.arrayContaining(['resume_code', 'instance_id', 'v']) + ); + expect(handoff.where).toBe('fragment'); + expect(hostedReturn.params.map((param) => param.name)).toEqual([ + 'didit_resume', + ]); + expect(hostedReturn.where).toBe('query'); + }); +}); + +describe('every example of the contract file', () => { + it.each(formats.map((format) => [format.name, format] as const))( + 'is accepted as the token of %s, unchanged', + async (_name, format) => { + await presentBankLink(format.example); + + expect(present).toHaveBeenLastCalledWith( + format.example, + expect.anything() + ); + } + ); + + it.each(formats.map((format) => [format.name, format] as const))( + 'survives the return address of %s, in the query and the fragment', + (_name, format) => { + for (const where of ['query', 'fragment'] as const) { + const url = returnAddress(where, format.example); + + handleBankLinkReturn(url); + + expect(handleReturn).toHaveBeenLastCalledWith(url); + // The dot is what a stricter parser splits on and loses the rest of. + const [forwarded] = + handleReturn.mock.calls[handleReturn.mock.calls.length - 1]; + expect(forwarded).toContain(encodeURIComponent(format.example)); + } + } + ); + + it('keeps credentials and unrelated fields out of event payloads', () => { + const fields = Object.fromEntries( + formats.map((format) => [format.name, format.example]) + ); + const listener = jest.fn(); + const stop = onBankLinkEvent(listener); + nativeHandler?.( + JSON.stringify({ + name: 'opened', + payload: { + ...fields, + session: fields.session_credential, + mode: { token: fields.client_token }, + }, + }) + ); + stop(); + expect(listener).toHaveBeenCalledWith({ + name: 'opened', + payload: { link_id: fields.link_id }, + }); + }); +}); diff --git a/src/__tests__/bank-link-native-gating.test.ts b/src/__tests__/bank-link-native-gating.test.ts new file mode 100644 index 0000000..2720942 --- /dev/null +++ b/src/__tests__/bank-link-native-gating.test.ts @@ -0,0 +1,177 @@ +import { existsSync, readFileSync } from 'fs'; +import { join } from 'path'; + +/** + * Bank Link is not in the released native SDK yet. The wrapper must still + * compile against it (the public CI's released-compatibility jobs link the + * released binaries), so the native calls are compiled only when the pinned + * native SDK carries them: a source pin, or `bankLink: true` once a release + * has them. Otherwise a stand-in compiles and the module rejects + * `not_available`. Without this gate those jobs fail on unresolved + * `BankLinkEvent` / `BankLinkResult` symbols. + */ + +const repoRoot = join(__dirname, '..', '..'); +const read = (relativePath: string) => + readFileSync(join(repoRoot, relativePath), 'utf8'); + +const pkg = JSON.parse(read('package.json')); + +describe('native Bank Link compile gate', () => { + it('declares the released-SDK capability next to the version pins', () => { + expect(typeof pkg.diditNativeSdkVersions.bankLink).toBe('boolean'); + }); + + it('selects one Android Bank Link source set from the same gate', () => { + const gradle = read('android/build.gradle'); + + expect(gradle).toContain( + 'def bankLinkEnabled = nativePins.source != null || nativePins.bankLink == true' + ); + expect(gradle).toContain('src/bankLink/java'); + expect(gradle).toContain('src/released/java'); + }); + + it('keeps the native Android calls out of the released-only source', () => { + const nativeCalls = + 'android/src/bankLink/java/com/sdkreactnative/BankLinkSupport.kt'; + const released = + 'android/src/released/java/com/sdkreactnative/BankLinkSupport.kt'; + + expect(existsSync(join(repoRoot, nativeCalls))).toBe(true); + expect(read(nativeCalls)).toContain('DiditSdk.presentBankLink'); + expect(existsSync(join(repoRoot, released))).toBe(true); + expect(read(released)).toContain('const val available = false'); + expect( + read('android/src/main/java/com/sdkreactnative/SdkReactNativeModule.kt') + ).not.toContain('me.didit.sdk.BankLink'); + }); + + it('maps the native Android types, wire names and a declined presentation', () => { + // The enabled adapter compiles only when the pinned native source carries + // Bank Link, so CI's released jobs build the stand-in and never see it. + // These assertions stand in for that compile: the package the native + // types live in, the wire names JavaScript listens for, the wrapped + // result variants, and a declined presentation that still settles. + const json = read( + 'android/src/bankLink/java/com/sdkreactnative/BankLinkJson.kt' + ); + const support = read( + 'android/src/bankLink/java/com/sdkreactnative/BankLinkSupport.kt' + ); + + expect(json).toContain( + 'import me.didit.sdk.features.bank.link.BankLinkEvent' + ); + expect(json).toContain( + 'import me.didit.sdk.features.bank.link.BankLinkResult' + ); + // The enum constants read `OPENED`; JavaScript listens for `opened`. + expect(json).toContain('.put("name", event.name.wire)'); + expect(json).not.toMatch(/name\.toString\(\)|event\.name\.name/); + // Success and exit fields hang under the result variant that wraps them. + expect(json).toContain('is BankLinkResult.Success ->'); + expect(json).toContain('result.success.linkId'); + expect(json).toContain('is BankLinkResult.Exit ->'); + expect(json).toContain('result.exit.reason.wire'); + expect(json).toContain('result.exit.step?.wire'); + // A declined presentation resolves no result, so the adapter must fail the + // call instead of leaving the host waiting and the slot occupied. + expect(support).toContain('val presented = DiditSdk.presentBankLink('); + expect(support).toContain('check(presented)'); + }); + + it('defines the iOS compile condition only when the native SDK has it', () => { + const podspec = read('SdkReactNative.podspec'); + + expect(podspec).toMatch( + /didit_sdk_bank_link_enabled = \([\s\S]*diditNativeSdkVersions", "source"[\s\S]*bankLink"\) == true/ + ); + expect(podspec).toContain( + 's.pod_target_xcconfig["SWIFT_ACTIVE_COMPILATION_CONDITIONS"] = "$(inherited) DIDIT_BANK_LINK"' + ); + }); + + it('guards the native iOS calls and keeps a released stand-in', () => { + const bridge = read('ios/DiditSdkBridge.swift'); + + expect(bridge).toContain('#if DIDIT_BANK_LINK'); + expect(bridge).toContain('public var bankLinkAvailable: Bool'); + expect(bridge).toContain('DiditSdk.shared.presentBankLink'); + expect(bridge).toContain('#else'); + + const objc = read('ios/SdkReactNative.mm'); + expect(objc).toContain( + 'reject(@"not_available", @"This native SDK version does not include Bank Link.", nil)' + ); + expect(objc).toContain('_bridge.bankLinkAvailable'); + }); + + it('calls the Bank Link selectors Swift exports for both bridge variants', () => { + // `@objcMembers` derives the Objective-C names. Swift adds `With` before a + // first label like `token` or `presenter`, but not before one that starts + // with a preposition like `onEvent`. A wrong spelling fails the iOS build + // for every app, Bank Link or not. + const bridge = read('ios/DiditSdkBridge.swift'); + const objc = read('ios/SdkReactNative.mm'); + + const swiftCount = (signature: string) => + bridge.split(signature).length - 1; + expect( + swiftCount('public func presentBankLink(\n token: String,') + ).toBe(2); + expect(swiftCount('public func resumeBankLink(\n presenter:')).toBe( + 2 + ); + expect(swiftCount('public func handleBankLinkReturn(url: String)')).toBe(2); + + expect(objc).toContain('[self->_bridge presentBankLinkWithToken:'); + expect(objc).toContain('[self->_bridge resumeBankLinkWithPresenter:'); + expect(objc).not.toContain('resumeBankLinkOnEvent'); + expect(objc).toContain('[_bridge handleBankLinkReturnWithUrl:'); + }); + + it('resolves the iOS presenter, and a missing one rejects as Android does', () => { + // A presentation with no view controller must never leave the JavaScript + // promise pending: it rejects with the code and message Android uses. + const bridge = read('ios/DiditSdkBridge.swift'); + const objc = read('ios/SdkReactNative.mm'); + const support = read( + 'android/src/bankLink/java/com/sdkreactnative/BankLinkSupport.kt' + ); + const module = read( + 'android/src/main/java/com/sdkreactnative/SdkReactNativeModule.kt' + ); + + // The presenter is resolved with React Native's helper, on the main queue. + expect(objc).toContain('#import '); + expect(objc).toContain('return RCTPresentedViewController();'); + expect(objc).toContain('dispatch_async(dispatch_get_main_queue()'); + // It is handed to native for a presentation and for a resume. + expect(bridge).toContain('from: presenter,'); + expect(bridge.split('from: presenter,').length - 1).toBe(2); + // Native's result is read untyped (Void or Bool) and a false rejects. + expect(bridge).toContain('let opened = DiditSdk.shared.presentBankLink('); + expect(bridge).not.toMatch(/: Bool = DiditSdk\.shared\.presentBankLink/); + expect(bridge).toContain('if (opened as Any) as? Bool == false {'); + // A missing presenter rejects instead of calling native. + expect( + bridge.split( + 'guard let presenter = presenter else {\n reject(Self.bankLinkDeclinedCode, Self.bankLinkDeclinedMessage)' + ).length - 1 + ).toBe(2); + expect(objc).toContain('reject(code, message, nil);'); + // One error on both platforms. + const androidCode = module.match(/promise\.reject\("(bank_link)"/)?.[1]; + const androidMessage = support.match( + /check\(presented\) \{ "([^"]+)" \}/ + )?.[1]; + expect(androidCode).toBe('bank_link'); + expect(bridge).toContain( + `static let bankLinkDeclinedCode = "${androidCode}"` + ); + expect(bridge).toContain( + `static let bankLinkDeclinedMessage = "${androidMessage}"` + ); + }); +}); diff --git a/src/__tests__/bank-link.test.ts b/src/__tests__/bank-link.test.ts new file mode 100644 index 0000000..ecd344f --- /dev/null +++ b/src/__tests__/bank-link.test.ts @@ -0,0 +1,625 @@ +/** + * The Bank Link wrapper: the Promise of a presentation, the events, the + * resume and the return address. Native is a fake module, as the issue + * requires: no flow of its own is tested, only the bridge contract. + */ + +jest.mock('../NativeSdkReactNative', () => ({ + __esModule: true, + default: { + startVerification: jest.fn(), + startVerificationWithWorkflow: jest.fn(), + onTransactionUpdated: jest.fn(() => ({ remove: jest.fn() })), + presentBankLink: jest.fn(), + resumeBankLink: jest.fn(), + handleBankLinkReturn: jest.fn(), + onBankLinkEvent: jest.fn(), + }, +})); + +// The example workspace can resolve a second copy of React Native. +jest.mock( + require.resolve('react-native', { + paths: [require.resolve('../../example/package.json')], + }), + () => jest.requireActual('react-native') +); +jest.mock( + '@didit-protocol/sdk-react-native', + () => jest.requireActual('../index'), + { virtual: true } +); +import formats from './fixtures/bank-link-formats.json'; +import { listenForBankReturns } from '../../example/src/App'; +import { readFileSync } from 'fs'; +import { join } from 'path'; +import { DeviceEventEmitter, Linking } from 'react-native'; +import NativeSdkReactNative from '../NativeSdkReactNative'; +import { + presentBankLink, + resumeBankLink, + onBankLinkEvent, + handleBankLinkReturn, +} from '../index'; +import type { BankLinkEvent, BankLinkResult } from '../index'; + +const present = NativeSdkReactNative.presentBankLink as jest.Mock; +const resume = NativeSdkReactNative.resumeBankLink as jest.Mock; +const handleReturn = NativeSdkReactNative.handleBankLinkReturn as jest.Mock; + +const repoRoot = join(__dirname, '..', '..'); + +const read = (relativePath: string) => + readFileSync(join(repoRoot, relativePath), 'utf8'); + +/** The body of the first braced declaration after `signature`. */ +function bracedBody(source: string, signature: RegExp): string { + const start = source.search(signature); + expect(start).toBeGreaterThanOrEqual(0); + + const open = source.indexOf('{', start); + let depth = 0; + + for (let index = open; index < source.length; index += 1) { + if (source[index] === '{') depth += 1; + if (source[index] === '}') depth -= 1; + if (depth === 0) return source.slice(open, index + 1); + } + + throw new Error('Unclosed declaration'); +} + +/** + * Every payload key of the link contract (`events.md`, section 1): ids and + * enums only, never a name, a token, an email or an account number. + */ +const CONTRACT_PAYLOAD_KEYS = [ + 'link_id', + 'mode', + 'access', + 'presentation', + 'consent_version', + 'institution_id', + 'country', + 'via', + 'result', + 'count', + 'connection_id', + 'check_id', + 'reason', + 'step', + 'code', + 'resumed', +]; + +/** + * The Codegen `EventEmitter` is a function property of the TurboModule: native + * `emitOnBankLinkEvent` reaches only the handler registered on the module, so + * the fake keeps it and every test emits through it. + */ +let nativeHandler: ((raw: string) => void) | null = null; + +beforeEach(() => { + nativeHandler = null; + (NativeSdkReactNative.onBankLinkEvent as jest.Mock).mockImplementation( + (handler: (raw: string) => void) => { + nativeHandler = handler; + return { + remove: () => { + if (nativeHandler === handler) { + nativeHandler = null; + } + }, + }; + } + ); +}); + +/** Emits one native event, exactly as the native modules do: a JSON string. */ +function emit(event: unknown): void { + nativeHandler?.(JSON.stringify(event)); +} + +/** Emits one raw native payload, for a payload that is not valid JSON. */ +function emitRaw(raw: string): void { + nativeHandler?.(raw); +} + +describe('presentBankLink', () => { + afterEach(() => { + jest.clearAllMocks(); + }); + + it('resolves the success result native returned', async () => { + present.mockResolvedValue( + JSON.stringify({ + type: 'success', + linkId: '0b9c4f1e-6a2d-4e8b-9f31-7c5d2e1a8b40', + connectionId: 'connection-1', + checkId: 'check-1', + resumed: false, + }) + ); + + const result = await presentBankLink('blt_Hs8Pa4Rb6Ye0Gf2Jc7Qm3Zx9Vd2Lc5W'); + + expect(result).toEqual({ + type: 'success', + linkId: '0b9c4f1e-6a2d-4e8b-9f31-7c5d2e1a8b40', + connectionId: 'connection-1', + checkId: 'check-1', + resumed: false, + }); + }); + + it('leaves absent optional ids absent, never as keys with undefined', async () => { + present.mockResolvedValue( + JSON.stringify({ + type: 'success', + linkId: '0b9c4f1e-6a2d-4e8b-9f31-7c5d2e1a8b40', + }) + ); + + const result = await presentBankLink('blt_token'); + + expect(Object.keys(result).sort()).toEqual(['linkId', 'type']); + }); + + it.each([ + ['closed', null], + ['cancelled', 'bank_hop'], + ['bank_unavailable', 'institution'], + ['expired', 'consent'], + ['failed', 'collecting'], + ])('resolves an exit with reason %s', async (reason, step) => { + present.mockResolvedValue( + JSON.stringify({ type: 'exit', reason, step, resumed: true }) + ); + + await expect(presentBankLink('blt_token')).resolves.toEqual({ + type: 'exit', + reason, + step, + resumed: true, + }); + }); + + it('maps a reason it does not know to failed, never to success', async () => { + present.mockResolvedValue( + JSON.stringify({ type: 'exit', reason: 'something_new', step: null }) + ); + + await expect(presentBankLink('blt_token')).resolves.toEqual({ + type: 'exit', + reason: 'failed', + step: null, + }); + }); + + it('forwards the token and the configuration to native', async () => { + present.mockResolvedValue( + JSON.stringify({ type: 'exit', reason: 'closed' }) + ); + + await presentBankLink('blt_token', { + config: { languageCode: 'es', loggingEnabled: true }, + }); + + expect(present).toHaveBeenCalledWith('blt_token', { + languageCode: 'es', + showLanguageSelector: undefined, + fontFamily: undefined, + loggingEnabled: true, + showCloseButton: undefined, + showExitConfirmation: undefined, + closeOnComplete: undefined, + defaultDocumentCamera: undefined, + defaultLivenessCamera: undefined, + showDocumentCameraSwitchButton: undefined, + showLivenessCameraSwitchButton: undefined, + }); + }); + + it('rejects a second presentation while one is open, without calling native', async () => { + let finish: (value: string) => void = () => {}; + present.mockReturnValue( + new Promise((resolve) => { + finish = resolve; + }) + ); + + const first = presentBankLink('blt_first'); + + await expect(presentBankLink('blt_second')).rejects.toThrow(/already open/); + expect(present).toHaveBeenCalledTimes(1); + + finish(JSON.stringify({ type: 'exit', reason: 'closed' })); + await expect(first).resolves.toEqual({ type: 'exit', reason: 'closed' }); + }); + + it('presents again once the first link settled', async () => { + present.mockResolvedValue( + JSON.stringify({ type: 'exit', reason: 'closed' }) + ); + + await presentBankLink('blt_first'); + await presentBankLink('blt_second'); + + expect(present).toHaveBeenCalledTimes(2); + }); + + it('refuses a resume while a link is open, without calling native', async () => { + let finish: (value: string) => void = () => {}; + present.mockReturnValueOnce( + new Promise((resolve) => { + finish = resolve; + }) + ); + + const presented = presentBankLink('blt_first'); + + await expect(resumeBankLink()).rejects.toThrow(/already open/); + expect(resume).not.toHaveBeenCalled(); + + // The presented promise still settles: its native callbacks were kept. + finish(JSON.stringify({ type: 'exit', reason: 'closed' })); + await expect(presented).resolves.toEqual({ + type: 'exit', + reason: 'closed', + }); + }); + + it('rejects when native answers a result it cannot read', async () => { + present.mockResolvedValue(JSON.stringify({ type: 'success' })); + + await expect(presentBankLink('blt_token')).rejects.toThrow(/link id/); + }); + + it('rejects with the declined-presentation error native raises when nothing opened', async () => { + // Both platforms reject `bank_link` / "Bank Link presentation was + // declined." when nothing could be presented (no Activity or view + // controller), so the promise never stays pending and the slot frees. + const declined = Object.assign( + new Error('Bank Link presentation was declined.'), + { code: 'bank_link' } + ); + present.mockRejectedValueOnce(declined); + resume.mockRejectedValueOnce(declined); + + await expect(presentBankLink('blt_token')).rejects.toMatchObject({ + code: 'bank_link', + message: 'Bank Link presentation was declined.', + }); + await expect(resumeBankLink()).rejects.toMatchObject({ + code: 'bank_link', + message: 'Bank Link presentation was declined.', + }); + }); + + it('releases the wrapper when native rejects, so the next link can open', async () => { + present.mockRejectedValueOnce(new Error('native failed')); + present.mockResolvedValueOnce( + JSON.stringify({ type: 'exit', reason: 'closed' }) + ); + + await expect(presentBankLink('blt_first')).rejects.toThrow('native failed'); + await expect(presentBankLink('blt_second')).resolves.toEqual({ + type: 'exit', + reason: 'closed', + }); + }); +}); + +describe('resumeBankLink', () => { + afterEach(() => { + jest.clearAllMocks(); + }); + + it('returns null when nothing is pending', async () => { + resume.mockResolvedValue('null'); + + await expect(resumeBankLink()).resolves.toBeNull(); + }); + + it('refuses a presentation while a resume is in flight, and frees the slot after', async () => { + let finish: (value: string) => void = () => {}; + resume.mockReturnValueOnce( + new Promise((resolve) => { + finish = resolve; + }) + ); + + const resuming = resumeBankLink(); + + await expect(presentBankLink('blt_second')).rejects.toThrow(/already open/); + expect(present).not.toHaveBeenCalled(); + + finish('null'); + await expect(resuming).resolves.toBeNull(); + + // The resume released the single-link slot, so the next link can open. + present.mockResolvedValueOnce( + JSON.stringify({ type: 'exit', reason: 'closed' }) + ); + await expect(presentBankLink('blt_third')).resolves.toEqual({ + type: 'exit', + reason: 'closed', + }); + }); + + it('frees the slot when native refuses the resume', async () => { + resume.mockRejectedValueOnce(new Error('no activity')); + resume.mockResolvedValueOnce('null'); + + await expect(resumeBankLink()).rejects.toThrow('no activity'); + await expect(resumeBankLink()).resolves.toBeNull(); + }); + + it('maps a step it does not know to unknown', async () => { + resume.mockResolvedValueOnce( + JSON.stringify({ + type: 'exit', + reason: 'cancelled', + step: 'a_step_from_a_newer_server', + }) + ); + + await expect(resumeBankLink()).resolves.toEqual({ + type: 'exit', + reason: 'cancelled', + step: 'unknown', + }); + }); + + it('returns the replayed result with resumed: true', async () => { + resume.mockResolvedValue( + JSON.stringify({ + type: 'success', + linkId: '0b9c4f1e-6a2d-4e8b-9f31-7c5d2e1a8b40', + connectionId: 'connection-1', + resumed: true, + }) + ); + + await expect(resumeBankLink()).resolves.toEqual({ + type: 'success', + linkId: '0b9c4f1e-6a2d-4e8b-9f31-7c5d2e1a8b40', + connectionId: 'connection-1', + resumed: true, + }); + }); +}); + +describe('onBankLinkEvent', () => { + afterEach(() => { + jest.clearAllMocks(); + }); + + it('subscribes through the module event property, the only route native emits on', () => { + const listener = jest.fn(); + const stop = onBankLinkEvent(listener); + + expect(NativeSdkReactNative.onBankLinkEvent).toHaveBeenCalledTimes(1); + expect(NativeSdkReactNative.onBankLinkEvent).toHaveBeenCalledWith( + expect.any(Function) + ); + + // A `NativeEventEmitter` would listen on the device emitter; the + // TurboModule `EventEmitter` never emits there. + DeviceEventEmitter.emit( + 'onBankLinkEvent', + JSON.stringify({ name: 'opened', payload: { link_id: null } }) + ); + expect(listener).not.toHaveBeenCalled(); + + emit({ name: 'opened', payload: { link_id: null } }); + expect(listener).toHaveBeenCalledTimes(1); + + stop(); + }); + + it('keeps delivering when one listener throws', () => { + const failing = jest.fn(() => { + throw new Error('listener failed'); + }); + const healthy = jest.fn(); + const stopFailing = onBankLinkEvent(failing); + const stopHealthy = onBankLinkEvent(healthy); + const consoleError = jest + .spyOn(console, 'error') + .mockImplementation(() => {}); + + expect(() => + emit({ name: 'opened', payload: { link_id: null } }) + ).not.toThrow(); + expect(healthy).toHaveBeenCalledTimes(1); + expect(consoleError).toHaveBeenCalled(); + + consoleError.mockRestore(); + stopFailing(); + stopHealthy(); + }); + + it.each([ + [ + 'opened', + { + link_id: 'link-1', + mode: 'connect', + access: 'ongoing', + presentation: 'rn', + }, + ], + ['consent_shown', { link_id: 'link-1', consent_version: '2026-11-22.1' }], + [ + 'consent_accepted', + { link_id: 'link-1', consent_version: '2026-11-22.1' }, + ], + [ + 'institution_selected', + { link_id: 'link-1', institution_id: 'institution-1', country: 'ES' }, + ], + ['bank_redirect', { link_id: 'link-1', via: 'popup' }], + ['bank_returned', { link_id: 'link-1', result: 'ok' }], + ['accounts_selected', { link_id: 'link-1', count: 2 }], + [ + 'success', + { link_id: 'link-1', connection_id: 'connection-1', check_id: 'check-1' }, + ], + [ + 'exit', + { link_id: null, resumed: true, reason: 'closed', step: 'bank_hop' }, + ], + ['error', { link_id: null, code: 'network' }], + ])('delivers %s once with its payload as sent', (name, payload) => { + const listener = jest.fn(); + const stop = onBankLinkEvent(listener); + + emit({ name, payload }); + emit({ name, payload }); + + expect(listener).toHaveBeenCalledTimes(2); + expect(listener).toHaveBeenNthCalledWith(1, { name, payload }); + stop(); + }); + + it('delivers to every listener and stops after unsubscribe', () => { + const first = jest.fn(); + const second = jest.fn(); + const stopFirst = onBankLinkEvent(first); + const stopSecond = onBankLinkEvent(second); + + emit({ name: 'opened', payload: { link_id: 'link-1' } }); + stopFirst(); + emit({ name: 'opened', payload: { link_id: 'link-1' } }); + stopSecond(); + + expect(first).toHaveBeenCalledTimes(1); + expect(second).toHaveBeenCalledTimes(2); + }); + + it('is safe to unsubscribe twice', () => { + const listener = jest.fn(); + const stop = onBankLinkEvent(listener); + + stop(); + expect(() => stop()).not.toThrow(); + emit({ name: 'opened', payload: { link_id: null } }); + expect(listener).not.toHaveBeenCalled(); + }); + + it('ignores an event name this version does not know, and a broken payload', () => { + const listener = jest.fn(); + const stop = onBankLinkEvent(listener); + + emit({ + name: 'a_name_from_a_newer_server', + payload: { link_id: 'link-1' }, + }); + emit({ name: 'opened', payload: {} }); + emit({ name: 'opened', payload: { link_id: {} } }); + emitRaw('not json'); + stop(); + + expect(listener).not.toHaveBeenCalled(); + }); + + it('declares no payload field of a person, a token or an account', () => { + // The link contract allows ids only. The wrapper's own payload type is the + // list of everything a listener can read, so a field outside the contract + // is a privacy defect here. + const body = bracedBody( + read('src/types.ts'), + /export interface BankLinkEventPayload {/ + ); + const keys = Array.from(body.matchAll(/^ {2}(\w+)\??:/gm), (match) => + String(match[1]) + ); + + expect(keys).toEqual( + expect.arrayContaining(['link_id', 'connection_id', 'reason', 'step']) + ); + expect(keys.filter((key) => !CONTRACT_PAYLOAD_KEYS.includes(key))).toEqual( + [] + ); + }); +}); + +describe('handleBankLinkReturn', () => { + afterEach(() => { + jest.clearAllMocks(); + }); + + it('forwards the cold return before restoring the interrupted step and listens for warm returns', async () => { + const code = formats.formats.find( + (format) => format.name === 'resume_code' + )!.example; + const url = `https://app.example.com/bank/return?didit_resume=${code}`; + const getUrl = jest.spyOn(Linking, 'getInitialURL').mockResolvedValue(url); + const remove = jest.fn(); + const subscribe = jest + .spyOn(Linking, 'addEventListener') + .mockReturnValue({ remove }); + const saved = { + type: 'exit', + reason: 'closed', + step: 'bank_hop', + resumed: true, + }; + resume.mockImplementationOnce(async () => { + expect(handleReturn).toHaveBeenCalledWith(url); + return JSON.stringify(saved); + }); + let stop: (() => void) | undefined; + try { + const restored = await new Promise((resolve) => { + stop = listenForBankReturns(resolve); + }); + expect(restored).toEqual(saved); + const warm = 'example://bank/return?didit_resume=rsc_another.secret'; + subscribe.mock.calls[0]![1]({ url: warm }); + expect(handleReturn).toHaveBeenLastCalledWith(warm); + expect(resume).toHaveBeenCalledTimes(1); + } finally { + stop?.(); + subscribe.mockRestore(); + getUrl.mockRestore(); + } + expect(remove).toHaveBeenCalledTimes(1); + }); + + it('forwards the address to native unchanged', () => { + const url = + 'https://app.example.com/bank/return?didit_resume=rsc_0b9c4f1e6a2d4e8b9f317c5d2e1a8b40.7Hq3Zx9Wd2Lm5Tn8Vc1Ks4Pa6Rb0Uv3'; + + handleBankLinkReturn(url); + + expect(handleReturn).toHaveBeenCalledWith(url); + }); +}); + +describe('result narrowing', () => { + it('narrows success and exit exhaustively', () => { + const describeResult = (result: BankLinkResult): string => { + switch (result.type) { + case 'success': + return `success:${result.linkId}`; + case 'exit': + return `exit:${result.reason}`; + } + }; + + expect(describeResult({ type: 'success', linkId: 'link-1' })).toBe( + 'success:link-1' + ); + expect(describeResult({ type: 'exit', reason: 'expired' })).toBe( + 'exit:expired' + ); + }); + + it('types an event listener payload', () => { + const listener = (event: BankLinkEvent) => event.payload.link_id; + + expect(typeof listener).toBe('function'); + }); +}); diff --git a/src/__tests__/fixtures/bank-link-formats.json b/src/__tests__/fixtures/bank-link-formats.json new file mode 100644 index 0000000..32ff143 --- /dev/null +++ b/src/__tests__/fixtures/bank-link-formats.json @@ -0,0 +1,262 @@ +{ + "version": 1, + "description": "Every identifier or token the Bank Link backend hands to a client (or a client sends back), where it travels and the regular expression every side checks it with. A value in a URL PATH is made of letters, digits, `_` and `-` only; a value in a query or fragment may also hold RFC 3986 unreserved characters (`.`, `~`). The backend test mints each one through the real minting function and asserts its pattern; the fixtures are checked against it by the contract replay test. Front ends copy this file into their own tests.", + "formats": [ + { + "name": "link_id", + "description": "The id of a link (a UUID).", + "travels": [ + "path", + "body", + "query" + ], + "pattern": "^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$", + "example": "0b9c4f1e-6a2d-4e8b-9f31-7c5d2e1a8b40", + "fields": [ + "link_id" + ], + "minted_by": "POST /v3/bank/links/ (id)" + }, + { + "name": "url_token", + "description": "The token of the hosted link address, `/bank/link/`; the SDK also reads it from the fragment (`#t=`).", + "travels": [ + "path", + "fragment" + ], + "pattern": "^blu_[A-Za-z0-9_-]{16,128}$", + "example": "blu_Wd2Lm5Tn8Vc1Ks4Pa6Rb0Hq3Zx9Ye7Jc", + "fields": [], + "minted_by": "POST /v3/bank/links/ (url)" + }, + { + "name": "client_token", + "description": "The token the customer's front end hands to the SDK.", + "travels": [ + "body", + "fragment" + ], + "pattern": "^blt_[A-Za-z0-9_-]{16,128}$", + "example": "blt_Hs8Pa4Rb6Ye0Gf2Jc7Qm3Zx9Vd2Lc5W", + "fields": [ + "client_token" + ], + "minted_by": "POST /v3/bank/links/ (client_token)" + }, + { + "name": "session_credential", + "description": "The credential of a person's session (`Authorization: BankLink `).", + "travels": [ + "body", + "header" + ], + "pattern": "^bls_[A-Za-z0-9_-]{16,128}$", + "example": "bls_9Kd2Xv7Qm4Tn1Wc8Lp5Rz3Hy6Ba0Ef", + "fields": [ + "session" + ], + "minted_by": "POST /v3/bank/link-session/ (session)" + }, + { + "name": "resume_code", + "description": "The code the hosted page keeps across the bank trip. Its head is the link id (32 hex characters, the format minted once `MINT_LINK_BASED_RESUME_CODES` is on) or the session's number (digits, the format still minted before that). The dot is allowed: a resume code travels in a query, a fragment or a body, never in a path.", + "travels": [ + "query", + "fragment", + "body" + ], + "pattern": "^rsc_(?:[0-9a-f]{32}|[0-9]{1,18})\\.[A-Za-z0-9_-]{16,128}$", + "example": "rsc_0b9c4f1e6a2d4e8b9f317c5d2e1a8b40.7Hq3Zx9Wd2Lm5Tn8Vc1Ks4Pa6Rb0Uv3", + "fields": [ + "resume_code" + ], + "minted_by": "POST /v3/bank/link-session/resume-code/" + }, + { + "name": "frame_id", + "description": "The non-secret id of the embedded frame route `/bank/frame/`. It travels in a PATH, so it holds only letters, digits, `_` and `-`: `frm_--`.", + "travels": [ + "path", + "body" + ], + "pattern": "^frm_[A-Za-z0-9_-]{8,124}$", + "example": "frm_0b9c4f1e6a2d4e8b9f317c5d2e1a8b40-1795400000-3f9a1c7e5b2d8a60", + "fields": [ + "frame_id" + ], + "minted_by": "POST /v3/bank/link-session/frame-policy/ (frame_id)" + }, + { + "name": "state", + "description": "The `state` of a bank attempt: in the fragment of the Test Bank launcher address and in the query of the bank's return.", + "travels": [ + "fragment", + "query" + ], + "pattern": "^bst_[A-Za-z0-9_-]{20,128}$", + "example": "bst_Wd2Lm5Tn8Vc1Ks4Pa6Rb0Hq3Zx9", + "fields": [], + "url_parts": [ + { + "field": "launch.url", + "name": "state" + } + ], + "minted_by": "POST /v3/bank/link-session/bank-start/ (launch.url)" + }, + { + "name": "link_ref", + "description": "The non-secret reference of a link in the return to the hosted page (`/bank/return?link_ref=`).", + "travels": [ + "query", + "body" + ], + "pattern": "^lr_[0-9a-f]{12}$", + "example": "lr_4c9a7e1b2f6d", + "fields": [ + "link_ref" + ], + "minted_by": "redirect states and frame messages" + }, + { + "name": "manage_token", + "description": "The token of the person's own access page, `/bank/manage/`: `mgu_--`. It travels in a PATH.", + "travels": [ + "path" + ], + "pattern": "^mgu_[0-9a-f]{32}-[0-9]{1,9}-[0-9a-f]{32}$", + "example": "mgu_0b9c4f1e6a2d4e8b9f317c5d2e1a8b40-1-3f9a1c7e5b2d8a603f9a1c7e5b2d8a60", + "fields": [], + "minted_by": "poll `manage_url`" + }, + { + "name": "selection_token", + "description": "The token naming an offered account in the account choice.", + "travels": [ + "body" + ], + "pattern": "^sel_[A-Za-z0-9_-]{19}$", + "example": "sel_Hs8Pa4Rb6Ye0Gf2Jc7x", + "fields": [ + "selection_token" + ], + "minted_by": "GET /v3/bank/link-session/accounts/ (items[].selection_token)" + }, + { + "name": "redirect_state", + "description": "The `state` the customer's `redirect_url` receives: a display-only signature.", + "travels": [ + "query" + ], + "pattern": "^[0-9a-f]{32}$", + "example": "2f8d41c9e07a5b13c6d9a0e4f7b82c15", + "fields": [ + "redirect.params.state" + ], + "minted_by": "poll `redirect.params.state`" + }, + { + "name": "instance_id", + "description": "The id the hosted page or SDK generates once per page instance (a UUID); the backend binds a resume code to it.", + "travels": [ + "body", + "header", + "query" + ], + "pattern": "^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$", + "example": "7b1d6a52-3c84-4e0f-9a21-5d8e3f6c0b19", + "fields": [ + "instance_id" + ], + "minted_by": "the client (generated, never minted by the backend)" + }, + { + "name": "error_code", + "description": "The `code` of an error body and of a link failure.", + "travels": [ + "body" + ], + "pattern": "^[a-z][a-z0-9_]{0,63}$", + "example": "wrong_step", + "fields": [ + "error.code", + "code" + ], + "minted_by": "every error body" + }, + { + "name": "institution_id", + "description": "The public id of a bank.", + "travels": [ + "body", + "path", + "query" + ], + "pattern": "^[a-z0-9][a-z0-9-]{1,63}$", + "example": "es-banco-norte", + "fields": [ + "detail.institution_id" + ], + "minted_by": "GET /v3/bank/link-session/institutions/" + } + ], + "addresses": [ + { + "name": "sdk_handoff", + "description": "Full-page redirect handoff, step 1: the SDK sends the TOP window of the host page to the hosted page when the popup was blocked (or on a phone browser). Everything travels in the fragment, so no server log sees it; the hosted page removes the fragment from its address at once (history.replaceState) after reading it. The older `#t=&resume=1&return=` form is gone: the token is never used, and `resume` is not a parameter (a page ignores it).", + "address": "/bank/link/", + "where": "fragment", + "encoding": "application/x-www-form-urlencoded (every value percent-encoded)", + "params": [ + { + "name": "resume_code", + "required": true, + "format": "resume_code", + "description": "The single-use code the frame obtained from `POST /v3/bank/link-session/resume-code/`." + }, + { + "name": "instance_id", + "required": true, + "format": "instance_id", + "description": "The id the SDK generated once for this page instance; the code is bound to it." + }, + { + "name": "v", + "required": true, + "pattern": "^[0-9]{1,3}$", + "example": "1", + "description": "The protocol number of the SDK (the wire contract is additive only)." + }, + { + "name": "return", + "required": false, + "pattern": "^.{1,2048}$", + "example": "https://app.example.com/accounts/connect", + "description": "The host page's own address, a CANDIDATE only. The hosted page sends it to the backend as `return_to` and navigates only to the `return_url` the backend answers." + }, + { + "name": "sdk_version", + "required": false, + "pattern": "^[0-9A-Za-z.+-]{1,32}$", + "example": "0.7.0", + "description": "The SDK's version, for diagnostics." + } + ] + }, + { + "name": "hosted_return", + "description": "Full-page redirect handoff, step 3: after the bank the hosted page asks `POST /v3/bank/link-session/resume-code/` for a new code and sends the browser to the `return_url` of that answer (never to an address of its own) with `didit_resume=` appended to the QUERY, before any hash. The host page's `resumeBankLink()` removes the parameter from the address and exchanges the code.", + "address": "", + "where": "query", + "encoding": "RFC 3986 query", + "params": [ + { + "name": "didit_resume", + "required": true, + "format": "resume_code", + "description": "The single-use resume code for the step after the bank." + } + ] + } + ] +} diff --git a/src/__tests__/rn-077-codegen.test.ts b/src/__tests__/rn-077-codegen.test.ts index f149f31..fdef9d3 100644 --- a/src/__tests__/rn-077-codegen.test.ts +++ b/src/__tests__/rn-077-codegen.test.ts @@ -13,6 +13,7 @@ describe('React Native 0.77 codegen compatibility', () => { const schema = new TypeScriptParser().parseString(spec, specPath); expect(schema.modules.NativeSdkReactNative.spec.eventEmitters).toEqual([ + expect.objectContaining({ name: 'onBankLinkEvent' }), expect.objectContaining({ name: 'onTransactionUpdated' }), ]); }); diff --git a/src/bankLink.ts b/src/bankLink.ts new file mode 100644 index 0000000..f4ac5e1 --- /dev/null +++ b/src/bankLink.ts @@ -0,0 +1,358 @@ +import type { EventSubscription } from 'react-native'; +import NativeSdkReactNative from './NativeSdkReactNative'; +import { toNativeConfig } from './nativeConfig'; +import type { + BankLinkEvent, + BankLinkEventListener, + BankLinkEventName, + BankLinkEventPayload, + BankLinkExit, + BankLinkExitReason, + BankLinkOptions, + BankLinkResult, + BankLinkStep, + BankLinkSuccess, +} from './types'; + +const EVENT_FIELDS = { + opened: ['mode', 'access', 'presentation'], + consent_shown: ['consent_version'], + consent_accepted: ['consent_version'], + institution_selected: ['institution_id', 'country'], + bank_redirect: ['via'], + bank_returned: ['result'], + accounts_selected: ['count'], + success: ['connection_id', 'check_id', 'resumed'], + exit: ['reason', 'step', 'resumed'], + error: ['code'], +} as const satisfies Record< + BankLinkEventName, + readonly (keyof BankLinkEventPayload)[] +>; + +const STEPS: readonly BankLinkStep[] = [ + 'consent', + 'segment', + 'institution', + 'unsupported', + 'email', + 'email_verify', + 'bank_hop', + 'accounts', + 'confirm_reuse', + 'confirm_one_time_fallback', + 'renew', + 'reconfirm', + 'collecting', + 'done', + 'ended', + 'unknown', +]; + +const EXIT_REASONS: readonly BankLinkExitReason[] = [ + 'closed', + 'cancelled', + 'bank_unavailable', + 'expired', + 'failed', +]; + +/** The raw shape native returns, as JSON. */ +interface BankLinkResultJS { + type?: string; + linkId?: string; + connectionId?: string; + checkId?: string; + reason?: string; + step?: string | null; + resumed?: boolean; +} + +// ─── Events ────────────────────────────────────────────────────────────────── + +const listeners = new Set(); +let nativeSubscription: EventSubscription | null = null; + +function parseEvent(raw: string): BankLinkEvent | null { + let parsed: { name?: unknown; payload?: unknown } | null; + try { + parsed = JSON.parse(raw) as { name?: unknown; payload?: unknown } | null; + } catch { + return null; + } + if (!parsed || typeof parsed !== 'object') { + return null; + } + const name = parsed.name; + // A name this version does not know is ignored, as the link contract + // requires: new events are additive. + if ( + typeof name !== 'string' || + !Object.prototype.hasOwnProperty.call(EVENT_FIELDS, name) + ) { + return null; + } + const rawPayload = parsed.payload; + if ( + !rawPayload || + typeof rawPayload !== 'object' || + !('link_id' in rawPayload) + ) { + return null; + } + const { link_id } = rawPayload; + if (link_id !== null && typeof link_id !== 'string') { + return null; + } + + const payload: BankLinkEventPayload = { link_id }; + const eventName = name as BankLinkEventName; + for (const key of EVENT_FIELDS[eventName]) { + const value = (rawPayload as Record)[key]; + if (key === 'count') { + if (typeof value === 'number') payload.count = value; + } else if (key === 'resumed') { + if (typeof value === 'boolean') payload.resumed = value; + } else if (typeof value === 'string' || value === null) { + Object.assign(payload, { [key]: value }); + } + } + return { name: eventName, payload }; +} + +function dispatch(raw: string): void { + const event = parseEvent(raw); + if (!event) { + return; + } + // Copied, so a listener that unsubscribes while being called does not make + // the loop skip the next one. + for (const listener of Array.from(listeners)) { + try { + listener(event); + } catch (error) { + // One listener must never starve the others, nor the native flow that + // emitted the event. The failure is reported, not rethrown into native. + console.error('A Bank Link event listener threw:', error); + } + } +} + +function subscribeNative(): void { + if (nativeSubscription || listeners.size === 0) { + return; + } + // The Bank Link events are a Codegen `EventEmitter`, which is a function + // property of the TurboModule: native delivers `emitOnBankLinkEvent` only to + // the handler registered here. A `NativeEventEmitter` listens on + // `RCTDeviceEventEmitter`, which this module never emits on, so subscribing + // that way would silently deliver nothing. + nativeSubscription = NativeSdkReactNative.onBankLinkEvent((raw: string) => + dispatch(String(raw)) + ); +} + +function unsubscribeNative(): void { + if (!nativeSubscription || listeners.size > 0) { + return; + } + nativeSubscription.remove(); + nativeSubscription = null; +} + +/** + * Listen to the events of a Bank Link: the names and payload keys of the link + * contract, identical to native and web, ids only. + * + * Subscribe before {@link presentBankLink} to see `opened` and every step + * after it. The returned function unsubscribes; a listener is never called + * after it returns. + * + * @param listener - Called once per event. + * @returns An unsubscribe function. + * + * @example + * ```ts + * const stop = onBankLinkEvent(({ name, payload }) => { + * console.log(name, payload.link_id); + * }); + * ``` + */ +export function onBankLinkEvent(listener: BankLinkEventListener): () => void { + listeners.add(listener); + subscribeNative(); + return () => { + if (!listeners.delete(listener)) { + return; + } + unsubscribeNative(); + }; +} + +// ─── Results ───────────────────────────────────────────────────────────────── + +/** + * The step a flow ended on: a member of the union, `null` before the first + * poll, and `unknown` for a step a newer server introduced. + */ +function mapStep(step: string | null): BankLinkStep | null { + if (typeof step === 'string' && STEPS.includes(step as BankLinkStep)) { + return step as BankLinkStep; + } + return step === null ? null : 'unknown'; +} + +function mapResult(raw: BankLinkResultJS): BankLinkResult { + if (raw.type === 'success') { + if (typeof raw.linkId !== 'string' || raw.linkId.length === 0) { + throw new Error('The Bank Link completed without a link id.'); + } + const success: BankLinkSuccess = { type: 'success', linkId: raw.linkId }; + if (raw.connectionId != null) { + success.connectionId = raw.connectionId; + } + if (raw.checkId != null) { + success.checkId = raw.checkId; + } + if (raw.resumed != null) { + success.resumed = raw.resumed; + } + return success; + } + + if (raw.type === 'exit') { + // Native only sends these five, per the contract; anything else is a + // failure, never a success. + const reason = EXIT_REASONS.includes(raw.reason as BankLinkExitReason) + ? (raw.reason as BankLinkExitReason) + : 'failed'; + const exit: BankLinkExit = { type: 'exit', reason }; + if (raw.step !== undefined) { + exit.step = mapStep(raw.step); + } + if (raw.resumed != null) { + exit.resumed = raw.resumed; + } + return exit; + } + + throw new Error( + `The native SDK returned an unrecognized Bank Link result: ${String( + raw.type + )}` + ); +} + +function parseResult(raw: string): BankLinkResult { + return mapResult(JSON.parse(raw) as BankLinkResultJS); +} + +// ─── Presentation ──────────────────────────────────────────────────────────── + +/** + * The link being presented or resumed, so a second call cannot replace the + * native callbacks of the first one and orphan its promise. + */ +let activeBankLink: Promise | null = null; + +/** + * Runs one presentation or resume in the single-link slot. While it runs, + * every other presentation or resume is refused: native keeps one coordinator, + * so a second call would take over its callbacks and the first promise would + * never settle. + */ +function runAsActiveBankLink( + refusal: string, + work: () => Promise +): Promise { + if (activeBankLink) { + return Promise.reject(new Error(refusal)); + } + + const result = work(); + activeBankLink = result; + const release = () => { + if (activeBankLink === result) { + activeBankLink = null; + } + }; + result.then(release, release); + return result; +} + +/** + * Open a Bank Link. + * + * Every screen, state and string is native: the wrapper only carries the + * result and the events. The promise settles exactly once, with `success` or + * `exit`; the same two events also arrive on {@link onBankLinkEvent}. + * + * @param token - The link's `client_token` (`blt_...`) from + * `POST /v3/bank/links/`. The API key never reaches the app. + * @param options - Optional SDK configuration. + * @returns A promise that resolves with the result. + * @throws When a Bank Link is already open, or the native result is unusable. + * + * @example + * ```ts + * const result = await presentBankLink(clientToken); + * if (result.type === 'success') { + * console.log('Connected', result.connectionId); + * } + * ``` + */ +export function presentBankLink( + token: string, + options?: BankLinkOptions +): Promise { + return runAsActiveBankLink( + 'A Bank Link is already open. Await its result before presenting another one.', + async () => { + const raw = await NativeSdkReactNative.presentBankLink( + token, + toNativeConfig(options?.config) + ); + return parseResult(raw); + } + ); +} + +/** + * Pick up a Bank Link whose bank hop outlived the app. + * + * Call it once at start-up, before rendering, after the person comes back to + * the app: it replays the result if the link finished while the app was + * closed, and otherwise carries on at the step the server says, with + * `resumed: true` on the result. + * + * A resume takes the single-link slot, so it is refused while a link is open + * (and a presentation is refused while a resume is in flight): native keeps + * one coordinator, and the second call would take over its callbacks. + * + * @returns The result, or `null` when nothing is pending. + * @throws When a Bank Link is already open, or the native result is unusable. + */ +export function resumeBankLink(): Promise { + return runAsActiveBankLink( + 'A Bank Link is already open. Await its result before resuming one.', + async () => { + const raw = await NativeSdkReactNative.resumeBankLink(); + const parsed = JSON.parse(raw) as BankLinkResultJS | null; + return parsed ? mapResult(parsed) : null; + } + ); +} + +/** + * Hand an address the app was opened with to the Bank Link, for hosts whose + * bank return is an app link or universal link. + * + * Call it from `onOpenURL`/`onNewIntent` with every address: native decides + * whether the address is a link return, and the poll decides the screen. The + * address is never parsed here, so a resume code keeps its dot. + * + * @param url - The address the app was opened with. + */ +export function handleBankLinkReturn(url: string): void { + NativeSdkReactNative.handleBankLinkReturn(url); +} diff --git a/src/index.tsx b/src/index.tsx index a435305..ceda6e0 100644 --- a/src/index.tsx +++ b/src/index.tsx @@ -1,6 +1,7 @@ import type { EventSubscription } from 'react-native'; import NativeSdkReactNative from './NativeSdkReactNative'; import type { VerificationResultJS } from './NativeSdkReactNative'; +import { toNativeConfig } from './nativeConfig'; import { VerificationStatus, DiditTransactionError } from './types'; import type { VerificationResult, @@ -14,6 +15,12 @@ import type { // Re-export all public types export { VerificationStatus, CameraLens, DiditTransactionError } from './types'; +export { + presentBankLink, + resumeBankLink, + onBankLinkEvent, + handleBankLinkReturn, +} from './bankLink'; export type { VerificationResult, VerificationCompleted, @@ -35,6 +42,16 @@ export type { DiditTransactionResult, DiditTransactionOptions, DiditTransactionErrorCode, + BankLinkOptions, + BankLinkResult, + BankLinkSuccess, + BankLinkExit, + BankLinkExitReason, + BankLinkStep, + BankLinkEvent, + BankLinkEventName, + BankLinkEventPayload, + BankLinkEventListener, } from './types'; // ─── Internal Helpers ──────────────────────────────────────────────────────── @@ -182,21 +199,7 @@ export async function startVerification( token: string, config?: DiditConfig ): Promise { - const nativeConfig = config - ? { - languageCode: config.languageCode, - showLanguageSelector: config.showLanguageSelector, - fontFamily: config.fontFamily, - loggingEnabled: config.loggingEnabled, - showCloseButton: config.showCloseButton, - showExitConfirmation: config.showExitConfirmation, - closeOnComplete: config.closeOnComplete, - defaultDocumentCamera: config.defaultDocumentCamera, - defaultLivenessCamera: config.defaultLivenessCamera, - showDocumentCameraSwitchButton: config.showDocumentCameraSwitchButton, - showLivenessCameraSwitchButton: config.showLivenessCameraSwitchButton, - } - : {}; + const nativeConfig = toNativeConfig(config); return runExclusively(JSON.stringify(['token', token, nativeConfig]), () => NativeSdkReactNative.startVerification(token, nativeConfig) @@ -228,23 +231,7 @@ export async function startVerificationWithWorkflow( workflowId: string, options?: WorkflowOptions ): Promise { - const nativeConfig = options?.config - ? { - languageCode: options.config.languageCode, - showLanguageSelector: options.config.showLanguageSelector, - fontFamily: options.config.fontFamily, - loggingEnabled: options.config.loggingEnabled, - showCloseButton: options.config.showCloseButton, - showExitConfirmation: options.config.showExitConfirmation, - closeOnComplete: options.config.closeOnComplete, - defaultDocumentCamera: options.config.defaultDocumentCamera, - defaultLivenessCamera: options.config.defaultLivenessCamera, - showDocumentCameraSwitchButton: - options.config.showDocumentCameraSwitchButton, - showLivenessCameraSwitchButton: - options.config.showLivenessCameraSwitchButton, - } - : {}; + const nativeConfig = toNativeConfig(options?.config); const nativeContactDetails = options?.contactDetails ? { diff --git a/src/nativeConfig.ts b/src/nativeConfig.ts new file mode 100644 index 0000000..42abfcc --- /dev/null +++ b/src/nativeConfig.ts @@ -0,0 +1,31 @@ +import type { VerificationConfig } from './NativeSdkReactNative'; +import type { DiditConfig } from './types'; + +/** + * The Codegen struct of a `DiditConfig`. + * + * The native bridges parse these keys independently, so every key the public + * type accepts must be listed here: `native-config-forwarding.test.ts` fails + * when a bridge and this mapping drift apart. The object is always returned + * (`{}` for no config) because the TurboModule struct is a required parameter. + */ +export function toNativeConfig( + config?: DiditConfig | null +): VerificationConfig { + if (!config) { + return {}; + } + return { + languageCode: config.languageCode, + showLanguageSelector: config.showLanguageSelector, + fontFamily: config.fontFamily, + loggingEnabled: config.loggingEnabled, + showCloseButton: config.showCloseButton, + showExitConfirmation: config.showExitConfirmation, + closeOnComplete: config.closeOnComplete, + defaultDocumentCamera: config.defaultDocumentCamera, + defaultLivenessCamera: config.defaultLivenessCamera, + showDocumentCameraSwitchButton: config.showDocumentCameraSwitchButton, + showLivenessCameraSwitchButton: config.showLivenessCameraSwitchButton, + }; +} diff --git a/src/types.ts b/src/types.ts index 22edbe9..bad51ab 100644 --- a/src/types.ts +++ b/src/types.ts @@ -389,3 +389,154 @@ export class DiditTransactionError extends Error { this.fieldErrors = fieldErrors; } } + +// ─── Bank Link ─────────────────────────────────────────────────────────────── + +/** + * Why a Bank Link ended without success (`exit.reason` of the link contract). + */ +export type BankLinkExitReason = + /** The person closed the screen. */ + | 'closed' + /** The person, or the server, cancelled the link. */ + | 'cancelled' + /** The bank cannot take part right now. */ + | 'bank_unavailable' + /** The link expired. */ + | 'expired' + /** Any other failure. */ + | 'failed'; + +/** + * The poll step the person was on when the flow ended, or `null` before the + * first poll. `unknown` is a step a newer server introduced. + */ +export type BankLinkStep = + | 'consent' + | 'segment' + | 'institution' + | 'unsupported' + | 'email' + | 'email_verify' + | 'bank_hop' + | 'accounts' + | 'confirm_reuse' + | 'confirm_one_time_fallback' + | 'renew' + | 'reconfirm' + | 'collecting' + | 'done' + | 'ended' + | 'unknown'; + +/** + * The names of the `onBankLinkEvent` events, identical on native and web. + */ +export type BankLinkEventName = + | 'opened' + | 'consent_shown' + | 'consent_accepted' + | 'institution_selected' + | 'bank_redirect' + | 'bank_returned' + | 'accounts_selected' + | 'success' + | 'exit' + | 'error'; + +/** + * The payload of a {@link BankLinkEvent}. Keys are snake_case as on native and + * web, and carry ids only: never a person's name, an account number, a token + * or an email. Optional keys native has no value for arrive as `null`, and a + * key a given event does not carry is absent. + */ +export interface BankLinkEventPayload { + /** The link id; carried by every event. */ + link_id: string | null; + /** `opened`: `connect`, `renew` or `manage`. */ + mode?: 'connect' | 'renew' | 'manage'; + /** `opened` and the steps it words: the access the link effectively has. */ + access?: 'one_time' | 'ongoing'; + /** `opened`: `ios`, `android` or `rn`. */ + presentation?: string; + /** `consent_shown` and `consent_accepted`: the consent version the server sent. */ + consent_version?: string; + /** `institution_selected`: the public id of the bank. */ + institution_id?: string; + /** `institution_selected`: the bank's country. */ + country?: string; + /** `bank_redirect`: `popup` (the native browser sheet included) or `redirect`. */ + via?: 'popup' | 'redirect'; + /** `bank_returned`: how the bank hop ended. */ + result?: 'ok' | 'cancelled' | 'failed' | 'timeout' | 'unsupported'; + /** `accounts_selected`: how many accounts were shared. */ + count?: number; + /** `success`: the connection the link produced. Never trusted by a server. */ + connection_id?: string | null; + /** `success`: the check the link produced. */ + check_id?: string | null; + /** `exit`: why the flow ended. */ + reason?: BankLinkExitReason; + /** `exit`: the step the person was on. */ + step?: BankLinkStep | null; + /** `success` and `exit`: the terminal result was replayed. */ + resumed?: boolean; + /** `error`: the error code of a non-terminal client or transport error. */ + code?: string; +} + +/** + * One Bank Link event, as delivered to an `onBankLinkEvent` listener. + */ +export interface BankLinkEvent { + name: BankLinkEventName; + payload: BankLinkEventPayload; +} + +/** + * Called for every Bank Link event while a listener is subscribed. + */ +export type BankLinkEventListener = (event: BankLinkEvent) => void; + +/** + * A link that completed: the ids the host needs, and nothing about the person. + */ +export interface BankLinkSuccess { + type: 'success'; + /** The link id. */ + linkId: string; + /** The connection the link produced. A server learns the outcome from its webhook. */ + connectionId?: string; + /** The check the link produced, when the flow created one. */ + checkId?: string; + /** The result was replayed by `resumeBankLink` after the app was closed. */ + resumed?: boolean; +} + +/** + * A link that ended without success. + */ +export interface BankLinkExit { + type: 'exit'; + reason: BankLinkExitReason; + /** The step the person was on when the flow ended, or `null` before the first poll. */ + step?: BankLinkStep | null; + /** The result was replayed by `resumeBankLink` after the app was closed. */ + resumed?: boolean; +} + +/** + * The result of a Bank Link. Use the `type` field to discriminate. + */ +export type BankLinkResult = BankLinkSuccess | BankLinkExit; + +/** + * Options for {@link presentBankLink}. + */ +export interface BankLinkOptions { + /** + * SDK configuration (language, font, logging) so the link matches the rest + * of the app's Didit flow. + */ + config?: DiditConfig; +}