pa-sdk-react-native 0.0.0-stage → 3.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (45) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +268 -2
  3. package/lib/api.d.ts +88 -0
  4. package/lib/api.js +163 -0
  5. package/lib/confirm.d.ts +66 -0
  6. package/lib/confirm.js +359 -0
  7. package/lib/errors.d.ts +38 -0
  8. package/lib/errors.generated.d.ts +13 -0
  9. package/lib/errors.generated.js +63 -0
  10. package/lib/errors.js +80 -0
  11. package/lib/index.d.ts +43 -0
  12. package/lib/index.js +94 -0
  13. package/lib/init.d.ts +47 -0
  14. package/lib/init.js +96 -0
  15. package/lib/locales.d.ts +36 -0
  16. package/lib/locales.generated.d.ts +22 -0
  17. package/lib/locales.generated.js +134 -0
  18. package/lib/locales.js +100 -0
  19. package/lib/poll.d.ts +61 -0
  20. package/lib/poll.js +172 -0
  21. package/lib/threeDs.d.ts +59 -0
  22. package/lib/threeDs.js +64 -0
  23. package/lib/threeDsHost.d.ts +17 -0
  24. package/lib/threeDsHost.js +159 -0
  25. package/lib/tokenize.d.ts +22 -0
  26. package/lib/tokenize.js +50 -0
  27. package/lib/types.d.ts +128 -0
  28. package/lib/types.js +17 -0
  29. package/lib/validator.d.ts +71 -0
  30. package/lib/validator.js +191 -0
  31. package/locales/en-US.json +30 -0
  32. package/locales/ms-MY.json +30 -0
  33. package/locales/zh-CN.json +30 -0
  34. package/locales/zh-TW.json +30 -0
  35. package/native/android/build.gradle +49 -0
  36. package/native/android/src/main/AndroidManifest.xml +41 -0
  37. package/native/android/src/main/java/com/pasdk/reactnative/PaSdk3dsActivity.kt +250 -0
  38. package/native/android/src/main/java/com/pasdk/reactnative/PaSdk3dsModule.kt +110 -0
  39. package/native/android/src/main/java/com/pasdk/reactnative/PaSdkReactNativePackage.kt +27 -0
  40. package/native/ios/PaSdk3ds.swift +311 -0
  41. package/native/ios/PaSdk3dsModule.m +47 -0
  42. package/pa-sdk-react-native.podspec +23 -0
  43. package/package.json +46 -3
  44. package/scripts/generate-errors.js +86 -0
  45. package/scripts/generate-locales.js +95 -0
