react-native-minimal-webview 0.0.0-stage → 1.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 (118) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +130 -2
  3. package/android/build.gradle +26 -0
  4. package/android/consumer-rules.pro +4 -0
  5. package/android/src/main/AndroidManifest.xml +2 -0
  6. package/android/src/main/java/expo/modules/minimalwebview/Asks.kt +44 -0
  7. package/android/src/main/java/expo/modules/minimalwebview/DocumentEnd.kt +31 -0
  8. package/android/src/main/java/expo/modules/minimalwebview/Hooks.kt +496 -0
  9. package/android/src/main/java/expo/modules/minimalwebview/MinimalWebView.kt +510 -0
  10. package/android/src/main/java/expo/modules/minimalwebview/MinimalWebViewClients.kt +359 -0
  11. package/android/src/main/java/expo/modules/minimalwebview/MinimalWebViewModule.kt +245 -0
  12. package/android/src/main/java/expo/modules/minimalwebview/MinimalWebViewNavigation.kt +199 -0
  13. package/android/src/main/java/expo/modules/minimalwebview/MinimalWebViewScripts.kt +191 -0
  14. package/android/src/main/java/expo/modules/minimalwebview/NavigationRules.kt +113 -0
  15. package/android/src/main/java/expo/modules/minimalwebview/PlatformSettings.kt +306 -0
  16. package/android/src/main/java/expo/modules/minimalwebview/PullToRefresh.kt +76 -0
  17. package/android/src/main/java/expo/modules/minimalwebview/requests/Downloads.kt +258 -0
  18. package/android/src/main/java/expo/modules/minimalwebview/requests/FileUpload.kt +44 -0
  19. package/android/src/main/java/expo/modules/minimalwebview/requests/FullscreenVideo.kt +87 -0
  20. package/android/src/main/java/expo/modules/minimalwebview/requests/Permissions.kt +77 -0
  21. package/build/WebView.d.ts +99 -0
  22. package/build/WebView.d.ts.map +1 -0
  23. package/build/WebView.js +448 -0
  24. package/build/WebView.js.map +1 -0
  25. package/build/bridge/createBridge.d.ts +32 -0
  26. package/build/bridge/createBridge.d.ts.map +1 -0
  27. package/build/bridge/createBridge.js +135 -0
  28. package/build/bridge/createBridge.js.map +1 -0
  29. package/build/bridge/endpoint.d.ts +35 -0
  30. package/build/bridge/endpoint.d.ts.map +1 -0
  31. package/build/bridge/endpoint.js +100 -0
  32. package/build/bridge/endpoint.js.map +1 -0
  33. package/build/bridge/origins.d.ts +25 -0
  34. package/build/bridge/origins.d.ts.map +1 -0
  35. package/build/bridge/origins.js +60 -0
  36. package/build/bridge/origins.js.map +1 -0
  37. package/build/bridge/pageClient.generated.d.ts +3 -0
  38. package/build/bridge/pageClient.generated.d.ts.map +1 -0
  39. package/build/bridge/pageClient.generated.js +4 -0
  40. package/build/bridge/pageClient.generated.js.map +1 -0
  41. package/build/bridge/protocol.d.ts +50 -0
  42. package/build/bridge/protocol.d.ts.map +1 -0
  43. package/build/bridge/protocol.js +52 -0
  44. package/build/bridge/protocol.js.map +1 -0
  45. package/build/defaultNavigationRules.d.ts +16 -0
  46. package/build/defaultNavigationRules.d.ts.map +1 -0
  47. package/build/defaultNavigationRules.js +23 -0
  48. package/build/defaultNavigationRules.js.map +1 -0
  49. package/build/index.d.ts +31 -0
  50. package/build/index.d.ts.map +1 -0
  51. package/build/index.js +30 -0
  52. package/build/index.js.map +1 -0
  53. package/build/platform.generated.d.ts +702 -0
  54. package/build/platform.generated.d.ts.map +1 -0
  55. package/build/platform.generated.js +199 -0
  56. package/build/platform.generated.js.map +1 -0
  57. package/build/reactNativeWebViewDefaults.d.ts +21 -0
  58. package/build/reactNativeWebViewDefaults.d.ts.map +1 -0
  59. package/build/reactNativeWebViewDefaults.js +12 -0
  60. package/build/reactNativeWebViewDefaults.js.map +1 -0
  61. package/build/reactNativeWebViewMessages.d.ts +22 -0
  62. package/build/reactNativeWebViewMessages.d.ts.map +1 -0
  63. package/build/reactNativeWebViewMessages.js +30 -0
  64. package/build/reactNativeWebViewMessages.js.map +1 -0
  65. package/build/refStore.d.ts +31 -0
  66. package/build/refStore.d.ts.map +1 -0
  67. package/build/refStore.js +113 -0
  68. package/build/refStore.js.map +1 -0
  69. package/build/types.d.ts +1127 -0
  70. package/build/types.d.ts.map +1 -0
  71. package/build/types.defaults.d.ts +8 -0
  72. package/build/types.defaults.d.ts.map +1 -0
  73. package/build/types.defaults.js +17 -0
  74. package/build/types.defaults.js.map +1 -0
  75. package/build/types.js +2 -0
  76. package/build/types.js.map +1 -0
  77. package/expo-module.config.json +9 -0
  78. package/ios/Asks.swift +45 -0
  79. package/ios/DelegateProxy.swift +162 -0
  80. package/ios/DocumentEnd.swift +23 -0
  81. package/ios/DownloadName.swift +12 -0
  82. package/ios/Downloads.swift +51 -0
  83. package/ios/Hooks.swift +308 -0
  84. package/ios/Loads.swift +44 -0
  85. package/ios/MRWExceptions.h +9 -0
  86. package/ios/MRWExceptions.m +10 -0
  87. package/ios/MRWInvoke.h +23 -0
  88. package/ios/MRWInvoke.m +187 -0
  89. package/ios/MinimalWebView+Dialogs.swift +99 -0
  90. package/ios/MinimalWebView+Navigation.swift +244 -0
  91. package/ios/MinimalWebView+Scripts.swift +92 -0
  92. package/ios/MinimalWebView.docc/MinimalWebView.md +13 -0
  93. package/ios/MinimalWebView.podspec +32 -0
  94. package/ios/MinimalWebView.swift +512 -0
  95. package/ios/MinimalWebViewModule.swift +110 -0
  96. package/ios/NavigationRules.swift +123 -0
  97. package/ios/OriginRules.swift +35 -0
  98. package/ios/PlatformCompletions.generated.swift +39 -0
  99. package/ios/PlatformSettings.swift +247 -0
  100. package/ios/ReadAccess.swift +19 -0
  101. package/ios/Recovery.swift +25 -0
  102. package/ios/SharedCookies.swift +59 -0
  103. package/package.json +94 -4
  104. package/src/WebView.tsx +623 -0
  105. package/src/bridge/createBridge.ts +176 -0
  106. package/src/bridge/endpoint.ts +119 -0
  107. package/src/bridge/origins.ts +62 -0
  108. package/src/bridge/pageClient.generated.ts +5 -0
  109. package/src/bridge/pageClient.ts +68 -0
  110. package/src/bridge/protocol.ts +78 -0
  111. package/src/defaultNavigationRules.ts +25 -0
  112. package/src/index.ts +37 -0
  113. package/src/platform.generated.ts +694 -0
  114. package/src/reactNativeWebViewDefaults.ts +13 -0
  115. package/src/reactNativeWebViewMessages.ts +32 -0
  116. package/src/refStore.ts +164 -0
  117. package/src/types.defaults.ts +24 -0
  118. package/src/types.ts +1194 -0
