@dynamic-labs/legacy-react-native-extension 5.9.0 → 5.9.2

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.
@@ -24,6 +24,15 @@ public final class EmbeddedWebViewController: NSObject {
24
24
  private var window: UIWindow?
25
25
  private var webView: WKWebView?
26
26
  private var debuggingEnabled = false
27
+
28
+ // Opt-in for window.open() popups, set via setAllowWebViewPopups before
29
+ // the first setUrl call. Read once, in ensureWebView(): WKWebViewConfiguration's
30
+ // javaScriptCanOpenWindowsAutomatically (unlike isInspectable) cannot be
31
+ // changed after the WKWebView is created, so there's no retroactive-apply
32
+ // path here the way setDebuggingEnabled has one. Defaults to false:
33
+ // consumers who never call the setter get the pre-Coinbase-popup behavior
34
+ // unchanged.
35
+ private var allowPopups = false
27
36
  private var pendingNavigationDecisions: [String: (WKNavigationActionPolicy) -> Void] = [:]
28
37
  private var navigationTimers: [String: Timer] = [:]
29
38
  private var emitterToken: UUID?
@@ -33,6 +42,16 @@ public final class EmbeddedWebViewController: NSObject {
33
42
  // still go through the JS allowlist.
34
43
  private var preApprovedOrigin: String?
35
44
 
45
+ // Some wallet-connect flows (e.g. Coinbase's keys.coinbase.com Smart
46
+ // Wallet flow) only work through a real window.open() popup, with the
47
+ // result posted back via `postMessage` to `window.opener` — there's no
48
+ // redirect-based fallback. `createWebViewWith` below hosts that popup in
49
+ // its own window, separate from `window`/`webView` above. Retained
50
+ // strongly since `WKWebView.navigationDelegate` is weak.
51
+ private var popupWindow: UIWindow?
52
+ private var popupWebView: WKWebView?
53
+ private var popupNavigationDelegate: PopupNavigationDelegate?
54
+
36
55
  private override init() {
37
56
  super.init()
38
57
  }
@@ -111,7 +130,12 @@ public final class EmbeddedWebViewController: NSObject {
111
130
  }
112
131
  }
113
132
 
133
+ public func setAllowWebViewPopups(_ enabled: Bool) {
134
+ allowPopups = enabled
135
+ }
136
+
114
137
  public func destroy() {
138
+ closePopup()
115
139
  webView?.stopLoading()
116
140
  if let userContentController = webView?.configuration.userContentController {
117
141
  userContentController.removeAllUserScripts()
@@ -157,6 +181,11 @@ public final class EmbeddedWebViewController: NSObject {
157
181
 
158
182
  let configuration = WKWebViewConfiguration()
159
183
  configuration.websiteDataStore = .default()
184
+ // Lets the page's own JS open a real popup window (createWebViewWith
185
+ // below), rather than only user-gesture-triggered ones. Opt-in via
186
+ // allowPopups (see setAllowWebViewPopups) — everyone else keeps the
187
+ // original refuse-popups behavior (uiDelegate left unset below).
188
+ configuration.preferences.javaScriptCanOpenWindowsAutomatically = allowPopups
160
189
 
161
190
  let userContentController = WKUserContentController()
162
191
  let polyfill = """
@@ -181,6 +210,12 @@ public final class EmbeddedWebViewController: NSObject {
181
210
  let frame = UIScreen.main.bounds
182
211
  let webView = WKWebView(frame: frame, configuration: configuration)
183
212
  webView.navigationDelegate = self
213
+ // Leaving uiDelegate unset when popups aren't allowed makes WebKit
214
+ // silently drop window.open() (its default with no WKUIDelegate),
215
+ // matching pre-Coinbase-popup behavior.
216
+ if allowPopups {
217
+ webView.uiDelegate = self
218
+ }
184
219
  webView.scrollView.contentInsetAdjustmentBehavior = .never
185
220
  webView.translatesAutoresizingMaskIntoConstraints = false
186
221
 
@@ -274,6 +309,112 @@ public final class EmbeddedWebViewController: NSObject {
274
309
  return "\(scheme)://\(host)"
275
310
  }
276
311
 
312
+ // MARK: - Popup window (window.open())
313
+
314
+ // WebKit requires createWebViewWith to build the new WKWebView from the
315
+ // exact `configuration` it hands us (it's the same process/pairing as the
316
+ // opener) — we only control the surrounding chrome: window, address bar,
317
+ // dismiss button, navigation-origin lock.
318
+ fileprivate func createPopupWebView(configuration: WKWebViewConfiguration) -> WKWebView {
319
+ closePopup()
320
+
321
+ let frame = UIScreen.main.bounds
322
+ let popup = WKWebView(frame: .zero, configuration: configuration)
323
+ popup.translatesAutoresizingMaskIntoConstraints = false
324
+ // Coinbase's keys.coinbase.com page refuses to proceed when it detects
325
+ // an embedded WKWebView — Mobile Safari's user agent ends in
326
+ // "Safari/<version>"; a bare WKWebView's default doesn't. Appending that
327
+ // token makes this popup present as a stock Safari tab, which is
328
+ // otherwise indistinguishable from one: it's a real window opened via
329
+ // WKUIDelegate#createWebViewWith, not a same-document overlay.
330
+ popup.customUserAgent = safariLikeUserAgent()
331
+
332
+ let addressBarLabel = UILabel()
333
+ addressBarLabel.textColor = UIColor(white: 0.88, alpha: 1)
334
+ addressBarLabel.font = .systemFont(ofSize: 13)
335
+ addressBarLabel.lineBreakMode = .byTruncatingMiddle
336
+ addressBarLabel.translatesAutoresizingMaskIntoConstraints = false
337
+
338
+ let dismissButton = UIButton(type: .system)
339
+ dismissButton.setTitle("✕", for: .normal)
340
+ dismissButton.setTitleColor(.white, for: .normal)
341
+ dismissButton.translatesAutoresizingMaskIntoConstraints = false
342
+ dismissButton.addTarget(self, action: #selector(dismissPopupTapped), for: .touchUpInside)
343
+
344
+ let navigationDelegate = PopupNavigationDelegate { [weak addressBarLabel] origin in
345
+ addressBarLabel?.text = "🔒 " + origin
346
+ .replacingOccurrences(of: "https://", with: "")
347
+ .replacingOccurrences(of: "http://", with: "")
348
+ }
349
+ popup.navigationDelegate = navigationDelegate
350
+ popup.uiDelegate = self
351
+
352
+ let addressBar = UIView()
353
+ addressBar.backgroundColor = UIColor(white: 0.12, alpha: 0.95)
354
+ addressBar.translatesAutoresizingMaskIntoConstraints = false
355
+ addressBar.addSubview(addressBarLabel)
356
+ addressBar.addSubview(dismissButton)
357
+
358
+ let rootVC = UIViewController()
359
+ rootVC.view.backgroundColor = .white
360
+ rootVC.view.addSubview(addressBar)
361
+ rootVC.view.addSubview(popup)
362
+ NSLayoutConstraint.activate([
363
+ addressBar.topAnchor.constraint(equalTo: rootVC.view.safeAreaLayoutGuide.topAnchor),
364
+ addressBar.leadingAnchor.constraint(equalTo: rootVC.view.leadingAnchor),
365
+ addressBar.trailingAnchor.constraint(equalTo: rootVC.view.trailingAnchor),
366
+
367
+ addressBarLabel.leadingAnchor.constraint(equalTo: addressBar.leadingAnchor, constant: 12),
368
+ addressBarLabel.centerYAnchor.constraint(equalTo: addressBar.centerYAnchor),
369
+ addressBarLabel.topAnchor.constraint(equalTo: addressBar.topAnchor, constant: 10),
370
+ addressBarLabel.bottomAnchor.constraint(equalTo: addressBar.bottomAnchor, constant: -10),
371
+
372
+ dismissButton.leadingAnchor.constraint(equalTo: addressBarLabel.trailingAnchor, constant: 8),
373
+ dismissButton.trailingAnchor.constraint(equalTo: addressBar.trailingAnchor, constant: -12),
374
+ dismissButton.centerYAnchor.constraint(equalTo: addressBar.centerYAnchor),
375
+
376
+ popup.topAnchor.constraint(equalTo: addressBar.bottomAnchor),
377
+ popup.leadingAnchor.constraint(equalTo: rootVC.view.leadingAnchor),
378
+ popup.trailingAnchor.constraint(equalTo: rootVC.view.trailingAnchor),
379
+ popup.bottomAnchor.constraint(equalTo: rootVC.view.bottomAnchor),
380
+ ])
381
+
382
+ let window = UIWindow(frame: frame)
383
+ window.windowLevel = .alert
384
+ window.rootViewController = rootVC
385
+ window.makeKeyAndVisible()
386
+
387
+ popupWindow = window
388
+ popupWebView = popup
389
+ popupNavigationDelegate = navigationDelegate
390
+ return popup
391
+ }
392
+
393
+ @objc private func dismissPopupTapped() {
394
+ closePopup()
395
+ }
396
+
397
+ fileprivate func closePopup() {
398
+ popupWebView?.stopLoading()
399
+ popupWebView?.navigationDelegate = nil
400
+ popupWebView?.uiDelegate = nil
401
+ popupWebView?.removeFromSuperview()
402
+ popupWebView = nil
403
+ popupNavigationDelegate = nil
404
+
405
+ popupWindow?.isHidden = true
406
+ popupWindow?.rootViewController = nil
407
+ popupWindow = nil
408
+ }
409
+
410
+ private func safariLikeUserAgent() -> String {
411
+ let osVersion = ProcessInfo.processInfo.operatingSystemVersion
412
+ let versionString = "\(osVersion.majorVersion)_\(osVersion.minorVersion)"
413
+ return "Mozilla/5.0 (iPhone; CPU iPhone OS \(versionString) like Mac OS X) "
414
+ + "AppleWebKit/605.1.15 (KHTML, like Gecko) "
415
+ + "Version/\(osVersion.majorVersion).\(osVersion.minorVersion) Mobile/15E148 Safari/604.1"
416
+ }
417
+
277
418
  // Use JSONSerialization to safely encode an arbitrary string as a JS string literal.
278
419
  private func jsStringLiteral(_ raw: String) -> String {
279
420
  guard
@@ -498,3 +639,97 @@ extension EmbeddedWebViewController: WKNavigationDelegate {
498
639
  ])
499
640
  }
500
641
  }
642
+
643
+ extension EmbeddedWebViewController: WKUIDelegate {
644
+ // WKUIDelegate's equivalent of Android's onCreateWindow: called when page
645
+ // JS invokes window.open(). Returning a WKWebView here (built from the
646
+ // configuration WebKit hands us) tells WebKit to load the popup's request
647
+ // into it; returning nil would silently drop the window.open() call.
648
+ public func webView(
649
+ _ _: WKWebView,
650
+ createWebViewWith configuration: WKWebViewConfiguration,
651
+ for _: WKNavigationAction,
652
+ windowFeatures _: WKWindowFeatures
653
+ ) -> WKWebView? {
654
+ return createPopupWebView(configuration: configuration)
655
+ }
656
+
657
+ // The wallet's own page calls window.close() once it has posted the
658
+ // connect result back via postMessage.
659
+ public func webViewDidClose(_ _: WKWebView) {
660
+ closePopup()
661
+ }
662
+ }
663
+
664
+ // The popup only ever needs to stay within the origin it started on (e.g.
665
+ // keys.coinbase.com) — that first navigation is trusted because it's the
666
+ // trusted top-frame's own JS that called window.open() with the target URL.
667
+ // Anything the popup subsequently tries to navigate to outside that origin
668
+ // is refused, closing off a mid-flow redirect to an attacker page.
669
+ private final class PopupNavigationDelegate: NSObject, WKNavigationDelegate {
670
+ private var popupOrigin: String?
671
+ // Tracks whether the trusted first navigation has already happened,
672
+ // separately from `popupOrigin` itself. An opaque first load (e.g.
673
+ // `about:blank`, `javascript:`) has no host and so no determinable
674
+ // origin — without this flag, `popupOrigin` would stay nil and the
675
+ // "first navigation is trusted" branch below would keep re-triggering
676
+ // on every subsequent navigation, never actually locking the origin.
677
+ private var hasApprovedFirstNavigation = false
678
+ private let onOriginChanged: (String) -> Void
679
+
680
+ init(onOriginChanged: @escaping (String) -> Void) {
681
+ self.onOriginChanged = onOriginChanged
682
+ }
683
+
684
+ // Sonar flags any decidePolicyFor override as a security hotspot (S6363,
685
+ // "unrestricted navigation") purely for existing, since it's the choke
686
+ // point that could let a WebView navigate anywhere. This one is the
687
+ // actual control, not a gap in it: it locks onto the popup's
688
+ // first-navigated origin below and rejects every subsequent navigation
689
+ // outside that origin. Removing or loosening this override would remove
690
+ // the security control the hotspot is asking about.
691
+ func webView( // NOSONAR
692
+ _ _: WKWebView,
693
+ decidePolicyFor navigationAction: WKNavigationAction,
694
+ decisionHandler: @escaping (WKNavigationActionPolicy) -> Void
695
+ ) {
696
+ guard navigationAction.targetFrame?.isMainFrame ?? true else {
697
+ decisionHandler(.allow)
698
+ return
699
+ }
700
+
701
+ let origin = originString(for: navigationAction.request.url)
702
+
703
+ if !hasApprovedFirstNavigation {
704
+ hasApprovedFirstNavigation = true
705
+ popupOrigin = origin
706
+ if let origin = origin { onOriginChanged(origin) }
707
+ decisionHandler(.allow)
708
+ return
709
+ }
710
+
711
+ if let origin = origin, let approvedOrigin = popupOrigin, origin == approvedOrigin {
712
+ decisionHandler(.allow)
713
+ return
714
+ }
715
+
716
+ decisionHandler(.cancel)
717
+ }
718
+
719
+ func webView(_ _: WKWebView, didFailProvisionalNavigation _: WKNavigation!, withError _: Error) {
720
+ // Cancelling our own navigation above surfaces here — not a real failure.
721
+ }
722
+
723
+ private func originString(for url: URL?) -> String? {
724
+ guard let url = url, let scheme = url.scheme, let host = url.host else {
725
+ return nil
726
+ }
727
+ if let port = url.port {
728
+ let isDefaultPort = (scheme == "https" && port == 443) || (scheme == "http" && port == 80)
729
+ if !isDefaultPort {
730
+ return "\(scheme)://\(host):\(port)"
731
+ }
732
+ }
733
+ return "\(scheme)://\(host)"
734
+ }
735
+ }
@@ -50,6 +50,12 @@ public class EmbeddedWebViewModule: Module {
50
50
  }
51
51
  }
52
52
 
53
+ AsyncFunction("setAllowWebViewPopups") { (enabled: Bool) in
54
+ DispatchQueue.main.async {
55
+ EmbeddedWebViewController.shared.setAllowWebViewPopups(enabled)
56
+ }
57
+ }
58
+
53
59
  AsyncFunction("destroy") {
54
60
  DispatchQueue.main.async {
55
61
  EmbeddedWebViewController.shared.destroy()
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@dynamic-labs/legacy-react-native-extension",
3
- "version": "5.9.0",
3
+ "version": "5.9.2",
4
4
  "main": "./index.cjs",
5
5
  "module": "./index.js",
6
6
  "types": "./src/index.d.ts",
@@ -18,11 +18,11 @@
18
18
  "@turnkey/react-native-passkey-stamper": "1.2.7",
19
19
  "@react-native-documents/picker": "^11.0.0",
20
20
  "react-native-fs": ">=2.20.0",
21
- "@dynamic-labs/assert-package-version": "5.9.0",
22
- "@dynamic-labs/legacy-client": "5.9.0",
23
- "@dynamic-labs/logger": "5.9.0",
24
- "@dynamic-labs/message-transport": "5.9.0",
25
- "@dynamic-labs/webview-messages": "5.9.0"
21
+ "@dynamic-labs/assert-package-version": "5.9.2",
22
+ "@dynamic-labs/legacy-client": "5.9.2",
23
+ "@dynamic-labs/logger": "5.9.2",
24
+ "@dynamic-labs/message-transport": "5.9.2",
25
+ "@dynamic-labs/webview-messages": "5.9.2"
26
26
  },
27
27
  "peerDependencies": {
28
28
  "react": ">=18.0.0 <20.0.0",
@@ -55,10 +55,19 @@ export type ReactNativeExtensionProps = {
55
55
  * documentation and defaults. Only tune this for pathological networks.
56
56
  */
57
57
  webviewLoad?: WebViewLoadOptions;
58
+ /**
59
+ * When true on the native overlay path (`embeddedWebView: true`), lets the
60
+ * webview open real `window.open()` popups — required by wallet-connect
61
+ * flows with no redirect fallback (e.g. Coinbase's keys.coinbase.com Smart
62
+ * Wallet flow). Ignored on the `react-native-webview` fallback path.
63
+ * Defaults to `false`: upgrading this package does not change webview
64
+ * behavior for consumers who don't set this.
65
+ */
66
+ allowWebViewPopups?: boolean;
58
67
  };
59
68
  export type IReactNativeExtension = {
60
69
  reactNative: {
61
70
  WebView: FC<WebViewProps> | (() => null);
62
71
  };
63
72
  };
64
- export declare const ReactNativeExtension: ({ webviewUrl, webviewDebuggingEnabled, appOrigin, embeddedWebView, webviewLoad, }?: ReactNativeExtensionProps) => Extension<IReactNativeExtension>;
73
+ export declare const ReactNativeExtension: ({ webviewUrl, webviewDebuggingEnabled, appOrigin, embeddedWebView, webviewLoad, allowWebViewPopups, }?: ReactNativeExtensionProps) => Extension<IReactNativeExtension>;
@@ -9,5 +9,12 @@ export type SetupEmbeddedWebViewArgs = {
9
9
  * See `WebViewLoadOptions` for the per-field documentation.
10
10
  */
11
11
  webviewLoad?: WebViewLoadOptions;
12
+ /**
13
+ * Opt-in for `window.open()` popups inside the embedded webview (e.g.
14
+ * Coinbase's keys.coinbase.com Smart Wallet connect flow, which has no
15
+ * redirect-based fallback). Defaults to `false` — upgrading this package
16
+ * does not change webview behavior for consumers who don't set this.
17
+ */
18
+ allowWebViewPopups?: boolean;
12
19
  };
13
- export declare const setupEmbeddedWebView: ({ webviewUrl, core, webviewDebuggingEnabled, webviewLoad, }: SetupEmbeddedWebViewArgs) => (() => void);
20
+ export declare const setupEmbeddedWebView: ({ webviewUrl, core, webviewDebuggingEnabled, webviewLoad, allowWebViewPopups, }: SetupEmbeddedWebViewArgs) => (() => void);
@@ -46,6 +46,14 @@ export type EmbeddedWebViewNativeModule = {
46
46
  setUrl: (url: string) => Promise<void>;
47
47
  setVisible: (visible: boolean) => Promise<void>;
48
48
  setDebuggingEnabled: (enabled: boolean) => Promise<void>;
49
+ /**
50
+ * Opt-in for `window.open()` popups (e.g. Coinbase's keys.coinbase.com
51
+ * Smart Wallet connect flow). Defaults to disabled natively — most
52
+ * consumers never need this, and enabling it is a one-line change here
53
+ * rather than a default flip in `ensureWebView`, so upgrading this
54
+ * package alone never changes behavior for anyone who doesn't opt in.
55
+ */
56
+ setAllowWebViewPopups: (enabled: boolean) => Promise<void>;
49
57
  destroy: () => Promise<void>;
50
58
  postMessage: (message: string) => Promise<void>;
51
59
  respondToShouldStartLoad: (id: string, allow: boolean) => Promise<void>;