@@ -0,0 +1,250 @@
1
+ package com.pasdk.reactnative
2
+
3
+ import android.annotation.SuppressLint
4
+ import android.content.Intent
5
+ import android.graphics.Color
6
+ import android.net.Uri
7
+ import android.os.Bundle
8
+ import android.view.Gravity
9
+ import android.view.ViewGroup
10
+ import android.view.View
11
+ import android.webkit.WebResourceRequest
12
+ import android.webkit.WebView
13
+ import android.webkit.WebViewClient
14
+ import android.widget.Button
15
+ import android.widget.FrameLayout
16
+ import android.widget.LinearLayout
17
+ import android.widget.TextView
18
+ import java.io.Serializable
19
+
20
+ /**
21
+ * Full-screen WebView presenting the 3DS challenge (RN-18 / RN-19).
22
+ *
23
+ * Loads a tiny HTML document that auto-submits a POST form (Cardinal JWT or
24
+ * ACS creq) to the challenge URL — the same handshake as the iOS side.
25
+ *
26
+ * Return consumption (RN-20): the manifest routes flow:// and
27
+ * https://app.flowtheroom.com here. onCreate/onNewIntent hand the URI to
28
+ * PaSdk3dsModule.consumeReturnUri() while a challenge is pending, so the
29
+ * app's own link handler never sees the 3DS return. When no challenge is
30
+ * pending, the SDK does not swallow the URI — it re-dispatches it to the
31
+ * app's launch intent so Flow's normal deep-link handling proceeds.
32
+ */
33
+ class PaSdk3dsActivity : android.app.Activity() {
34
+
35
+ companion object {
36
+ const val EXTRA_PARAMS = "pa_sdk_3ds_params"
37
+
38
+ private var activityInstance: PaSdk3dsActivity? = null
39
+
40
+ fun dismiss() {
41
+ activityInstance?.finish()
42
+ }
43
+ }
44
+
45
+ private var webView: WebView? = null
46
+ private var returnUrlScheme: String? = null
47
+ private var returnUrlUniversalHost: String? = null
48
+ private var finishedBySdk = false
49
+
50
+ override fun onCreate(savedInstanceState: Bundle?) {
51
+ super.onCreate(savedInstanceState)
52
+ activityInstance = this
53
+
54
+ val params = @Suppress("DEPRECATION") (intent.getSerializableExtra(EXTRA_PARAMS) as? HashMap<*, *>)
55
+ val strings = (params?.get("strings") as? HashMap<*, *>)
56
+ fun str(key: String, fallback: String): String =
57
+ (strings?.get(key) as? String)?.takeIf { it.isNotEmpty() } ?: fallback
58
+
59
+ returnUrlScheme = params?.get("returnUrlScheme") as? String
60
+ returnUrlUniversalHost = params?.get("returnUrlUniversalHost") as? String
61
+
62
+ val root = FrameLayout(this)
63
+ root.setBackgroundColor(Color.WHITE)
64
+
65
+ // -- Chrome bar: title + cancel ------------------------------------
66
+ val bar = LinearLayout(this)
67
+ bar.orientation = LinearLayout.HORIZONTAL
68
+ bar.gravity = Gravity.CENTER_VERTICAL
69
+ bar.setPadding(dp(16), dp(12), dp(16), dp(12))
70
+ root.addView(
71
+ bar,
72
+ FrameLayout.LayoutParams(
73
+ ViewGroup.LayoutParams.MATCH_PARENT, dp(52)
74
+ )
75
+ )
76
+
77
+ val title = TextView(this).apply {
78
+ text = str("title", "Secure Authentication")
79
+ textSize = 16f
80
+ setTextColor(Color.parseColor("#111111"))
81
+ gravity = Gravity.CENTER_VERTICAL
82
+ }
83
+ bar.addView(
84
+ title,
85
+ LinearLayout.LayoutParams(0, ViewGroup.LayoutParams.WRAP_CONTENT, 1f)
86
+ )
87
+
88
+ val cancel = Button(this, null, android.R.attr.borderlessButtonStyle).apply {
89
+ text = str("cancel", "Cancel")
90
+ setTextColor(Color.parseColor("#0a84ff"))
91
+ setOnClickListener { finishCancelled() }
92
+ }
93
+ bar.addView(
94
+ cancel,
95
+ LinearLayout.LayoutParams(
96
+ ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT
97
+ )
98
+ )
99
+
100
+ // -- WebView ---------------------------------------------------------
101
+ val web = WebView(this)
102
+ web.settings.javaScriptEnabled = true
103
+ web.settings.domStorageEnabled = true
104
+ web.webViewClient = ChallengeWebViewClient()
105
+ root.addView(
106
+ web,
107
+ FrameLayout.LayoutParams(
108
+ ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT
109
+ ).apply { topMargin = dp(52) }
110
+ )
111
+ webView = web
112
+
113
+ setContentView(root)
114
+
115
+ val url = params?.get("url") as? String
116
+ @Suppress("UNCHECKED_CAST")
117
+ val fields = (params?.get("fields") as? HashMap<String, String>) ?: hashMapOf()
118
+ if (url.isNullOrEmpty()) {
119
+ finishCancelled()
120
+ return
121
+ }
122
+ web.loadDataWithBaseURL(null, buildPostHtml(url, fields, str("redirecting", "Redirecting...")), "text/html", "utf-8", null)
123
+
124
+ // RN-20: this activity may itself be the target of the 3DS return
125
+ // (cold start straight into the return URI).
126
+ handlePossibleReturn(intent)
127
+ }
128
+
129
+ override fun onNewIntent(intent: Intent) {
130
+ super.onNewIntent(intent)
131
+ handlePossibleReturn(intent)
132
+ }
133
+
134
+ private fun handlePossibleReturn(intent: Intent?) {
135
+ val uri = intent?.data ?: return
136
+ if (!isReturnUri(uri)) {
137
+ return
138
+ }
139
+ // Consume silently (RN-20): resolve the pending present() promise and
140
+ // finish. The gateway posts the challenge result server-side; the JS
141
+ // poller (/intent-status) observes the terminal state.
142
+ if (PaSdk3dsModule.consumeReturnUri(uri)) {
143
+ finishedBySdk = true
144
+ finish()
145
+ return
146
+ }
147
+ // No challenge pending: this return is not the SDK's. Hand it on to
148
+ // the app's launch activity so Flow's own deep-link handling proceeds.
149
+ reDispatchToApp(uri)
150
+ }
151
+
152
+ private fun reDispatchToApp(uri: Uri) {
153
+ try {
154
+ val launch = packageManager.getLaunchIntentForPackage(packageName)
155
+ if (launch != null) {
156
+ launch.data = uri
157
+ launch.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
158
+ startActivity(launch)
159
+ }
160
+ } catch (ignored: Exception) {
161
+ // Best effort only.
162
+ }
163
+ finish()
164
+ }
165
+
166
+ private fun isReturnUri(uri: Uri): Boolean {
167
+ val scheme = uri.scheme?.lowercase() ?: return false
168
+ returnUrlScheme?.let { configured ->
169
+ val configuredScheme = configured.substringBefore(":").lowercase()
170
+ if (configuredScheme.isNotEmpty() && scheme == configuredScheme) {
171
+ return true
172
+ }
173
+ }
174
+ returnUrlUniversalHost?.let { configured ->
175
+ val configuredHost = configured.substringAfter("://").trimEnd('/').lowercase()
176
+ if (scheme == "https" && uri.host?.lowercase() == configuredHost) {
177
+ return true
178
+ }
179
+ }
180
+ // Flow defaults, in case the JS layer did not pass them.
181
+ if (scheme == "flow") {
182
+ return true
183
+ }
184
+ if (scheme == "https" && uri.host?.lowercase() == "app.flowtheroom.com") {
185
+ return true
186
+ }
187
+ return false
188
+ }
189
+
190
+ private fun finishCancelled() {
191
+ finishedBySdk = true
192
+ PaSdk3dsModule.cancelPending()
193
+ finish()
194
+ }
195
+
196
+ @Deprecated("Deprecated in Java")
197
+ override fun onBackPressed() {
198
+ // The challenge is not navigable; back means cancel (WEB-49 analog).
199
+ finishCancelled()
200
+ }
201
+
202
+ override fun onDestroy() {
203
+ if (!finishedBySdk) {
204
+ // Dismissed by the system (swipe away, memory pressure): resolve
205
+ // as dismissed so the JS layer falls back to polling.
206
+ PaSdk3dsModule.resolveDismissed()
207
+ }
208
+ activityInstance = null
209
+ webView?.destroy()
210
+ webView = null
211
+ super.onDestroy()
212
+ }
213
+
214
+ private inner class ChallengeWebViewClient : WebViewClient() {
215
+ override fun shouldOverrideUrlLoading(view: WebView?, request: WebResourceRequest?): Boolean {
216
+ val uri = request?.url ?: return false
217
+ if (isReturnUri(uri)) {
218
+ // Consume the 3DS return inside the SDK (RN-20) instead of
219
+ // letting the WebView attempt a custom-scheme navigation.
220
+ if (PaSdk3dsModule.consumeReturnUri(uri)) {
221
+ finishedBySdk = true
222
+ finish()
223
+ }
224
+ return true
225
+ }
226
+ return false
227
+ }
228
+ }
229
+
230
+ private fun dp(value: Int): Int = (value * resources.displayMetrics.density).toInt()
231
+
232
+ private fun buildPostHtml(url: String, fields: Map<String, String>, redirecting: String): String {
233
+ val inputs = fields.entries.joinToString("") { (name, value) ->
234
+ "<input type=\"hidden\" name=\"${escapeHtml(name)}\" value=\"${escapeHtml(value)}\">"
235
+ }
236
+ return """
237
+ <!DOCTYPE html><html><head><meta charset="utf-8">
238
+ <meta name="viewport" content="width=device-width, initial-scale=1">
239
+ <style>body{font-family:sans-serif;color:#444;}</style>
240
+ </head><body>
241
+ <p style="text-align:center;margin-top:40%">${escapeHtml(redirecting)}</p>
242
+ <form id="f" method="POST" action="${escapeHtml(url)}">$inputs</form>
243
+ <script>document.getElementById("f").submit();</script>
244
+ </body></html>
245
+ """.trimIndent()
246
+ }
247
+
248
+ private fun escapeHtml(value: String): String =
249
+ value.replace("&", "&amp;").replace("<", "&lt;").replace(">", "&gt;").replace("\"", "&quot;")
250
+ }
@@ -0,0 +1,110 @@
1
+ package com.pasdk.reactnative
2
+
3
+ import android.content.Intent
4
+ import android.net.Uri
5
+ import com.facebook.react.bridge.Promise
6
+ import com.facebook.react.bridge.ReactApplicationContext
7
+ import com.facebook.react.bridge.ReactContextBaseJavaModule
8
+ import com.facebook.react.bridge.ReactMethod
9
+ import com.facebook.react.bridge.ReadableMap
10
+ import com.facebook.react.bridge.WritableNativeMap
11
+
12
+ /**
13
+ * PaSdk3ds — SDK-presented 3DS challenge for Android (RN-18 / RN-19).
14
+ *
15
+ * present({url, fields, strings, returnUrlScheme, returnUrlUniversalHost})
16
+ * launches PaSdk3dsActivity full-screen; the promise resolves when the
17
+ * challenge is dismissed:
18
+ * { cancelled: Boolean, returnUrlConsumed: Boolean }
19
+ *
20
+ * close() dismisses the challenge after the JS poller observed a terminal
21
+ * state server-side.
22
+ */
23
+ class PaSdk3dsModule(private val reactContext: ReactApplicationContext) :
24
+ ReactContextBaseJavaModule(reactContext) {
25
+
26
+ companion object {
27
+ const val NAME = "PaSdk3ds"
28
+
29
+ @Volatile
30
+ var pendingPromise: Promise? = null
31
+
32
+ /** Consume a 3DS return (flow:// / https://app.flowtheroom.com) that
33
+ * landed on PaSdk3dsActivity (RN-20). Returns true when a challenge
34
+ * was pending and the return was consumed by the SDK. */
35
+ fun consumeReturnUri(uri: Uri?): Boolean {
36
+ val promise = pendingPromise ?: return false
37
+ pendingPromise = null
38
+ val result = WritableNativeMap().apply {
39
+ putBoolean("cancelled", false)
40
+ putBoolean("returnUrlConsumed", true)
41
+ }
42
+ promise.resolve(result)
43
+ return true
44
+ }
45
+
46
+ fun cancelPending(): Boolean {
47
+ val promise = pendingPromise ?: return false
48
+ pendingPromise = null
49
+ val result = WritableNativeMap().apply {
50
+ putBoolean("cancelled", true)
51
+ putBoolean("returnUrlConsumed", false)
52
+ }
53
+ promise.resolve(result)
54
+ return true
55
+ }
56
+
57
+ fun resolveDismissed() {
58
+ val promise = pendingPromise ?: return
59
+ pendingPromise = null
60
+ val result = WritableNativeMap().apply {
61
+ putBoolean("cancelled", false)
62
+ putBoolean("returnUrlConsumed", false)
63
+ }
64
+ promise.resolve(result)
65
+ }
66
+ }
67
+
68
+ override fun getName(): String = NAME
69
+
70
+ @ReactMethod
71
+ fun present(params: ReadableMap, promise: Promise) {
72
+ val activity = currentActivity
73
+ if (activity == null) {
74
+ promise.reject("internal_error", "No current activity to present the 3DS challenge.")
75
+ return
76
+ }
77
+ val url = if (params.hasKey("url")) params.getString("url") else null
78
+ if (url.isNullOrEmpty()) {
79
+ promise.reject("request_invalid", "present(): 'url' is required")
80
+ return
81
+ }
82
+ // One challenge at a time — a stale promise resolves as dismissed.
83
+ if (pendingPromise != null) {
84
+ resolveDismissed()
85
+ }
86
+ pendingPromise = promise
87
+
88
+ val intent = Intent(activity, PaSdk3dsActivity::class.java)
89
+ intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
90
+ intent.putExtra(PaSdk3dsActivity.EXTRA_PARAMS, params.toHashMap() as java.io.Serializable)
91
+ activity.startActivity(intent)
92
+ }
93
+
94
+ @ReactMethod
95
+ fun close(promise: Promise) {
96
+ PaSdk3dsActivity.dismiss()
97
+ resolveDismissed()
98
+ promise.resolve(null)
99
+ }
100
+
101
+ @ReactMethod
102
+ fun addListener(@Suppress("UNUSED_PARAMETER") eventName: String) {
103
+ // Required by the RN event emitter contract; no JS events emitted today.
104
+ }
105
+
106
+ @ReactMethod
107
+ fun removeListeners(@Suppress("UNUSED_PARAMETER") count: Int) {
108
+ // See addListener.
109
+ }
110
+ }
@@ -0,0 +1,27 @@
1
+ package com.pasdk.reactnative
2
+
3
+ import android.view.View
4
+ import com.facebook.react.ReactPackage
5
+ import com.facebook.react.bridge.NativeModule
6
+ import com.facebook.react.bridge.ReactApplicationContext
7
+ import com.facebook.react.uimanager.ReactShadowNode
8
+ import com.facebook.react.uimanager.ViewManager
9
+
10
+ /**
11
+ * React Package registering the PA SDK native modules.
12
+ *
13
+ * Classic NativeModules bridge (works on the New Architecture through the
14
+ * interop layer — RN 0.79+, no codegen spec required).
15
+ */
16
+ class PaSdkReactNativePackage : ReactPackage {
17
+
18
+ override fun createNativeModules(reactContext: ReactApplicationContext): List<NativeModule> {
19
+ return listOf(PaSdk3dsModule(reactContext))
20
+ }
21
+
22
+ override fun createViewManagers(
23
+ reactContext: ReactApplicationContext
24
+ ): List<ViewManager<View, ReactShadowNode<*>>> {
25
+ return emptyList()
26
+ }
27
+ }
@@ -0,0 +1,311 @@
1
+ import Foundation
2
+ import UIKit
3
+ import WebKit
4
+
5
+ /**
6
+ * PaSdk3ds — SDK-presented 3DS challenge for iOS (RN-18 / RN-19 / WEB-49).
7
+ *
8
+ * Presents a full-screen WKWebView view controller that auto-submits a POST
9
+ * form carrying the Cardinal JWT (3DS2 StepUp) or the ACS creq (3DS1
10
+ * fallback) to the challenge URL. The gateway posts the challenge result
11
+ * server-side; the JS layer observes it via /intent-status polling and calls
12
+ * `close`, or the user taps Cancel, which resolves `cancelled` (A3).
13
+ *
14
+ * Bridged by PaSdk3dsModule.m via RCT_EXTERN_METHOD (classic NativeModules
15
+ * bridge; runs on the New Architecture through the interop layer).
16
+ *
17
+ * Note on types: the resolver/rejecter blocks use ObjC-representable
18
+ * signatures ((Any?) -> Void / (NSString?, NSString?, NSError?) -> Void) so
19
+ * this file does not need to import React; the block layouts match
20
+ * RCTPromiseResolveBlock / RCTPromiseRejectBlock.
21
+ */
22
+
23
+ @objc(PaSdk3dsSwift)
24
+ public final class PaSdk3ds: NSObject {
25
+
26
+ static var activeViewController: PaSdk3dsViewController?
27
+ static var pendingResolve: ((Any?) -> Void)?
28
+
29
+ /// present({ url, fields, strings, returnUrlScheme, returnUrlUniversalHost })
30
+ @objc(present:resolver:rejecter:)
31
+ public func present(_ params: NSDictionary,
32
+ resolver resolve: @escaping (Any?) -> Void,
33
+ rejecter reject: @escaping (NSString?, NSString?, NSError?) -> Void) {
34
+ DispatchQueue.main.async {
35
+ guard let url = params["url"] as? String, !url.isEmpty else {
36
+ reject("request_invalid", "present(): 'url' is required", nil)
37
+ return
38
+ }
39
+ var fields: [String: String] = [:]
40
+ if let raw = params["fields"] as? [String: String] {
41
+ fields = raw
42
+ } else if let raw = params["fields"] as? NSDictionary {
43
+ for case let (key as String, value as String) in raw {
44
+ fields[key] = value
45
+ }
46
+ }
47
+ let strings = PaSdk3dsStrings(from: params["strings"] as? NSDictionary)
48
+ let returnUrlScheme = params["returnUrlScheme"] as? String
49
+ let returnUrlUniversalHost = params["returnUrlUniversalHost"] as? String
50
+
51
+ // A challenge already on screen: close it before presenting a new one.
52
+ PaSdk3ds.dismissActive(animated: false)
53
+
54
+ let viewController = PaSdk3dsViewController(
55
+ url: url,
56
+ fields: fields,
57
+ strings: strings,
58
+ returnUrlScheme: returnUrlScheme,
59
+ returnUrlUniversalHost: returnUrlUniversalHost
60
+ ) { dismissal in
61
+ PaSdk3ds.activeViewController = nil
62
+ PaSdk3ds.pendingResolve = nil
63
+ resolve(["cancelled": dismissal.cancelled,
64
+ "returnUrlConsumed": dismissal.returnUrlConsumed])
65
+ }
66
+ PaSdk3ds.activeViewController = viewController
67
+
68
+ guard let root = PaSdk3ds.rootViewController() else {
69
+ reject("internal_error", "No root view controller to present the 3DS challenge.", nil)
70
+ return
71
+ }
72
+ viewController.modalPresentationStyle = .fullScreen
73
+ viewController.modalTransitionStyle = .coverVertical
74
+ root.present(viewController, animated: true, completion: nil)
75
+ }
76
+ }
77
+
78
+ /// close() — dismiss the challenge after the JS poller observed a terminal
79
+ /// state; the present() promise resolves with cancelled: false.
80
+ @objc(close:)
81
+ public func close(_ resolve: (Any?) -> Void) {
82
+ DispatchQueue.main.async {
83
+ PaSdk3ds.dismissActive(animated: true)
84
+ resolve(nil)
85
+ }
86
+ }
87
+
88
+ static func dismissActive(animated: Bool) {
89
+ if let active = activeViewController {
90
+ active.finishDismissal = nil // resolve via close, not as a cancel
91
+ active.dismiss(animated: animated, completion: nil)
92
+ activeViewController = nil
93
+ if let pending = pendingResolve {
94
+ pendingResolve = nil
95
+ pending(["cancelled": false, "returnUrlConsumed": false])
96
+ }
97
+ }
98
+ }
99
+
100
+ private static func rootViewController() -> UIViewController? {
101
+ var keyWindow: UIWindow?
102
+ if #available(iOS 13.0, *) {
103
+ for scene in UIApplication.shared.connectedScenes {
104
+ if let windowScene = scene as? UIWindowScene, windowScene.activationState == .foregroundActive {
105
+ keyWindow = windowScene.windows.first(where: { $0.isKeyWindow })
106
+ if keyWindow != nil { break }
107
+ }
108
+ }
109
+ if keyWindow == nil {
110
+ keyWindow = UIApplication.shared.windows.first(where: { $0.isKeyWindow })
111
+ }
112
+ } else {
113
+ keyWindow = UIApplication.shared.keyWindow
114
+ }
115
+ var root = keyWindow?.rootViewController
116
+ while let presented = root?.presentedViewController {
117
+ root = presented
118
+ }
119
+ return root
120
+ }
121
+ }
122
+
123
+ struct PaSdk3dsStrings {
124
+ let title: String
125
+ let cancel: String
126
+ let close: String
127
+ let processing: String
128
+ let redirecting: String
129
+
130
+ init(from dictionary: NSDictionary?) {
131
+ title = (dictionary?["title"] as? String) ?? "Secure Authentication"
132
+ cancel = (dictionary?["cancel"] as? String) ?? "Cancel"
133
+ close = (dictionary?["close"] as? String) ?? "Close"
134
+ processing = (dictionary?["processing"] as? String) ?? "Processing, please wait..."
135
+ redirecting = (dictionary?["redirecting"] as? String) ?? "Redirecting..."
136
+ }
137
+ }
138
+
139
+ public final class PaSdk3dsViewController: UIViewController, WKNavigationDelegate {
140
+
141
+ private let challengeURL: String
142
+ private let fields: [String: String]
143
+ private let strings: PaSdk3dsStrings
144
+ private let returnUrlScheme: String?
145
+ private let returnUrlUniversalHost: String?
146
+ /// Called exactly once when the challenge ends from this side (user cancel
147
+ /// or an observed 3DS return). Cleared when close() dismisses instead.
148
+ var finishDismissal: ((_ cancelled: Bool, _ returnUrlConsumed: Bool) -> Void)?
149
+ private var finished = false
150
+
151
+ private var webView: WKWebView?
152
+ private let activityIndicator = UIActivityIndicatorView(style: .medium)
153
+
154
+ init(url: String,
155
+ fields: [String: String],
156
+ strings: PaSdk3dsStrings,
157
+ returnUrlScheme: String?,
158
+ returnUrlUniversalHost: String?,
159
+ onDismiss: @escaping (_ cancelled: Bool, _ returnUrlConsumed: Bool) -> Void) {
160
+ self.challengeURL = url
161
+ self.fields = fields
162
+ self.strings = strings
163
+ self.returnUrlScheme = returnUrlScheme
164
+ self.returnUrlUniversalHost = returnUrlUniversalHost
165
+ self.finishDismissal = onDismiss
166
+ super.init(nibName: nil, bundle: nil)
167
+ }
168
+
169
+ required init?(coder: NSCoder) {
170
+ fatalError("init(coder:) is not supported")
171
+ }
172
+
173
+ public override func viewDidLoad() {
174
+ super.viewDidLoad()
175
+ view.backgroundColor = .systemBackground
176
+
177
+ let container = UIView()
178
+ container.translatesAutoresizingMaskIntoConstraints = false
179
+ view.addSubview(container)
180
+
181
+ let titleLabel = UILabel()
182
+ titleLabel.text = strings.title
183
+ titleLabel.font = .preferredFont(forTextStyle: .headline)
184
+ titleLabel.adjustsFontSizeToFitWidth = true
185
+ titleLabel.translatesAutoresizingMaskIntoConstraints = false
186
+ container.addSubview(titleLabel)
187
+
188
+ let cancelButton = UIButton(type: .system)
189
+ cancelButton.setTitle(strings.cancel, for: .normal)
190
+ cancelButton.addTarget(self, action: #selector(cancelTapped), for: .touchUpInside)
191
+ cancelButton.translatesAutoresizingMaskIntoConstraints = false
192
+ container.addSubview(cancelButton)
193
+
194
+ NSLayoutConstraint.activate([
195
+ container.topAnchor.constraint(equalTo: view.safeAreaLayoutGuide.topAnchor),
196
+ container.leadingAnchor.constraint(equalTo: view.leadingAnchor),
197
+ container.trailingAnchor.constraint(equalTo: view.trailingAnchor),
198
+ container.heightAnchor.constraint(equalToConstant: 52),
199
+ titleLabel.leadingAnchor.constraint(equalTo: container.leadingAnchor, constant: 16),
200
+ titleLabel.centerYAnchor.constraint(equalTo: container.centerYAnchor),
201
+ titleLabel.trailingAnchor.constraint(lessThanOrEqualTo: cancelButton.leadingAnchor, constant: -8),
202
+ cancelButton.trailingAnchor.constraint(equalTo: container.trailingAnchor, constant: -16),
203
+ cancelButton.centerYAnchor.constraint(equalTo: container.centerYAnchor),
204
+ ])
205
+
206
+ let configuration = WKWebViewConfiguration()
207
+ configuration.websiteDataStore = .nonPersistent()
208
+ let web = WKWebView(frame: .zero, configuration: configuration)
209
+ web.navigationDelegate = self
210
+ web.translatesAutoresizingMaskIntoConstraints = false
211
+ container.addSubview(web)
212
+ webView = web
213
+
214
+ NSLayoutConstraint.activate([
215
+ web.topAnchor.constraint(equalTo: container.bottomAnchor),
216
+ web.leadingAnchor.constraint(equalTo: view.leadingAnchor),
217
+ web.trailingAnchor.constraint(equalTo: view.trailingAnchor),
218
+ web.bottomAnchor.constraint(equalTo: view.bottomAnchor),
219
+ ])
220
+
221
+ activityIndicator.hidesWhenStopped = true
222
+ activityIndicator.translatesAutoresizingMaskIntoConstraints = false
223
+ view.addSubview(activityIndicator)
224
+ NSLayoutConstraint.activate([
225
+ activityIndicator.centerXAnchor.constraint(equalTo: view.centerXAnchor),
226
+ activityIndicator.centerYAnchor.constraint(equalTo: view.centerYAnchor),
227
+ ])
228
+
229
+ loadChallenge()
230
+ }
231
+
232
+ /// Load a tiny HTML document that auto-submits the POST form (JWT / creq)
233
+ /// to the challenge URL — the standard Cardinal StepUp handshake.
234
+ private func loadChallenge() {
235
+ let inputs = fields.map { name, value in
236
+ "<input type=\"hidden\" name=\"\(escapeHtml(name))\" value=\"\(escapeHtml(value))\">"
237
+ }.joined()
238
+ let html = """
239
+ <!DOCTYPE html><html><head><meta charset="utf-8">\
240
+ <meta name="viewport" content="width=device-width, initial-scale=1">\
241
+ <style>body{font-family:-apple-system,sans-serif;color:#444;}</style>\
242
+ </head><body>\
243
+ <p style="text-align:center;margin-top:40%">\(escapeHtml(strings.redirecting))</p>\
244
+ <form id="f" method="POST" action="\(escapeHtml(challengeURL))">\(inputs)</form>\
245
+ <script>document.getElementById("f").submit();</script>\
246
+ </body></html>
247
+ """
248
+ webView?.loadHTMLString(html, baseURL: nil)
249
+ }
250
+
251
+ @objc private func cancelTapped() {
252
+ finish(cancelled: true, returnUrlConsumed: false)
253
+ }
254
+
255
+ private func finish(cancelled: Bool, returnUrlConsumed: Bool) {
256
+ guard !finished else { return }
257
+ finished = true
258
+ let handler = finishDismissal
259
+ finishDismissal = nil
260
+ dismiss(animated: true) {
261
+ handler?(cancelled, returnUrlConsumed)
262
+ }
263
+ }
264
+
265
+ // WKNavigationDelegate — RN-20: when the ACS bounces through the 3DS
266
+ // return URLs (flow:// or the universal-link host), consume the navigation
267
+ // here so the app's own link handler never sees it, then let the JS
268
+ // poller observe the server-side result.
269
+ public func webView(_ webView: WKWebView,
270
+ decidePolicyFor navigationAction: WKNavigationAction,
271
+ decisionHandler: @escaping (WKNavigationActionPolicy) -> Void) {
272
+ let url = navigationAction.request.url
273
+ if let scheme = returnUrlScheme,
274
+ let url = url,
275
+ url.absoluteString.lowercased().hasPrefix(scheme.lowercased()) {
276
+ decisionHandler(.cancel)
277
+ finish(cancelled: false, returnUrlConsumed: true)
278
+ return
279
+ }
280
+ if let host = returnUrlUniversalHost,
281
+ let url = url,
282
+ let hostComponent = URLComponents(url: url, resolvingAgainstBaseURL: false)?.host,
283
+ hostComponent.lowercased().hasSuffix(host.lowercased().replacingOccurrences(of: "https://", with: "")) {
284
+ decisionHandler(.cancel)
285
+ finish(cancelled: false, returnUrlConsumed: true)
286
+ return
287
+ }
288
+ decisionHandler(.allow)
289
+ }
290
+
291
+ public func webView(_ webView: WKWebView, didStartProvisionalNavigation navigation: WKNavigation!) {
292
+ activityIndicator.startAnimating()
293
+ }
294
+
295
+ public func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!) {
296
+ activityIndicator.stopAnimating()
297
+ }
298
+
299
+ public func webView(_ webView: WKWebView, didFail navigation: WKNavigation!, withError error: Error) {
300
+ activityIndicator.stopAnimating()
301
+ }
302
+
303
+ private func escapeHtml(_ value: String) -> String {
304
+ var escaped = value
305
+ escaped = escaped.replacingOccurrences(of: "&", with: "&amp;")
306
+ escaped = escaped.replacingOccurrences(of: "<", with: "&lt;")
307
+ escaped = escaped.replacingOccurrences(of: ">", with: "&gt;")
308
+ escaped = escaped.replacingOccurrences(of: "\"", with: "&quot;")
309
+ return escaped
310
+ }
311
+ }