@dynamic-labs/legacy-react-native-extension 0.0.0 → 5.1.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 (76) hide show
  1. package/README.md +7 -0
  2. package/android/AndroidManifest.xml +1 -0
  3. package/android/EmbeddedWebViewController.kt +559 -0
  4. package/android/EmbeddedWebViewModule.kt +62 -0
  5. package/android/KeyStoreKeyManager.kt +154 -0
  6. package/android/KeychainModule.kt +71 -0
  7. package/android/build.gradle +38 -0
  8. package/android/dynamic/embeddedwebview/EmbeddedWebViewController.kt +559 -0
  9. package/android/dynamic/embeddedwebview/EmbeddedWebViewModule.kt +62 -0
  10. package/android/dynamic/keychain/KeyStoreKeyManager.kt +154 -0
  11. package/android/dynamic/keychain/KeychainModule.kt +71 -0
  12. package/android/embeddedwebview/EmbeddedWebViewController.kt +559 -0
  13. package/android/embeddedwebview/EmbeddedWebViewModule.kt +62 -0
  14. package/android/java/xyz/dynamic/embeddedwebview/EmbeddedWebViewController.kt +559 -0
  15. package/android/java/xyz/dynamic/embeddedwebview/EmbeddedWebViewModule.kt +62 -0
  16. package/android/java/xyz/dynamic/keychain/KeyStoreKeyManager.kt +154 -0
  17. package/android/java/xyz/dynamic/keychain/KeychainModule.kt +71 -0
  18. package/android/keychain/KeyStoreKeyManager.kt +154 -0
  19. package/android/keychain/KeychainModule.kt +71 -0
  20. package/android/main/AndroidManifest.xml +1 -0
  21. package/android/main/java/xyz/dynamic/embeddedwebview/EmbeddedWebViewController.kt +559 -0
  22. package/android/main/java/xyz/dynamic/embeddedwebview/EmbeddedWebViewModule.kt +62 -0
  23. package/android/main/java/xyz/dynamic/keychain/KeyStoreKeyManager.kt +154 -0
  24. package/android/main/java/xyz/dynamic/keychain/KeychainModule.kt +71 -0
  25. package/android/src/main/AndroidManifest.xml +1 -0
  26. package/android/src/main/java/xyz/dynamic/embeddedwebview/EmbeddedWebViewController.kt +559 -0
  27. package/android/src/main/java/xyz/dynamic/embeddedwebview/EmbeddedWebViewModule.kt +62 -0
  28. package/android/src/main/java/xyz/dynamic/keychain/KeyStoreKeyManager.kt +154 -0
  29. package/android/src/main/java/xyz/dynamic/keychain/KeychainModule.kt +71 -0
  30. package/android/xyz/dynamic/embeddedwebview/EmbeddedWebViewController.kt +559 -0
  31. package/android/xyz/dynamic/embeddedwebview/EmbeddedWebViewModule.kt +62 -0
  32. package/android/xyz/dynamic/keychain/KeyStoreKeyManager.kt +154 -0
  33. package/android/xyz/dynamic/keychain/KeychainModule.kt +71 -0
  34. package/expo-module.config.json +12 -0
  35. package/index.cjs +998 -0
  36. package/index.js +973 -0
  37. package/ios/EmbeddedWebViewController.swift +500 -0
  38. package/ios/EmbeddedWebViewModule.swift +69 -0
  39. package/ios/Keychain.podspec +15 -0
  40. package/ios/KeychainModule.swift +39 -0
  41. package/ios/SecureEnclaveKeyManager.swift +187 -0
  42. package/package.json +44 -1
  43. package/src/ReactNativeExtension/ReactNativeExtension.d.ts +64 -0
  44. package/src/ReactNativeExtension/index.d.ts +1 -0
  45. package/src/ReactNativeExtension/logNativeModuleAvailability.d.ts +19 -0
  46. package/src/ReactNativeExtension/setupKeychainHandler/index.d.ts +1 -0
  47. package/src/ReactNativeExtension/setupKeychainHandler/setupKeychainHandler.d.ts +2 -0
  48. package/src/ReactNativeExtension/setupPasskeyHandler/index.d.ts +1 -0
  49. package/src/ReactNativeExtension/setupPasskeyHandler/setupPasskeyHandler.d.ts +2 -0
  50. package/src/ReactNativeExtension/setupPlatformHandler/index.d.ts +1 -0
  51. package/src/ReactNativeExtension/setupPlatformHandler/setupPlatformHandler.d.ts +2 -0
  52. package/src/ReactNativeExtension/setupStorageHandler/index.d.ts +1 -0
  53. package/src/ReactNativeExtension/setupStorageHandler/setupStorageHandler.d.ts +2 -0
  54. package/src/ReactNativeExtension/setupTurnkeyPasskeyHandler/index.d.ts +1 -0
  55. package/src/ReactNativeExtension/setupTurnkeyPasskeyHandler/setupTurnkeyPasskeyHandler.d.ts +2 -0
  56. package/src/components/WebView/EmbeddedWebView/EmbeddedWebView.d.ts +13 -0
  57. package/src/components/WebView/EmbeddedWebView/index.d.ts +1 -0
  58. package/src/components/WebView/WebView.d.ts +37 -0
  59. package/src/components/WebView/WebView.styles.d.ts +26 -0
  60. package/src/components/WebView/index.d.ts +1 -0
  61. package/src/components/WebView/useMessageTransportWebViewBridge/index.d.ts +1 -0
  62. package/src/components/WebView/useMessageTransportWebViewBridge/useMessageTransportWebViewBridge.d.ts +6 -0
  63. package/src/components/WebView/useWebViewVisibility/index.d.ts +1 -0
  64. package/src/components/WebView/useWebViewVisibility/useWebViewVisibility.d.ts +4 -0
  65. package/src/components/WebView/utils/shouldAllowNavigation/index.d.ts +1 -0
  66. package/src/components/WebView/utils/shouldAllowNavigation/shouldAllowNavigation.d.ts +5 -0
  67. package/src/errors/WebViewFailedToLoadError.d.ts +1 -0
  68. package/src/index.d.ts +2 -0
  69. package/src/nativeModules/EmbeddedWebView.d.ts +68 -0
  70. package/src/nativeModules/Keychain.d.ts +23 -0
  71. package/src/nativeModules/index.d.ts +1 -0
  72. package/src/utils/logger.d.ts +2 -0
  73. package/turboModules/NativeDynamicWebView.ts +47 -0
  74. package/turboModules/NativeKeychain.ts +22 -0
  75. package/turboModules/NativeReactNativeManifest.ts +24 -0
  76. package/turboModules/NativeScreenshotProtection.ts +29 -0