@@ -0,0 +1,199 @@
1
+ package expo.modules.minimalwebview
2
+
3
+ import android.content.ActivityNotFoundException
4
+ import android.content.Intent
5
+ import android.net.Uri
6
+ import android.os.FileUriExposedException
7
+ import android.os.Message
8
+ import android.util.Log
9
+ import android.webkit.RenderProcessGoneDetail
10
+ import android.webkit.WebResourceRequest
11
+ import android.webkit.WebView
12
+ import android.webkit.WebViewClient
13
+ import java.net.URISyntaxException
14
+
15
+ /** Navigation decisions: the rules, `ask`, external links and new windows. */
16
+ internal class MinimalWebViewNavigation(
17
+ private val owner: MinimalWebView,
18
+ private val onNavigation: (Map<String, Any?>) -> Unit
19
+ ) {
20
+ private val webView get() = owner.webView
21
+
22
+ // URLs an `ask` allowed in this Document: a redirect back to one is not asked again (a later tap on it is).
23
+ private val askedAndAllowed = mutableSetOf<String>()
24
+
25
+ // New windows still waiting for their first URL (createWindow).
26
+ private val children = mutableSetOf<WebView>()
27
+
28
+ fun documentEnded() {
29
+ askedAndAllowed.clear()
30
+ // Not on a child's stack (a commit, a crash, destroy): destroy them now. Cleared first, so a finish() finds none.
31
+ val ended = children.toList()
32
+ children.clear()
33
+ ended.forEach { it.destroy() }
34
+ }
35
+
36
+ /** Returns true to cancel the navigation (shouldOverrideUrlLoading's meaning). */
37
+ fun decide(request: NavigationRules.Request): Boolean {
38
+ val asked = if (request.isRedirect) askedAndAllowed else emptySet()
39
+ val decision = NavigationRules.decide(owner.navigationRules, request, asked, "onNavigationRequest" in owner.requestHandlers)
40
+ val action = if (decision.action == "ask" && !request.mainFrame) {
41
+ // Android can't hold a navigation, so `ask` cancels and reissues it: a subframe's can't be reissued.
42
+ Log.w(TAG, "`ask` only works for main-frame navigations on Android; blocked ${request.url}")
43
+ "block"
44
+ } else {
45
+ decision.action
46
+ }
47
+ if (action == "ask") {
48
+ ask(request, decision.rule)
49
+ return true
50
+ }
51
+ if (action == "external") {
52
+ openExternal(request, decision.rule)
53
+ return true
54
+ }
55
+ notifyNavigation(request, action, decision.rule)
56
+ return action != "allow"
57
+ }
58
+
59
+ private fun fields(request: NavigationRules.Request) = mapOf(
60
+ "url" to request.url,
61
+ "mainFrame" to request.mainFrame,
62
+ "newWindow" to request.newWindow,
63
+ "userInitiated" to request.userInitiated
64
+ )
65
+
66
+ private fun notifyNavigation(request: NavigationRules.Request, action: String, rule: Int?) {
67
+ if ("onNavigation" in owner.requestHandlers) onNavigation(fields(request) + mapOf("action" to action, "rule" to rule))
68
+ }
69
+
70
+ // Cancel now, ask JS, reissue on allow. Never blocks the UI thread. Loses the gesture flag and the redirect chain.
71
+ private fun ask(request: NavigationRules.Request, rule: Int?) {
72
+ val referrer = webView.url
73
+ val id = owner.asks.ask("core", "onNavigationRequest", fields(request)) { answer ->
74
+ val action = NavigationRules.answer(answer)
75
+ if (action == "allow") {
76
+ askedAndAllowed += request.url
77
+ reissue(request.url, referrer)
78
+ }
79
+ if (action == "external") openExternal(request, rule) else notifyNavigation(request, action, rule)
80
+ }
81
+ // Unanswered after the timeout: block (the answer callback runs with null). A late answer finds nothing.
82
+ owner.mainHandler.postDelayed({ owner.asks.cancel(id) }, ASK_TIMEOUT_MS)
83
+ }
84
+
85
+ // WebView's request headers on a navigation are empty, so the page's URL goes as the referrer. WebView applies its
86
+ // default policy to it (origin only cross-origin, none from https to http); the page's own referrer policy is lost.
87
+ // loadUrl skips shouldOverrideUrlLoading, so the reissued URL isn't asked again (its redirects still go to decide).
88
+ private fun reissue(url: String, referrer: String?) = webView.loadUrl(url, referrer?.let { mapOf("Referer" to it) }.orEmpty())
89
+
90
+ /** A download no `onDownload` takes. */
91
+ fun openDownload(url: String) {
92
+ if (url.startsWith("http:") || url.startsWith("https:")) {
93
+ openExternal(NavigationRules.Request(url, true, false, false), null)
94
+ } else {
95
+ Log.w(TAG, "dropped a download from ${url.take(40)}")
96
+ }
97
+ }
98
+
99
+ /**
100
+ * Opens an `external` navigation and reports it (`block` when nothing opened it): the app's `onOpenExternal` if set,
101
+ * and [open] when it isn't or answers false.
102
+ */
103
+ private fun openExternal(request: NavigationRules.Request, rule: Int?) {
104
+ val report = { opened: Boolean -> notifyNavigation(request, if (opened) "external" else "block", rule) }
105
+ if ("onOpenExternal" !in owner.requestHandlers) return report(open(request.url))
106
+ // A page that moved on first answers null, which counts as opened. No timeout: nothing waits for the answer.
107
+ owner.asks.ask("core", "onOpenExternal", fields(request)) { answer ->
108
+ report(answer != false || open(request.url))
109
+ }
110
+ }
111
+
112
+ /**
113
+ * Opens a URL outside the WebView. Returns false when it could not be opened (the caller reports `block`): a page
114
+ * controls the URL, so a malformed intent (bad syntax, launchFlags=zz), a refused activity or a `file:` URL (which
115
+ * Android refuses to hand to another app) must not crash the app.
116
+ */
117
+ private fun open(url: String): Boolean {
118
+ val intent = try {
119
+ browsableIntent(url)
120
+ } catch (e: URISyntaxException) {
121
+ return failed("malformed external URL $url", e)
122
+ } catch (e: IllegalArgumentException) {
123
+ return failed("malformed external URL $url", e)
124
+ }
125
+ return try {
126
+ owner.context.startActivity(intent)
127
+ true
128
+ } catch (e: ActivityNotFoundException) {
129
+ openFallback(intent, url, e)
130
+ } catch (e: SecurityException) {
131
+ failed("not allowed to open $url", e)
132
+ } catch (e: FileUriExposedException) {
133
+ failed("not allowed to open $url", e)
134
+ }
135
+ }
136
+
137
+ /** Only what a browser would allow: BROWSABLE, no explicit component or selector, and no URI permission grants. */
138
+ private fun browsableIntent(url: String): Intent {
139
+ val intent = if (url.startsWith("intent:", ignoreCase = true)) {
140
+ Intent.parseUri(url, Intent.URI_INTENT_SCHEME).apply {
141
+ component = null
142
+ selector = null
143
+ }
144
+ } else {
145
+ Intent(Intent.ACTION_VIEW, Uri.parse(url))
146
+ }
147
+ intent.addCategory(Intent.CATEGORY_BROWSABLE)
148
+ intent.flags = Intent.FLAG_ACTIVITY_NEW_TASK
149
+ return intent
150
+ }
151
+
152
+ // No app for the link: an intent may name a web fallback, as Chrome supports. It goes through the rules like any
153
+ // other navigation. Otherwise nothing happens.
154
+ private fun openFallback(intent: Intent, url: String, error: ActivityNotFoundException): Boolean {
155
+ val fallback = intent.getStringExtra("browser_fallback_url")?.takeIf { it.startsWith("https://") || it.startsWith("http://") }
156
+ ?: return failed("no app opens $url", error)
157
+ if (!decide(NavigationRules.Request(fallback, true, false, false))) webView.loadUrl(fallback)
158
+ // Nothing opened externally: the intent is reported as blocked, the fallback by its own decision.
159
+ return false
160
+ }
161
+
162
+ // Never a second WebView: a popup model is more than almost any app wants, so a throwaway one only catches the URL.
163
+ fun createWindow(isUserGesture: Boolean, resultMsg: Message): Boolean {
164
+ val child = WebView(owner.context)
165
+ // It only catches a URL: none of the page's access, and no JS of its own.
166
+ child.settings.allowFileAccess = false
167
+ child.settings.allowContentAccess = false
168
+ child.settings.javaScriptEnabled = false
169
+ children += child
170
+ // Finishes once, whichever comes first: the first URL, the timeout, a crash, the Document's end (documentEnded).
171
+ // Destroyed later: this may run inside the child's own callback.
172
+ fun finish(): Boolean {
173
+ val wasPending = children.remove(child)
174
+ if (wasPending) owner.mainHandler.post { child.destroy() }
175
+ return wasPending
176
+ }
177
+ child.webViewClient = object : WebViewClient() {
178
+ // A renderer crash in the throwaway window must not take the app down.
179
+ override fun onRenderProcessGone(view: WebView, detail: RenderProcessGoneDetail): Boolean {
180
+ finish()
181
+ return true
182
+ }
183
+
184
+ override fun shouldOverrideUrlLoading(view: WebView, request: WebResourceRequest): Boolean {
185
+ val target = request.url.toString()
186
+ if (finish() && !decide(NavigationRules.Request(target, true, true, isUserGesture))) reissue(target, webView.url)
187
+ return true
188
+ }
189
+ }
190
+ // window.open('') or about:blank never navigates: give up on it.
191
+ owner.mainHandler.postDelayed({ finish() }, NEW_WINDOW_TIMEOUT_MS)
192
+ (resultMsg.obj as WebView.WebViewTransport).webView = child
193
+ resultMsg.sendToTarget()
194
+ return true
195
+ }
196
+ }
197
+
198
+ private const val ASK_TIMEOUT_MS = 1000L
199
+ private const val NEW_WINDOW_TIMEOUT_MS = 5000L
@@ -0,0 +1,191 @@
1
+ package expo.modules.minimalwebview
2
+
3
+ import androidx.webkit.JavaScriptReplyProxy
4
+ import androidx.webkit.ScriptHandler
5
+ import androidx.webkit.WebMessageCompat
6
+ import androidx.webkit.WebViewCompat
7
+ import androidx.webkit.WebViewFeature
8
+ import expo.modules.kotlin.exception.CodedException
9
+ import org.json.JSONArray
10
+
11
+ /** Scripts in the page: the bridge transport, `injectedScripts` and `evaluate`. */
12
+ internal class MinimalWebViewScripts(private val owner: MinimalWebView, private val onBridge: (Map<String, Any?>) -> Unit) {
13
+ private val webView get() = owner.webView
14
+
15
+ // Bridge: the page posts through `window.nativeBridgeTransport`; replies go to the main frame's latest proxy.
16
+ private var replyProxy: JavaScriptReplyProxy? = null
17
+ private var installedScripts: List<InjectedScript>? = null
18
+ private val scriptHandlers = mutableListOf<ScriptHandler>()
19
+ private val evaluations = Evaluations()
20
+
21
+ /**
22
+ * Installs everything into a new WebView, the first or the one after a crash. The evaluate channel and the bridge go
23
+ * in only here: JS fixes `bridge` at mount.
24
+ */
25
+ fun install() {
26
+ // After a crash they are the destroyed WebView's: removing them would call into it.
27
+ scriptHandlers.clear()
28
+ installEvaluate()
29
+ installBridge()
30
+ installScripts(force = true)
31
+ }
32
+
33
+ /** A later prop batch: only `injectedScripts` can change. */
34
+ fun update() = installScripts()
35
+
36
+ private fun installBridge() {
37
+ val script = owner.bridgeScript ?: return
38
+ val bridgeFeatures = listOf(WebViewFeature.WEB_MESSAGE_LISTENER, WebViewFeature.DOCUMENT_START_SCRIPT)
39
+ if (lacks("bridge", bridgeFeatures, "bridge calls reject with `unavailable`")) {
40
+ onBridge(mapOf("unavailable" to true))
41
+ return
42
+ }
43
+ val origins = owner.bridgeOrigins.orEmpty().toSet()
44
+ // A malformed origin rule makes WebView throw; createBridge validates them, so this only guards against misuse.
45
+ // JS learns of it: calls reject with `unavailable`.
46
+ try {
47
+ WebViewCompat.addWebMessageListener(webView, "nativeBridgeTransport", origins) { _, message, sourceOrigin, isMainFrame, proxy ->
48
+ // Main frame only, like iOS. The origin rules already filtered the sender; its origin goes to the handlers.
49
+ if (!isMainFrame) return@addWebMessageListener
50
+ // An ArrayBuffer has no string data (`data` throws); iOS drops a non-string message too.
51
+ if (message.type != WebMessageCompat.TYPE_STRING) return@addWebMessageListener
52
+ replyProxy = proxy
53
+ onBridge(mapOf("message" to message.data, "origin" to sourceOrigin.toString()))
54
+ }
55
+ // Runs before the page's own scripts, after the transport object exists.
56
+ WebViewCompat.addDocumentStartJavaScript(webView, script, origins)
57
+ } catch (e: IllegalArgumentException) {
58
+ failed("bridge not installed: invalid allowedOrigins $origins", e)
59
+ onBridge(mapOf("unavailable" to true))
60
+ }
61
+ }
62
+
63
+ /** Changed scripts take effect from the next navigation. */
64
+ private fun installScripts(force: Boolean = false) {
65
+ val scripts = owner.injectedScripts.orEmpty()
66
+ if (!force && scripts == installedScripts) return
67
+ installedScripts = scripts
68
+ scriptHandlers.forEach { it.remove() }
69
+ scriptHandlers.clear()
70
+ if (scripts.isEmpty() || lacks("injectedScripts", listOf(WebViewFeature.DOCUMENT_START_SCRIPT), "injected scripts don't run")) return
71
+ for (script in scripts) {
72
+ val code = script.code ?: continue
73
+ // No frame selector in androidx.webkit 1.17: main-frame-only scripts guard themselves.
74
+ // A prefix, not a wrapping block: top-level const/let/class in the script must stay global.
75
+ val source = if (script.allFrames != true) "if (window !== window.top) throw 0;\n$code" else code
76
+ scriptHandlers += WebViewCompat.addDocumentStartJavaScript(webView, source, setOf("*"))
77
+ }
78
+ }
79
+
80
+ fun post(message: String) {
81
+ replyProxy?.postMessage(message)
82
+ }
83
+
84
+ /** The Document ended: its evaluations fail and its reply proxy is gone. JS queues bridge messages until the next
85
+ * page is ready; at unmount it rejects what is in flight itself. */
86
+ fun documentEnded(reason: DocumentEnd) {
87
+ evaluations.failAll()
88
+ // At a commit this runs one main-thread hop after Chromium's (the NavigationListener's executor posts it), and
89
+ // relies on landing before the new page's first message sets replyProxy (the bridge suite's head-script call).
90
+ replyProxy = null
91
+ if (reason != DocumentEnd.CLOSING && owner.bridgeScript != null) onBridge(mapOf("navigated" to true))
92
+ }
93
+
94
+ /** `evaluate` results come back through one global in every frame (`*`, before the first document); only the main
95
+ * frame's replies count. A page can forge them, as it can already shape any value its own world returns. */
96
+ private fun installEvaluate() {
97
+ if (!WebViewFeature.isFeatureSupported(WebViewFeature.WEB_MESSAGE_LISTENER)) return
98
+ WebViewCompat.addWebMessageListener(webView, EVALUATE, setOf("*")) { _, message, _, isMainFrame, _ ->
99
+ // An ArrayBuffer has no string data (`data` throws).
100
+ if (message.type == WebMessageCompat.TYPE_STRING) evaluations.settle(message.data, isMainFrame)
101
+ }
102
+ }
103
+
104
+ /** The `evaluate` ref method. A new document rejects what is still waiting: WebView drops the callback when the
105
+ * document is replaced first. */
106
+ fun evaluate(script: String, onResult: (Result<String>) -> Unit) {
107
+ if (!WebViewFeature.isFeatureSupported(WebViewFeature.WEB_MESSAGE_LISTENER)) {
108
+ return onResult(failure("unavailable", "evaluate needs WEB_MESSAGE_LISTENER; update Android System WebView"))
109
+ }
110
+ val id = evaluations.add(onResult)
111
+ // The script sits in a scope of its own (no wrapper names shadow the page's); the sync value is 1 once it started.
112
+ val code = """typeof $EVALUATE === 'object' ? ((t, p) => (p.then(
113
+ (v) => { try { v = JSON.stringify(v) } catch { v = null } t.postMessage(JSON.stringify([$id, v ?? 'null'])) },
114
+ (e) => { try { e = String(e) } catch { e = 'Error' } t.postMessage(JSON.stringify([$id, null, e])) }
115
+ ), 1))($EVALUATE, (async () => (
116
+ $script
117
+ ))()) : 0"""
118
+ webView.evaluateJavascript(code) { value ->
119
+ if (value == "1") return@evaluateJavascript
120
+ // 0: the page has no channel (it loaded before the listener); null: the script didn't parse.
121
+ evaluations.fail(id, if (value == "0") "no evaluate channel in this page" else "the script did not run (a syntax error?)")
122
+ }
123
+ }
124
+
125
+ /** Whether this device's WebView lacks one of [features] that [prop] needs; warns about it once per process. */
126
+ private fun lacks(prop: String, features: List<String>, lost: String): Boolean {
127
+ val missing = features.filterNot(WebViewFeature::isFeatureSupported)
128
+ if (missing.isEmpty()) return false
129
+ if (warnedProps.add(prop)) {
130
+ val provider = WebViewCompat.getCurrentWebViewPackage(owner.context)
131
+ owner.warn(
132
+ "$prop needs WebView features ${missing.joinToString()}, missing in ${provider?.packageName} ${provider?.versionName}: $lost. " +
133
+ "Update Android System WebView."
134
+ )
135
+ }
136
+ return true
137
+ }
138
+
139
+ private companion object {
140
+ val warnedProps = mutableSetOf<String>()
141
+ }
142
+ }
143
+
144
+ /**
145
+ * The `evaluate` calls waiting for their result, by id. Each settles once: by the page's reply, a script that didn't
146
+ * run, or the Document's end. Main thread only.
147
+ */
148
+ internal class Evaluations {
149
+ private val waiting = mutableMapOf<Int, (Result<String>) -> Unit>()
150
+ private var next = 0
151
+
152
+ /** Keeps [onResult] until its evaluation settles; returns the id the page's reply carries. */
153
+ fun add(onResult: (Result<String>) -> Unit): Int {
154
+ val id = next++
155
+ waiting[id] = onResult
156
+ return id
157
+ }
158
+
159
+ /**
160
+ * The page's [reply], `[id, valueJson]` or `[id, null, errorMessage]`, settles evaluation `id` with the value or a
161
+ * `script_error`. Only the main frame's replies count; a malformed one, or one for an id not waiting, is dropped.
162
+ */
163
+ fun settle(reply: String?, mainFrame: Boolean) {
164
+ if (!mainFrame) return
165
+ val parts = runCatching { JSONArray(reply) }.getOrNull() ?: return
166
+ val onResult = waiting.remove(parts.optInt(0, -1)) ?: return
167
+ onResult(
168
+ if (parts.length() > 2) failure("script_error", parts.optString(2))
169
+ else Result.success(parts.optString(1, "null"))
170
+ )
171
+ }
172
+
173
+ /** The script didn't run: evaluation [id] fails with a `script_error` saying [why], unless it settled already. */
174
+ fun fail(id: Int, why: String) {
175
+ waiting.remove(id)?.invoke(failure("script_error", why))
176
+ }
177
+
178
+ /** The Document ended: every waiting evaluation fails with `navigated`. */
179
+ fun failAll() {
180
+ val all = waiting.values.toList()
181
+ waiting.clear()
182
+ all.forEach { it(failure("navigated", "the page navigated before the script finished")) }
183
+ }
184
+ }
185
+
186
+ /** Why an `evaluate` failed; its code is the JS error code (`script_error`, `navigated`, `unavailable`). */
187
+ internal class EvaluateError(code: String, message: String) : CodedException(code, message, null)
188
+
189
+ private fun failure(code: String, message: String) = Result.failure<String>(EvaluateError(code, message))
190
+
191
+ private const val EVALUATE = "nativeEvaluateResult"
@@ -0,0 +1,113 @@
1
+ package expo.modules.minimalwebview
2
+
3
+ /** The structured navigation rules. Semantics and cases: src/__tests__/vectors/navigation-rules.json (shared with Swift). */
4
+ internal object NavigationRules {
5
+ data class Request(
6
+ val url: String,
7
+ val mainFrame: Boolean,
8
+ val newWindow: Boolean,
9
+ val userInitiated: Boolean,
10
+ val isRedirect: Boolean = false
11
+ )
12
+
13
+ /** [action] is allow, block, external or ask; [rule] is the matching rule's index, null when a default decided. */
14
+ data class Decision(val action: String, val rule: Int?)
15
+
16
+ /** Load in place without the rules. */
17
+ private val internalSchemes = setOf("about", "data", "javascript")
18
+
19
+ /**
20
+ * Never open as a new window, whatever the rules say: the core loads an allowed new window in the main frame itself,
21
+ * past the engine's limits on what a page may navigate the top frame to.
22
+ */
23
+ private val noNewWindowSchemes = internalSchemes + setOf("blob", "file")
24
+ private val actions = setOf("allow", "block", "external", "ask")
25
+ private val answers = setOf("allow", "block", "external")
26
+
27
+ /**
28
+ * The rules' decision, gated for `ask`: blocked when nothing can answer it ([canAsk] false), allowed when its URL is
29
+ * in [asked] (URLs an `ask` already allowed). An unknown rule action blocks.
30
+ */
31
+ fun decide(rules: List<Map<String, Any?>>?, request: Request, asked: Set<String>, canAsk: Boolean): Decision {
32
+ val decision = match(rules, request)
33
+ return when {
34
+ decision.action != "ask" -> decision
35
+ !canAsk -> Decision("block", decision.rule)
36
+ request.url in asked -> Decision("allow", decision.rule)
37
+ else -> decision
38
+ }
39
+ }
40
+
41
+ /** An `ask` answer: allow, block or external; anything else (null on a timeout) blocks. */
42
+ fun answer(value: Any?): String = (value as? String)?.takeIf { it in answers } ?: "block"
43
+
44
+ private fun match(rules: List<Map<String, Any?>>?, request: Request): Decision {
45
+ val scheme = request.url.substringBefore(':', "").lowercase()
46
+ if (request.newWindow && scheme in noNewWindowSchemes) return Decision("block", null)
47
+ if (scheme in internalSchemes) return Decision("allow", null)
48
+ // JS sends defaultNavigationRules when the prop is unset; no rules, null or empty, match nothing.
49
+ if (rules.isNullOrEmpty()) return Decision("block", null)
50
+ val parts = (if (scheme == "blob") blobOrigin(request.url) else parts(scheme, request.url))
51
+ ?: return Decision("block", null)
52
+ val index = rules.indexOfFirst { matches(it, parts, request) }
53
+ return if (index < 0) Decision("block", null) else Decision((rules[index]["action"] as? String)?.takeIf { it in actions } ?: "block", index)
54
+ }
55
+
56
+ // scheme ":" ["//" authority] path ["?" query]. java.net.URI rejects URLs Chromium accepts (a raw `|` in the query,
57
+ // `_` in a host), so the parts are split with a regex.
58
+ private val urlParts = Regex("^([a-zA-Z][a-zA-Z0-9+.-]*):(?://([^/?#]*))?([^?#]*)(?:\\?([^#]*))?")
59
+
60
+ private data class Parts(val scheme: String, val host: String?, val path: String, val params: List<String>)
61
+
62
+ private fun parts(scheme: String, url: String): Parts {
63
+ val match = urlParts.find(url) ?: return Parts(scheme, null, "/", emptyList())
64
+ val authority = match.groups[2]?.value
65
+ val path = match.groupValues[3]
66
+ val params = match.groups[4]?.value?.split('&')?.filter { it.isNotEmpty() }.orEmpty()
67
+ return Parts(scheme, hostOf(authority), if (authority != null && path.isNotEmpty()) path else "/", params)
68
+ }
69
+
70
+ /**
71
+ * A blob: document has the origin its URL carries (`blob:https://a.test/…`), so the rules see that origin, with
72
+ * path "/"; null for an opaque one (`blob:null/…`), which no rule describes.
73
+ */
74
+ private fun blobOrigin(url: String): Parts? {
75
+ val match = urlParts.find(url.substringAfter(':')) ?: return null
76
+ return Parts(match.groupValues[1].lowercase(), hostOf(match.groups[2]?.value), "/", emptyList())
77
+ }
78
+
79
+ /** Host without userinfo, port or a trailing dot, lowercased; null when there is none. */
80
+ private fun hostOf(authority: String?): String? {
81
+ if (authority.isNullOrEmpty()) return null
82
+ val withoutUser = authority.substringAfterLast('@')
83
+ val host = if (withoutUser.startsWith("[")) withoutUser.substringBefore(']') + "]" else withoutUser.replace(Regex(":\\d*$"), "")
84
+ return host.lowercase().removeSuffix(".").ifEmpty { null }
85
+ }
86
+
87
+ /** null when the field is unset; a value that isn't a list (a string from untyped JS) matches nothing. */
88
+ private fun list(value: Any?): List<String>? = value?.let { (it as? List<*>)?.map(Any?::toString).orEmpty() }
89
+
90
+ private fun matches(rule: Map<String, Any?>, parts: Parts, request: Request): Boolean {
91
+ val (scheme, host, path, params) = parts
92
+ val schemes = list(rule["scheme"])
93
+ val hosts = list(rule["host"])
94
+ val paths = list(rule["path"])
95
+ val queries = list(rule["query"])
96
+ return (schemes == null || schemes.any { it.equals(scheme, ignoreCase = true) }) &&
97
+ (hosts == null || host != null && hosts.any { hostMatches(it.lowercase(), host) }) &&
98
+ (paths == null || paths.any { path.startsWith(it) }) &&
99
+ (queries == null || queries.any { paramMatches(it, params) }) &&
100
+ flag(rule, "mainFrame", request.mainFrame) &&
101
+ flag(rule, "newWindow", request.newWindow) &&
102
+ flag(rule, "userInitiated", request.userInitiated)
103
+ }
104
+
105
+ /** `name=value` matches that exact parameter; `name` matches a parameter with that name, whatever its value. */
106
+ private fun paramMatches(entry: String, params: List<String>) =
107
+ params.any { if ('=' in entry) it == entry else it.substringBefore('=') == entry }
108
+
109
+ private fun flag(rule: Map<String, Any?>, name: String, value: Boolean) = (rule[name] as? Boolean)?.let { it == value } ?: true
110
+
111
+ private fun hostMatches(pattern: String, host: String) =
112
+ if (pattern.startsWith("*.")) host.endsWith(pattern.substring(1)) else host == pattern
113
+ }