From 5e5e5432835f0498d5f7e00fe5dd39487ce556b8 Mon Sep 17 00:00:00 2001 From: Alejandro Rosas <46827020+arosasg@users.noreply.github.com> Date: Sun, 22 Nov 2026 09:44:11 +0000 Subject: [PATCH 1/6] DID-12138: React Native: Bank Link wrapper over the native SDKs (sdk-react-native) --- README.md | 117 +++++ .../java/com/sdkreactnative/BankLinkJson.kt | 48 +++ .../sdkreactnative/SdkReactNativeModule.kt | 61 +++ example/src/App.tsx | 118 ++++- ios/DiditSdkBridge.swift | 133 ++++++ ios/SdkReactNative.mm | 38 ++ src/NativeSdkReactNative.ts | 30 ++ src/__tests__/bank-link-formats.test.ts | 200 +++++++++ src/__tests__/bank-link.test.ts | 403 ++++++++++++++++++ src/__tests__/fixtures/bank-link-formats.json | 262 ++++++++++++ src/__tests__/rn-077-codegen.test.ts | 1 + src/bankLink.ts | 298 +++++++++++++ src/index.tsx | 51 +-- src/nativeConfig.ts | 31 ++ src/types.ts | 149 +++++++ 15 files changed, 1907 insertions(+), 33 deletions(-) create mode 100644 android/src/main/java/com/sdkreactnative/BankLinkJson.kt create mode 100644 src/__tests__/bank-link-formats.test.ts create mode 100644 src/__tests__/bank-link.test.ts create mode 100644 src/__tests__/fixtures/bank-link-formats.json create mode 100644 src/bankLink.ts create mode 100644 src/nativeConfig.ts diff --git a/README.md b/README.md index 3679f96..de90987 100644 --- a/README.md +++ b/README.md @@ -93,6 +93,55 @@ 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. + +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); +}); + +const result: BankLinkResult = await presentBankLink(clientToken); +stop(); + +if (result.type === 'success') { + console.log('Linked', result.connectionId); +} else { + console.log('Ended', result.reason, result.step); +} +``` + +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, so a second call 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 +875,60 @@ 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. + +### `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` | `institution_id`, `country` | +| `bank_redirect` | `via` | +| `bank_returned` | `result` | +| `accounts_selected` | `count` | +| `success` | `link_id`, `connection_id?`, `check_id?` | +| `exit` | `reason`, `step` | +| `error` | `code` | + +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 +938,10 @@ import { startVerificationWithWorkflow, submitTransaction, getTransaction, + presentBankLink, + resumeBankLink, + onBankLinkEvent, + handleBankLinkReturn, // Enum VerificationStatus, @@ -863,6 +970,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/android/src/main/java/com/sdkreactnative/BankLinkJson.kt b/android/src/main/java/com/sdkreactnative/BankLinkJson.kt new file mode 100644 index 0000000..195cd32 --- /dev/null +++ b/android/src/main/java/com/sdkreactnative/BankLinkJson.kt @@ -0,0 +1,48 @@ +package com.sdkreactnative + +import me.didit.sdk.BankLinkEvent +import me.didit.sdk.BankLinkResult +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. + * + * Native Bank Link is not released yet: this file and the module's three Bank + * Link overrides are the only place that touches it, and they are reconciled + * with the native Android API of the Bank Link issue when the version that + * carries it is pinned. + */ +internal object BankLinkJson { + + /** The JSON `null` a resume answers when nothing is pending. */ + const val NONE = "null" + + fun event(event: BankLinkEvent): String = JSONObject() + .put("name", event.name) + .put("payload", JSONObject(event.payload)) + .toString() + + fun result(result: BankLinkResult): String = when (result) { + is BankLinkResult.Success -> JSONObject() + .put("type", "success") + .put("linkId", result.linkId) + .put("connectionId", result.connectionId ?: JSONObject.NULL) + .put("checkId", result.checkId ?: JSONObject.NULL) + .put("resumed", result.resumed) + .toString() + + is BankLinkResult.Exit -> exit(result.reason, result.step, result.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/main/java/com/sdkreactnative/SdkReactNativeModule.kt b/android/src/main/java/com/sdkreactnative/SdkReactNativeModule.kt index be584b4..4f25082 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,66 @@ 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 + } + scope.launch { + try { + DiditSdk.presentBankLink( + activity = activity, + token = token, + configuration = parseConfiguration(config), + onEvent = { event -> emitOnBankLinkEvent(BankLinkJson.event(event)) }, + onResult = { result -> promise.resolve(BankLinkJson.result(result)) } + ) + } catch (e: Exception) { + logDebugError("presentBankLink: exception", e) + promise.reject("bank_link", e.message, e) + } + } + } + + override fun resumeBankLink(promise: Promise) { + val activity = reactApplicationContext.currentActivity + if (activity == null) { + // Never reported as "nothing to resume": a link may well be pending. + logDebugError("resumeBankLink: no active Activity at call time") + promise.reject("no_activity", "No active Activity available to resume Bank Link.") + return + } + scope.launch { + try { + val resumed = DiditSdk.resumeBankLink( + activity = activity, + onEvent = { event -> emitOnBankLinkEvent(BankLinkJson.event(event)) }, + onResult = { result -> promise.resolve(BankLinkJson.result(result)) } + ) + if (!resumed) { + promise.resolve(BankLinkJson.NONE) + } + } catch (e: Exception) { + logDebugError("resumeBankLink: exception", e) + promise.reject("bank_link", e.message, e) + } + } + } + + override fun handleBankLinkReturn(url: String) { + // 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 { + DiditSdk.handleBankLinkReturn(uri) + } + } + // ─── Diagnostics ───────────────────────────────────────────────────────── /** diff --git a/example/src/App.tsx b/example/src/App.tsx index 2c639cb..7e99790 100644 --- a/example/src/App.tsx +++ b/example/src/App.tsx @@ -1,4 +1,4 @@ -import { useState, useCallback } from 'react'; +import { useState, useCallback, useEffect } from 'react'; import { Text, View, @@ -15,10 +15,15 @@ import { startVerification, startVerificationWithWorkflow, submitTransaction, + presentBankLink, + resumeBankLink, + onBankLinkEvent, DiditTransactionError, VerificationStatus, type VerificationResult, type DiditTransactionResult, + type BankLinkEvent, + type BankLinkResult, } from '@didit-protocol/sdk-react-native'; const DEMO_WALLET_ADDRESS = '0x71C7656EC7ab88b098defB751B7401B5f6d8976F'; @@ -32,6 +37,62 @@ 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 + ) + ); + }), + [] + ); + + 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 +344,61 @@ 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..6642946 100644 --- a/ios/DiditSdkBridge.swift +++ b/ios/DiditSdkBridge.swift @@ -413,6 +413,139 @@ public class DiditSdkBridge: NSObject, @unchecked Sendable { } } + // MARK: - Bank Link + + /// 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. Presentation starts on the main + /// queue and lets the SDK pick the view controller, as it does for hosts + /// that call it directly. + public func presentBankLink( + token: String, + config: NSDictionary?, + onEvent: @escaping @Sendable (String) -> Void, + completion: @escaping @Sendable (String) -> Void + ) { + let parsed = ParsedConfig(config) + DispatchQueue.main.async { + MainActor.assumeIsolated { + DiditSdk.shared.presentBankLink( + token: token, + configuration: parsed.toConfiguration(), + onEvent: { event in + onEvent(Self.bankLinkEventJson(event)) + }, + onResult: { result in + completion(Self.bankLinkResultJson(result)) + } + ) + } + } + } + + /// 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( + onEvent: @escaping @Sendable (String) -> Void, + completion: @escaping @Sendable (String) -> Void + ) { + DispatchQueue.main.async { + MainActor.assumeIsolated { + let resumed = DiditSdk.shared.resumeBankLink( + 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() + } + } + // 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..0ae2308 100644 --- a/ios/SdkReactNative.mm +++ b/ios/SdkReactNative.mm @@ -187,6 +187,44 @@ - (void)getTransaction:(NSString *)transactionToken }]; } +// MARK: - Bank Link + +- (void)presentBankLink:(NSString *)token + config:(JS::NativeSdkReactNative::VerificationConfig &)config + resolve:(RCTPromiseResolveBlock)resolve + reject:(RCTPromiseRejectBlock)reject +{ + NSDictionary *configDict = (&config != nullptr) ? [self configDictFrom:config] : nil; + __weak SdkReactNative *weakSelf = self; + + [_bridge presentBankLinkWithToken:token + config:configDict + onEvent:^(NSString *eventJson) { + [weakSelf emitOnBankLinkEvent:eventJson]; + } + completion:^(NSString *resultJson) { + resolve(resultJson); + }]; +} + +- (void)resumeBankLink:(RCTPromiseResolveBlock)resolve + reject:(RCTPromiseRejectBlock)reject +{ + __weak SdkReactNative *weakSelf = self; + + [_bridge resumeBankLinkWithOnEvent:^(NSString *eventJson) { + [weakSelf emitOnBankLinkEvent:eventJson]; + } + completion:^(NSString *resultJson) { + resolve(resultJson); + }]; +} + +- (void)handleBankLinkReturn:(NSString *)url +{ + [_bridge handleBankLinkReturnWithUrl:url]; +} + // MARK: - TurboModule Registration - (std::shared_ptr)getTurboModule: 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..21d9d79 --- /dev/null +++ b/src/__tests__/bank-link-formats.test.ts @@ -0,0 +1,200 @@ +/** + * 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. + * + * This test walks every example through the three places the wrapper touches a + * value - the token of a presentation, a parameter of a return address (query + * and fragment), and an event payload - and asserts each one is accepted and + * forwarded unchanged. A validator here may be looser than the file, never + * stricter: a rejection or a truncated value fails. + */ + +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(), + addListener: jest.fn(), + removeListeners: jest.fn(), + }, +})); + +import { readFileSync } from 'fs'; +import { join } from 'path'; +import { DeviceEventEmitter } from 'react-native'; +import NativeSdkReactNative from '../NativeSdkReactNative'; +import { + presentBankLink, + onBankLinkEvent, + handleBankLinkReturn, +} from '../index'; +import type { BankLinkEventPayload } 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 payload key a value of this format travels in, when it has one. */ +function payloadKey(format: Format): keyof BankLinkEventPayload { + return (format.fields?.[0] ?? 'link_id') as keyof BankLinkEventPayload; +} + +beforeEach(() => { + jest.clearAllMocks(); + 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.each(formats.map((format) => [format.name, format] as const))( + 'arrives in an event payload as %s, unchanged', + (_name, format) => { + const listener = jest.fn(); + const stop = onBankLinkEvent(listener); + + DeviceEventEmitter.emit( + 'onBankLinkEvent', + JSON.stringify({ + name: 'opened', + payload: { link_id: 'link-1', [payloadKey(format)]: format.example }, + }) + ); + stop(); + + expect(listener).toHaveBeenCalledTimes(1); + expect(listener.mock.calls[0][0].payload[payloadKey(format)]).toBe( + format.example + ); + } + ); +}); diff --git a/src/__tests__/bank-link.test.ts b/src/__tests__/bank-link.test.ts new file mode 100644 index 0000000..2c04c80 --- /dev/null +++ b/src/__tests__/bank-link.test.ts @@ -0,0 +1,403 @@ +/** + * 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(), + addListener: jest.fn(), + removeListeners: jest.fn(), + }, +})); + +import { readFileSync } from 'fs'; +import { join } from 'path'; +import { DeviceEventEmitter } 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', +]; + +/** Emits one native event, exactly as the native modules do: a JSON string. */ +function emit(event: unknown): void { + DeviceEventEmitter.emit('onBankLinkEvent', JSON.stringify(event)); +} + +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('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('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('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.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', + { institution_id: 'institution-1', country: 'ES' }, + ], + ['bank_redirect', { via: 'popup' }], + ['bank_returned', { result: 'ok' }], + ['accounts_selected', { count: 2 }], + [ + 'success', + { link_id: 'link-1', connection_id: 'connection-1', check_id: 'check-1' }, + ], + ['exit', { reason: 'closed', step: 'bank_hop' }], + ['error', { 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: {} }); + 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' }, + }); + DeviceEventEmitter.emit('onBankLinkEvent', '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 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..97a0ce0 --- /dev/null +++ b/src/bankLink.ts @@ -0,0 +1,298 @@ +import { NativeEventEmitter } from 'react-native'; +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'; + +/** + * The event name the native modules emit on: the name of the TurboModule + * `EventEmitter` property, shared by every platform. + */ +const EVENT_NAME = 'onBankLinkEvent'; + +const EVENT_NAMES: readonly BankLinkEventName[] = [ + 'opened', + 'consent_shown', + 'consent_accepted', + 'institution_selected', + 'bank_redirect', + 'bank_returned', + 'accounts_selected', + 'success', + 'exit', + 'error', +]; + +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 ────────────────────────────────────────────────────────────────── + +/** + * What `NativeEventEmitter` needs of the module: the listener counter the + * Codegen base class provides on both platforms, which the spec it generates + * does not declare. + */ +interface NativeEventEmitterModule { + addListener: (eventType: string) => void; + removeListeners: (count: number) => void; +} + +const listeners = new Set(); +let emitter: NativeEventEmitter | null = null; +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' || + !EVENT_NAMES.includes(name as BankLinkEventName) + ) { + return null; + } + const payload = parsed.payload; + return { + name: name as BankLinkEventName, + payload: + payload && typeof payload === 'object' + ? (payload as BankLinkEventPayload) + : {}, + }; +} + +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)) { + listener(event); + } +} + +function subscribeNative(): void { + if (nativeSubscription || listeners.size === 0) { + return; + } + if (!emitter) { + emitter = new NativeEventEmitter( + NativeSdkReactNative as unknown as NativeEventEmitterModule + ); + } + nativeSubscription = emitter.addListener(EVENT_NAME, (raw: unknown) => + 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 ───────────────────────────────────────────────────────────────── + +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 = raw.step as BankLinkStep | null; + } + 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, so a second `presentBankLink` cannot replace the + * result of the first one. + */ +let activeBankLink: Promise | null = null; + +/** + * 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 { + if (activeBankLink) { + return Promise.reject( + new Error( + 'A Bank Link is already open. Await its result before presenting another one.' + ) + ); + } + + const result = (async () => { + const raw = await NativeSdkReactNative.presentBankLink( + token, + toNativeConfig(options?.config) + ); + return parseResult(raw); + })(); + + activeBankLink = result; + const release = () => { + if (activeBankLink === result) { + activeBankLink = null; + } + }; + result.then(release, release); + return result; +} + +/** + * 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. + * + * @returns The result, or `null` when nothing is pending. + */ +export async function resumeBankLink(): Promise { + 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..c69a692 100644 --- a/src/types.ts +++ b/src/types.ts @@ -389,3 +389,152 @@ 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; + /** `opened`: `connect` or `renew`. */ + mode?: 'connect' | 'renew'; + /** `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; + /** `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; +} From 971430f3d907b23ac0651b352cf0ee6fa39df460 Mon Sep 17 00:00:00 2001 From: Alejandro Rosas <46827020+arosasg@users.noreply.github.com> Date: Sun, 22 Nov 2026 10:21:20 +0000 Subject: [PATCH 2/6] DID-12138: React Native: Bank Link wrapper over the native SDKs (sdk-react-native) --- README.md | 16 +- .../java/com/sdkreactnative/BankLinkJson.kt | 49 +++++- .../sdkreactnative/SdkReactNativeModule.kt | 64 +++++++- src/__tests__/bank-link-formats.test.ts | 26 ++- src/__tests__/bank-link.test.ts | 149 ++++++++++++++++- src/bankLink.ts | 151 +++++++++++------- 6 files changed, 372 insertions(+), 83 deletions(-) diff --git a/README.md b/README.md index de90987..d86fb8d 100644 --- a/README.md +++ b/README.md @@ -140,7 +140,7 @@ import { handleBankLinkReturn } from '@didit-protocol/sdk-react-native'; handleBankLinkReturn(url); ``` -`presentBankLink` presents from the current view controller or activity, so a second call while a link is open rejects instead of replacing the first one's result. +`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 @@ -894,6 +894,8 @@ Pick up a link whose bank hop outlived the app, for example after the app was ki 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. @@ -909,13 +911,13 @@ Returns: `() => void` - the unsubscribe function. | `opened` | `link_id`, `mode`, `access`, `presentation` | | `consent_shown` | `link_id`, `consent_version` | | `consent_accepted` | `link_id`, `consent_version` | -| `institution_selected` | `institution_id`, `country` | -| `bank_redirect` | `via` | -| `bank_returned` | `result` | -| `accounts_selected` | `count` | +| `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` | `reason`, `step` | -| `error` | `code` | +| `exit` | `link_id`, `reason`, `step` | +| `error` | `link_id`, `code` | 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. diff --git a/android/src/main/java/com/sdkreactnative/BankLinkJson.kt b/android/src/main/java/com/sdkreactnative/BankLinkJson.kt index 195cd32..7a6f58c 100644 --- a/android/src/main/java/com/sdkreactnative/BankLinkJson.kt +++ b/android/src/main/java/com/sdkreactnative/BankLinkJson.kt @@ -2,6 +2,8 @@ package com.sdkreactnative import me.didit.sdk.BankLinkEvent import me.didit.sdk.BankLinkResult +import org.json.JSONArray +import org.json.JSONException import org.json.JSONObject /** @@ -22,10 +24,49 @@ internal object BankLinkJson { /** The JSON `null` a resume answers when nothing is pending. */ const val NONE = "null" - fun event(event: BankLinkEvent): String = JSONObject() - .put("name", event.name) - .put("payload", JSONObject(event.payload)) - .toString() + fun event(event: BankLinkEvent): String = try { + JSONObject() + .put("name", event.name) + .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) + .put("payload", JSONObject()) + .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() diff --git a/android/src/main/java/com/sdkreactnative/SdkReactNativeModule.kt b/android/src/main/java/com/sdkreactnative/SdkReactNativeModule.kt index 4f25082..2aaf0ce 100644 --- a/android/src/main/java/com/sdkreactnative/SdkReactNativeModule.kt +++ b/android/src/main/java/com/sdkreactnative/SdkReactNativeModule.kt @@ -424,14 +424,18 @@ class SdkReactNativeModule(reactContext: ReactApplicationContext) : } override fun resumeBankLink(promise: Promise) { - val activity = reactApplicationContext.currentActivity - if (activity == null) { - // Never reported as "nothing to resume": a link may well be pending. - logDebugError("resumeBankLink: no active Activity at call time") - promise.reject("no_activity", "No active Activity available to resume 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 = DiditSdk.resumeBankLink( activity = activity, @@ -448,6 +452,49 @@ class SdkReactNativeModule(reactContext: ReactApplicationContext) : } } + /** + * 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) { // 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 @@ -478,5 +525,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/src/__tests__/bank-link-formats.test.ts b/src/__tests__/bank-link-formats.test.ts index 21d9d79..2c8f6c2 100644 --- a/src/__tests__/bank-link-formats.test.ts +++ b/src/__tests__/bank-link-formats.test.ts @@ -23,14 +23,12 @@ jest.mock('../NativeSdkReactNative', () => ({ presentBankLink: jest.fn(), resumeBankLink: jest.fn(), handleBankLinkReturn: jest.fn(), - addListener: jest.fn(), - removeListeners: jest.fn(), + onBankLinkEvent: jest.fn(), }, })); import { readFileSync } from 'fs'; import { join } from 'path'; -import { DeviceEventEmitter } from 'react-native'; import NativeSdkReactNative from '../NativeSdkReactNative'; import { presentBankLink, @@ -90,8 +88,27 @@ function payloadKey(format: Format): keyof BankLinkEventPayload { return (format.fields?.[0] ?? 'link_id') as keyof BankLinkEventPayload; } +/** + * 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' })); }); @@ -182,8 +199,7 @@ describe('every example of the contract file', () => { const listener = jest.fn(); const stop = onBankLinkEvent(listener); - DeviceEventEmitter.emit( - 'onBankLinkEvent', + nativeHandler?.( JSON.stringify({ name: 'opened', payload: { link_id: 'link-1', [payloadKey(format)]: format.example }, diff --git a/src/__tests__/bank-link.test.ts b/src/__tests__/bank-link.test.ts index 2c04c80..19da136 100644 --- a/src/__tests__/bank-link.test.ts +++ b/src/__tests__/bank-link.test.ts @@ -13,8 +13,7 @@ jest.mock('../NativeSdkReactNative', () => ({ presentBankLink: jest.fn(), resumeBankLink: jest.fn(), handleBankLinkReturn: jest.fn(), - addListener: jest.fn(), - removeListeners: jest.fn(), + onBankLinkEvent: jest.fn(), }, })); @@ -78,9 +77,37 @@ const CONTRACT_PAYLOAD_KEYS = [ 'code', ]; +/** + * 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 { - DeviceEventEmitter.emit('onBankLinkEvent', JSON.stringify(event)); + 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', () => { @@ -206,6 +233,27 @@ describe('presentBankLink', () => { 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' })); @@ -237,6 +285,56 @@ describe('resumeBankLink', () => { 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({ @@ -261,6 +359,49 @@ describe('onBankLinkEvent', () => { 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: {} }) + ); + expect(listener).not.toHaveBeenCalled(); + + emit({ name: 'opened', payload: {} }); + 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: {} })).not.toThrow(); + expect(healthy).toHaveBeenCalledTimes(1); + expect(consoleError).toHaveBeenCalled(); + + consoleError.mockRestore(); + stopFailing(); + stopHealthy(); + }); + it.each([ [ 'opened', @@ -334,7 +475,7 @@ describe('onBankLinkEvent', () => { name: 'a_name_from_a_newer_server', payload: { link_id: 'link-1' }, }); - DeviceEventEmitter.emit('onBankLinkEvent', 'not json'); + emitRaw('not json'); stop(); expect(listener).not.toHaveBeenCalled(); diff --git a/src/bankLink.ts b/src/bankLink.ts index 97a0ce0..4a2477c 100644 --- a/src/bankLink.ts +++ b/src/bankLink.ts @@ -1,4 +1,3 @@ -import { NativeEventEmitter } from 'react-native'; import type { EventSubscription } from 'react-native'; import NativeSdkReactNative from './NativeSdkReactNative'; import { toNativeConfig } from './nativeConfig'; @@ -15,12 +14,6 @@ import type { BankLinkSuccess, } from './types'; -/** - * The event name the native modules emit on: the name of the TurboModule - * `EventEmitter` property, shared by every platform. - */ -const EVENT_NAME = 'onBankLinkEvent'; - const EVENT_NAMES: readonly BankLinkEventName[] = [ 'opened', 'consent_shown', @@ -34,6 +27,25 @@ const EVENT_NAMES: readonly BankLinkEventName[] = [ 'error', ]; +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', @@ -55,18 +67,7 @@ interface BankLinkResultJS { // ─── Events ────────────────────────────────────────────────────────────────── -/** - * What `NativeEventEmitter` needs of the module: the listener counter the - * Codegen base class provides on both platforms, which the spec it generates - * does not declare. - */ -interface NativeEventEmitterModule { - addListener: (eventType: string) => void; - removeListeners: (count: number) => void; -} - const listeners = new Set(); -let emitter: NativeEventEmitter | null = null; let nativeSubscription: EventSubscription | null = null; function parseEvent(raw: string): BankLinkEvent | null { @@ -106,7 +107,13 @@ function dispatch(raw: string): void { // 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)) { - listener(event); + 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); + } } } @@ -114,12 +121,12 @@ function subscribeNative(): void { if (nativeSubscription || listeners.size === 0) { return; } - if (!emitter) { - emitter = new NativeEventEmitter( - NativeSdkReactNative as unknown as NativeEventEmitterModule - ); - } - nativeSubscription = emitter.addListener(EVENT_NAME, (raw: unknown) => + // 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)) ); } @@ -163,6 +170,17 @@ export function onBankLinkEvent(listener: BankLinkEventListener): () => void { // ─── 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) { @@ -189,7 +207,7 @@ function mapResult(raw: BankLinkResultJS): BankLinkResult { : 'failed'; const exit: BankLinkExit = { type: 'exit', reason }; if (raw.step !== undefined) { - exit.step = raw.step as BankLinkStep | null; + exit.step = mapStep(raw.step); } if (raw.resumed != null) { exit.resumed = raw.resumed; @@ -211,10 +229,35 @@ function parseResult(raw: string): BankLinkResult { // ─── Presentation ──────────────────────────────────────────────────────────── /** - * The link being presented, so a second `presentBankLink` cannot replace the - * result of the first one. + * 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; +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. @@ -241,30 +284,16 @@ export function presentBankLink( token: string, options?: BankLinkOptions ): Promise { - if (activeBankLink) { - return Promise.reject( - new Error( - 'A Bank Link is already open. Await its result before presenting another one.' - ) - ); - } - - const result = (async () => { - const raw = await NativeSdkReactNative.presentBankLink( - token, - toNativeConfig(options?.config) - ); - return parseResult(raw); - })(); - - activeBankLink = result; - const release = () => { - if (activeBankLink === result) { - activeBankLink = null; + 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); } - }; - result.then(release, release); - return result; + ); } /** @@ -275,12 +304,22 @@ export function presentBankLink( * 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 async function resumeBankLink(): Promise { - const raw = await NativeSdkReactNative.resumeBankLink(); - const parsed = JSON.parse(raw) as BankLinkResultJS | null; - return parsed ? mapResult(parsed) : null; +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; + } + ); } /** From e1cdd660ee744c70dc4f4ed75a187e80e481bb87 Mon Sep 17 00:00:00 2001 From: Alejandro Rosas <46827020+arosasg@users.noreply.github.com> Date: Sun, 22 Nov 2026 11:09:45 +0000 Subject: [PATCH 3/6] DID-12138: React Native: Bank Link wrapper over the native SDKs (sdk-react-native) --- SdkReactNative.podspec | 13 ++++ android/build.gradle | 12 +++ .../java/com/sdkreactnative/BankLinkJson.kt | 10 +-- .../com/sdkreactnative/BankLinkSupport.kt | 51 +++++++++++++ .../sdkreactnative/SdkReactNativeModule.kt | 27 +++++-- .../com/sdkreactnative/BankLinkSupport.kt | 36 +++++++++ ios/DiditSdkBridge.swift | 39 ++++++++++ ios/SdkReactNative.mm | 11 +++ package.json | 3 +- src/__tests__/bank-link-native-gating.test.ts | 75 +++++++++++++++++++ 10 files changed, 261 insertions(+), 16 deletions(-) rename android/src/{main => bankLink}/java/com/sdkreactnative/BankLinkJson.kt (89%) create mode 100644 android/src/bankLink/java/com/sdkreactnative/BankLinkSupport.kt create mode 100644 android/src/released/java/com/sdkreactnative/BankLinkSupport.kt create mode 100644 src/__tests__/bank-link-native-gating.test.ts 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/main/java/com/sdkreactnative/BankLinkJson.kt b/android/src/bankLink/java/com/sdkreactnative/BankLinkJson.kt similarity index 89% rename from android/src/main/java/com/sdkreactnative/BankLinkJson.kt rename to android/src/bankLink/java/com/sdkreactnative/BankLinkJson.kt index 7a6f58c..4d04b82 100644 --- a/android/src/main/java/com/sdkreactnative/BankLinkJson.kt +++ b/android/src/bankLink/java/com/sdkreactnative/BankLinkJson.kt @@ -14,16 +14,12 @@ import org.json.JSONObject * a presentation travels as one result object. JavaScript maps both, so the * keys here are the ones `src/bankLink.ts` reads and nothing else. * - * Native Bank Link is not released yet: this file and the module's three Bank - * Link overrides are the only place that touches it, and they are reconciled - * with the native Android API of the Bank Link issue when the version that - * carries it is pinned. + * 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 { - /** The JSON `null` a resume answers when nothing is pending. */ - const val NONE = "null" - fun event(event: BankLinkEvent): String = try { JSONObject() .put("name", event.name) 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..fd9543c --- /dev/null +++ b/android/src/bankLink/java/com/sdkreactnative/BankLinkSupport.kt @@ -0,0 +1,51 @@ +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 + ) { + DiditSdk.presentBankLink( + activity = activity, + token = token, + configuration = configuration, + onEvent = { event -> onEvent(BankLinkJson.event(event)) }, + onResult = { result -> onResult(BankLinkJson.result(result)) } + ) + } + + 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 2aaf0ce..949f442 100644 --- a/android/src/main/java/com/sdkreactnative/SdkReactNativeModule.kt +++ b/android/src/main/java/com/sdkreactnative/SdkReactNativeModule.kt @@ -407,14 +407,18 @@ class SdkReactNativeModule(reactContext: ReactApplicationContext) : 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 { - DiditSdk.presentBankLink( + BankLinkSupport.present( activity = activity, token = token, configuration = parseConfiguration(config), - onEvent = { event -> emitOnBankLinkEvent(BankLinkJson.event(event)) }, - onResult = { result -> promise.resolve(BankLinkJson.result(result)) } + onEvent = { eventJson -> emitOnBankLinkEvent(eventJson) }, + onResult = { resultJson -> promise.resolve(resultJson) } ) } catch (e: Exception) { logDebugError("presentBankLink: exception", e) @@ -424,6 +428,10 @@ class SdkReactNativeModule(reactContext: ReactApplicationContext) : } 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, @@ -437,13 +445,13 @@ class SdkReactNativeModule(reactContext: ReactApplicationContext) : return@launch } try { - val resumed = DiditSdk.resumeBankLink( + val resumed = BankLinkSupport.resume( activity = activity, - onEvent = { event -> emitOnBankLinkEvent(BankLinkJson.event(event)) }, - onResult = { result -> promise.resolve(BankLinkJson.result(result)) } + onEvent = { eventJson -> emitOnBankLinkEvent(eventJson) }, + onResult = { resultJson -> promise.resolve(resultJson) } ) if (!resumed) { - promise.resolve(BankLinkJson.NONE) + promise.resolve(BankLinkSupport.NONE) } } catch (e: Exception) { logDebugError("resumeBankLink: exception", e) @@ -496,12 +504,15 @@ class SdkReactNativeModule(reactContext: ReactApplicationContext) : } 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 { - DiditSdk.handleBankLinkReturn(uri) + BankLinkSupport.handle(uri) } } 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/ios/DiditSdkBridge.swift b/ios/DiditSdkBridge.swift index 6642946..71a2f5c 100644 --- a/ios/DiditSdkBridge.swift +++ b/ios/DiditSdkBridge.swift @@ -415,6 +415,19 @@ 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 + /// Opens a Bank Link with the link's `client_token`. /// /// Every screen, state and string is native; the bridge carries the events @@ -546,6 +559,32 @@ public class DiditSdkBridge: NSObject, @unchecked Sendable { } } +#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?, + onEvent: @escaping @Sendable (String) -> Void, + completion: @escaping @Sendable (String) -> Void + ) { + completion("null") + } + + public func resumeBankLink( + onEvent: @escaping @Sendable (String) -> Void, + completion: @escaping @Sendable (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 0ae2308..b38a339 100644 --- a/ios/SdkReactNative.mm +++ b/ios/SdkReactNative.mm @@ -194,6 +194,10 @@ - (void)presentBankLink:(NSString *)token 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; @@ -210,6 +214,10 @@ - (void)presentBankLink:(NSString *)token - (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; [_bridge resumeBankLinkWithOnEvent:^(NSString *eventJson) { @@ -222,6 +230,9 @@ - (void)resumeBankLink:(RCTPromiseResolveBlock)resolve - (void)handleBankLinkReturn:(NSString *)url { + if (!_bridge.bankLinkAvailable) { + return; + } [_bridge handleBankLinkReturnWithUrl:url]; } 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/__tests__/bank-link-native-gating.test.ts b/src/__tests__/bank-link-native-gating.test.ts new file mode 100644 index 0000000..24de34c --- /dev/null +++ b/src/__tests__/bank-link-native-gating.test.ts @@ -0,0 +1,75 @@ +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('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'); + }); +}); From deab75d1d05b3cd9edd8a764886f2ac197e54b82 Mon Sep 17 00:00:00 2001 From: Alejandro Rosas <46827020+arosasg@users.noreply.github.com> Date: Sun, 22 Nov 2026 11:20:52 +0000 Subject: [PATCH 4/6] DID-12138: React Native: Bank Link wrapper over the native SDKs (sdk-react-native) --- example/src/App.tsx | 7 +++++- ios/SdkReactNative.mm | 4 ++-- src/__tests__/bank-link-native-gating.test.ts | 23 +++++++++++++++++++ src/types.ts | 4 ++-- 4 files changed, 33 insertions(+), 5 deletions(-) diff --git a/example/src/App.tsx b/example/src/App.tsx index 7e99790..4859fc2 100644 --- a/example/src/App.tsx +++ b/example/src/App.tsx @@ -372,8 +372,13 @@ export default function App() { )} Resume after relaunch diff --git a/ios/SdkReactNative.mm b/ios/SdkReactNative.mm index b38a339..804e512 100644 --- a/ios/SdkReactNative.mm +++ b/ios/SdkReactNative.mm @@ -206,7 +206,7 @@ - (void)presentBankLink:(NSString *)token onEvent:^(NSString *eventJson) { [weakSelf emitOnBankLinkEvent:eventJson]; } - completion:^(NSString *resultJson) { + completion:^(NSString *resultJson) { resolve(resultJson); }]; } @@ -220,7 +220,7 @@ - (void)resumeBankLink:(RCTPromiseResolveBlock)resolve } __weak SdkReactNative *weakSelf = self; - [_bridge resumeBankLinkWithOnEvent:^(NSString *eventJson) { + [_bridge resumeBankLinkOnEvent:^(NSString *eventJson) { [weakSelf emitOnBankLinkEvent:eventJson]; } completion:^(NSString *resultJson) { diff --git a/src/__tests__/bank-link-native-gating.test.ts b/src/__tests__/bank-link-native-gating.test.ts index 24de34c..00618f8 100644 --- a/src/__tests__/bank-link-native-gating.test.ts +++ b/src/__tests__/bank-link-native-gating.test.ts @@ -72,4 +72,27 @@ describe('native Bank Link compile gate', () => { ); 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`, but not before one that starts with a + // preposition like `onEvent`, so `resumeBankLink(onEvent:completion:)` + // is `resumeBankLinkOnEvent:completion:`. The `With` 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 onEvent:')).toBe(2); + expect(swiftCount('public func handleBankLinkReturn(url: String)')).toBe(2); + + expect(objc).toContain('[_bridge presentBankLinkWithToken:'); + expect(objc).toContain('[_bridge resumeBankLinkOnEvent:'); + expect(objc).not.toContain('resumeBankLinkWithOnEvent'); + expect(objc).toContain('[_bridge handleBankLinkReturnWithUrl:'); + }); }); diff --git a/src/types.ts b/src/types.ts index c69a692..72adde5 100644 --- a/src/types.ts +++ b/src/types.ts @@ -453,8 +453,8 @@ export type BankLinkEventName = export interface BankLinkEventPayload { /** The link id; carried by every event. */ link_id?: string; - /** `opened`: `connect` or `renew`. */ - mode?: 'connect' | 'renew'; + /** `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`. */ From ee7d7c598cfe29ead659fd6e6fbd804953034b48 Mon Sep 17 00:00:00 2001 From: Alejandro Rosas <46827020+arosasg@users.noreply.github.com> Date: Sun, 22 Nov 2026 22:51:53 +0000 Subject: [PATCH 5/6] DID-12138: React Native: Bank Link wrapper over the native SDKs (sdk-react-native) --- README.md | 18 ++-- .../java/com/sdkreactnative/BankLinkJson.kt | 20 ++--- .../com/sdkreactnative/BankLinkSupport.kt | 3 +- .../SdkReactNativeExample/AppDelegate.swift | 14 ++++ example/src/App.tsx | 31 +++++++ src/__tests__/bank-link-formats.test.ts | 55 ++++++------- src/__tests__/bank-link.test.ts | 82 ++++++++++++++++--- src/bankLink.ts | 63 +++++++++----- src/types.ts | 4 +- 9 files changed, 207 insertions(+), 83 deletions(-) diff --git a/README.md b/README.md index d86fb8d..b5454a7 100644 --- a/README.md +++ b/README.md @@ -110,13 +110,15 @@ const stop = onBankLinkEvent(({ name, payload }) => { console.log(name, payload.link_id); }); -const result: BankLinkResult = await presentBankLink(clientToken); -stop(); - -if (result.type === 'success') { - console.log('Linked', result.connectionId); -} else { - console.log('Ended', result.reason, result.step); +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(); } ``` @@ -919,7 +921,7 @@ Returns: `() => void` - the unsubscribe function. | `exit` | `link_id`, `reason`, `step` | | `error` | `link_id`, `code` | -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. +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)` diff --git a/android/src/bankLink/java/com/sdkreactnative/BankLinkJson.kt b/android/src/bankLink/java/com/sdkreactnative/BankLinkJson.kt index 4d04b82..6fa4c43 100644 --- a/android/src/bankLink/java/com/sdkreactnative/BankLinkJson.kt +++ b/android/src/bankLink/java/com/sdkreactnative/BankLinkJson.kt @@ -1,7 +1,7 @@ package com.sdkreactnative -import me.didit.sdk.BankLinkEvent -import me.didit.sdk.BankLinkResult +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 @@ -22,15 +22,15 @@ internal object BankLinkJson { fun event(event: BankLinkEvent): String = try { JSONObject() - .put("name", event.name) + .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) - .put("payload", JSONObject()) + .put("name", event.name.wire) + .put("payload", JSONObject().put("link_id", JSONObject.NULL)) .toString() } @@ -67,13 +67,13 @@ internal object BankLinkJson { fun result(result: BankLinkResult): String = when (result) { is BankLinkResult.Success -> JSONObject() .put("type", "success") - .put("linkId", result.linkId) - .put("connectionId", result.connectionId ?: JSONObject.NULL) - .put("checkId", result.checkId ?: JSONObject.NULL) - .put("resumed", result.resumed) + .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.reason, result.step, result.resumed) + 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() diff --git a/android/src/bankLink/java/com/sdkreactnative/BankLinkSupport.kt b/android/src/bankLink/java/com/sdkreactnative/BankLinkSupport.kt index fd9543c..764c3ca 100644 --- a/android/src/bankLink/java/com/sdkreactnative/BankLinkSupport.kt +++ b/android/src/bankLink/java/com/sdkreactnative/BankLinkSupport.kt @@ -26,13 +26,14 @@ internal object BankLinkSupport { onEvent: (String) -> Unit, onResult: (String) -> Unit ) { - DiditSdk.presentBankLink( + 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( 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 4859fc2..6a64533 100644 --- a/example/src/App.tsx +++ b/example/src/App.tsx @@ -1,5 +1,6 @@ import { useState, useCallback, useEffect } from 'react'; import { + Linking, Text, View, StyleSheet, @@ -17,6 +18,7 @@ import { submitTransaction, presentBankLink, resumeBankLink, + handleBankLinkReturn, onBankLinkEvent, DiditTransactionError, VerificationStatus, @@ -28,6 +30,33 @@ import { 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(''); @@ -58,6 +87,8 @@ export default function App() { [] ); + useEffect(() => listenForBankReturns(setBankLinkResult), []); + const handlePresentBankLink = useCallback(async () => { if (!bankLinkToken.trim()) { Alert.alert('Error', 'Please enter a Bank Link client token.'); diff --git a/src/__tests__/bank-link-formats.test.ts b/src/__tests__/bank-link-formats.test.ts index 2c8f6c2..d77627c 100644 --- a/src/__tests__/bank-link-formats.test.ts +++ b/src/__tests__/bank-link-formats.test.ts @@ -7,11 +7,8 @@ * 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. * - * This test walks every example through the three places the wrapper touches a - * value - the token of a presentation, a parameter of a return address (query - * and fragment), and an event payload - and asserts each one is accepted and - * forwarded unchanged. A validator here may be looser than the file, never - * stricter: a rejection or a truncated value fails. + * Each example passes unchanged through presentation and return URLs. Only + * the fields defined for an event may reach an event listener. */ jest.mock('../NativeSdkReactNative', () => ({ @@ -35,7 +32,6 @@ import { onBankLinkEvent, handleBankLinkReturn, } from '../index'; -import type { BankLinkEventPayload } from '../index'; interface Format { name: string; @@ -83,11 +79,6 @@ function returnAddress(where: 'query' | 'fragment', code: string): string { : `https://app.example.com/bank/return#${params}`; } -/** The payload key a value of this format travels in, when it has one. */ -function payloadKey(format: Format): keyof BankLinkEventPayload { - return (format.fields?.[0] ?? 'link_id') as keyof BankLinkEventPayload; -} - /** * 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. @@ -193,24 +184,26 @@ describe('every example of the contract file', () => { } ); - it.each(formats.map((format) => [format.name, format] as const))( - 'arrives in an event payload as %s, unchanged', - (_name, format) => { - const listener = jest.fn(); - const stop = onBankLinkEvent(listener); - - nativeHandler?.( - JSON.stringify({ - name: 'opened', - payload: { link_id: 'link-1', [payloadKey(format)]: format.example }, - }) - ); - stop(); - - expect(listener).toHaveBeenCalledTimes(1); - expect(listener.mock.calls[0][0].payload[payloadKey(format)]).toBe( - 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.test.ts b/src/__tests__/bank-link.test.ts index 19da136..feb3ffa 100644 --- a/src/__tests__/bank-link.test.ts +++ b/src/__tests__/bank-link.test.ts @@ -17,9 +17,23 @@ jest.mock('../NativeSdkReactNative', () => ({ }, })); +// 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 } from 'react-native'; +import { DeviceEventEmitter, Linking } from 'react-native'; import NativeSdkReactNative from '../NativeSdkReactNative'; import { presentBankLink, @@ -75,6 +89,7 @@ const CONTRACT_PAYLOAD_KEYS = [ 'reason', 'step', 'code', + 'resumed', ]; /** @@ -372,11 +387,11 @@ describe('onBankLinkEvent', () => { // TurboModule `EventEmitter` never emits there. DeviceEventEmitter.emit( 'onBankLinkEvent', - JSON.stringify({ name: 'opened', payload: {} }) + JSON.stringify({ name: 'opened', payload: { link_id: null } }) ); expect(listener).not.toHaveBeenCalled(); - emit({ name: 'opened', payload: {} }); + emit({ name: 'opened', payload: { link_id: null } }); expect(listener).toHaveBeenCalledTimes(1); stop(); @@ -393,7 +408,9 @@ describe('onBankLinkEvent', () => { .spyOn(console, 'error') .mockImplementation(() => {}); - expect(() => emit({ name: 'opened', payload: {} })).not.toThrow(); + expect(() => + emit({ name: 'opened', payload: { link_id: null } }) + ).not.toThrow(); expect(healthy).toHaveBeenCalledTimes(1); expect(consoleError).toHaveBeenCalled(); @@ -419,17 +436,20 @@ describe('onBankLinkEvent', () => { ], [ 'institution_selected', - { institution_id: 'institution-1', country: 'ES' }, + { link_id: 'link-1', institution_id: 'institution-1', country: 'ES' }, ], - ['bank_redirect', { via: 'popup' }], - ['bank_returned', { result: 'ok' }], - ['accounts_selected', { count: 2 }], + ['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', { reason: 'closed', step: 'bank_hop' }], - ['error', { code: 'network' }], + [ + '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); @@ -463,7 +483,7 @@ describe('onBankLinkEvent', () => { stop(); expect(() => stop()).not.toThrow(); - emit({ name: 'opened', payload: {} }); + emit({ name: 'opened', payload: { link_id: null } }); expect(listener).not.toHaveBeenCalled(); }); @@ -475,6 +495,8 @@ describe('onBankLinkEvent', () => { 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(); @@ -507,6 +529,44 @@ describe('handleBankLinkReturn', () => { 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'; diff --git a/src/bankLink.ts b/src/bankLink.ts index 4a2477c..f4ac5e1 100644 --- a/src/bankLink.ts +++ b/src/bankLink.ts @@ -14,18 +14,21 @@ import type { BankLinkSuccess, } from './types'; -const EVENT_NAMES: readonly BankLinkEventName[] = [ - 'opened', - 'consent_shown', - 'consent_accepted', - 'institution_selected', - 'bank_redirect', - 'bank_returned', - 'accounts_selected', - 'success', - 'exit', - 'error', -]; +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', @@ -85,18 +88,36 @@ function parseEvent(raw: string): BankLinkEvent | null { // requires: new events are additive. if ( typeof name !== 'string' || - !EVENT_NAMES.includes(name as BankLinkEventName) + !Object.prototype.hasOwnProperty.call(EVENT_FIELDS, name) ) { return null; } - const payload = parsed.payload; - return { - name: name as BankLinkEventName, - payload: - payload && typeof payload === 'object' - ? (payload as BankLinkEventPayload) - : {}, - }; + 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 { diff --git a/src/types.ts b/src/types.ts index 72adde5..bad51ab 100644 --- a/src/types.ts +++ b/src/types.ts @@ -452,7 +452,7 @@ export type BankLinkEventName = */ export interface BankLinkEventPayload { /** The link id; carried by every event. */ - link_id?: string; + 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. */ @@ -479,6 +479,8 @@ export interface BankLinkEventPayload { 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; } From b1a89fbaf0925a72d253d9ca5d7f039e1c18ad7f Mon Sep 17 00:00:00 2001 From: Alejandro Rosas <46827020+arosasg@users.noreply.github.com> Date: Sun, 22 Nov 2026 23:53:58 +0000 Subject: [PATCH 6/6] DID-12138: React Native: Bank Link wrapper over the native SDKs (sdk-react-native) --- src/__tests__/bank-link-native-gating.test.ts | 34 +++++++++++++++++++ 1 file changed, 34 insertions(+) diff --git a/src/__tests__/bank-link-native-gating.test.ts b/src/__tests__/bank-link-native-gating.test.ts index 00618f8..a218385 100644 --- a/src/__tests__/bank-link-native-gating.test.ts +++ b/src/__tests__/bank-link-native-gating.test.ts @@ -47,6 +47,40 @@ describe('native Bank Link compile gate', () => { ).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');