@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
package/index.js ADDED
@@ -0,0 +1,973 @@
1
+ import { assertPackageVersion } from '@dynamic-labs/assert-package-version';
2
+ import { StyleSheet, Platform } from 'react-native';
3
+ import { useEffect, useRef, useState } from 'react';
4
+ import { WebView as WebView$1 } from 'react-native-webview';
5
+ import { createWebViewLoadController, EMBEDDED_WEBVIEW_HTTP_ERROR_DOMAIN } from '@dynamic-labs/legacy-client';
6
+ export { WebViewFailedToLoadError } from '@dynamic-labs/legacy-client';
7
+ import { Logger } from '@dynamic-labs/logger';
8
+ import { messageTransportDataJsonReviver, parseMessageTransportData, messageTransportDataJsonReplacer, createRequestChannel } from '@dynamic-labs/message-transport';
9
+ import { jsx } from 'react/jsx-runtime';
10
+ import { requireOptionalNativeModule, requireNativeModule } from 'expo-modules-core';
11
+ import { Passkey } from 'react-native-passkey';
12
+ import { createURL, getInitialURL, addEventListener, openURL } from 'expo-linking';
13
+ import { openAuthSessionAsync } from 'expo-web-browser';
14
+ import { getGenericPassword, resetGenericPassword, setGenericPassword } from 'react-native-keychain';
15
+ import { createPasskey, PasskeyStamper } from '@turnkey/react-native-passkey-stamper';
16
+
17
+ var version = "5.1.0";
18
+
19
+ function _extends() {
20
+ return _extends = Object.assign ? Object.assign.bind() : function (n) {
21
+ for (var e = 1; e < arguments.length; e++) {
22
+ var t = arguments[e];
23
+ for (var r in t) ({}).hasOwnProperty.call(t, r) && (n[r] = t[r]);
24
+ }
25
+ return n;
26
+ }, _extends.apply(null, arguments);
27
+ }
28
+
29
+ const logger = new Logger('react-native-extension');
30
+
31
+ const useMessageTransportWebViewBridge = (core, webViewRef) => {
32
+ /**
33
+ * Receive a message from the webview and forward it to the client
34
+ * message transport
35
+ */
36
+ const onMessageHandler = event => {
37
+ var _a;
38
+ let parsedData = null;
39
+ try {
40
+ parsedData = JSON.parse(event.nativeEvent.data, messageTransportDataJsonReviver);
41
+ } catch (err) {
42
+ logger.debug('error parsing data', err);
43
+ return;
44
+ }
45
+ const message = parseMessageTransportData(parsedData);
46
+ if (!message) {
47
+ logger.debug('invalid message', message);
48
+ return;
49
+ }
50
+ /**
51
+ * Only forward messages from the created by the webview
52
+ */
53
+ if (message.origin === 'webview') {
54
+ if ((_a = core.debug) === null || _a === void 0 ? void 0 : _a.messageTransport) {
55
+ logger.debug('WEBVIEW >>>> HOST', JSON.stringify(message, null, 2));
56
+ }
57
+ core.messageTransport.emit(message);
58
+ }
59
+ };
60
+ /**
61
+ * Send messages created by the client to the webview
62
+ */
63
+ useEffect(() => {
64
+ const sendMessageToWebView = message => {
65
+ var _a;
66
+ if (!webViewRef.current) {
67
+ logger.instrument('WebView ref not found — dropping message', {
68
+ environmentId: core.environmentId,
69
+ hostSdkSessionId: core.hostSdkSessionId,
70
+ key: 'webview.message_dropped',
71
+ messageOrigin: message.origin,
72
+ messageType: message.type,
73
+ time: 0
74
+ });
75
+ return;
76
+ }
77
+ /**
78
+ * Only forward messages to the webview
79
+ * that where created by the client/host
80
+ */
81
+ if (message.origin === 'host' && webViewRef.current) {
82
+ if ((_a = core.debug) === null || _a === void 0 ? void 0 : _a.messageTransport) {
83
+ logger.debug('HOST >>>> WEBVIEW', JSON.stringify(message, null, 2));
84
+ }
85
+ webViewRef.current.postMessage(JSON.stringify(message, messageTransportDataJsonReplacer));
86
+ }
87
+ };
88
+ core.messageTransport.on(sendMessageToWebView);
89
+ return () => {
90
+ core.messageTransport.off(sendMessageToWebView);
91
+ };
92
+ }, [core, webViewRef]);
93
+ return {
94
+ onMessageHandler
95
+ };
96
+ };
97
+
98
+ const useWebViewVisibility = core => {
99
+ const webViewVisibilityRequestChannelRef = useRef(createRequestChannel(core.messageTransport));
100
+ const [visible, setVisible] = useState(false);
101
+ useEffect(() => webViewVisibilityRequestChannelRef.current.handle('setVisibility', setVisible), [setVisible]);
102
+ return {
103
+ visible
104
+ };
105
+ };
106
+
107
+ const styles = StyleSheet.create({
108
+ container: {
109
+ backgroundColor: 'transparent',
110
+ bottom: 0,
111
+ flex: 1,
112
+ left: 0,
113
+ position: 'absolute',
114
+ right: 0,
115
+ top: 0,
116
+ width: '100%'
117
+ },
118
+ hide: {
119
+ elevation: 0,
120
+ opacity: 0,
121
+ zIndex: -10000
122
+ },
123
+ show: {
124
+ elevation: 10000,
125
+ opacity: 1,
126
+ zIndex: 10000
127
+ },
128
+ webview: {
129
+ backgroundColor: 'transparent',
130
+ flex: 1
131
+ }
132
+ });
133
+
134
+ const waasOrigins = ['https://app.dynamic-preprod.xyz', 'https://app.dynamicauth.com'];
135
+ const turnkeyOrigins = ['https://recovery.turnkey.com', 'https://export.turnkey.com'];
136
+ const isNonProductionBuild = () => process.env['NODE_ENV'] !== 'production';
137
+ const isAllowedWaasOrigin = origin => {
138
+ if (waasOrigins.includes(origin)) {
139
+ return true;
140
+ }
141
+ if (isNonProductionBuild() && /^http:\/\/localhost:\d+$/.test(origin)) {
142
+ return true;
143
+ }
144
+ return false;
145
+ };
146
+ const parseUrl = url => {
147
+ try {
148
+ return new URL(url);
149
+ } catch (error) {
150
+ logger.error('Failed to get origin from url', error);
151
+ return null;
152
+ }
153
+ };
154
+ const shouldAllowNavigation = (request, webViewUrl) => {
155
+ const requestUrl = parseUrl(request.url);
156
+ if (!requestUrl) return false;
157
+ // Sub-frame (iframe) requests are controlled by the trusted web app
158
+ // content — allow them through without restriction.
159
+ if (!request.isTopFrame) return true;
160
+ if (webViewUrl.origin === requestUrl.origin) return true;
161
+ if (requestUrl.pathname.startsWith('/waas-v1') && isAllowedWaasOrigin(requestUrl.origin)) {
162
+ return true;
163
+ }
164
+ if (turnkeyOrigins.includes(requestUrl.origin)) return true;
165
+ return false;
166
+ };
167
+
168
+ const REACT_NATIVE_WEBVIEW_TYPE = 'react_native_webview';
169
+ // react-native-webview's `onError` only carries a `domain` on iOS/macOS.
170
+ // When it is absent (Android) this stable literal stands in so
171
+ // `classifyWebViewLoadError` still receives a domain and classifies the
172
+ // failure by its code alone (unknown domains default to transient).
173
+ const REACT_NATIVE_WEBVIEW_LOAD_ERROR_DOMAIN = 'ReactNativeWebViewLoadError';
174
+ // All load, timeout, retry, telemetry, and terminal-error logic is owned by
175
+ // the webview load controller (`createWebViewLoadController`). This
176
+ // component only owns the platform bindings: the react-native-webview
177
+ // element, its lifecycle-event mapping, the message bridge, visibility
178
+ // handling, and the navigation allowlist.
179
+ const WebView = ({
180
+ webviewUrl,
181
+ core,
182
+ webviewDebuggingEnabled: _webviewDebuggingEnabled = false,
183
+ recoveryTimeout,
184
+ loadingTimeout,
185
+ webviewLoad
186
+ }) => {
187
+ const webViewRef = useRef(null);
188
+ const {
189
+ visible
190
+ } = useWebViewVisibility(core);
191
+ // The URL of the load attempt currently in flight. The controller owns
192
+ // URL construction (environmentId, start time, retry counter); loading a
193
+ // new URL remounts the webview via `key`, which is how reloads work on
194
+ // this path. `null` until the controller issues the first load.
195
+ const [currentAttemptUrl, setCurrentAttemptUrl] = useState(null);
196
+ const controllerRef = useRef(null);
197
+ const {
198
+ onMessageHandler
199
+ } = useMessageTransportWebViewBridge(core, webViewRef);
200
+ /**
201
+ * Owns the load-controller lifecycle: created once per mount, torn down
202
+ * on unmount (keeping the unmount warning + transport block so a stray
203
+ * unmount doesn't leave host messages hitting a dead page).
204
+ */
205
+ useEffect(() => {
206
+ const adapter = {
207
+ load: url => setCurrentAttemptUrl(url),
208
+ webviewType: REACT_NATIVE_WEBVIEW_TYPE
209
+ };
210
+ const controller = createWebViewLoadController(Object.assign(Object.assign(Object.assign(Object.assign({
211
+ adapter,
212
+ core
213
+ }, webviewLoad), loadingTimeout !== undefined && {
214
+ pageLoadTimeoutMs: loadingTimeout
215
+ }), recoveryTimeout !== undefined && {
216
+ sdkReadyTimeoutMs: recoveryTimeout
217
+ }), {
218
+ webviewUrl
219
+ }));
220
+ controllerRef.current = controller;
221
+ // Hands the controller to the client core, which wires the
222
+ // customer-facing `client.sdk.loadState` / `client.sdk.retry()`
223
+ // surface to it.
224
+ core.registerWebViewLoadController(controller);
225
+ controller.start();
226
+ return () => {
227
+ logger.warn(unmountWebViewWarningMessage);
228
+ controller.teardown();
229
+ controllerRef.current = null;
230
+ core.messageTransport.block();
231
+ };
232
+ // eslint-disable-next-line react-hooks/exhaustive-deps -- the controller lifecycle is strictly mount/unmount
233
+ }, []);
234
+ const dispatch = event => {
235
+ var _a;
236
+ return (_a = controllerRef.current) === null || _a === void 0 ? void 0 : _a.dispatch(event);
237
+ };
238
+ const onError = ({
239
+ nativeEvent
240
+ }) => {
241
+ var _a;
242
+ return dispatch({
243
+ code: nativeEvent.code,
244
+ description: nativeEvent.description,
245
+ domain: (_a = nativeEvent.domain) !== null && _a !== void 0 ? _a : REACT_NATIVE_WEBVIEW_LOAD_ERROR_DOMAIN,
246
+ failedUrl: nativeEvent.url,
247
+ type: 'native_error'
248
+ });
249
+ };
250
+ const onHttpError = ({
251
+ nativeEvent
252
+ }) => dispatch({
253
+ code: nativeEvent.statusCode,
254
+ description: nativeEvent.description,
255
+ domain: EMBEDDED_WEBVIEW_HTTP_ERROR_DOMAIN,
256
+ failedUrl: nativeEvent.url,
257
+ type: 'native_error'
258
+ });
259
+ /**
260
+ * iOS and Android both may kill the webview content process under memory
261
+ * pressure. The controller routes the signal through the bounded
262
+ * backed-off reload cycle, blocking the message transport while the
263
+ * reload is in flight (the machine handles it both mid-load and
264
+ * post-ready).
265
+ */
266
+ const onProcessTerminated = () => dispatch({
267
+ type: 'recovery_requested'
268
+ });
269
+ const containerStyles = [styles['container'], visible ? styles.show : styles.hide];
270
+ if (currentAttemptUrl === null) return null;
271
+ const currentAttemptUrlString = currentAttemptUrl.toString();
272
+ return /*#__PURE__*/jsx(WebView$1, {
273
+ ref: webViewRef,
274
+ source: {
275
+ uri: currentAttemptUrlString
276
+ },
277
+ containerStyle: containerStyles,
278
+ style: styles['webview'],
279
+ onMessage: onMessageHandler,
280
+ onLoadStart: () => dispatch({
281
+ type: 'load_started'
282
+ }),
283
+ onLoad: () => dispatch({
284
+ type: 'response_committed'
285
+ }),
286
+ onLoadEnd: () => dispatch({
287
+ type: 'page_finished'
288
+ }),
289
+ hideKeyboardAccessoryView: true,
290
+ webviewDebuggingEnabled: _webviewDebuggingEnabled,
291
+ onContentProcessDidTerminate: onProcessTerminated,
292
+ onRenderProcessGone: onProcessTerminated,
293
+ onError: onError,
294
+ onHttpError: onHttpError,
295
+ setSupportMultipleWindows: false,
296
+ onShouldStartLoadWithRequest: request => shouldAllowNavigation({
297
+ isTopFrame: request.isTopFrame,
298
+ url: request.url
299
+ }, currentAttemptUrl)
300
+ }, currentAttemptUrlString);
301
+ };
302
+ const createWebView = internalProps => {
303
+ const WebViewWrapper = props => /*#__PURE__*/jsx(WebView, _extends({}, internalProps, props));
304
+ return WebViewWrapper;
305
+ };
306
+ const unmountWebViewWarningMessage = `WebView unmounted.
307
+
308
+ The Dynamic WebView may malfunction if it is unmounted.
309
+
310
+ Render the WebView at the top level of your component tree to ensure it is not unmounted.
311
+
312
+ For more information, please refer to the documentation:
313
+ https://docs.dynamic.xyz/react-native/react-native-extension
314
+ `;
315
+
316
+ // eslint-disable-next-line import/no-extraneous-dependencies
317
+ const NATIVE_MODULE_NAME = 'EmbeddedWebView';
318
+ /**
319
+ * Reports whether the EmbeddedWebView native module is linked into the
320
+ * currently running native binary.
321
+ *
322
+ * The embedded webview was introduced mid-version, so an over-the-air JS
323
+ * update can land on an older binary that predates the native module. Callers
324
+ * use this to decide between the native overlay path and the
325
+ * react-native-webview fallback before wiring any side effects.
326
+ *
327
+ * `requireOptionalNativeModule` returns `null` (instead of throwing) when the
328
+ * module is absent. Any unexpected throw is treated as "unavailable" so a
329
+ * runtime quirk can never break the calling flow.
330
+ */
331
+ const isEmbeddedWebViewAvailable = () => {
332
+ try {
333
+ return Boolean(requireOptionalNativeModule(NATIVE_MODULE_NAME));
334
+ } catch (_a) {
335
+ return false;
336
+ }
337
+ };
338
+ const getEmbeddedWebView = () => {
339
+ try {
340
+ return requireNativeModule(NATIVE_MODULE_NAME);
341
+ } catch (_a) {
342
+ logger.warn('Could not get EmbeddedWebView native module, using unavailable fallback');
343
+ const unavailableError = new Error('EmbeddedWebView is not available');
344
+ const unavailable = {
345
+ addListener: () => ({
346
+ remove: () => undefined
347
+ }),
348
+ destroy: () => Promise.reject(unavailableError),
349
+ postMessage: () => Promise.reject(unavailableError),
350
+ respondToShouldStartLoad: () => Promise.reject(unavailableError),
351
+ setDebuggingEnabled: () => Promise.reject(unavailableError),
352
+ setUrl: () => Promise.reject(unavailableError),
353
+ setVisible: () => Promise.reject(unavailableError)
354
+ };
355
+ return unavailable;
356
+ }
357
+ };
358
+
359
+ // The platform discriminator the load controller attaches to every
360
+ // consolidated `webview.load_*` telemetry event emitted for this path.
361
+ const EMBEDDED_WEBVIEW_TYPE = 'embedded_native';
362
+ // Debug log labels matching the react-native-webview bridge
363
+ // (`useMessageTransportWebViewBridge`) so both paths surface the same
364
+ // HOST/WEBVIEW message trace under `core.debug.messageTransport`.
365
+ const HOST_TO_WEBVIEW_LOG = 'HOST >>>> WEBVIEW';
366
+ const WEBVIEW_TO_HOST_LOG = 'WEBVIEW >>>> HOST';
367
+ // Wires the JS-side bridge to the native WKWebView singleton owned by Swift.
368
+ // This is intentionally not a React component: the embedded webview lives
369
+ // outside the React tree (in a dedicated UIWindow on iOS), so its setup runs
370
+ // once when the SDK is initialised — there's nothing to mount or unmount.
371
+ //
372
+ // All load, timeout, retry, telemetry, and terminal-error logic is owned by
373
+ // the webview load controller (`createWebViewLoadController`). This module
374
+ // only owns the platform bindings: the native-module wiring, the message
375
+ // bridge, visibility handling, and the navigation allowlist.
376
+ //
377
+ // Returns a teardown that removes every JS-side subscription. The native
378
+ // singleton is intentionally NOT destroyed — re-running setup with a fresh
379
+ // `core` (e.g. on client recreation with a new environmentId) just reloads
380
+ // the existing webview via setUrl.
381
+ const setupEmbeddedWebView = ({
382
+ webviewUrl,
383
+ core,
384
+ webviewDebuggingEnabled: _webviewDebuggingEnabled = false,
385
+ webviewLoad
386
+ }) => {
387
+ const native = getEmbeddedWebView();
388
+ // The URL of the load attempt currently in flight. The controller owns
389
+ // URL construction (environmentId, start time, retry counter), so the
390
+ // navigation allowlist below must compare against the URL the native
391
+ // webview was actually pointed at. Until the first `adapter.load` the
392
+ // base URL stands in — only its origin is ever compared.
393
+ let currentAttemptUrl = new URL(webviewUrl);
394
+ const adapter = {
395
+ load: url => {
396
+ var _a;
397
+ currentAttemptUrl = url;
398
+ logger.debug(`[EmbeddedWebView] calling setUrl: ${url.toString()}`);
399
+ (_a = native.setUrl(url.toString())) === null || _a === void 0 ? void 0 : _a.catch(err => {
400
+ logger.warn('EmbeddedWebView.setUrl failed', err);
401
+ });
402
+ },
403
+ webviewType: EMBEDDED_WEBVIEW_TYPE
404
+ };
405
+ const controller = createWebViewLoadController(Object.assign(Object.assign({
406
+ adapter,
407
+ core
408
+ }, webviewLoad), {
409
+ webviewUrl
410
+ }));
411
+ // Hands the controller to the client core, which wires the customer-facing
412
+ // `client.sdk.loadState` / `client.sdk.retry()` surface to it.
413
+ core.registerWebViewLoadController(controller);
414
+ const visibilityChannel = createRequestChannel(core.messageTransport);
415
+ const removeVisibilityHandler = visibilityChannel.handle('setVisibility', visible => {
416
+ native.setVisible(visible).catch(err => {
417
+ logger.warn('EmbeddedWebView.setVisible failed', err);
418
+ });
419
+ });
420
+ const handleHostMessage = message => {
421
+ var _a;
422
+ if (message.origin !== 'host') return;
423
+ if ((_a = core.debug) === null || _a === void 0 ? void 0 : _a.messageTransport) {
424
+ logger.debug(HOST_TO_WEBVIEW_LOG, JSON.stringify(message, null, 2));
425
+ }
426
+ native.postMessage(JSON.stringify(message, messageTransportDataJsonReplacer)).catch(err => {
427
+ logger.warn('EmbeddedWebView.postMessage failed', err);
428
+ });
429
+ };
430
+ core.messageTransport.on(handleHostMessage);
431
+ const onMessageSub = native.addListener('onMessage', event => {
432
+ var _a;
433
+ let parsed = null;
434
+ try {
435
+ parsed = JSON.parse(event.message, messageTransportDataJsonReviver);
436
+ } catch (_b) {
437
+ return;
438
+ }
439
+ const message = parseMessageTransportData(parsed);
440
+ if (!message) return;
441
+ if (message.origin === 'webview') {
442
+ if ((_a = core.debug) === null || _a === void 0 ? void 0 : _a.messageTransport) {
443
+ logger.debug(WEBVIEW_TO_HOST_LOG, JSON.stringify(message, null, 2));
444
+ }
445
+ core.messageTransport.emit(message);
446
+ }
447
+ });
448
+ const onShouldStartLoadSub = native.addListener('onShouldStartLoad', event => {
449
+ const allow = shouldAllowNavigation({
450
+ isTopFrame: event.isTopFrame,
451
+ url: event.url
452
+ }, currentAttemptUrl);
453
+ logger.debug(`[EmbeddedWebView] onShouldStartLoad id=${event.id} url=${event.url} isTopFrame=${event.isTopFrame} allow=${allow}`);
454
+ native.respondToShouldStartLoad(event.id, allow).catch(err => {
455
+ logger.warn('EmbeddedWebView.respondToShouldStartLoad failed', err);
456
+ });
457
+ });
458
+ const onLoadStartSub = native.addListener('onLoadStart', () => {
459
+ logger.debug('[EmbeddedWebView] onLoadStart');
460
+ controller.dispatch({
461
+ type: 'load_started'
462
+ });
463
+ });
464
+ const onLoadSub = native.addListener('onLoad', () => {
465
+ logger.debug('[EmbeddedWebView] onLoad (response committed)');
466
+ controller.dispatch({
467
+ type: 'response_committed'
468
+ });
469
+ });
470
+ const onLoadEndSub = native.addListener('onLoadEnd', () => {
471
+ logger.debug('[EmbeddedWebView] onLoadEnd (page finished)');
472
+ controller.dispatch({
473
+ type: 'page_finished'
474
+ });
475
+ });
476
+ const onLoadErrorSub = native.addListener('onLoadError', event => {
477
+ logger.debug(`[EmbeddedWebView] onLoadError domain=${event.domain} code=${event.code} url=${event.url}`);
478
+ logger.warn('EmbeddedWebView load error', event);
479
+ controller.dispatch({
480
+ code: event.code,
481
+ description: event.description,
482
+ domain: event.domain,
483
+ failedUrl: event.url,
484
+ isProvisional: event.isProvisional,
485
+ type: 'native_error'
486
+ });
487
+ });
488
+ native.setDebuggingEnabled(_webviewDebuggingEnabled).catch(err => {
489
+ logger.warn('EmbeddedWebView.setDebuggingEnabled failed', err);
490
+ });
491
+ // Defer the initial load by one event-loop tick so the JS thread has fully
492
+ // settled after listener registration. On cold boot the main thread is
493
+ // congested with bundle evaluation — yielding here gives pending microtasks
494
+ // and native bridge batches a chance to flush before the native side starts
495
+ // firing navigation events that require a JS round-trip response.
496
+ const warmupTimer = setTimeout(() => {
497
+ controller.start();
498
+ }, 0);
499
+ return () => {
500
+ logger.debug('[EmbeddedWebView] teardown — removing listeners');
501
+ clearTimeout(warmupTimer);
502
+ controller.teardown();
503
+ removeVisibilityHandler();
504
+ core.messageTransport.off(handleHostMessage);
505
+ onMessageSub.remove();
506
+ onShouldStartLoadSub.remove();
507
+ onLoadStartSub.remove();
508
+ onLoadSub.remove();
509
+ onLoadEndSub.remove();
510
+ onLoadErrorSub.remove();
511
+ };
512
+ };
513
+
514
+ // eslint-disable-next-line import/no-extraneous-dependencies
515
+ const KEYCHAIN_MODULE_NAME = 'Keychain';
516
+ /**
517
+ * Reports whether the Keychain native module is linked into the currently
518
+ * running native binary. Mirrors `isEmbeddedWebViewAvailable`: an over-the-air
519
+ * JS update can run on an older binary that predates the module, so any
520
+ * unexpected throw is treated as "unavailable".
521
+ */
522
+ const isKeychainAvailable = () => {
523
+ try {
524
+ return Boolean(requireOptionalNativeModule(KEYCHAIN_MODULE_NAME));
525
+ } catch (_a) {
526
+ return false;
527
+ }
528
+ };
529
+ const getKeychain = () => {
530
+ try {
531
+ const keychain = requireNativeModule(KEYCHAIN_MODULE_NAME);
532
+ return keychain;
533
+ } catch (error) {
534
+ logger.warn('Could not get dynamic keychain, using unavailable keychain');
535
+ const keychainUnavailableError = new Error('Keychain is not available');
536
+ const unavailableKeychain = {
537
+ deleteKey: () => Promise.reject(keychainUnavailableError),
538
+ generateKeyPair: () => Promise.reject(keychainUnavailableError),
539
+ getPublicKey: () => Promise.reject(keychainUnavailableError),
540
+ hasKey: () => Promise.reject(keychainUnavailableError),
541
+ isAvailable: () => Promise.resolve(false),
542
+ sign: () => Promise.reject(keychainUnavailableError)
543
+ };
544
+ return unavailableKeychain;
545
+ }
546
+ };
547
+
548
+ const NATIVE_MODULES_INSTRUMENT_KEY = 'react_native_extension.native_modules';
549
+ const describeAvailability = available => available ? 'available' : 'unavailable';
550
+ /**
551
+ * Reports the running package version and which native modules are linked into
552
+ * the current binary. The embedded webview / keychain modules were introduced
553
+ * mid-version, so an over-the-air JS update can run ahead of the native binary;
554
+ * pairing the version with the availability matrix surfaces that gap (and lets
555
+ * `embeddedWebViewRequested && !embeddedWebViewAvailable` quantify the
556
+ * react-native-webview fallback rate).
557
+ */
558
+ const logNativeModuleAvailability = ({
559
+ core,
560
+ embeddedWebView,
561
+ embeddedWebViewAvailable,
562
+ keychainAvailable
563
+ }) => {
564
+ const platform = Platform.OS;
565
+ logger.instrument('React Native extension native module availability', {
566
+ embeddedWebViewAvailable,
567
+ embeddedWebViewRequested: embeddedWebView,
568
+ environmentId: core.environmentId,
569
+ hostSdkSessionId: core.hostSdkSessionId,
570
+ key: NATIVE_MODULES_INSTRUMENT_KEY,
571
+ keychainAvailable,
572
+ platform,
573
+ time: 0,
574
+ version
575
+ });
576
+ logger.info(`@dynamic-labs/legacy-react-native-extension v${version} (${platform}) — native modules: Keychain=${describeAvailability(keychainAvailable)}, EmbeddedWebView=${describeAvailability(embeddedWebViewAvailable)}`);
577
+ };
578
+
579
+ /******************************************************************************
580
+ Copyright (c) Microsoft Corporation.
581
+
582
+ Permission to use, copy, modify, and/or distribute this software for any
583
+ purpose with or without fee is hereby granted.
584
+
585
+ THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
586
+ REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
587
+ AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
588
+ INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
589
+ LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
590
+ OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
591
+ PERFORMANCE OF THIS SOFTWARE.
592
+ ***************************************************************************** */
593
+
594
+ function __awaiter(thisArg, _arguments, P, generator) {
595
+ function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
596
+ return new (P || (P = Promise))(function (resolve, reject) {
597
+ function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
598
+ function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
599
+ function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
600
+ step((generator = generator.apply(thisArg, _arguments || [])).next());
601
+ });
602
+ }
603
+
604
+ typeof SuppressedError === "function" ? SuppressedError : function (error, suppressed, message) {
605
+ var e = new Error(message);
606
+ return e.name = "SuppressedError", e.error = error, e.suppressed = suppressed, e;
607
+ };
608
+
609
+ const setupPasskeyHandler = core => {
610
+ const passkeyRequestChannel = createRequestChannel(core.messageTransport);
611
+ passkeyRequestChannel.handle('passkey_register', _a => __awaiter(void 0, [_a], void 0, function* ({
612
+ optionsJSON
613
+ }) {
614
+ /**
615
+ * It is safe to cast the request type here because the react-native-passkey
616
+ * package follow the web API spec but typescript does not match both types
617
+ * correctly
618
+ */
619
+ const result = yield Passkey.create(
620
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
621
+ optionsJSON);
622
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
623
+ return result;
624
+ }));
625
+ passkeyRequestChannel.handle('passkey_authenticate', _b => __awaiter(void 0, [_b], void 0, function* ({
626
+ optionsJSON
627
+ }) {
628
+ /**
629
+ * It is safe to cast the request type here because the react-native-passkey
630
+ * package follow the web API spec but typescript does not match both types
631
+ * correctly
632
+ */
633
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
634
+ const result = yield Passkey.get(optionsJSON);
635
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
636
+ return result;
637
+ }));
638
+ };
639
+
640
+ const log = (...args) => logger.logVerboseTroubleshootingMessage('[react-native-extension] setupPlatformHandler', ...args);
641
+ const setupPlatformHandler = core => {
642
+ const platformChannel = createRequestChannel(core.messageTransport);
643
+ const redirectUrl = createURL('');
644
+ log('Setting up platform handler', {
645
+ redirectUrl
646
+ });
647
+ core.manifest.setPlatform('react-native');
648
+ core.manifest.setRedirectUrl(redirectUrl);
649
+ platformChannel.handle('openURL', url => __awaiter(void 0, void 0, void 0, function* () {
650
+ log('openURL called', {
651
+ url
652
+ });
653
+ try {
654
+ yield openURL(url);
655
+ } catch (error) {
656
+ // Re-throw the error so it propagates through the message transport
657
+ // This ensures that if opening the URL fails, the connection promise rejects
658
+ log('openURL failed', {
659
+ error,
660
+ url
661
+ });
662
+ throw error;
663
+ }
664
+ }));
665
+ platformChannel.handle('openAuthenticationWindow', _a => __awaiter(void 0, [_a], void 0, function* ({
666
+ url,
667
+ redirectUrl
668
+ }) {
669
+ log('openAuthenticationWindow called', {
670
+ redirectUrl,
671
+ url
672
+ });
673
+ const result = yield openAuthSessionAsync(url, redirectUrl);
674
+ log('openAuthenticationWindow result', {
675
+ result
676
+ });
677
+ // When not a success, result can only have a type which is a string describing
678
+ // what happened in a single word.
679
+ if (result.type !== 'success') throw new Error(result.type);
680
+ return result.url;
681
+ }));
682
+ platformChannel.handle('downloadFile', _b => __awaiter(void 0, [_b], void 0, function* ({
683
+ base64Content,
684
+ fileName,
685
+ mimeType
686
+ }) {
687
+ /**
688
+ * Sanitize the caller-provided fileName to prevent path traversal
689
+ * (CWE-22). The fileName is used to build a path inside the app cache
690
+ * directory, so a value containing path separators or `..` segments
691
+ * could escape the cache directory and delete/overwrite arbitrary files
692
+ * in the app sandbox. Reject anything that is not a plain basename:
693
+ * empty, `.`/`..`, or containing `/` or `\` (any `..` segment within a
694
+ * path is caught by the separator checks). Reducing to the basename here
695
+ * would silently write attacker-chosen data under a different name, so we
696
+ * reject instead.
697
+ */
698
+ if (!fileName || fileName === '.' || fileName === '..' || fileName.includes('/') || fileName.includes('\\')) {
699
+ throw new Error(`Invalid fileName: ${fileName}`);
700
+ }
701
+ /**
702
+ * Because this is an iOS and Android only package, we need to import
703
+ * dynamically to avoid react-native-web build errors.
704
+ */
705
+ const {
706
+ saveDocuments
707
+ } = yield import('@react-native-documents/picker');
708
+ const {
709
+ CachesDirectoryPath,
710
+ exists,
711
+ unlink,
712
+ writeFile
713
+ } = yield import('react-native-fs');
714
+ /**
715
+ * On native platforms you first need to create a file in the app directory
716
+ * so we can then request the file to be moved by the user to the OS file system.
717
+ */
718
+ const fileUri = `file://${CachesDirectoryPath}/${fileName}`;
719
+ /**
720
+ * Remove the file from the app directory.
721
+ */
722
+ const clearFile = () => __awaiter(void 0, void 0, void 0, function* () {
723
+ const fileExists = yield exists(fileUri);
724
+ if (fileExists) {
725
+ yield unlink(fileUri);
726
+ }
727
+ });
728
+ /**
729
+ * Remove the file from the app directory if it exists.
730
+ */
731
+ yield clearFile();
732
+ try {
733
+ yield writeFile(fileUri, base64Content, {
734
+ encoding: 'base64',
735
+ mimeType
736
+ });
737
+ yield saveDocuments({
738
+ copy: false,
739
+ fileName,
740
+ mimeType,
741
+ sourceUris: [fileUri]
742
+ });
743
+ } finally {
744
+ /**
745
+ * Remove the file after it has been saved
746
+ */
747
+ yield clearFile();
748
+ }
749
+ }));
750
+ // Handle incoming deep links (e.g., wallet redirect flows like Phantom)
751
+ const handleIncomingUrl = url => {
752
+ log('handleIncomingUrl called', {
753
+ hasUrl: Boolean(url),
754
+ url,
755
+ urlParams: url ? new URL(url).searchParams.toString() : null
756
+ });
757
+ if (url) {
758
+ platformChannel.emit('incomingUrl', url);
759
+ }
760
+ };
761
+ getInitialURL().then(url => {
762
+ log('getInitialURL resolved', {
763
+ url
764
+ });
765
+ handleIncomingUrl(url);
766
+ });
767
+ addEventListener('url', ({
768
+ url
769
+ }) => {
770
+ log('addEventListener url event', {
771
+ url
772
+ });
773
+ handleIncomingUrl(url);
774
+ });
775
+ };
776
+
777
+ const assertValidSource = source => {
778
+ if (source !== 'secureStorage') {
779
+ throw new Error(`Invalid storage source "${source}"`);
780
+ }
781
+ };
782
+ const setupStorageHandler = core => {
783
+ const storageRequestChannel = createRequestChannel(core.messageTransport);
784
+ storageRequestChannel.handle('getItem', _a => __awaiter(void 0, [_a], void 0, function* ({
785
+ key,
786
+ source
787
+ }) {
788
+ assertValidSource(source);
789
+ const stored = yield getGenericPassword({
790
+ service: key
791
+ });
792
+ return stored ? stored.password : null;
793
+ }));
794
+ storageRequestChannel.handle('deleteItem', _b => __awaiter(void 0, [_b], void 0, function* ({
795
+ key,
796
+ source
797
+ }) {
798
+ assertValidSource(source);
799
+ yield resetGenericPassword({
800
+ service: key
801
+ });
802
+ }));
803
+ storageRequestChannel.handle('setItem', _c => __awaiter(void 0, [_c], void 0, function* ({
804
+ key,
805
+ data,
806
+ source
807
+ }) {
808
+ assertValidSource(source);
809
+ yield setGenericPassword(key, data, {
810
+ service: key
811
+ });
812
+ }));
813
+ };
814
+
815
+ const setupTurnkeyPasskeyHandler = core => {
816
+ const turnkeyPasskeysRequestChannel = createRequestChannel(core.messageTransport);
817
+ turnkeyPasskeysRequestChannel.handle('createPasskey', _a => __awaiter(void 0, [_a], void 0, function* ({
818
+ publicKey
819
+ }) {
820
+ try {
821
+ const {
822
+ attestation
823
+ } = yield createPasskey(publicKey);
824
+ return {
825
+ attestation
826
+ };
827
+ } catch (err) {
828
+ logger.error(err);
829
+ throw err;
830
+ }
831
+ }));
832
+ turnkeyPasskeysRequestChannel.handle('passkeyStamp', (rpId, payload) => __awaiter(void 0, void 0, void 0, function* () {
833
+ try {
834
+ const stamper = new PasskeyStamper({
835
+ rpId
836
+ });
837
+ const stamped = yield stamper.stamp(payload);
838
+ return stamped;
839
+ } catch (err) {
840
+ logger.error(err);
841
+ throw err;
842
+ }
843
+ }));
844
+ };
845
+
846
+ const setupKeychainHandler = core => {
847
+ const keychainRequestChannel = createRequestChannel(core.messageTransport);
848
+ const keychain = getKeychain();
849
+ keychainRequestChannel.handle('keychain_isAvailable', () => __awaiter(void 0, void 0, void 0, function* () {
850
+ return keychain.isAvailable();
851
+ }));
852
+ keychainRequestChannel.handle('keychain_hasKey', _a => __awaiter(void 0, [_a], void 0, function* ({
853
+ key
854
+ }) {
855
+ return keychain.hasKey(key);
856
+ }));
857
+ keychainRequestChannel.handle('keychain_generateKey', _b => __awaiter(void 0, [_b], void 0, function* ({
858
+ key
859
+ }) {
860
+ return keychain.generateKeyPair(key);
861
+ }));
862
+ keychainRequestChannel.handle('keychain_getPublicKey', _c => __awaiter(void 0, [_c], void 0, function* ({
863
+ key
864
+ }) {
865
+ return keychain.getPublicKey(key);
866
+ }));
867
+ keychainRequestChannel.handle('keychain_sign', _d => __awaiter(void 0, [_d], void 0, function* ({
868
+ key,
869
+ payload
870
+ }) {
871
+ return keychain.sign(key, payload);
872
+ }));
873
+ keychainRequestChannel.handle('keychain_removeKey', _e => __awaiter(void 0, [_e], void 0, function* ({
874
+ key
875
+ }) {
876
+ return keychain.deleteKey(key);
877
+ }));
878
+ };
879
+
880
+ const defaultWebviewUrl = `https://webview.dynamicauth.com/${version}`;
881
+ // The native webview singleton outlives the JS bridge, so a re-invocation
882
+ // of the extension factory (e.g. when the consumer recreates the client
883
+ // with a new environmentId) would otherwise stack JS-side listeners on top
884
+ // of the prior ones. We retain the previous teardown at module scope and
885
+ // run it before wiring the next bridge.
886
+ let previousEmbeddedWebViewTeardown = null;
887
+ const ReactNativeExtension = ({
888
+ webviewUrl: _webviewUrl = defaultWebviewUrl,
889
+ webviewDebuggingEnabled,
890
+ appOrigin,
891
+ embeddedWebView: _embeddedWebView = false,
892
+ webviewLoad
893
+ } = {}) => (_, core) => {
894
+ const isPlatformSupportedByWebView = Platform.OS === 'android' || Platform.OS === 'ios';
895
+ /**
896
+ * If react-native-webview does not supported it will return
897
+ * a dummy webview component so it does not break expo for web
898
+ */
899
+ if (!isPlatformSupportedByWebView) {
900
+ return {
901
+ reactNative: {
902
+ WebView: () => null
903
+ }
904
+ };
905
+ }
906
+ // The embedded webview / keychain modules were introduced mid-version, so
907
+ // an over-the-air JS update can run on an older binary that predates them.
908
+ // Resolve availability once, here, and reuse it for both telemetry and the
909
+ // path-selection gate below. (We are past the web early-return, so the
910
+ // native resolvers only ever run on iOS / Android.)
911
+ const embeddedWebViewAvailable = isEmbeddedWebViewAvailable();
912
+ const keychainAvailable = isKeychainAvailable();
913
+ logNativeModuleAvailability({
914
+ core,
915
+ embeddedWebView: _embeddedWebView,
916
+ embeddedWebViewAvailable,
917
+ keychainAvailable
918
+ });
919
+ if (appOrigin) core.manifest.setAppOrigin(appOrigin);
920
+ setupPasskeyHandler(core);
921
+ setupTurnkeyPasskeyHandler(core);
922
+ setupPlatformHandler(core);
923
+ setupStorageHandler(core);
924
+ setupKeychainHandler(core);
925
+ // Native overlay-webview path (iOS WKWebView / Android android.webkit
926
+ // .WebView). When the native module isn't linked — e.g. an OTA JS update on
927
+ // an older binary that predates it — fall through to the
928
+ // react-native-webview path instead of wiring a bridge to a missing module
929
+ // (which would hang silently).
930
+ const useNativeEmbeddedWebView = _embeddedWebView && embeddedWebViewAvailable;
931
+ if (useNativeEmbeddedWebView) {
932
+ // The native WKWebView lives in its own UIWindow, outside the React
933
+ // tree. Wire the JS bridge once at extension construction and hand the
934
+ // consumer a no-op component so its render never touches the webview.
935
+ if (previousEmbeddedWebViewTeardown) {
936
+ previousEmbeddedWebViewTeardown();
937
+ previousEmbeddedWebViewTeardown = null;
938
+ }
939
+ try {
940
+ previousEmbeddedWebViewTeardown = setupEmbeddedWebView({
941
+ core,
942
+ webviewDebuggingEnabled,
943
+ webviewLoad,
944
+ webviewUrl: _webviewUrl
945
+ });
946
+ } catch (err) {
947
+ // Setup failed — leave the slot empty so the next invocation isn't
948
+ // wedged with a stale teardown reference. The error itself is left
949
+ // to bubble: the consumer needs to see that the bridge isn't wired.
950
+ previousEmbeddedWebViewTeardown = null;
951
+ throw err;
952
+ }
953
+ return {
954
+ reactNative: {
955
+ WebView: () => null
956
+ }
957
+ };
958
+ }
959
+ return {
960
+ reactNative: {
961
+ WebView: createWebView({
962
+ core,
963
+ webviewDebuggingEnabled,
964
+ webviewLoad,
965
+ webviewUrl: _webviewUrl
966
+ })
967
+ }
968
+ };
969
+ };
970
+
971
+ assertPackageVersion('@dynamic-labs/legacy-react-native-extension', version);
972
+
973
+ export { ReactNativeExtension };