@@ -0,0 +1,500 @@
1
+ import UIKit
2
+ import WebKit
3
+
4
+ private let scriptHandlerName = "dynamicEmbeddedWebView"
5
+ private let navigationDecisionTimeout: TimeInterval = 5.0
6
+
7
+ // Cleartext http is only permitted in debug builds (e.g. Metro at
8
+ // http://localhost:4202). Release builds reject http top-frame and sub-frame
9
+ // navigations regardless of what the JS allowlist says — so a JS compromise
10
+ // cannot trick production into loading http content.
11
+ #if DEBUG
12
+ private let allowsHttpScheme = true
13
+ #else
14
+ private let allowsHttpScheme = false
15
+ #endif
16
+
17
+ public typealias EmbeddedWebViewEventEmitter = (String, [String: Any]) -> Void
18
+
19
+ public final class EmbeddedWebViewController: NSObject {
20
+ public static let shared = EmbeddedWebViewController()
21
+
22
+ public var eventEmitter: EmbeddedWebViewEventEmitter?
23
+
24
+ private var window: UIWindow?
25
+ private var webView: WKWebView?
26
+ private var debuggingEnabled = false
27
+ private var pendingNavigationDecisions: [String: (WKNavigationActionPolicy) -> Void] = [:]
28
+ private var navigationTimers: [String: Timer] = [:]
29
+ private var emitterToken: UUID?
30
+ // Origin pre-approved by `setUrl`. When `decidePolicyFor` sees a top-frame
31
+ // navigation whose origin matches, it allows it immediately — no JS
32
+ // round-trip required. Cleared after first use so subsequent navigations
33
+ // still go through the JS allowlist.
34
+ private var preApprovedOrigin: String?
35
+
36
+ private override init() {
37
+ super.init()
38
+ }
39
+
40
+ // Module-side hook: assign the emitter under a token. The token lets
41
+ // OnDestroy avoid clobbering an emitter that a newer OnCreate has already
42
+ // installed — relevant during dev hot reloads where module instances briefly
43
+ // overlap.
44
+ @discardableResult
45
+ public func setEmitter(_ emitter: @escaping EmbeddedWebViewEventEmitter) -> UUID {
46
+ let token = UUID()
47
+ emitterToken = token
48
+ eventEmitter = emitter
49
+ return token
50
+ }
51
+
52
+ public func clearEmitter(token: UUID) {
53
+ if emitterToken == token {
54
+ eventEmitter = nil
55
+ emitterToken = nil
56
+ }
57
+ }
58
+
59
+ // MARK: - Public API (must be called on main thread)
60
+
61
+ public func setUrl(_ url: String) {
62
+ // Match react-native-webview parity: any invalid URL surfaces as a load
63
+ // error instead of silently no-op'ing. WKWebView accepts URLs without a
64
+ // scheme but never emits a navigation event for them — fail fast here so
65
+ // the JS side throws WebViewFailedToLoadError.
66
+ guard let parsed = URL(string: url), parsed.scheme != nil else {
67
+ emitInvalidUrlError(url: url)
68
+ return
69
+ }
70
+ ensureWebView()
71
+ // Pre-approve the origin so the first `decidePolicyFor` call can skip
72
+ // the JS round-trip. On cold boot the JS thread may be too congested to
73
+ // respond within the navigation-decision timeout, silently
74
+ // cancelling the load.
75
+ preApprovedOrigin = originString(for: parsed)
76
+ webView?.load(URLRequest(url: parsed))
77
+ }
78
+
79
+ private func emitInvalidUrlError(url: String) {
80
+ eventEmitter?("onLoadError", [
81
+ "url": url,
82
+ "code": -1,
83
+ "domain": "EmbeddedWebViewInvalidUrl",
84
+ "description": "Invalid URL: \(url)",
85
+ "isProvisional": true,
86
+ ])
87
+ }
88
+
89
+ public func setVisible(_ visible: Bool) {
90
+ ensureWebView()
91
+ // We deliberately do NOT toggle `isHidden`. WKWebView attached to a hidden
92
+ // UIWindow gets throttled by iOS — JS timers slow, fetch callbacks stall,
93
+ // message events stop dispatching — so the page effectively pauses until
94
+ // the window becomes visible again. By keeping the window in the visible
95
+ // window stack and toggling `alpha` + interaction instead, the WKWebView
96
+ // stays "foreground" from the OS's POV and continues running normally.
97
+ if visible {
98
+ window?.alpha = 1
99
+ window?.isUserInteractionEnabled = true
100
+ window?.makeKeyAndVisible()
101
+ } else {
102
+ window?.alpha = 0
103
+ window?.isUserInteractionEnabled = false
104
+ }
105
+ }
106
+
107
+ public func setDebuggingEnabled(_ enabled: Bool) {
108
+ debuggingEnabled = enabled
109
+ if let webView = webView, #available(iOS 16.4, *) {
110
+ webView.isInspectable = enabled
111
+ }
112
+ }
113
+
114
+ public func destroy() {
115
+ webView?.stopLoading()
116
+ if let userContentController = webView?.configuration.userContentController {
117
+ userContentController.removeAllUserScripts()
118
+ userContentController.removeScriptMessageHandler(forName: scriptHandlerName)
119
+ }
120
+ webView?.navigationDelegate = nil
121
+ webView?.removeFromSuperview()
122
+ webView = nil
123
+
124
+ window?.isHidden = true
125
+ window?.rootViewController = nil
126
+ window = nil
127
+
128
+ // WKWebView contract: every policy decision handler must be invoked
129
+ // exactly once. Cancel any in-flight decisions before clearing.
130
+ pendingNavigationDecisions.values.forEach { $0(.cancel) }
131
+ pendingNavigationDecisions.removeAll()
132
+ navigationTimers.values.forEach { $0.invalidate() }
133
+ navigationTimers.removeAll()
134
+ preApprovedOrigin = nil
135
+ }
136
+
137
+ public func postMessage(_ message: String) {
138
+ guard let webView = webView else { return }
139
+ let escaped = jsStringLiteral(message)
140
+ let script = "window.dispatchEvent(new MessageEvent('message', { data: \(escaped) }));"
141
+ webView.evaluateJavaScript(script, completionHandler: nil)
142
+ }
143
+
144
+ public func respondToShouldStartLoad(id: String, allow: Bool) {
145
+ DispatchQueue.main.async { [weak self] in
146
+ guard let self = self else { return }
147
+ guard let handler = self.pendingNavigationDecisions.removeValue(forKey: id) else { return }
148
+ self.navigationTimers.removeValue(forKey: id)?.invalidate()
149
+ handler(allow ? .allow : .cancel)
150
+ }
151
+ }
152
+
153
+ // MARK: - Lazy creation
154
+
155
+ private func ensureWebView() {
156
+ if webView != nil { return }
157
+
158
+ let configuration = WKWebViewConfiguration()
159
+ configuration.websiteDataStore = .default()
160
+
161
+ let userContentController = WKUserContentController()
162
+ let polyfill = """
163
+ (function() {
164
+ if (window.ReactNativeWebView) return;
165
+ window.ReactNativeWebView = {
166
+ postMessage: function(message) {
167
+ window.webkit.messageHandlers.\(scriptHandlerName).postMessage(message);
168
+ }
169
+ };
170
+ })();
171
+ """
172
+ let userScript = WKUserScript(
173
+ source: polyfill,
174
+ injectionTime: .atDocumentStart,
175
+ forMainFrameOnly: false
176
+ )
177
+ userContentController.addUserScript(userScript)
178
+ userContentController.add(self, name: scriptHandlerName)
179
+ configuration.userContentController = userContentController
180
+
181
+ let frame = UIScreen.main.bounds
182
+ let webView = WKWebView(frame: frame, configuration: configuration)
183
+ webView.navigationDelegate = self
184
+ webView.scrollView.contentInsetAdjustmentBehavior = .never
185
+ webView.translatesAutoresizingMaskIntoConstraints = false
186
+
187
+ // Make the WKWebView transparent so the RN content beneath shows through
188
+ // when the webview-controller renders without an opaque backdrop.
189
+ webView.isOpaque = false
190
+ webView.backgroundColor = .clear
191
+ webView.scrollView.backgroundColor = .clear
192
+
193
+ if #available(iOS 16.4, *) {
194
+ webView.isInspectable = debuggingEnabled
195
+ }
196
+
197
+ let rootVC = UIViewController()
198
+ rootVC.view.backgroundColor = .clear
199
+ rootVC.view.isOpaque = false
200
+ rootVC.view.addSubview(webView)
201
+ NSLayoutConstraint.activate([
202
+ webView.topAnchor.constraint(equalTo: rootVC.view.topAnchor),
203
+ webView.bottomAnchor.constraint(equalTo: rootVC.view.bottomAnchor),
204
+ webView.leadingAnchor.constraint(equalTo: rootVC.view.leadingAnchor),
205
+ webView.trailingAnchor.constraint(equalTo: rootVC.view.trailingAnchor),
206
+ ])
207
+
208
+ let window = UIWindow(frame: frame)
209
+ window.windowLevel = .alert
210
+ window.backgroundColor = .clear
211
+ window.isOpaque = false
212
+ window.rootViewController = rootVC
213
+ // Keep the window in the visible window stack from creation onward so
214
+ // iOS does not throttle the WKWebView's JS execution. We start fully
215
+ // transparent and non-interactive — `setVisible(true)` flips `alpha` and
216
+ // interaction back on without ever hiding the window.
217
+ window.isHidden = false
218
+ window.alpha = 0
219
+ window.isUserInteractionEnabled = false
220
+
221
+ self.webView = webView
222
+ self.window = window
223
+ }
224
+
225
+ // Walk the WKWebView subview tree, find the WKContentView (the first
226
+ // responder for keyboard input), and dynamically subclass it so its
227
+ // `inputAccessoryView` getter returns nil. This is the same technique
228
+ // react-native-webview uses for `hideKeyboardAccessoryView`.
229
+ private func hideInputAccessoryView(on webView: WKWebView) {
230
+ let hiddenClassName = "DynamicEmbeddedWebViewHiddenAccessory"
231
+ guard let contentView = findContentView(in: webView) else { return }
232
+ if NSStringFromClass(type(of: contentView)) == hiddenClassName { return }
233
+ guard let baseClass = object_getClass(contentView) else { return }
234
+ let existing: AnyClass? = NSClassFromString(hiddenClassName)
235
+ let targetClass: AnyClass
236
+ if let existing = existing {
237
+ targetClass = existing
238
+ } else {
239
+ guard let newClass = objc_allocateClassPair(baseClass, hiddenClassName, 0) else { return }
240
+ let block: @convention(block) (Any) -> UIView? = { _ in nil }
241
+ let imp = imp_implementationWithBlock(block)
242
+ let selector = #selector(getter: UIResponder.inputAccessoryView)
243
+ class_addMethod(newClass, selector, imp, "@@:")
244
+ objc_registerClassPair(newClass)
245
+ targetClass = newClass
246
+ }
247
+ object_setClass(contentView, targetClass)
248
+ }
249
+
250
+ private func findContentView(in view: UIView) -> UIView? {
251
+ for subview in view.subviews {
252
+ let className = NSStringFromClass(type(of: subview))
253
+ if className.contains("WKContentView") { return subview }
254
+ if let found = findContentView(in: subview) { return found }
255
+ }
256
+ return nil
257
+ }
258
+
259
+ // Extract the scheme + host + port origin from a URL (e.g.
260
+ // "https://webview.dynamicauth.com"). Returns nil for URLs without a host.
261
+ // Default ports (443 for HTTPS, 80 for HTTP) are omitted so that
262
+ // "https://example.com" and "https://example.com:443" produce the same
263
+ // origin string.
264
+ private func originString(for url: URL?) -> String? {
265
+ guard let url = url, let scheme = url.scheme, let host = url.host else {
266
+ return nil
267
+ }
268
+ if let port = url.port {
269
+ let isDefaultPort = (scheme == "https" && port == 443) || (scheme == "http" && port == 80)
270
+ if !isDefaultPort {
271
+ return "\(scheme)://\(host):\(port)"
272
+ }
273
+ }
274
+ return "\(scheme)://\(host)"
275
+ }
276
+
277
+ // Use JSONSerialization to safely encode an arbitrary string as a JS string literal.
278
+ private func jsStringLiteral(_ raw: String) -> String {
279
+ guard
280
+ let data = try? JSONSerialization.data(withJSONObject: [raw], options: []),
281
+ let arrayString = String(data: data, encoding: .utf8),
282
+ arrayString.count >= 2
283
+ else {
284
+ return "\"\""
285
+ }
286
+ let start = arrayString.index(after: arrayString.startIndex)
287
+ let end = arrayString.index(before: arrayString.endIndex)
288
+ return String(arrayString[start..<end])
289
+ }
290
+ }
291
+
292
+ extension EmbeddedWebViewController: WKScriptMessageHandler {
293
+ public func userContentController(
294
+ _: WKUserContentController,
295
+ didReceive message: WKScriptMessage
296
+ ) {
297
+ guard message.name == scriptHandlerName else { return }
298
+ let payload: String
299
+ if let asString = message.body as? String {
300
+ payload = asString
301
+ } else {
302
+ payload = String(describing: message.body)
303
+ }
304
+ eventEmitter?("onMessage", ["message": payload])
305
+ }
306
+ }
307
+
308
+ extension EmbeddedWebViewController: WKNavigationDelegate {
309
+ public func webView(
310
+ _: WKWebView,
311
+ decidePolicyFor navigationAction: WKNavigationAction,
312
+ decisionHandler: @escaping (WKNavigationActionPolicy) -> Void
313
+ ) {
314
+ let url = navigationAction.request.url?.absoluteString ?? ""
315
+ let scheme = navigationAction.request.url?.scheme?.lowercased()
316
+ let isTopFrame = navigationAction.targetFrame?.isMainFrame ?? true
317
+
318
+ // Sub-frame requests are auto-allowed (matches Android + JS allowlist).
319
+ // The trusted top-frame controls iframe content; iframes routinely start
320
+ // as `about:blank` and use `blob:` / `data:` / `about:srcdoc` URLs for
321
+ // legitimate functionality (WaaS MPC iframes, web workers, sandboxed
322
+ // inline content), so we defer iframe trust to the top-frame.
323
+ if !isTopFrame {
324
+ decisionHandler(.allow)
325
+ return
326
+ }
327
+
328
+ // Defense-in-depth: reject non-https top-frame schemes at the native layer
329
+ // before prompting JS. The JS allowlist would also reject these, but a JS
330
+ // bug approving a `javascript:` / `file:` / `data:` URL must not be enough
331
+ // to load it. http is permitted only in debug builds.
332
+ let isAllowedTopFrameScheme =
333
+ scheme == "https" || (allowsHttpScheme && scheme == "http")
334
+ if !isAllowedTopFrameScheme {
335
+ decisionHandler(.cancel)
336
+ eventEmitter?("onLoadError", [
337
+ "url": url,
338
+ "code": -1,
339
+ "domain": "EmbeddedWebViewBlockedScheme",
340
+ "description": "Blocked navigation to disallowed scheme: \(url)",
341
+ "isProvisional": true,
342
+ ])
343
+ return
344
+ }
345
+
346
+ // Fast-path: if the URL's origin matches the pre-approved origin (set
347
+ // by `setUrl`), allow immediately. This eliminates the cold-boot race
348
+ // where the JS thread is too congested to respond to
349
+ // `onShouldStartLoad` within the navigation-decision timeout.
350
+ if let approved = preApprovedOrigin,
351
+ approved == originString(for: navigationAction.request.url) {
352
+ preApprovedOrigin = nil
353
+ decisionHandler(.allow)
354
+ return
355
+ }
356
+
357
+ let id = UUID().uuidString
358
+ pendingNavigationDecisions[id] = decisionHandler
359
+
360
+ let timer = Timer.scheduledTimer(withTimeInterval: navigationDecisionTimeout, repeats: false) { [weak self] _ in
361
+ guard let self = self else { return }
362
+ DispatchQueue.main.async {
363
+ if let handler = self.pendingNavigationDecisions.removeValue(forKey: id) {
364
+ self.navigationTimers.removeValue(forKey: id)?.invalidate()
365
+ handler(.cancel)
366
+ // Surface an explicit load error so the SDK's error path runs
367
+ // immediately instead of waiting for the 20 s html_load timer.
368
+ // Matches Android's EmbeddedWebViewNavigationTimeout behavior.
369
+ let timeoutMs = Int(navigationDecisionTimeout * 1000)
370
+ self.eventEmitter?("onLoadError", [
371
+ "url": url,
372
+ "code": -1,
373
+ "domain": "EmbeddedWebViewNavigationTimeout",
374
+ "description": "Navigation decision timed out after \(timeoutMs)ms",
375
+ "isProvisional": true,
376
+ ])
377
+ }
378
+ }
379
+ }
380
+ navigationTimers[id] = timer
381
+
382
+ eventEmitter?("onShouldStartLoad", [
383
+ "id": id,
384
+ "url": url,
385
+ "isTopFrame": isTopFrame,
386
+ ])
387
+ }
388
+
389
+ public func webView(
390
+ _: WKWebView,
391
+ decidePolicyFor navigationResponse: WKNavigationResponse,
392
+ decisionHandler: @escaping (WKNavigationResponsePolicy) -> Void
393
+ ) {
394
+ // WKWebView does not fire didFail / didFailProvisionalNavigation for HTTP
395
+ // error status codes — a 404 or 500 just renders an empty page. Surface
396
+ // main-frame HTTP errors as onLoadError so the SDK's load-error path runs.
397
+ if let httpResponse = navigationResponse.response as? HTTPURLResponse,
398
+ navigationResponse.isForMainFrame,
399
+ httpResponse.statusCode >= 400 {
400
+ let url = httpResponse.url?.absoluteString ?? ""
401
+ let description = HTTPURLResponse.localizedString(forStatusCode: httpResponse.statusCode)
402
+ decisionHandler(.cancel)
403
+ eventEmitter?("onLoadError", [
404
+ "url": url,
405
+ "code": httpResponse.statusCode,
406
+ "domain": "EmbeddedWebViewHttpError",
407
+ "description": "HTTP \(httpResponse.statusCode): \(description)",
408
+ "isProvisional": false,
409
+ ])
410
+ return
411
+ }
412
+ decisionHandler(.allow)
413
+ }
414
+
415
+ public func webView(
416
+ _ webView: WKWebView,
417
+ didFailProvisionalNavigation _: WKNavigation!,
418
+ withError error: Error
419
+ ) {
420
+ emitLoadError(error: error as NSError, isProvisional: true, url: webView.url?.absoluteString)
421
+ }
422
+
423
+ public func webView(
424
+ _ webView: WKWebView,
425
+ didFail _: WKNavigation!,
426
+ withError error: Error
427
+ ) {
428
+ emitLoadError(error: error as NSError, isProvisional: false, url: webView.url?.absoluteString)
429
+ }
430
+
431
+ public func webView(
432
+ _ webView: WKWebView,
433
+ didStartProvisionalNavigation _: WKNavigation!
434
+ ) {
435
+ eventEmitter?("onLoadStart", [
436
+ "url": webView.url?.absoluteString ?? "",
437
+ ])
438
+ }
439
+
440
+ public func webView(_ webView: WKWebView, didCommit _: WKNavigation!) {
441
+ // WKContentView is created lazily once content starts being committed —
442
+ // suppress its input accessory bar here so focusing inputs in the page
443
+ // doesn't show the system "< > Done" toolbar. Matches the
444
+ // `hideKeyboardAccessoryView` setting used by `react-native-webview`.
445
+ hideInputAccessoryView(on: webView)
446
+
447
+ // didCommit fires when the first byte of the response is rendered —
448
+ // analogous to RN's `onLoad` callback (page content has actually
449
+ // started arriving, not just the navigation request).
450
+ eventEmitter?("onLoad", [
451
+ "url": webView.url?.absoluteString ?? "",
452
+ ])
453
+ }
454
+
455
+ public func webView(_ webView: WKWebView, didFinish _: WKNavigation!) {
456
+ eventEmitter?("onLoadEnd", [
457
+ "url": webView.url?.absoluteString ?? "",
458
+ ])
459
+ }
460
+
461
+ public func webViewWebContentProcessDidTerminate(_ webView: WKWebView) {
462
+ eventEmitter?("onLoadError", [
463
+ "url": webView.url?.absoluteString ?? "",
464
+ "code": -1,
465
+ "domain": "EmbeddedWebViewProcessTerminated",
466
+ "description": "WebContent process terminated",
467
+ "isProvisional": false,
468
+ ])
469
+ // The content process is dead — this WKWebView can never load anything
470
+ // again. Tear it down so the next `setUrl` recreates a fresh webview via
471
+ // the lazy `ensureWebView` path (mirrors Android's onRenderProcessGone).
472
+ destroy()
473
+ }
474
+
475
+ // Errors from cancelling our own navigation (e.g. when the JS allowlist
476
+ // returns false or the navigation-decision timeout fires) are not real load
477
+ // failures and should not be instrumented as such.
478
+ private func isCancellationError(_ error: NSError) -> Bool {
479
+ if error.domain == NSURLErrorDomain && error.code == NSURLErrorCancelled {
480
+ return true
481
+ }
482
+ // WebKit "frame load interrupted" — fired when our policy decision cancels
483
+ // the navigation.
484
+ if error.domain == "WebKitErrorDomain" && error.code == 102 {
485
+ return true
486
+ }
487
+ return false
488
+ }
489
+
490
+ private func emitLoadError(error: NSError, isProvisional: Bool, url: String?) {
491
+ if isCancellationError(error) { return }
492
+ eventEmitter?("onLoadError", [
493
+ "url": url ?? "",
494
+ "code": error.code,
495
+ "domain": "EmbeddedWebViewLoadError",
496
+ "description": error.localizedDescription,
497
+ "isProvisional": isProvisional,
498
+ ])
499
+ }
500
+ }
@@ -0,0 +1,69 @@
1
+ import ExpoModulesCore
2
+
3
+ public class EmbeddedWebViewModule: Module {
4
+ private var emitterToken: UUID?
5
+
6
+ public func definition() -> ModuleDefinition {
7
+ Name("EmbeddedWebView")
8
+
9
+ Events(
10
+ "onMessage",
11
+ "onShouldStartLoad",
12
+ "onLoadError",
13
+ "onLoadStart",
14
+ "onLoad",
15
+ "onLoadEnd"
16
+ )
17
+
18
+ OnCreate {
19
+ self.emitterToken = EmbeddedWebViewController.shared.setEmitter { [weak self] name, payload in
20
+ guard let self = self else { return }
21
+ self.sendEvent(name, payload)
22
+ }
23
+ }
24
+
25
+ OnDestroy {
26
+ // Only clear if our emitter is still the live one. Prevents a stale
27
+ // OnDestroy (e.g. during dev hot reload after a newer OnCreate already
28
+ // ran) from nulling the active emitter.
29
+ if let token = self.emitterToken {
30
+ EmbeddedWebViewController.shared.clearEmitter(token: token)
31
+ self.emitterToken = nil
32
+ }
33
+ }
34
+
35
+ AsyncFunction("setUrl") { (url: String) in
36
+ DispatchQueue.main.async {
37
+ EmbeddedWebViewController.shared.setUrl(url)
38
+ }
39
+ }
40
+
41
+ AsyncFunction("setVisible") { (visible: Bool) in
42
+ DispatchQueue.main.async {
43
+ EmbeddedWebViewController.shared.setVisible(visible)
44
+ }
45
+ }
46
+
47
+ AsyncFunction("setDebuggingEnabled") { (enabled: Bool) in
48
+ DispatchQueue.main.async {
49
+ EmbeddedWebViewController.shared.setDebuggingEnabled(enabled)
50
+ }
51
+ }
52
+
53
+ AsyncFunction("destroy") {
54
+ DispatchQueue.main.async {
55
+ EmbeddedWebViewController.shared.destroy()
56
+ }
57
+ }
58
+
59
+ AsyncFunction("postMessage") { (message: String) in
60
+ DispatchQueue.main.async {
61
+ EmbeddedWebViewController.shared.postMessage(message)
62
+ }
63
+ }
64
+
65
+ AsyncFunction("respondToShouldStartLoad") { (id: String, allow: Bool) in
66
+ EmbeddedWebViewController.shared.respondToShouldStartLoad(id: id, allow: allow)
67
+ }
68
+ }
69
+ }
@@ -0,0 +1,15 @@
1
+ Pod::Spec.new do |s|
2
+ s.name = 'Keychain'
3
+ s.version = '1.0.0'
4
+ s.summary = 'Native iOS modules for Dynamic SDK'
5
+ s.description = 'Provides Secure Enclave keychain operations and an embedded WKWebView host for the Dynamic webview-controller, exposed via Expo Modules.'
6
+ s.homepage = 'https://www.dynamic.xyz'
7
+ s.license = { type: 'MIT' }
8
+ s.author = 'Dynamic Labs'
9
+ s.source = { git: '' }
10
+ s.platform = :ios, '15.1'
11
+ s.swift_version = '5.4'
12
+ s.source_files = '*.swift'
13
+
14
+ s.dependency 'ExpoModulesCore'
15
+ end
@@ -0,0 +1,39 @@
1
+ import ExpoModulesCore
2
+
3
+ public class KeychainModule: Module {
4
+ private let keyManager = SecureEnclaveKeyManager()
5
+
6
+ public func definition() -> ModuleDefinition {
7
+ Name("Keychain")
8
+
9
+ AsyncFunction("isAvailable") { () -> Bool in
10
+ self.keyManager.isAvailable()
11
+ }
12
+
13
+ AsyncFunction("hasKey") { (key: String) -> Bool in
14
+ self.keyManager.hasKey(tag: key)
15
+ }
16
+
17
+ AsyncFunction("generateKeyPair") { (key: String) -> [String: String] in
18
+ let publicKey = try self.keyManager.generateKeyPair(tag: key)
19
+ return ["publicKey": publicKey]
20
+ }
21
+
22
+ AsyncFunction("getPublicKey") { (key: String) -> [String: String]? in
23
+ guard let publicKey = try self.keyManager.getPublicKey(tag: key) else {
24
+ return nil
25
+ }
26
+ return ["publicKey": publicKey]
27
+ }
28
+
29
+ AsyncFunction("sign") { (key: String, payload: String) -> [String: String] in
30
+ let payloadData = try base64urlDecode(payload)
31
+ let signature = try self.keyManager.sign(tag: key, payload: payloadData)
32
+ return ["signature": signature]
33
+ }
34
+
35
+ AsyncFunction("deleteKey") { (key: String) in
36
+ self.keyManager.deleteKey(tag: key)
37
+ }
38
+ }
39
+ }