From 99b77d93a70d42147e2700a4e571f5cdeabed4bd Mon Sep 17 00:00:00 2001 From: Lagoon Date: Fri, 20 Nov 2026 03:44:54 +0000 Subject: [PATCH 1/6] feat(webview): Web Share API with files in the Android web container (slock #15772) Android's WebView has no navigator.share. A document-start shim (the page's own origin) gives the page a synchronous navigator.canShare and a Promise-returning navigator.share that posts the files in base64 chunks to the origin-bound download port; the app writes them under its FileProvider share folder and opens the system share sheet (ACTION_SEND / SEND_MULTIPLE; text-only shares send text), then resolves the Promise once the sheet is shown or rejects it (AbortError / DataError). iOS WKWebView already has Web Share level 2 (WebKit WebShareEnabled / WebShareFileAPIEnabled on for Cocoa), so the shim steps aside wherever the page has the API. Co-Authored-By: Claude Opus 5.5 --- .../1.27.0/changesets/webview-share-files.md | 20 ++ .../raft/app/RaftSandboxWebView.android.kt | 92 ++++++++- .../kotlin/build/raft/app/RaftWebViewShare.kt | 188 ++++++++++++++++++ .../build/raft/app/RaftWebViewShareTest.kt | 76 +++++++ 4 files changed, 374 insertions(+), 2 deletions(-) create mode 100644 change-logs/1.27.0/changesets/webview-share-files.md create mode 100644 compose/shared/src/commonMain/kotlin/build/raft/app/RaftWebViewShare.kt create mode 100644 compose/shared/src/commonTest/kotlin/build/raft/app/RaftWebViewShareTest.kt diff --git a/change-logs/1.27.0/changesets/webview-share-files.md b/change-logs/1.27.0/changesets/webview-share-files.md new file mode 100644 index 0000000000..f6f2291e35 --- /dev/null +++ b/change-logs/1.27.0/changesets/webview-share-files.md @@ -0,0 +1,20 @@ +--- +type: added +area: artifacts +platforms: + - android +pull_request: 0 +rollout: full +--- + +## zh-CN + +安卓 App 里打开的网页(例如 Artifact 查看页的「分享」)现在可以直接调出系统分享,把文件分享到其他应用。 + +## en + +Web pages in the Android app (such as Share in the Artifact viewer) can now open the system share sheet and send files to other apps. + +## ja + +Android アプリ内の Web ページ(Artifact ビューアの「共有」など)から、システムの共有シートを開いてファイルを他のアプリに送れるようになりました。 diff --git a/compose/shared/src/androidMain/kotlin/build/raft/app/RaftSandboxWebView.android.kt b/compose/shared/src/androidMain/kotlin/build/raft/app/RaftSandboxWebView.android.kt index f158c61635..ba859397ff 100644 --- a/compose/shared/src/androidMain/kotlin/build/raft/app/RaftSandboxWebView.android.kt +++ b/compose/shared/src/androidMain/kotlin/build/raft/app/RaftSandboxWebView.android.kt @@ -158,6 +158,8 @@ internal class RaftAndroidSandboxWebView( private val pendingBlobDownloads = LinkedHashMap() private var downloadMessageListener: WebViewCompat.WebMessageListener? = null private var downloadNameScriptHandler: ScriptHandler? = null + /** The page's `navigator.share` calls in flight ([raftWebViewShareShimScript]). */ + private val shareAssembler = RaftWebViewShareAssembler() private var documentStartScriptHandler: ScriptHandler? = null /** [raftWebViewFirstPaintThemeScript] at document start; separate from the auth/bridge script. */ private var firstPaintScriptHandler: ScriptHandler? = null @@ -842,7 +844,8 @@ internal class RaftAndroidSandboxWebView( notifyNavigationState() val documentStartInstalled = installDocumentStartScript(normalized) installHostMessageListener(normalized) - if (events.onDownloadRequested != null) installDownloadSupport(normalized) else removeDownloadSupport() + // The page's downloads and `navigator.share`: for a host that takes downloads, or any origin-locked page. + if (events.onDownloadRequested != null || mainFrameOrigin != null) installDownloadSupport(normalized) else removeDownloadSupport() if (shouldBootstrapInjectedJavaScript(documentStartInstalled)) { val bootstrapDocumentUrl = raftInjectedJavaScriptBootstrapBaseUrl(documentUrl) ?: documentUrl bootstrapNavigationFence.begin(targetUrl = documentUrl) @@ -1108,6 +1111,76 @@ internal class RaftAndroidSandboxWebView( } } + /** + * The page's `navigator.share` ([raftWebViewShareShimScript]): its files are written to the app's + * share folder (served by the app's FileProvider) and the system share sheet opens; the page's + * Promise resolves once it is shown, or is rejected when it cannot be. + */ + private fun presentShare(request: RaftWebViewShareRequest) { + val context = webView.context + val result = + runCatching { + val intent = + if (request.files.isEmpty()) { + android.content.Intent(android.content.Intent.ACTION_SEND).apply { + type = "text/plain" + putExtra(android.content.Intent.EXTRA_TEXT, raftWebViewShareText(request.title, request.text, request.url)) + if (request.title.isNotBlank()) putExtra(android.content.Intent.EXTRA_SUBJECT, request.title) + } + } else { + val folder = + java.io.File(context.cacheDir, "slock-share-files/web-share/" + request.id.filter { it.isLetterOrDigit() || it == '_' }) + folder.deleteRecursively() + check(folder.mkdirs()) { "share folder" } + val uris = + ArrayList( + request.files.map { file -> + val target = java.io.File(folder, file.name) + target.writeBytes(file.bytes) + androidx.core.content.FileProvider.getUriForFile(context, "${context.packageName}.fileprovider", target) + } + ) + val type = + request.files.map { it.mimeType }.distinct().singleOrNull() + ?: request.files.map { it.mimeType.substringBefore('/') }.distinct().singleOrNull()?.let { "$it/*" } + ?: "*/*" + ( + if (uris.size == 1) { + android.content.Intent(android.content.Intent.ACTION_SEND).putExtra(android.content.Intent.EXTRA_STREAM, uris[0]) + } else { + android.content.Intent(android.content.Intent.ACTION_SEND_MULTIPLE) + .putParcelableArrayListExtra(android.content.Intent.EXTRA_STREAM, uris) + } + ).apply { + this.type = type + if (request.title.isNotBlank()) putExtra(android.content.Intent.EXTRA_SUBJECT, request.title) + raftWebViewShareText("", request.text, request.url).takeIf { it.isNotBlank() } + ?.let { putExtra(android.content.Intent.EXTRA_TEXT, it) } + clipData = + android.content.ClipData.newRawUri(request.files.first().name, uris[0]).also { clip -> + uris.drop(1).forEach { clip.addItem(android.content.ClipData.Item(it)) } + } + addFlags(android.content.Intent.FLAG_GRANT_READ_URI_PERMISSION) + } + } + val chooser = android.content.Intent.createChooser(intent, request.title.takeIf { it.isNotBlank() }) + if (context !is android.app.Activity) chooser.addFlags(android.content.Intent.FLAG_ACTIVITY_NEW_TASK) + context.startActivity(chooser) + } + if (result.isSuccess) { + diagnosticsInfo("page_share result=shown files=${request.files.size}") + settleShare(request.id, null) + } else { + diagnosticsWarn("page_share result=failed type=${result.exceptionOrNull()?.javaClass?.simpleName}") + settleShare(request.id, "AbortError") + } + } + + private fun settleShare(id: String, errorName: String?) { + if (destroyed) return + webView.evaluateJavascript(raftWebViewShareSettleScript(id, errorName), null) + } + private fun installDownloadSupport(targetUrl: String) { removeDownloadSupport() if (!WebViewFeature.isFeatureSupported(WebViewFeature.WEB_MESSAGE_LISTENER) || @@ -1129,6 +1202,17 @@ internal class RaftAndroidSandboxWebView( ) { if (destroyed || !isMainFrame || sourceOrigin.toString() != originRule) return val raw = message.data ?: return + if (raftWebViewIsShareMessage(raw)) { + when (val share = shareAssembler.accept(raw)) { + is RaftWebViewShareAssembly.Ready -> presentShare(share.request) + is RaftWebViewShareAssembly.Failed -> { + diagnosticsWarn("page_share result=failed reason=${share.reason}") + settleShare(share.id, "DataError") + } + null -> Unit + } + return + } val token = runCatching { AndroidJSONObject(raw).optString("t") }.getOrNull() ?: return val assembler = pendingBlobDownloads[token] ?: return val result = assembler.accept(raw) ?: return @@ -1144,7 +1228,11 @@ internal class RaftAndroidSandboxWebView( WebViewCompat.addWebMessageListener(webView, RaftWebViewDownloadPortName, setOf(originRule), listener) downloadMessageListener = listener downloadNameScriptHandler = - WebViewCompat.addDocumentStartJavaScript(webView, RaftWebViewDownloadNameHookScript, setOf(originRule)) + WebViewCompat.addDocumentStartJavaScript( + webView, + RaftWebViewDownloadNameHookScript + "\n" + raftWebViewShareShimScript(), + setOf(originRule) + ) }.onFailure { Log.w(LOG_TAG, "download_support unavailable", it) } } diff --git a/compose/shared/src/commonMain/kotlin/build/raft/app/RaftWebViewShare.kt b/compose/shared/src/commonMain/kotlin/build/raft/app/RaftWebViewShare.kt new file mode 100644 index 0000000000..b648588cd6 --- /dev/null +++ b/compose/shared/src/commonMain/kotlin/build/raft/app/RaftWebViewShare.kt @@ -0,0 +1,188 @@ +package build.raft.app + +import build.raft.app.compat.json.JSONObject +import build.raft.app.network.raftSafeDownloadFileName +import kotlin.io.encoding.Base64 +import kotlin.io.encoding.ExperimentalEncodingApi + +/** + * The Web Share API (with files) for a hosted page whose WebView has none (Android's WebView; iOS + * WKWebView has it natively, Web Share level 2), as a browser offers it (slock #15772: the + * Artifact viewer's ⋯ › Share, shown only when `navigator.canShare({ files })` answers true). + * + * Installed at document start in the page's own origin (main frame): `navigator.canShare` answers + * synchronously; `navigator.share` returns a Promise, reads each File/Blob as base64 in chunks and + * posts them to [RaftWebViewDownloadPortName] (the origin-bound port the page's downloads use). + * The app writes the files and opens the system share sheet, then settles the Promise with + * [raftWebViewShareSettleScript]: resolved once the sheet is shown, rejected (`AbortError`, + * `DataError`, ...) when it could not be. + */ +internal fun raftWebViewShareShimScript(maxBytes: Long = RaftWebViewShareMaxBytes): String = + "(function(){if(window.__raftShareSettle)return;var n=navigator;" + + "if(typeof n.share==='function'&&typeof n.canShare==='function')return;" + + "var port=function(){return window.$RaftWebViewDownloadPortName;};" + + "var pending={},seq=0;" + + "function isFile(f){return typeof Blob!=='undefined'&&f instanceof Blob;}" + + "function canShare(d){if(!d||typeof d!=='object'||!port())return false;" + + "var f=d.files;if(f!==undefined&&f!==null){if(!f.length)return false;var total=0;" + + "for(var i=0;i=files.length){post({k:'share-end'});return;}var f=files[fi];" + + "if(off>=f.size){fi++;off=0;ci=0;next();return;}" + + "var fr=new FileReader();fr.onload=function(){var s=String(fr.result);var c=s.indexOf(',');" + + "post({k:'share-chunk',f:fi,i:ci,d:c>=0?s.substring(c+1):''});ci++;off+=size;next();};" + + "fr.onerror=function(){post({k:'share-error'});window.__raftShareSettle(id,'DataError');};" + + "fr.readAsDataURL(f.slice(off,Math.min(off+size,f.size)));}next();});};})();" + +/** Settles the page's `navigator.share` Promise [id]: resolved when [errorName] is null, else rejected with it. */ +internal fun raftWebViewShareSettleScript(id: String, errorName: String?): String = + "(function(){var s=window.__raftShareSettle;if(s)s(${JSONObject.quote(id)},${if (errorName == null) "null" else JSONObject.quote(errorName)});})();" + +/** At most this many bytes in one share (the files together). */ +internal const val RaftWebViewShareMaxBytes: Long = 100L * 1024L * 1024L + +internal class RaftWebViewShareFile(val name: String, val mimeType: String, val bytes: ByteArray) + +internal class RaftWebViewShareRequest( + val id: String, + val title: String, + val text: String, + val url: String, + val files: List, +) + +internal sealed interface RaftWebViewShareAssembly { + class Ready(val request: RaftWebViewShareRequest) : RaftWebViewShareAssembly + + data class Failed(val id: String, val reason: String) : RaftWebViewShareAssembly +} + +/** Whether a port message ([raftWebViewShareShimScript]) is part of a share rather than a download read. */ +internal fun raftWebViewIsShareMessage(raw: String): Boolean = raw.contains("\"k\":\"share-") + +/** + * Puts the page's share messages back together, per share id: the files announced at `share-start`, + * their chunks in order and to their announced sizes, under [maxBytes] together. + */ +internal class RaftWebViewShareAssembler(private val maxBytes: Long = RaftWebViewShareMaxBytes) { + private class Pending( + val title: String, + val text: String, + val url: String, + val names: List, + val types: List, + val sizes: List, + ) { + val parts = sizes.map { ArrayList() } + val received = LongArray(sizes.size) + val nextChunk = IntArray(sizes.size) + var nextFile = 0 + } + + private val pending = LinkedHashMap() + + @OptIn(ExperimentalEncodingApi::class) + fun accept(raw: String): RaftWebViewShareAssembly? { + val message = runCatching { JSONObject(raw) }.getOrNull() ?: return null + val id = message.optString("s").takeIf { it.isNotBlank() } ?: return null + when (message.optString("k")) { + "share-start" -> { + val files = message.optJSONArray("files") + val names = ArrayList() + val types = ArrayList() + val sizes = ArrayList() + for (index in 0 until (files?.length() ?: 0)) { + val file = files?.optJSONObject(index) ?: return fail(id, "file_meta") + names += file.optString("name") + types += file.optString("type") + sizes += file.optLong("size", -1L).also { if (it < 0) return fail(id, "file_meta") } + } + if (sizes.sum() > maxBytes) return fail(id, "too_large") + while (pending.size >= 4) pending.remove(pending.keys.first()) + pending[id] = Pending(message.optString("title"), message.optString("text"), message.optString("url"), names, types, sizes) + return null + } + "share-chunk" -> { + val share = pending[id] ?: return null + val file = message.optInt("f", -1) + if (file < share.nextFile || file >= share.sizes.size) return fail(id, "chunk_order") + // Files are read one after another; an empty one sends no chunk. + if (file > share.nextFile && (share.nextFile until file).any { share.received[it] != share.sizes[it] }) { + return fail(id, "chunk_order") + } + share.nextFile = file + if (message.optInt("i", -1) != share.nextChunk[file]) return fail(id, "chunk_order") + val bytes = runCatching { Base64.decode(message.optString("d")) }.getOrNull() ?: return fail(id, "chunk_decode") + share.received[file] += bytes.size + if (share.received[file] > share.sizes[file]) return fail(id, "size_mismatch") + share.parts[file] += bytes + share.nextChunk[file]++ + return null + } + "share-end" -> { + val share = pending.remove(id) ?: return null + if (share.sizes.indices.any { share.received[it] != share.sizes[it] }) { + return RaftWebViewShareAssembly.Failed(id, "size_mismatch") + } + val used = HashSet() + val files = + share.sizes.indices.map { index -> + val all = ByteArray(share.sizes[index].toInt()) + var offset = 0 + share.parts[index].forEach { part -> + part.copyInto(all, offset) + offset += part.size + } + val type = share.types[index].ifBlank { "application/octet-stream" } + RaftWebViewShareFile( + name = raftWebViewShareUniqueName( + raftWebViewDownloadFileName(share.names[index].takeIf { it.isNotBlank() }, null, "", type), + used, + ), + mimeType = type, + bytes = all, + ) + } + return RaftWebViewShareAssembly.Ready(RaftWebViewShareRequest(id, share.title, share.text, share.url, files)) + } + "share-error" -> { + pending.remove(id) + return null + } + else -> return null + } + } + + private fun fail(id: String, reason: String): RaftWebViewShareAssembly { + pending.remove(id) + return RaftWebViewShareAssembly.Failed(id, reason) + } +} + +/** [name], or `name (2).ext`, ... when another file of the same share already has it. */ +internal fun raftWebViewShareUniqueName(name: String, used: MutableSet): String { + val safe = raftSafeDownloadFileName(name) ?: "file" + if (used.add(safe)) return safe + val dot = safe.lastIndexOf('.').takeIf { it > 0 } ?: safe.length + var index = 2 + while (true) { + val candidate = safe.substring(0, dot) + " ($index)" + safe.substring(dot) + if (used.add(candidate)) return candidate + index++ + } +} + +/** The text an Android text-only share sends: title, text and url, each once, on their own lines. */ +internal fun raftWebViewShareText(title: String, text: String, url: String): String = + listOf(text, url).filter { it.isNotBlank() }.distinct().joinToString("\n").ifBlank { title } diff --git a/compose/shared/src/commonTest/kotlin/build/raft/app/RaftWebViewShareTest.kt b/compose/shared/src/commonTest/kotlin/build/raft/app/RaftWebViewShareTest.kt new file mode 100644 index 0000000000..8d1992e940 --- /dev/null +++ b/compose/shared/src/commonTest/kotlin/build/raft/app/RaftWebViewShareTest.kt @@ -0,0 +1,76 @@ +package build.raft.app + +import build.raft.app.compat.json.JSONArray +import build.raft.app.compat.json.JSONObject +import kotlin.io.encoding.Base64 +import kotlin.io.encoding.ExperimentalEncodingApi +import kotlin.test.Test +import kotlin.test.assertEquals +import kotlin.test.assertIs +import kotlin.test.assertNull +import kotlin.test.assertTrue + +/** slock #15772 / #proj-workspace:#346: `navigator.share` with files in the app's web container. */ +@OptIn(ExperimentalEncodingApi::class) +class RaftWebViewShareTest { + @Test + fun shimAnswersCanShareAndPostsToTheOriginBoundPort() { + val script = raftWebViewShareShimScript(maxBytes = 1234) + assertTrue("n.canShare=canShare" in script) + assertTrue("n.share=function(d){return new Promise" in script) + assertTrue("window.$RaftWebViewDownloadPortName" in script) + assertTrue("total<=1234" in script) + // A WebView that already has the API keeps its own. + assertTrue("typeof n.share==='function'&&typeof n.canShare==='function')return" in script) + } + + @Test + fun settleScriptResolvesOrRejectsById() { + assertEquals( + "(function(){var s=window.__raftShareSettle;if(s)s(\"s1_9\",null);})();", + raftWebViewShareSettleScript("s1_9", null), + ) + assertTrue("\"AbortError\"" in raftWebViewShareSettleScript("s1_9", "AbortError")) + } + + private fun msg(vararg pairs: Pair): String = JSONObject().apply { pairs.forEach { (k, v) -> put(k, v) } }.toString() + + private fun start(id: String, vararg files: Triple): String = + msg( + "s" to id, "k" to "share-start", "title" to "周报", "text" to "", "url" to "", + "files" to JSONArray().apply { + files.forEach { (name, type, size) -> put(JSONObject().put("name", name).put("type", type).put("size", size)) } + }, + ) + + @Test + fun assemblesTwoFilesAndDeduplicatesNames() { + val assembler = RaftWebViewShareAssembler() + val a = "第一个".encodeToByteArray() + val b = byteArrayOf(1, 2, 3) + assertNull(assembler.accept(start("s1", Triple("周报.md", "text/markdown", a.size), Triple("周报.md", "text/markdown", b.size)))) + assertTrue(raftWebViewIsShareMessage(start("s1"))) + assertNull(assembler.accept(msg("s" to "s1", "k" to "share-chunk", "f" to 0, "i" to 0, "d" to Base64.encode(a)))) + assertNull(assembler.accept(msg("s" to "s1", "k" to "share-chunk", "f" to 1, "i" to 0, "d" to Base64.encode(b)))) + val ready = assertIs(assembler.accept(msg("s" to "s1", "k" to "share-end"))) + assertEquals(listOf("周报.md", "周报 (2).md"), ready.request.files.map { it.name }) + assertEquals("第一个", ready.request.files[0].bytes.decodeToString()) + assertEquals("周报", ready.request.title) + } + + @Test + fun missingBytesOrOversizeFail() { + val assembler = RaftWebViewShareAssembler(maxBytes = 10) + assertIs(assembler.accept(start("big", Triple("a.zip", "application/zip", 11)))) + assertNull(assembler.accept(start("s2", Triple("a.txt", "text/plain", 4)))) + assertNull(assembler.accept(msg("s" to "s2", "k" to "share-chunk", "f" to 0, "i" to 0, "d" to Base64.encode(ByteArray(2))))) + val failed = assertIs(assembler.accept(msg("s" to "s2", "k" to "share-end"))) + assertEquals("size_mismatch", failed.reason) + } + + @Test + fun textOnlyShareText() { + assertEquals("hi\nhttps://x.y", raftWebViewShareText("t", "hi", "https://x.y")) + assertEquals("t", raftWebViewShareText("t", "", "")) + } +} From 091653f132997e9dc2826f6a090047ca0f792d6c Mon Sep 17 00:00:00 2001 From: Lagoon Date: Fri, 20 Nov 2026 04:18:42 +0000 Subject: [PATCH 2/6] chore(changeset): link webview-share-files to #5120 Co-Authored-By: Claude Opus 5.5 --- change-logs/1.27.0/changesets/webview-share-files.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/change-logs/1.27.0/changesets/webview-share-files.md b/change-logs/1.27.0/changesets/webview-share-files.md index f6f2291e35..ba0854fb93 100644 --- a/change-logs/1.27.0/changesets/webview-share-files.md +++ b/change-logs/1.27.0/changesets/webview-share-files.md @@ -3,7 +3,7 @@ type: added area: artifacts platforms: - android -pull_request: 0 +pull_request: 5120 rollout: full --- From 0aadc44310efce36d58f18d8fd999527b2cc05e0 Mon Sep 17 00:00:00 2001 From: Lagoon Date: Fri, 20 Nov 2026 04:40:20 +0000 Subject: [PATCH 3/6] fix(webview): tell a share message by its parsed kind Co-Authored-By: Claude Opus 5.5 --- .../src/commonMain/kotlin/build/raft/app/RaftWebViewShare.kt | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/compose/shared/src/commonMain/kotlin/build/raft/app/RaftWebViewShare.kt b/compose/shared/src/commonMain/kotlin/build/raft/app/RaftWebViewShare.kt index b648588cd6..9e0f133ca7 100644 --- a/compose/shared/src/commonMain/kotlin/build/raft/app/RaftWebViewShare.kt +++ b/compose/shared/src/commonMain/kotlin/build/raft/app/RaftWebViewShare.kt @@ -69,7 +69,8 @@ internal sealed interface RaftWebViewShareAssembly { } /** Whether a port message ([raftWebViewShareShimScript]) is part of a share rather than a download read. */ -internal fun raftWebViewIsShareMessage(raw: String): Boolean = raw.contains("\"k\":\"share-") +internal fun raftWebViewIsShareMessage(raw: String): Boolean = + "share-" in raw && runCatching { JSONObject(raw).optString("k").startsWith("share-") }.getOrDefault(false) /** * Puts the page's share messages back together, per share id: the files announced at `share-start`, From 3fc65fe43799be4584778324787e731e8fd80841 Mon Sep 17 00:00:00 2001 From: Lagoon Date: Fri, 20 Nov 2026 05:59:38 +0000 Subject: [PATCH 4/6] chore(changeset): webview-share-files ships in 1.28.0 Co-Authored-By: Claude Opus 5.5 --- change-logs/{1.27.0 => 1.28.0}/changesets/webview-share-files.md | 0 1 file changed, 0 insertions(+), 0 deletions(-) rename change-logs/{1.27.0 => 1.28.0}/changesets/webview-share-files.md (100%) diff --git a/change-logs/1.27.0/changesets/webview-share-files.md b/change-logs/1.28.0/changesets/webview-share-files.md similarity index 100% rename from change-logs/1.27.0/changesets/webview-share-files.md rename to change-logs/1.28.0/changesets/webview-share-files.md From 93740c3add6ecca62002d1a47875c3df3327dee5 Mon Sep 17 00:00:00 2001 From: Lagoon Date: Fri, 20 Nov 2026 10:08:05 +0000 Subject: [PATCH 5/6] fix(webview): stream page shares to staged files off the UI thread Review findings on #5120: - each chunk is parsed, decoded and appended to its file on one background thread, acknowledged before the page reads the next; no file is held in memory, and pending shares end with the port, on eviction, or after two silent minutes (AbortError) - a share is staged in its own entry of slock-share-files, under the attachment share's age and count rules, not in a web-share/ parent - the shim rejects without user activation (NotAllowedError), while a share is in flight (InvalidStateError), and is not installed in subframes - sizes are bounded one by one with a checked sum; ids and file names are validated (RaftShareFileName.sanitize); the intent type is normalised Co-Authored-By: Claude Fable 5.2 --- .../shared/AndroidAttachmentShareStaging.kt | 5 + .../raft/app/RaftSandboxWebView.android.kt | 236 +++++++++-- .../kotlin/build/raft/app/RaftWebViewShare.kt | 399 +++++++++++++----- .../build/raft/app/RaftWebViewShareTest.kt | 303 ++++++++++++- 4 files changed, 795 insertions(+), 148 deletions(-) diff --git a/compose/androidApp/src/main/java/build/raft/app/shared/AndroidAttachmentShareStaging.kt b/compose/androidApp/src/main/java/build/raft/app/shared/AndroidAttachmentShareStaging.kt index 1a2e112766..dcfb1d9d82 100644 --- a/compose/androidApp/src/main/java/build/raft/app/shared/AndroidAttachmentShareStaging.kt +++ b/compose/androidApp/src/main/java/build/raft/app/shared/AndroidAttachmentShareStaging.kt @@ -54,6 +54,11 @@ internal fun sanitizeAndroidAttachmentShareFileName(displayName: String, mimeTyp * Removes share entries older than [maxAgeMs], foreign children, and all but the newest * [maxEntries] entries. A receiver may keep reading a granted URI after the chooser returns, so a * fresh entry is never removed just because a new share started. + * + * A web page's `navigator.share` (`RaftAndroidWebViewShareSession` in the shared module) stages its + * files in this same root, one `` entry per share, so these rules cover them too; it applies + * the age and count rules itself (`raftWebViewShareStaleStagingEntries`) before each of its shares. + * Keep the entry name pattern and the limits of the two in step. */ internal fun sweepAndroidAttachmentShareStaging( shareRoot: File, diff --git a/compose/shared/src/androidMain/kotlin/build/raft/app/RaftSandboxWebView.android.kt b/compose/shared/src/androidMain/kotlin/build/raft/app/RaftSandboxWebView.android.kt index ba859397ff..9b1efae71f 100644 --- a/compose/shared/src/androidMain/kotlin/build/raft/app/RaftSandboxWebView.android.kt +++ b/compose/shared/src/androidMain/kotlin/build/raft/app/RaftSandboxWebView.android.kt @@ -158,8 +158,10 @@ internal class RaftAndroidSandboxWebView( private val pendingBlobDownloads = LinkedHashMap() private var downloadMessageListener: WebViewCompat.WebMessageListener? = null private var downloadNameScriptHandler: ScriptHandler? = null - /** The page's `navigator.share` calls in flight ([raftWebViewShareShimScript]). */ - private val shareAssembler = RaftWebViewShareAssembler() + /** The page's `navigator.share` calls being received ([raftWebViewShareShimScript]); one per installed port. */ + private var shareSession: RaftAndroidWebViewShareSession? = null + private val shareMainHandler = android.os.Handler(android.os.Looper.getMainLooper()) + private var shareExpiryCheck: Runnable? = null private var documentStartScriptHandler: ScriptHandler? = null /** [raftWebViewFirstPaintThemeScript] at document start; separate from the auth/bridge script. */ private var firstPaintScriptHandler: ScriptHandler? = null @@ -1112,11 +1114,86 @@ internal class RaftAndroidSandboxWebView( } /** - * The page's `navigator.share` ([raftWebViewShareShimScript]): its files are written to the app's - * share folder (served by the app's FileProvider) and the system share sheet opens; the page's - * Promise resolves once it is shown, or is rejected when it cannot be. + * A message of the page's `navigator.share` ([raftWebViewShareShimScript]). The UI thread only + * hands it on: it is parsed, decoded and written to the share's staging folder on + * [RaftWebViewShareIo], in the order posted, and what follows (the next chunk asked for, the share + * sheet, the Promise settled) comes back here. Nothing thrown leaves this function. */ - private fun presentShare(request: RaftWebViewShareRequest) { + private fun acceptShareMessage(session: RaftAndroidWebViewShareSession, raw: String) { + scheduleShareExpiry(session) + runShareIo(session, notShare = { handleDownloadMessage(raw) }) { session.accept(raw) } + } + + /** Runs [work] on the share thread and its signals back on the main thread. */ + private fun runShareIo( + session: RaftAndroidWebViewShareSession, + notShare: (() -> Unit)? = null, + work: () -> List? + ) { + runCatching { + RaftWebViewShareIo.execute { + val signals = runCatching(work).getOrElse { runCatching { session.abortAll("internal") }.getOrDefault(emptyList()) } + if (signals == null) { + if (notShare != null) shareMainHandler.post { if (!destroyed && shareSession === session) notShare() } + } else if (signals.isNotEmpty()) { + shareMainHandler.post { deliverShareSignals(session, signals) } + } + } + }.onFailure { Log.w(LOG_TAG, "page_share io unavailable", it) } + } + + private fun deliverShareSignals(session: RaftAndroidWebViewShareSession, signals: List) { + val current = !destroyed && shareSession === session + signals.forEach { staged -> + runCatching { + when (val signal = staged.signal) { + is RaftWebViewShareSignal.Ack -> + if (current) webView.evaluateJavascript(raftWebViewShareAckScript(signal.id), null) + is RaftWebViewShareSignal.Failed -> { + diagnosticsWarn("page_share result=failed reason=${signal.reason}") + settleShare(signal.id, signal.errorName) + } + is RaftWebViewShareSignal.Ready -> + if (current) { + presentShare(signal.request, staged.folder) + } else { + // The page went away while its last bytes were written. + discardShareFolder(staged.folder) + settleShare(signal.request.id, "AbortError") + } + } + Unit + }.onFailure { Log.w(LOG_TAG, "page_share deliver failed", it) } + } + } + + /** + * Gives up shares whose page has gone silent: every share message pushes this check + * [RaftWebViewShareIdleTimeoutMs] ahead, so when it runs none of them has had one for that long. + */ + private fun scheduleShareExpiry(session: RaftAndroidWebViewShareSession) { + shareExpiryCheck?.let { shareMainHandler.removeCallbacks(it) } + val check = + Runnable { + shareExpiryCheck = null + if (!destroyed && shareSession === session) runShareIo(session) { session.expire() } + } + shareExpiryCheck = check + shareMainHandler.postDelayed(check, RaftWebViewShareIdleTimeoutMs + 1_000L) + } + + private fun discardShareFolder(folder: java.io.File?) { + if (folder == null) return + runCatching { RaftWebViewShareIo.execute { runCatching { folder.deleteRecursively() } } } + } + + /** + * Opens the system share sheet for a received share. Its files are already in [folder], the + * share's own `` entry of the app's share staging folder (served by the app's + * FileProvider, swept by age like an attachment share's). The page's Promise resolves once the + * sheet is shown, or is rejected when it cannot be. + */ + private fun presentShare(request: RaftWebViewShareRequest, folder: java.io.File?) { val context = webView.context val result = runCatching { @@ -1128,22 +1205,24 @@ internal class RaftAndroidSandboxWebView( if (request.title.isNotBlank()) putExtra(android.content.Intent.EXTRA_SUBJECT, request.title) } } else { - val folder = - java.io.File(context.cacheDir, "slock-share-files/web-share/" + request.id.filter { it.isLetterOrDigit() || it == '_' }) - folder.deleteRecursively() - check(folder.mkdirs()) { "share folder" } + checkNotNull(folder) { "share folder" } val uris = ArrayList( request.files.map { file -> val target = java.io.File(folder, file.name) - target.writeBytes(file.bytes) + check(target.isFile && target.parentFile == folder && target.length() == file.size) { "share file" } androidx.core.content.FileProvider.getUriForFile(context, "${context.packageName}.fileprovider", target) } ) + // Receivers match on a bare `type/subtype`: no parameters, a generic type read from the name. val type = - request.files.map { it.mimeType }.distinct().singleOrNull() - ?: request.files.map { it.mimeType.substringBefore('/') }.distinct().singleOrNull()?.let { "$it/*" } - ?: "*/*" + raftWebViewShareIntentType( + request.files.map { file -> + build.raft.app.downloads.RaftShareFileName.resolveMimeType(file.name, file.mimeType) { extension -> + android.webkit.MimeTypeMap.getSingleton().getMimeTypeFromExtension(extension) + } + } + ) ( if (uris.size == 1) { android.content.Intent(android.content.Intent.ACTION_SEND).putExtra(android.content.Intent.EXTRA_STREAM, uris[0]) @@ -1172,6 +1251,7 @@ internal class RaftAndroidSandboxWebView( settleShare(request.id, null) } else { diagnosticsWarn("page_share result=failed type=${result.exceptionOrNull()?.javaClass?.simpleName}") + discardShareFolder(folder) settleShare(request.id, "AbortError") } } @@ -1181,6 +1261,20 @@ internal class RaftAndroidSandboxWebView( webView.evaluateJavascript(raftWebViewShareSettleScript(id, errorName), null) } + /** A chunk of a `blob:` / `data:` save the page is reading back ([startPageDownload]). */ + private fun handleDownloadMessage(raw: String) { + val token = runCatching { AndroidJSONObject(raw).optString("t") }.getOrNull() ?: return + val assembler = pendingBlobDownloads[token] ?: return + val result = assembler.accept(raw) ?: return + pendingBlobDownloads.remove(token) + when (result) { + is RaftWebViewDownload.Failed -> diagnosticsWarn("page_download result=failed reason=${result.reason}") + is RaftWebViewDownload.Bytes -> diagnosticsInfo("page_download result=read bytes=${result.bytes.size}") + is RaftWebViewDownload.Url -> Unit + } + events.onDownloadRequested?.invoke(result) + } + private fun installDownloadSupport(targetUrl: String) { removeDownloadSupport() if (!WebViewFeature.isFeatureSupported(WebViewFeature.WEB_MESSAGE_LISTENER) || @@ -1191,6 +1285,7 @@ internal class RaftAndroidSandboxWebView( val originRule = raftDocumentStartScriptOriginRule(targetUrl) ?: return if (mainFrameOrigin != null && originRule != mainFrameOrigin) return runCatching { + val session = RaftAndroidWebViewShareSession(java.io.File(webView.context.cacheDir, RaftWebViewShareStagingDirName)) val listener = object : WebViewCompat.WebMessageListener { override fun onPostMessage( @@ -1202,31 +1297,17 @@ internal class RaftAndroidSandboxWebView( ) { if (destroyed || !isMainFrame || sourceOrigin.toString() != originRule) return val raw = message.data ?: return - if (raftWebViewIsShareMessage(raw)) { - when (val share = shareAssembler.accept(raw)) { - is RaftWebViewShareAssembly.Ready -> presentShare(share.request) - is RaftWebViewShareAssembly.Failed -> { - diagnosticsWarn("page_share result=failed reason=${share.reason}") - settleShare(share.id, "DataError") - } - null -> Unit - } + // A share message goes to the share thread whole; this (UI) thread neither parses nor decodes it. + if (raftWebViewMayBeShareMessage(raw)) { + acceptShareMessage(session, raw) return } - val token = runCatching { AndroidJSONObject(raw).optString("t") }.getOrNull() ?: return - val assembler = pendingBlobDownloads[token] ?: return - val result = assembler.accept(raw) ?: return - pendingBlobDownloads.remove(token) - when (result) { - is RaftWebViewDownload.Failed -> diagnosticsWarn("page_download result=failed reason=${result.reason}") - is RaftWebViewDownload.Bytes -> diagnosticsInfo("page_download result=read bytes=${result.bytes.size}") - is RaftWebViewDownload.Url -> Unit - } - events.onDownloadRequested?.invoke(result) + handleDownloadMessage(raw) } } WebViewCompat.addWebMessageListener(webView, RaftWebViewDownloadPortName, setOf(originRule), listener) downloadMessageListener = listener + shareSession = session downloadNameScriptHandler = WebViewCompat.addDocumentStartJavaScript( webView, @@ -1244,6 +1325,13 @@ internal class RaftAndroidSandboxWebView( runCatching { downloadNameScriptHandler?.remove() } downloadNameScriptHandler = null pendingBlobDownloads.clear() + // Shares still being received end here: their partial files go, their Promises are rejected. + shareExpiryCheck?.let { shareMainHandler.removeCallbacks(it) } + shareExpiryCheck = null + shareSession?.let { session -> + shareSession = null + runShareIo(session) { session.abortAll("closed") } + } } private fun removeHostMessageListener() { @@ -1456,3 +1544,85 @@ private fun String.raftSanitizedLogValue(limit: Int = 160): String = internal actual val raftWebViewNeedsHostBottomInsets: Boolean = true internal actual val raftWebViewDesktopModeViaViewportMeta: Boolean = true + +/** + * One thread for every page share ([raftWebViewShareShimScript]): parsing, base64 decoding and file + * writes stay off the UI thread and run in the order the messages were posted. It ends when idle. + */ +private val RaftWebViewShareIo: java.util.concurrent.Executor by lazy { + java.util.concurrent.ThreadPoolExecutor( + 0, + 1, + 30L, + java.util.concurrent.TimeUnit.SECONDS, + java.util.concurrent.LinkedBlockingQueue() + ) +} + +/** A share signal with, for a share that is ready, the folder its files are in. */ +private class RaftAndroidStagedShareSignal(val signal: RaftWebViewShareSignal, val folder: java.io.File?) + +/** + * The shares one page is sending ([RaftWebViewShareReceiver]) and where their bytes go: each share + * in its own `` entry right under the app's share staging folder (`cache/slock-share-files`, + * the attachment share's; see `AndroidAttachmentShareStaging`), each chunk appended to its file as + * it arrives. Entries follow that folder's rules (a day, the newest sixteen), applied here before a + * new one is made and by the attachment share's own sweep; a failed or abandoned share's entry is + * removed at once. Used from [RaftWebViewShareIo] only. + */ +private class RaftAndroidWebViewShareSession(private val shareRoot: java.io.File) : RaftWebViewShareSink { + private val folders = HashMap() + private val fileNames = HashMap>() + private val receiver = RaftWebViewShareReceiver(sink = this, nowMillis = { android.os.SystemClock.elapsedRealtime() }) + + @Synchronized + fun accept(raw: String): List? = receiver.accept(raw)?.map(::staged) + + @Synchronized + fun expire(): List = receiver.expire().map(::staged) + + @Synchronized + fun abortAll(reason: String): List = receiver.abortAll(reason).map(::staged) + + private fun staged(signal: RaftWebViewShareSignal): RaftAndroidStagedShareSignal { + val folder = + if (signal is RaftWebViewShareSignal.Ready) { + fileNames.remove(signal.request.id) + // The entry's age counts from when the share was complete. + folders.remove(signal.request.id)?.also { it.setLastModified(System.currentTimeMillis()) } + } else { + null + } + return RaftAndroidStagedShareSignal(signal, folder) + } + + override fun open(id: String, fileNames: List) { + discard(id) + sweep() + val folder = java.io.File(shareRoot, java.util.UUID.randomUUID().toString()) + check(folder.mkdirs()) { "share folder" } + folders[id] = folder + this.fileNames[id] = fileNames + fileNames.forEach { name -> + val target = java.io.File(folder, name) + check(target.parentFile == folder && target.createNewFile()) { "share file" } + } + } + + override fun append(id: String, fileIndex: Int, bytes: ByteArray) { + val folder = checkNotNull(folders[id]) { "share folder" } + val target = java.io.File(folder, checkNotNull(fileNames[id]) { "share files" }[fileIndex]) + java.io.FileOutputStream(target, true).use { it.write(bytes) } + } + + override fun discard(id: String) { + fileNames.remove(id) + folders.remove(id)?.deleteRecursively() + } + + private fun sweep() { + val entries = shareRoot.listFiles()?.filter { it.isDirectory } ?: return + val stale = raftWebViewShareStaleStagingEntries(entries.map { it.name to it.lastModified() }, System.currentTimeMillis()).toSet() + entries.filter { it.name in stale }.forEach { runCatching { it.deleteRecursively() } } + } +} diff --git a/compose/shared/src/commonMain/kotlin/build/raft/app/RaftWebViewShare.kt b/compose/shared/src/commonMain/kotlin/build/raft/app/RaftWebViewShare.kt index 9e0f133ca7..547fdc9be4 100644 --- a/compose/shared/src/commonMain/kotlin/build/raft/app/RaftWebViewShare.kt +++ b/compose/shared/src/commonMain/kotlin/build/raft/app/RaftWebViewShare.kt @@ -1,7 +1,7 @@ package build.raft.app import build.raft.app.compat.json.JSONObject -import build.raft.app.network.raftSafeDownloadFileName +import build.raft.app.downloads.RaftShareFileName import kotlin.io.encoding.Base64 import kotlin.io.encoding.ExperimentalEncodingApi @@ -10,49 +10,78 @@ import kotlin.io.encoding.ExperimentalEncodingApi * WKWebView has it natively, Web Share level 2), as a browser offers it (slock #15772: the * Artifact viewer's ⋯ › Share, shown only when `navigator.canShare({ files })` answers true). * - * Installed at document start in the page's own origin (main frame): `navigator.canShare` answers - * synchronously; `navigator.share` returns a Promise, reads each File/Blob as base64 in chunks and - * posts them to [RaftWebViewDownloadPortName] (the origin-bound port the page's downloads use). - * The app writes the files and opens the system share sheet, then settles the Promise with - * [raftWebViewShareSettleScript]: resolved once the sheet is shown, rejected (`AbortError`, - * `DataError`, ...) when it could not be. + * Installed at document start in the page's own origin, top frame only (the app takes the port's + * messages from the main frame alone, so a subframe's share could never settle): `navigator.canShare` + * answers synchronously; `navigator.share` returns a Promise, reads each File/Blob as base64 in + * chunks and posts them to [RaftWebViewDownloadPortName] (the origin-bound port the page's downloads + * use), one chunk at a time: the next is read once the app has written the last + * ([raftWebViewShareAckScript]), so neither side holds more than a chunk. The app opens the system + * share sheet, then settles the Promise with [raftWebViewShareSettleScript]: resolved once the sheet + * is shown, rejected (`AbortError`, `DataError`, ...) when it could not be. + * + * As the Web Share spec has it, `share` rejects with `InvalidStateError` while an earlier share of + * this page is still in flight, with `NotAllowedError` without a user activation (where the WebView + * reports one), and with `TypeError` for data it cannot share. */ internal fun raftWebViewShareShimScript(maxBytes: Long = RaftWebViewShareMaxBytes): String = - "(function(){if(window.__raftShareSettle)return;var n=navigator;" + + "(function(){if(window.__raftShareSettle)return;" + + "try{if(window.top!==window)return;}catch(e){return;}" + + "var n=navigator;" + "if(typeof n.share==='function'&&typeof n.canShare==='function')return;" + "var port=function(){return window.$RaftWebViewDownloadPortName;};" + - "var pending={},seq=0;" + + "var pending={},seq=0,active=null;" + "function isFile(f){return typeof Blob!=='undefined'&&f instanceof Blob;}" + "function canShare(d){if(!d||typeof d!=='object'||!port())return false;" + - "var f=d.files;if(f!==undefined&&f!==null){if(!f.length)return false;var total=0;" + + "var f=d.files;if(f!==undefined&&f!==null){if(!f.length||f.length>$RaftWebViewShareMaxFiles)return false;var total=0;" + "for(var i=0;i=files.length){post({k:'share-end'});return;}var f=files[fi];" + + "function next(){if(pending[id]!==entry)return;if(fi>=files.length){post({k:'share-end'});return;}var f=files[fi];" + "if(off>=f.size){fi++;off=0;ci=0;next();return;}" + - "var fr=new FileReader();fr.onload=function(){var s=String(fr.result);var c=s.indexOf(',');" + - "post({k:'share-chunk',f:fi,i:ci,d:c>=0?s.substring(c+1):''});ci++;off+=size;next();};" + - "fr.onerror=function(){post({k:'share-error'});window.__raftShareSettle(id,'DataError');};" + + "var fr=new FileReader();fr.onload=function(){if(pending[id]!==entry)return;var s=String(fr.result);var c=s.indexOf(',');" + + "entry.next=function(){ci++;off+=size;next();};" + + "post({k:'share-chunk',f:fi,i:ci,d:c>=0?s.substring(c+1):''});};" + + "fr.onerror=function(){if(pending[id]!==entry)return;post({k:'share-error'});settle(id,'DataError');};" + "fr.readAsDataURL(f.slice(off,Math.min(off+size,f.size)));}next();});};})();" /** Settles the page's `navigator.share` Promise [id]: resolved when [errorName] is null, else rejected with it. */ internal fun raftWebViewShareSettleScript(id: String, errorName: String?): String = "(function(){var s=window.__raftShareSettle;if(s)s(${JSONObject.quote(id)},${if (errorName == null) "null" else JSONObject.quote(errorName)});})();" +/** Tells the page's share [id] that its last chunk is written, so it reads and posts the next. */ +internal fun raftWebViewShareAckScript(id: String): String = + "(function(){var a=window.__raftShareAck;if(a)a(${JSONObject.quote(id)});})();" + /** At most this many bytes in one share (the files together). */ internal const val RaftWebViewShareMaxBytes: Long = 100L * 1024L * 1024L -internal class RaftWebViewShareFile(val name: String, val mimeType: String, val bytes: ByteArray) +/** At most this many files in one share. */ +internal const val RaftWebViewShareMaxFiles: Int = 64 + +/** At most this many shares being received at once (a page has one in flight; this bounds a page that posts by hand). */ +internal const val RaftWebViewShareMaxPending: Int = 4 + +/** A share whose page has posted nothing for this long is given up (`AbortError`). */ +internal const val RaftWebViewShareIdleTimeoutMs: Long = 2L * 60L * 1_000L + +/** One received file: its safe on-disk [name] (unique in the share), the page's type as given, its byte count. */ +internal class RaftWebViewShareFile(val name: String, val mimeType: String, val size: Long) internal class RaftWebViewShareRequest( val id: String, @@ -62,10 +91,31 @@ internal class RaftWebViewShareRequest( val files: List, ) -internal sealed interface RaftWebViewShareAssembly { - class Ready(val request: RaftWebViewShareRequest) : RaftWebViewShareAssembly +/** What the app does after a share message ([RaftWebViewShareReceiver.accept]). */ +internal sealed interface RaftWebViewShareSignal { + /** The chunk is written; the page may post the next ([raftWebViewShareAckScript]). */ + data class Ack(val id: String) : RaftWebViewShareSignal + + /** Every file is complete in the sink; the share sheet can open. */ + class Ready(val request: RaftWebViewShareRequest) : RaftWebViewShareSignal + + /** The share is over; the page's Promise is to be rejected with [errorName]. */ + data class Failed(val id: String, val errorName: String, val reason: String) : RaftWebViewShareSignal +} + +/** + * Where a share's bytes go as they arrive (Android: files in a staging folder). Calls come from the + * receiver's own thread, in message order; a throw fails the share (`DataError`). + */ +internal interface RaftWebViewShareSink { + /** A new share [id] with these files (safe, unique names), all empty so far. */ + fun open(id: String, fileNames: List) + + /** The next [bytes] of file [fileIndex] of share [id]. */ + fun append(id: String, fileIndex: Int, bytes: ByteArray) - data class Failed(val id: String, val reason: String) : RaftWebViewShareAssembly + /** Share [id] failed or was given up: drop what was written. Unknown ids are fine. */ + fun discard(id: String) } /** Whether a port message ([raftWebViewShareShimScript]) is part of a share rather than a download read. */ @@ -73,10 +123,33 @@ internal fun raftWebViewIsShareMessage(raw: String): Boolean = "share-" in raw && runCatching { JSONObject(raw).optString("k").startsWith("share-") }.getOrDefault(false) /** - * Puts the page's share messages back together, per share id: the files announced at `share-start`, - * their chunks in order and to their announced sizes, under [maxBytes] together. + * A cheap first look (no parse; the message may be a 500 KB chunk on the UI thread): false means + * [raw] is surely not a share message, true means [RaftWebViewShareReceiver.accept] decides. */ -internal class RaftWebViewShareAssembler(private val maxBytes: Long = RaftWebViewShareMaxBytes) { +internal fun raftWebViewMayBeShareMessage(raw: String): Boolean = "\"share-" in raw + +/** A share id as the shim makes it (`s3_1700000000000`): letters, digits and `_`, never empty. */ +internal fun raftWebViewShareIdIsValid(id: String): Boolean = + id.length in 1..64 && id.all { it in 'a'..'z' || it in 'A'..'Z' || it in '0'..'9' || it == '_' } + +/** + * Receives the page's share messages, per share id: the files announced at `share-start`, their + * chunks in order and to their announced sizes, under [maxBytes] together. Each decoded chunk goes + * straight to [sink]; no file is held in memory. Not thread-safe: one thread (not the UI thread; a + * chunk is parsed and decoded here), messages in the order the page posted them. + * + * Every share that starts ends in exactly one [RaftWebViewShareSignal.Ready] or + * [RaftWebViewShareSignal.Failed] (or the page's own `share-error`, which it has settled itself), + * so the page's Promise always settles: a bad message fails it, one evicted by newer shares or + * silent for [idleTimeoutMs] ([expire]) or still open at [abortAll] is aborted. + */ +internal class RaftWebViewShareReceiver( + private val sink: RaftWebViewShareSink, + private val nowMillis: () -> Long, + private val maxBytes: Long = RaftWebViewShareMaxBytes, + private val maxFiles: Int = RaftWebViewShareMaxFiles, + private val idleTimeoutMs: Long = RaftWebViewShareIdleTimeoutMs, +) { private class Pending( val title: String, val text: String, @@ -84,8 +157,8 @@ internal class RaftWebViewShareAssembler(private val maxBytes: Long = RaftWebVie val names: List, val types: List, val sizes: List, + var lastMessageAt: Long, ) { - val parts = sizes.map { ArrayList() } val received = LongArray(sizes.size) val nextChunk = IntArray(sizes.size) var nextFile = 0 @@ -93,97 +166,221 @@ internal class RaftWebViewShareAssembler(private val maxBytes: Long = RaftWebVie private val pending = LinkedHashMap() - @OptIn(ExperimentalEncodingApi::class) - fun accept(raw: String): RaftWebViewShareAssembly? { + val pendingCount: Int get() = pending.size + + /** The signals [raw] leads to (often none), or null when it is not a share message at all. */ + fun accept(raw: String): List? { val message = runCatching { JSONObject(raw) }.getOrNull() ?: return null - val id = message.optString("s").takeIf { it.isNotBlank() } ?: return null - when (message.optString("k")) { - "share-start" -> { - val files = message.optJSONArray("files") - val names = ArrayList() - val types = ArrayList() - val sizes = ArrayList() - for (index in 0 until (files?.length() ?: 0)) { - val file = files?.optJSONObject(index) ?: return fail(id, "file_meta") - names += file.optString("name") - types += file.optString("type") - sizes += file.optLong("size", -1L).also { if (it < 0) return fail(id, "file_meta") } - } - if (sizes.sum() > maxBytes) return fail(id, "too_large") - while (pending.size >= 4) pending.remove(pending.keys.first()) - pending[id] = Pending(message.optString("title"), message.optString("text"), message.optString("url"), names, types, sizes) - return null - } - "share-chunk" -> { - val share = pending[id] ?: return null - val file = message.optInt("f", -1) - if (file < share.nextFile || file >= share.sizes.size) return fail(id, "chunk_order") - // Files are read one after another; an empty one sends no chunk. - if (file > share.nextFile && (share.nextFile until file).any { share.received[it] != share.sizes[it] }) { - return fail(id, "chunk_order") - } - share.nextFile = file - if (message.optInt("i", -1) != share.nextChunk[file]) return fail(id, "chunk_order") - val bytes = runCatching { Base64.decode(message.optString("d")) }.getOrNull() ?: return fail(id, "chunk_decode") - share.received[file] += bytes.size - if (share.received[file] > share.sizes[file]) return fail(id, "size_mismatch") - share.parts[file] += bytes - share.nextChunk[file]++ - return null - } + val kind = message.optString("k") + if (!kind.startsWith("share-")) return null + val now = nowMillis() + val out = ArrayList() + expireInto(now, out) + val id = message.optString("s") + if (id.isBlank()) return out + if (!raftWebViewShareIdIsValid(id)) { + // Never a folder or a key; the page (if it is waiting on this id at all) is told. + if (id.length <= 128) out += RaftWebViewShareSignal.Failed(id, "DataError", "id") + return out + } + when (kind) { + "share-start" -> start(id, message, now, out) + "share-chunk" -> chunk(id, message, now, out) "share-end" -> { - val share = pending.remove(id) ?: return null + val share = pending.remove(id) ?: return out if (share.sizes.indices.any { share.received[it] != share.sizes[it] }) { - return RaftWebViewShareAssembly.Failed(id, "size_mismatch") + discard(id) + out += RaftWebViewShareSignal.Failed(id, "DataError", "size_mismatch") + } else { + val files = + share.sizes.indices.map { RaftWebViewShareFile(share.names[it], share.types[it], share.sizes[it]) } + out += RaftWebViewShareSignal.Ready(RaftWebViewShareRequest(id, share.title, share.text, share.url, files)) } - val used = HashSet() - val files = - share.sizes.indices.map { index -> - val all = ByteArray(share.sizes[index].toInt()) - var offset = 0 - share.parts[index].forEach { part -> - part.copyInto(all, offset) - offset += part.size - } - val type = share.types[index].ifBlank { "application/octet-stream" } - RaftWebViewShareFile( - name = raftWebViewShareUniqueName( - raftWebViewDownloadFileName(share.names[index].takeIf { it.isNotBlank() }, null, "", type), - used, - ), - mimeType = type, - bytes = all, - ) - } - return RaftWebViewShareAssembly.Ready(RaftWebViewShareRequest(id, share.title, share.text, share.url, files)) } - "share-error" -> { - pending.remove(id) - return null - } - else -> return null + "share-error" -> if (pending.remove(id) != null) discard(id) + } + return out + } + + /** Gives up the shares whose page has been silent for [idleTimeoutMs]. */ + fun expire(): List = ArrayList().also { expireInto(nowMillis(), it) } + + /** Gives up every share still being received (the page is going away). */ + fun abortAll(reason: String = "closed"): List { + val ids = pending.keys.toList() + pending.clear() + return ids.map { id -> + discard(id) + RaftWebViewShareSignal.Failed(id, "AbortError", reason) + } + } + + private fun expireInto(now: Long, out: MutableList) { + val expired = pending.filter { (_, share) -> now - share.lastMessageAt > idleTimeoutMs }.keys.toList() + expired.forEach { id -> + pending.remove(id) + discard(id) + out += RaftWebViewShareSignal.Failed(id, "AbortError", "expired") + } + } + + private fun start(id: String, message: JSONObject, now: Long, out: MutableList) { + if (pending.containsKey(id)) return fail(id, "restart", out) + val files = message.optJSONArray("files") + val count = files?.length() ?: 0 + if (count > maxFiles) return fail(id, "too_many_files", out) + val names = ArrayList(count) + val types = ArrayList(count) + val sizes = ArrayList(count) + val used = HashSet() + var total = 0L + for (index in 0 until count) { + val file = files?.optJSONObject(index) ?: return fail(id, "file_meta", out) + val size = file.optLong("size", -1L) + if (size < 0L) return fail(id, "file_meta", out) + // Page-supplied sizes: each one bounded on its own, and the sum kept from wrapping. + if (size > maxBytes || size > maxBytes - total) return fail(id, "too_large", out) + total += size + val type = file.optString("type") + names += raftWebViewShareFileName(file.optString("name"), type, used) + types += type + sizes += size + } + while (pending.size >= RaftWebViewShareMaxPending) { + val oldest = pending.keys.first() + pending.remove(oldest) + discard(oldest) + out += RaftWebViewShareSignal.Failed(oldest, "AbortError", "evicted") + } + if (count > 0 && runCatching { sink.open(id, names) }.isFailure) return fail(id, "stage_open", out) + pending[id] = + Pending(message.optString("title"), message.optString("text"), message.optString("url"), names, types, sizes, now) + } + + @OptIn(ExperimentalEncodingApi::class) + private fun chunk(id: String, message: JSONObject, now: Long, out: MutableList) { + val share = pending[id] ?: return + share.lastMessageAt = now + val file = message.optInt("f", -1) + if (file < share.nextFile || file >= share.sizes.size) return fail(id, "chunk_order", out) + // Files are read one after another; an empty one sends no chunk. + if (file > share.nextFile && (share.nextFile until file).any { share.received[it] != share.sizes[it] }) { + return fail(id, "chunk_order", out) } + share.nextFile = file + if (message.optInt("i", -1) != share.nextChunk[file]) return fail(id, "chunk_order", out) + val data = message.optString("d") + val remaining = share.sizes[file] - share.received[file] + // Base64 of n characters is at least n / 4 * 3 - 2 bytes: too much is refused before it is decoded. + if (data.length.toLong() / 4L * 3L - 2L > remaining) return fail(id, "size_mismatch", out) + val bytes = runCatching { Base64.decode(data) }.getOrNull() ?: return fail(id, "chunk_decode", out) + if (bytes.isEmpty()) return fail(id, "chunk_decode", out) + if (bytes.size > remaining) return fail(id, "size_mismatch", out) + if (runCatching { sink.append(id, file, bytes) }.isFailure) return fail(id, "stage_write", out) + share.received[file] += bytes.size.toLong() + share.nextChunk[file]++ + out += RaftWebViewShareSignal.Ack(id) } - private fun fail(id: String, reason: String): RaftWebViewShareAssembly { + private fun fail(id: String, reason: String, out: MutableList) { pending.remove(id) - return RaftWebViewShareAssembly.Failed(id, reason) + discard(id) + out += RaftWebViewShareSignal.Failed(id, "DataError", reason) + } + + private fun discard(id: String) { + runCatching { sink.discard(id) } } } -/** [name], or `name (2).ext`, ... when another file of the same share already has it. */ +/** + * The on-disk name of a shared file: the page's [name] as one safe path component + * ([RaftShareFileName.sanitize]: no path, no control or reserved characters, at most + * [RaftShareFileName.MAX_UTF8_BYTES] bytes; `download` with the type's extension when the page gave + * none), made unique among the share's files ([used]). + */ +internal fun raftWebViewShareFileName(name: String, mimeType: String, used: MutableSet): String = + raftWebViewShareUniqueName( + RaftShareFileName.sanitize(raftWebViewDownloadFileName(name.takeIf { it.isNotBlank() }, null, "", mimeType), null), + used, + ) + +/** + * [name], or `name (2).ext`, ... when another file of the same share already has it (compared + * without case, as some filesystems do), still within [RaftShareFileName.MAX_UTF8_BYTES]. + */ internal fun raftWebViewShareUniqueName(name: String, used: MutableSet): String { - val safe = raftSafeDownloadFileName(name) ?: "file" - if (used.add(safe)) return safe - val dot = safe.lastIndexOf('.').takeIf { it > 0 } ?: safe.length + val safe = RaftShareFileName.sanitize(name, null) + if (used.add(safe.lowercase())) return safe + val dot = safe.lastIndexOf('.').takeIf { it > 0 && safe.length - it <= 17 } ?: safe.length + val stem = safe.substring(0, dot) + val extension = safe.substring(dot) var index = 2 while (true) { - val candidate = safe.substring(0, dot) + " ($index)" + safe.substring(dot) - if (used.add(candidate)) return candidate + val suffix = " ($index)$extension" + val candidate = + raftWebViewShareUtf8Prefix(stem, RaftShareFileName.MAX_UTF8_BYTES - suffix.encodeToByteArray().size) + suffix + if (used.add(candidate.lowercase())) return candidate index++ } } +/** The longest prefix of [text] within [maxBytes] of UTF-8, no surrogate pair split. */ +private fun raftWebViewShareUtf8Prefix(text: String, maxBytes: Int): String { + if (text.encodeToByteArray().size <= maxBytes) return text + var used = 0 + var index = 0 + while (index < text.length) { + val step = if (text[index].isHighSurrogate() && index + 1 < text.length) 2 else 1 + val bytes = text.substring(index, index + step).encodeToByteArray().size + if (used + bytes > maxBytes) break + used += bytes + index += step + } + return text.substring(0, index) +} + +/** + * The type of the share intent: the files' one type, else their one top-level type (`image/` + `*`), + * else any type. [mimeTypes] are already normalised (`type/subtype`, no parameters). + */ +internal fun raftWebViewShareIntentType(mimeTypes: List): String { + val distinct = mimeTypes.distinct() + distinct.singleOrNull()?.let { return it } + val major = distinct.map { it.substringBefore('/') }.distinct().singleOrNull()?.takeIf { it.isNotBlank() && it != "*" } + return if (major != null) "$major/*" else "*/*" +} + +/** The folder under the app's cache that shares are staged in; the attachment share's own (`slock-share-files`). */ +internal const val RaftWebViewShareStagingDirName: String = "slock-share-files" + +/** The staging lifetime rules of the attachment share (`sweepAndroidAttachmentShareStaging`), which sweeps the same folder. */ +internal const val RaftWebViewShareStagingMaxAgeMs: Long = 24L * 60L * 60L * 1_000L +internal const val RaftWebViewShareStagingMaxEntries: Int = 16 + +private val RaftWebViewShareStagingEntryPattern = Regex("[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}") + +/** Whether [name] is a share entry of the staging folder: a lower-case UUID, as the attachment share names its own. */ +internal fun raftWebViewShareStagingIsEntryName(name: String): Boolean = name.matches(RaftWebViewShareStagingEntryPattern) + +/** + * The staging entries (name to last-modified) to remove before a new share is staged, by the + * attachment share's rules: those older than [maxAgeMs] and all but the newest [maxEntries]. A + * receiver may keep reading a granted URI after the chooser returns, so a fresh entry stays. Names + * that are not share entries are left to the attachment sweep. + */ +internal fun raftWebViewShareStaleStagingEntries( + entries: List>, + nowMillis: Long, + maxAgeMs: Long = RaftWebViewShareStagingMaxAgeMs, + maxEntries: Int = RaftWebViewShareStagingMaxEntries, +): List { + val own = entries.filter { raftWebViewShareStagingIsEntryName(it.first) } + val (kept, expired) = own.partition { (nowMillis - it.second).coerceAtLeast(0L) <= maxAgeMs } + val overflow = kept.sortedByDescending { it.second }.drop(maxEntries.coerceAtLeast(0)) + return (expired + overflow).map { it.first } +} + /** The text an Android text-only share sends: title, text and url, each once, on their own lines. */ internal fun raftWebViewShareText(title: String, text: String, url: String): String = listOf(text, url).filter { it.isNotBlank() }.distinct().joinToString("\n").ifBlank { title } diff --git a/compose/shared/src/commonTest/kotlin/build/raft/app/RaftWebViewShareTest.kt b/compose/shared/src/commonTest/kotlin/build/raft/app/RaftWebViewShareTest.kt index 8d1992e940..89e5320011 100644 --- a/compose/shared/src/commonTest/kotlin/build/raft/app/RaftWebViewShareTest.kt +++ b/compose/shared/src/commonTest/kotlin/build/raft/app/RaftWebViewShareTest.kt @@ -6,7 +6,9 @@ import kotlin.io.encoding.Base64 import kotlin.io.encoding.ExperimentalEncodingApi import kotlin.test.Test import kotlin.test.assertEquals +import kotlin.test.assertFalse import kotlin.test.assertIs +import kotlin.test.assertNotNull import kotlin.test.assertNull import kotlin.test.assertTrue @@ -33,9 +35,57 @@ class RaftWebViewShareTest { assertTrue("\"AbortError\"" in raftWebViewShareSettleScript("s1_9", "AbortError")) } + @Test + fun shimGuardsActivationInFlightAndTopFrame() { + val script = raftWebViewShareShimScript() + // Not in a subframe: the app only takes the port's messages from the main frame. + assertTrue("try{if(window.top!==window)return;}catch(e){return;}" in script) + assertTrue(script.indexOf("window.top!==window") < script.indexOf("n.canShare=canShare")) + // One share at a time, and only on a user gesture, before the data is looked at (Web Share's order). + val inFlight = script.indexOf("if(active!==null){rej(err('InvalidStateError'") + val activation = script.indexOf("var ua=n.userActivation;if(ua&&ua.isActive===false){rej(err('NotAllowedError'") + val data = script.indexOf("if(!canShare(d)){rej(new TypeError(") + assertTrue(inFlight > 0 && activation > inFlight && data > activation) + assertTrue("pending[id]=entry;active=id;" in script) + assertTrue("if(active===id)active=null;" in script) + // A chunk is read only after the app has written the one before. + assertTrue("'__raftShareAck'" in script) + assertTrue("entry.next=function(){ci++;off+=size;next();};" in script) + assertTrue("f.length>$RaftWebViewShareMaxFiles" in script) + assertEquals("(function(){var a=window.__raftShareAck;if(a)a(\"s1_9\");})();", raftWebViewShareAckScript("s1_9")) + } + + private class FakeSink : RaftWebViewShareSink { + val files = LinkedHashMap>>>() + val discarded = ArrayList() + var failWrites = false + + override fun open(id: String, fileNames: List) { + files[id] = fileNames.map { it to ArrayList() } + } + + override fun append(id: String, fileIndex: Int, bytes: ByteArray) { + if (failWrites) error("disk full") + files.getValue(id)[fileIndex].second.addAll(bytes.toList()) + } + + override fun discard(id: String) { + discarded += id + files.remove(id) + } + + fun bytes(id: String, fileIndex: Int): ByteArray = files.getValue(id)[fileIndex].second.toByteArray() + } + + private var now = 1_000L + private val sink = FakeSink() + + private fun receiver(maxBytes: Long = RaftWebViewShareMaxBytes) = + RaftWebViewShareReceiver(sink = sink, nowMillis = { now }, maxBytes = maxBytes) + private fun msg(vararg pairs: Pair): String = JSONObject().apply { pairs.forEach { (k, v) -> put(k, v) } }.toString() - private fun start(id: String, vararg files: Triple): String = + private fun start(id: String, vararg files: Triple): String = msg( "s" to id, "k" to "share-start", "title" to "周报", "text" to "", "url" to "", "files" to JSONArray().apply { @@ -43,29 +93,254 @@ class RaftWebViewShareTest { }, ) + private fun chunk(id: String, file: Int, index: Int, bytes: ByteArray): String = + msg("s" to id, "k" to "share-chunk", "f" to file, "i" to index, "d" to Base64.encode(bytes)) + + private fun end(id: String): String = msg("s" to id, "k" to "share-end") + + private fun List?.failure(): RaftWebViewShareSignal.Failed = + assertIs(assertNotNull(this).single()) + @Test - fun assemblesTwoFilesAndDeduplicatesNames() { - val assembler = RaftWebViewShareAssembler() + fun streamsTwoFilesToTheSinkAndDeduplicatesNames() { + val receiver = receiver() val a = "第一个".encodeToByteArray() val b = byteArrayOf(1, 2, 3) - assertNull(assembler.accept(start("s1", Triple("周报.md", "text/markdown", a.size), Triple("周报.md", "text/markdown", b.size)))) + assertEquals( + emptyList(), + receiver.accept(start("s1", Triple("周报.md", "text/markdown", a.size.toLong()), Triple("周报.md", "text/markdown", b.size.toLong()))), + ) assertTrue(raftWebViewIsShareMessage(start("s1"))) - assertNull(assembler.accept(msg("s" to "s1", "k" to "share-chunk", "f" to 0, "i" to 0, "d" to Base64.encode(a)))) - assertNull(assembler.accept(msg("s" to "s1", "k" to "share-chunk", "f" to 1, "i" to 0, "d" to Base64.encode(b)))) - val ready = assertIs(assembler.accept(msg("s" to "s1", "k" to "share-end"))) + assertTrue(raftWebViewMayBeShareMessage(start("s1"))) + assertEquals(listOf("周报.md", "周报 (2).md"), sink.files.getValue("s1").map { it.first }) + // Each chunk is written as it comes and acknowledged, so the page posts the next. + assertEquals(listOf(RaftWebViewShareSignal.Ack("s1")), receiver.accept(chunk("s1", 0, 0, a.copyOfRange(0, 4)))) + assertEquals(4, sink.bytes("s1", 0).size) + assertEquals(listOf(RaftWebViewShareSignal.Ack("s1")), receiver.accept(chunk("s1", 0, 1, a.copyOfRange(4, a.size)))) + assertEquals(listOf(RaftWebViewShareSignal.Ack("s1")), receiver.accept(chunk("s1", 1, 0, b))) + val ready = assertIs(assertNotNull(receiver.accept(end("s1"))).single()) assertEquals(listOf("周报.md", "周报 (2).md"), ready.request.files.map { it.name }) - assertEquals("第一个", ready.request.files[0].bytes.decodeToString()) + assertEquals(listOf(a.size.toLong(), 3L), ready.request.files.map { it.size }) + assertEquals("第一个", sink.bytes("s1", 0).decodeToString()) + assertEquals(listOf(1, 2, 3), sink.bytes("s1", 1).toList()) assertEquals("周报", ready.request.title) + assertEquals(0, receiver.pendingCount) + assertTrue(sink.discarded.isEmpty()) + } + + @Test + fun notAShareMessageIsLeftToTheDownloadReader() { + val receiver = receiver() + assertNull(receiver.accept(msg("t" to "d1", "k" to "chunk", "d" to "\"share-"))) + assertNull(receiver.accept("not json")) + assertFalse(raftWebViewMayBeShareMessage(msg("t" to "d1", "d" to "AAAA"))) + } + + @Test + fun textOnlyShareNeedsNoSink() { + val receiver = receiver() + assertEquals(emptyList(), receiver.accept(start("s1"))) + val ready = assertIs(assertNotNull(receiver.accept(end("s1"))).single()) + assertTrue(ready.request.files.isEmpty()) + assertTrue(sink.files.isEmpty()) } @Test fun missingBytesOrOversizeFail() { - val assembler = RaftWebViewShareAssembler(maxBytes = 10) - assertIs(assembler.accept(start("big", Triple("a.zip", "application/zip", 11)))) - assertNull(assembler.accept(start("s2", Triple("a.txt", "text/plain", 4)))) - assertNull(assembler.accept(msg("s" to "s2", "k" to "share-chunk", "f" to 0, "i" to 0, "d" to Base64.encode(ByteArray(2))))) - val failed = assertIs(assembler.accept(msg("s" to "s2", "k" to "share-end"))) - assertEquals("size_mismatch", failed.reason) + val receiver = receiver(maxBytes = 10) + assertEquals("too_large", receiver.accept(start("big", Triple("a.zip", "application/zip", 11L))).failure().reason) + assertEquals(emptyList(), receiver.accept(start("s2", Triple("a.txt", "text/plain", 4L)))) + assertNotNull(receiver.accept(chunk("s2", 0, 0, ByteArray(2)))) + val failed = receiver.accept(end("s2")).failure() + assertEquals(RaftWebViewShareSignal.Failed("s2", "DataError", "size_mismatch"), failed) + assertEquals(listOf("s2"), sink.discarded.filter { it == "s2" }) + assertTrue(sink.files.isEmpty()) + } + + @Test + fun sizesThatAreNegativeOrOverflowTheSumAreRefused() { + val receiver = receiver() + assertEquals("file_meta", receiver.accept(start("neg", Triple("a", "", -1L))).failure().reason) + assertEquals("file_meta", receiver.accept(start("min", Triple("a", "", Long.MIN_VALUE))).failure().reason) + assertEquals("too_large", receiver.accept(start("one", Triple("a", "", RaftWebViewShareMaxBytes + 1L))).failure().reason) + // Two sizes whose sum wraps negative. + assertEquals( + "too_large", + receiver.accept(start("wrap", Triple("a", "", Long.MAX_VALUE), Triple("b", "", Long.MAX_VALUE))).failure().reason, + ) + assertEquals( + "too_large", + receiver.accept(start("sum", Triple("a", "", RaftWebViewShareMaxBytes), Triple("b", "", 1L))).failure().reason, + ) + assertEquals("file_meta", receiver.accept(msg("s" to "bad", "k" to "share-start", "files" to JSONArray().put("x"))).failure().reason) + assertEquals(0, receiver.pendingCount) + assertTrue(sink.files.isEmpty()) + // Exactly the limit is fine. + assertEquals(emptyList(), receiver.accept(start("max", Triple("a", "", RaftWebViewShareMaxBytes - 1L), Triple("b", "", 1L)))) + } + + @Test + fun tooManyFilesAreRefused() { + val files = Array(RaftWebViewShareMaxFiles + 1) { Triple("f$it.txt", "text/plain", 0L) } + assertEquals("too_many_files", receiver().accept(start("s1", *files)).failure().reason) + assertEquals(emptyList(), receiver().accept(start("s2", *files.copyOfRange(0, RaftWebViewShareMaxFiles)))) + } + + @Test + fun chunksOutOfOrderFailTheShare() { + fun started(id: String): RaftWebViewShareReceiver = + receiver().also { assertEquals(emptyList(), it.accept(start(id, Triple("a", "", 4L), Triple("b", "", 0L), Triple("c", "", 2L)))) } + // A chunk index skipped, and one repeated. + assertEquals("chunk_order", started("o1").accept(chunk("o1", 0, 1, ByteArray(2))).failure().reason) + started("o2").let { + assertNotNull(it.accept(chunk("o2", 0, 0, ByteArray(2)))) + assertEquals("chunk_order", it.accept(chunk("o2", 0, 0, ByteArray(2))).failure().reason) + // The share is gone: what the page still posts for it is ignored. + assertEquals(emptyList(), it.accept(chunk("o2", 0, 1, ByteArray(2)))) + assertEquals(emptyList(), it.accept(end("o2"))) + } + // The next file before this one is complete; a file that does not exist; going back. + assertEquals("chunk_order", started("o3").accept(chunk("o3", 2, 0, ByteArray(2))).failure().reason) + assertEquals("chunk_order", started("o4").accept(chunk("o4", 3, 0, ByteArray(1))).failure().reason) + assertEquals("chunk_order", started("o5").accept(chunk("o5", -1, 0, ByteArray(1))).failure().reason) + started("o6").let { + assertNotNull(it.accept(chunk("o6", 0, 0, ByteArray(4)))) + // The empty middle file sends nothing. + assertEquals(listOf(RaftWebViewShareSignal.Ack("o6")), it.accept(chunk("o6", 2, 0, ByteArray(2)))) + assertEquals("chunk_order", it.accept(chunk("o6", 0, 1, ByteArray(1))).failure().reason) + } + // More bytes than announced, bad base64, an empty chunk. + assertEquals("size_mismatch", started("o7").accept(chunk("o7", 0, 0, ByteArray(5))).failure().reason) + assertEquals("size_mismatch", started("o8").accept(chunk("o8", 0, 0, ByteArray(4096))).failure().reason) + assertEquals( + "chunk_decode", + started("o9").accept(msg("s" to "o9", "k" to "share-chunk", "f" to 0, "i" to 0, "d" to "!!")).failure().reason, + ) + assertEquals("chunk_decode", started("o10").accept(chunk("o10", 0, 0, ByteArray(0))).failure().reason) + assertTrue(sink.files.isEmpty()) + } + + @Test + fun aFailedWriteSettlesTheShare() { + val receiver = receiver() + assertEquals(emptyList(), receiver.accept(start("s1", Triple("a.txt", "text/plain", 4L)))) + sink.failWrites = true + assertEquals(RaftWebViewShareSignal.Failed("s1", "DataError", "stage_write"), receiver.accept(chunk("s1", 0, 0, ByteArray(4))).failure()) + assertEquals(0, receiver.pendingCount) + assertTrue("s1" in sink.discarded) + } + + @Test + fun hostileNamesBecomeOneSafeComponent() { + val used = HashSet() + assertEquals("x.txt", raftWebViewShareFileName("../x", "text/plain", used)) + assertEquals("evil.pdf", raftWebViewShareFileName("..\\..\\evil.pdf", "", used)) + assertEquals("a_b.txt", raftWebViewShareFileName("a:b.txt", "", used)) + // No name at all: `download`, with the type's extension; a second one is told apart. + assertEquals("download.md", raftWebViewShareFileName("", "text/markdown;charset=utf-8", used)) + assertEquals("download (2).md", raftWebViewShareFileName(" ", "text/markdown", used)) + assertEquals("download (3).md", raftWebViewShareFileName("..", "text/markdown", used)) + // Names differing only in case share a file on some filesystems. + assertEquals("X (2).txt", raftWebViewShareFileName("X.txt", "", used)) + val long = raftWebViewShareFileName("长".repeat(100) + ".pdf", "application/pdf", used) + assertEquals(300 + 4, ("长".repeat(100) + ".pdf").encodeToByteArray().size) + assertTrue(long.encodeToByteArray().size <= 200) + assertTrue(long.endsWith(".pdf")) + val again = raftWebViewShareFileName("长".repeat(100) + ".pdf", "application/pdf", used) + assertTrue(again.encodeToByteArray().size <= 200) + assertTrue(again.endsWith(" (2).pdf")) + assertTrue(again != long) + listOf(long, again).forEach { name -> assertTrue('/' !in name && '\\' !in name && !name.startsWith(".")) } + // Through the receiver, every announced file gets such a name. + val receiver = receiver() + assertEquals( + emptyList(), + receiver.accept(start("s1", Triple("../../etc/passwd", "", 0L), Triple("", "", 0L), Triple("a".repeat(300), "", 0L))), + ) + val names = sink.files.getValue("s1").map { it.first } + assertEquals(listOf("passwd", "download"), names.take(2)) + assertEquals(200, names[2].length) + } + + @Test + fun anIdThatIsNotAShimIdIsRefused() { + val receiver = receiver() + listOf("-", "../x", "a b", "s1/..", "s".repeat(65)).forEach { id -> + assertFalse(raftWebViewShareIdIsValid(id)) + assertEquals(RaftWebViewShareSignal.Failed(id, "DataError", "id"), receiver.accept(start(id, Triple("a", "", 1L))).failure()) + } + assertFalse(raftWebViewShareIdIsValid("")) + // Nothing to settle without an id. + assertEquals(emptyList(), receiver.accept(start("", Triple("a", "", 1L)))) + assertEquals(emptyList(), receiver.accept(start(" ", Triple("a", "", 1L)))) + assertTrue(raftWebViewShareIdIsValid("s3_1700000000000")) + assertEquals(0, receiver.pendingCount) + assertTrue(sink.files.isEmpty()) + } + + @Test + fun evictedExpiredAndAbandonedSharesAreAborted() { + val receiver = receiver() + (1..RaftWebViewShareMaxPending).forEach { assertEquals(emptyList(), receiver.accept(start("s$it", Triple("a", "", 1L)))) } + // One more: the oldest is given up, and its page told. + assertEquals(RaftWebViewShareSignal.Failed("s1", "AbortError", "evicted"), receiver.accept(start("s5", Triple("a", "", 1L))).failure()) + assertTrue("s1" in sink.discarded && "s1" !in sink.files) + assertEquals(RaftWebViewShareMaxPending, receiver.pendingCount) + // A share that goes silent expires; one that keeps posting does not. + now += RaftWebViewShareIdleTimeoutMs + assertEquals(listOf(RaftWebViewShareSignal.Ack("s5")), receiver.accept(chunk("s5", 0, 0, ByteArray(1)))) + now += 1L + assertEquals( + listOf("s2", "s3", "s4").map { RaftWebViewShareSignal.Failed(it, "AbortError", "expired") }, + receiver.expire(), + ) + assertEquals(1, receiver.pendingCount) + assertEquals(emptyList(), receiver.expire()) + // The page going away ends the rest. + assertEquals(listOf(RaftWebViewShareSignal.Failed("s5", "AbortError", "closed")), receiver.abortAll()) + assertEquals(0, receiver.pendingCount) + assertTrue(sink.files.isEmpty()) + // A second start of an id in flight fails it. + assertEquals(emptyList(), receiver.accept(start("s9", Triple("a", "", 1L)))) + assertEquals("restart", receiver.accept(start("s9", Triple("a", "", 1L))).failure().reason) + // The page's own read error ends its share without a signal: it has settled it itself. + assertEquals(emptyList(), receiver.accept(start("s10", Triple("a", "", 1L)))) + assertEquals(emptyList(), receiver.accept(msg("s" to "s10", "k" to "share-error"))) + assertEquals(0, receiver.pendingCount) + assertTrue(sink.files.isEmpty()) + } + + @Test + fun intentTypeIsTheCommonTypeOrAWildcard() { + assertEquals("text/markdown", raftWebViewShareIntentType(listOf("text/markdown"))) + assertEquals("image/png", raftWebViewShareIntentType(listOf("image/png", "image/png"))) + assertEquals("image/*", raftWebViewShareIntentType(listOf("image/png", "image/jpeg"))) + assertEquals("*/*", raftWebViewShareIntentType(listOf("image/png", "application/pdf"))) + assertEquals("*/*", raftWebViewShareIntentType(emptyList())) + } + + @Test + fun stagingEntriesFollowTheAttachmentSharesLifetime() { + val day = RaftWebViewShareStagingMaxAgeMs + val at = 10L * day + fun uuid(index: Int) = "00000000-0000-0000-0000-" + index.toString().padStart(12, '0') + assertTrue(raftWebViewShareStagingIsEntryName(uuid(1))) + assertFalse(raftWebViewShareStagingIsEntryName("web-share")) + assertFalse(raftWebViewShareStagingIsEntryName(uuid(1).uppercase().replace('0', 'A'))) + // A fresh entry stays (a receiver may still be reading it); a day-old one goes; others are not ours to judge. + assertEquals( + listOf(uuid(2)), + raftWebViewShareStaleStagingEntries( + listOf(uuid(1) to at - 60_000L, uuid(2) to at - day - 1L, "not-a-share-entry" to 0L, uuid(3) to at + 5_000L), + nowMillis = at, + ), + ) + // All but the newest ones go. + assertEquals( + listOf(uuid(3), uuid(4)), + raftWebViewShareStaleStagingEntries((0 until 5).map { uuid(it) to at - it * 1_000L }, nowMillis = at, maxEntries = 3), + ) + assertTrue(raftWebViewShareStaleStagingEntries((0 until RaftWebViewShareStagingMaxEntries).map { uuid(it) to at }, at).isEmpty()) } @Test From 25e4f903ab597826f1b05c2eba78fbcfa71ca406 Mon Sep 17 00:00:00 2001 From: Lagoon Date: Fri, 20 Nov 2026 10:40:33 +0000 Subject: [PATCH 6/6] fix(webview): re-arm share expiry and tell share messages exactly Second review of #5120: - the expiry check comes back while a share is still being received, so one whose last message was handled late still ends - a session whose port is gone takes no more messages - a share message is told by its leading kind, so a download read can never be detoured past its own chunks - the data URL is split at its last comma - tests assert the acknowledged chunk rather than any non-null result Co-Authored-By: Claude Fable 5.2 --- .../raft/app/RaftSandboxWebView.android.kt | 56 ++++++++++++++----- .../kotlin/build/raft/app/RaftWebViewShare.kt | 16 +++--- .../build/raft/app/RaftWebViewShareTest.kt | 26 +++++++-- 3 files changed, 70 insertions(+), 28 deletions(-) diff --git a/compose/shared/src/androidMain/kotlin/build/raft/app/RaftSandboxWebView.android.kt b/compose/shared/src/androidMain/kotlin/build/raft/app/RaftSandboxWebView.android.kt index 9b1efae71f..bdc77ba0f2 100644 --- a/compose/shared/src/androidMain/kotlin/build/raft/app/RaftSandboxWebView.android.kt +++ b/compose/shared/src/androidMain/kotlin/build/raft/app/RaftSandboxWebView.android.kt @@ -1120,23 +1120,31 @@ internal class RaftAndroidSandboxWebView( * sheet, the Promise settled) comes back here. Nothing thrown leaves this function. */ private fun acceptShareMessage(session: RaftAndroidWebViewShareSession, raw: String) { + // A session whose port is gone takes nothing more: nothing would abort what it started. + if (destroyed || shareSession !== session) return scheduleShareExpiry(session) - runShareIo(session, notShare = { handleDownloadMessage(raw) }) { session.accept(raw) } + runShareIo(session) { session.accept(raw) } } - /** Runs [work] on the share thread and its signals back on the main thread. */ + /** + * Runs [work] on the share thread and its signals back on the main thread. With [rearmExpiry], + * the expiry check is set again while the session still has a share being received. + */ private fun runShareIo( session: RaftAndroidWebViewShareSession, - notShare: (() -> Unit)? = null, + rearmExpiry: Boolean = false, work: () -> List? ) { runCatching { RaftWebViewShareIo.execute { val signals = runCatching(work).getOrElse { runCatching { session.abortAll("internal") }.getOrDefault(emptyList()) } - if (signals == null) { - if (notShare != null) shareMainHandler.post { if (!destroyed && shareSession === session) notShare() } - } else if (signals.isNotEmpty()) { - shareMainHandler.post { deliverShareSignals(session, signals) } + if (!signals.isNullOrEmpty()) shareMainHandler.post { deliverShareSignals(session, signals) } + if (rearmExpiry && runCatching { session.hasPending() }.getOrDefault(false)) { + shareMainHandler.post { + if (!destroyed && shareSession === session && shareExpiryCheck == null) { + scheduleShareExpiry(session, RaftWebViewShareExpiryRecheckMs) + } + } } } }.onFailure { Log.w(LOG_TAG, "page_share io unavailable", it) } @@ -1169,17 +1177,22 @@ internal class RaftAndroidSandboxWebView( /** * Gives up shares whose page has gone silent: every share message pushes this check - * [RaftWebViewShareIdleTimeoutMs] ahead, so when it runs none of them has had one for that long. + * [RaftWebViewShareIdleTimeoutMs] ahead. A share's silence is counted from when its last message + * was handled on the share thread, which may be later than when it was posted, so the check comes + * back every [RaftWebViewShareExpiryRecheckMs] until no share is left being received. */ - private fun scheduleShareExpiry(session: RaftAndroidWebViewShareSession) { + private fun scheduleShareExpiry( + session: RaftAndroidWebViewShareSession, + delayMs: Long = RaftWebViewShareIdleTimeoutMs + 1_000L + ) { shareExpiryCheck?.let { shareMainHandler.removeCallbacks(it) } val check = Runnable { shareExpiryCheck = null - if (!destroyed && shareSession === session) runShareIo(session) { session.expire() } + if (!destroyed && shareSession === session) runShareIo(session, rearmExpiry = true) { session.expire() } } shareExpiryCheck = check - shareMainHandler.postDelayed(check, RaftWebViewShareIdleTimeoutMs + 1_000L) + shareMainHandler.postDelayed(check, delayMs) } private fun discardShareFolder(folder: java.io.File?) { @@ -1298,7 +1311,7 @@ internal class RaftAndroidSandboxWebView( if (destroyed || !isMainFrame || sourceOrigin.toString() != originRule) return val raw = message.data ?: return // A share message goes to the share thread whole; this (UI) thread neither parses nor decodes it. - if (raftWebViewMayBeShareMessage(raw)) { + if (raftWebViewIsShareMessage(raw)) { acceptShareMessage(session, raw) return } @@ -1330,7 +1343,7 @@ internal class RaftAndroidSandboxWebView( shareExpiryCheck = null shareSession?.let { session -> shareSession = null - runShareIo(session) { session.abortAll("closed") } + runShareIo(session) { session.close() } } } @@ -1549,6 +1562,8 @@ internal actual val raftWebViewDesktopModeViaViewportMeta: Boolean = true * One thread for every page share ([raftWebViewShareShimScript]): parsing, base64 decoding and file * writes stay off the UI thread and run in the order the messages were posted. It ends when idle. */ +private const val RaftWebViewShareExpiryRecheckMs: Long = 10_000L + private val RaftWebViewShareIo: java.util.concurrent.Executor by lazy { java.util.concurrent.ThreadPoolExecutor( 0, @@ -1575,8 +1590,21 @@ private class RaftAndroidWebViewShareSession(private val shareRoot: java.io.File private val fileNames = HashMap>() private val receiver = RaftWebViewShareReceiver(sink = this, nowMillis = { android.os.SystemClock.elapsedRealtime() }) + private var closed = false + + /** Nothing is taken once the session is closed: a message still on its way then starts no share. */ + @Synchronized + fun accept(raw: String): List? = if (closed) emptyList() else receiver.accept(raw)?.map(::staged) + @Synchronized - fun accept(raw: String): List? = receiver.accept(raw)?.map(::staged) + fun hasPending(): Boolean = receiver.pendingCount > 0 + + /** The page's port is gone: every share still being received is given up, and no more are taken. */ + @Synchronized + fun close(): List { + closed = true + return receiver.abortAll("closed").map(::staged) + } @Synchronized fun expire(): List = receiver.expire().map(::staged) diff --git a/compose/shared/src/commonMain/kotlin/build/raft/app/RaftWebViewShare.kt b/compose/shared/src/commonMain/kotlin/build/raft/app/RaftWebViewShare.kt index 547fdc9be4..15a014305d 100644 --- a/compose/shared/src/commonMain/kotlin/build/raft/app/RaftWebViewShare.kt +++ b/compose/shared/src/commonMain/kotlin/build/raft/app/RaftWebViewShare.kt @@ -54,7 +54,7 @@ internal fun raftWebViewShareShimScript(maxBytes: Long = RaftWebViewShareMaxByte "var fi=0,off=0,ci=0,size=393216;" + "function next(){if(pending[id]!==entry)return;if(fi>=files.length){post({k:'share-end'});return;}var f=files[fi];" + "if(off>=f.size){fi++;off=0;ci=0;next();return;}" + - "var fr=new FileReader();fr.onload=function(){if(pending[id]!==entry)return;var s=String(fr.result);var c=s.indexOf(',');" + + "var fr=new FileReader();fr.onload=function(){if(pending[id]!==entry)return;var s=String(fr.result);var c=s.lastIndexOf(',');" + "entry.next=function(){ci++;off+=size;next();};" + "post({k:'share-chunk',f:fi,i:ci,d:c>=0?s.substring(c+1):''});};" + "fr.onerror=function(){if(pending[id]!==entry)return;post({k:'share-error'});settle(id,'DataError');};" + @@ -118,15 +118,15 @@ internal interface RaftWebViewShareSink { fun discard(id: String) } -/** Whether a port message ([raftWebViewShareShimScript]) is part of a share rather than a download read. */ -internal fun raftWebViewIsShareMessage(raw: String): Boolean = - "share-" in raw && runCatching { JSONObject(raw).optString("k").startsWith("share-") }.getOrDefault(false) - /** - * A cheap first look (no parse; the message may be a 500 KB chunk on the UI thread): false means - * [raw] is surely not a share message, true means [RaftWebViewShareReceiver.accept] decides. + * Whether a port message is part of a share rather than a download read. Exact and constant-time + * (the message may be a 500 KB chunk on the UI thread): the shim serialises every message with its + * kind `k` first (`{"k":"share-chunk",...}`), and a download read's messages never start so, whatever + * names or bytes they carry. [RaftWebViewShareReceiver.accept] still reads the parsed kind. */ -internal fun raftWebViewMayBeShareMessage(raw: String): Boolean = "\"share-" in raw +internal fun raftWebViewIsShareMessage(raw: String): Boolean = raw.startsWith(RaftWebViewShareMessagePrefix) + +private const val RaftWebViewShareMessagePrefix = "{\"k\":\"share-" /** A share id as the shim makes it (`s3_1700000000000`): letters, digits and `_`, never empty. */ internal fun raftWebViewShareIdIsValid(id: String): Boolean = diff --git a/compose/shared/src/commonTest/kotlin/build/raft/app/RaftWebViewShareTest.kt b/compose/shared/src/commonTest/kotlin/build/raft/app/RaftWebViewShareTest.kt index 89e5320011..350addc815 100644 --- a/compose/shared/src/commonTest/kotlin/build/raft/app/RaftWebViewShareTest.kt +++ b/compose/shared/src/commonTest/kotlin/build/raft/app/RaftWebViewShareTest.kt @@ -110,8 +110,6 @@ class RaftWebViewShareTest { emptyList(), receiver.accept(start("s1", Triple("周报.md", "text/markdown", a.size.toLong()), Triple("周报.md", "text/markdown", b.size.toLong()))), ) - assertTrue(raftWebViewIsShareMessage(start("s1"))) - assertTrue(raftWebViewMayBeShareMessage(start("s1"))) assertEquals(listOf("周报.md", "周报 (2).md"), sink.files.getValue("s1").map { it.first }) // Each chunk is written as it comes and acknowledged, so the page posts the next. assertEquals(listOf(RaftWebViewShareSignal.Ack("s1")), receiver.accept(chunk("s1", 0, 0, a.copyOfRange(0, 4)))) @@ -133,7 +131,23 @@ class RaftWebViewShareTest { val receiver = receiver() assertNull(receiver.accept(msg("t" to "d1", "k" to "chunk", "d" to "\"share-"))) assertNull(receiver.accept("not json")) - assertFalse(raftWebViewMayBeShareMessage(msg("t" to "d1", "d" to "AAAA"))) + } + + @Test + fun aShareMessageIsToldByItsLeadingKindAlone() { + // As the shim serialises them: the kind first, the id last. + assertTrue(raftWebViewIsShareMessage("{\"k\":\"share-start\",\"title\":\"\",\"files\":[],\"s\":\"s1_9\"}")) + assertTrue(raftWebViewIsShareMessage("{\"k\":\"share-chunk\",\"f\":0,\"i\":0,\"d\":\"AAAA\",\"s\":\"s1_9\"}")) + val script = raftWebViewShareShimScript() + assertTrue("function post(o){o.s=id;" in script) + listOf("share-start", "share-chunk", "share-end", "share-error").forEach { assertTrue("post({k:'$it'" in script) } + // A download read is never one, whatever its file name or bytes hold. + assertFalse(raftWebViewIsShareMessage("{\"k\":\"start\",\"name\":\"share-notes.md\",\"t\":\"d1\"}")) + assertFalse(raftWebViewIsShareMessage("{\"name\":\"\\\"k\\\":\\\"share-x\",\"t\":\"d1\"}")) + assertFalse(raftWebViewIsShareMessage("{\"t\":\"d1\",\"k\":\"share-start\"}")) + assertFalse(raftWebViewIsShareMessage("")) + // The data URL is split at its last comma: a Blob type may hold one, base64 never does. + assertTrue("var c=s.lastIndexOf(',');" in script) } @Test @@ -150,7 +164,7 @@ class RaftWebViewShareTest { val receiver = receiver(maxBytes = 10) assertEquals("too_large", receiver.accept(start("big", Triple("a.zip", "application/zip", 11L))).failure().reason) assertEquals(emptyList(), receiver.accept(start("s2", Triple("a.txt", "text/plain", 4L)))) - assertNotNull(receiver.accept(chunk("s2", 0, 0, ByteArray(2)))) + assertEquals(listOf(RaftWebViewShareSignal.Ack("s2")), receiver.accept(chunk("s2", 0, 0, ByteArray(2)))) val failed = receiver.accept(end("s2")).failure() assertEquals(RaftWebViewShareSignal.Failed("s2", "DataError", "size_mismatch"), failed) assertEquals(listOf("s2"), sink.discarded.filter { it == "s2" }) @@ -193,7 +207,7 @@ class RaftWebViewShareTest { // A chunk index skipped, and one repeated. assertEquals("chunk_order", started("o1").accept(chunk("o1", 0, 1, ByteArray(2))).failure().reason) started("o2").let { - assertNotNull(it.accept(chunk("o2", 0, 0, ByteArray(2)))) + assertEquals(listOf(RaftWebViewShareSignal.Ack("o2")), it.accept(chunk("o2", 0, 0, ByteArray(2)))) assertEquals("chunk_order", it.accept(chunk("o2", 0, 0, ByteArray(2))).failure().reason) // The share is gone: what the page still posts for it is ignored. assertEquals(emptyList(), it.accept(chunk("o2", 0, 1, ByteArray(2)))) @@ -204,7 +218,7 @@ class RaftWebViewShareTest { assertEquals("chunk_order", started("o4").accept(chunk("o4", 3, 0, ByteArray(1))).failure().reason) assertEquals("chunk_order", started("o5").accept(chunk("o5", -1, 0, ByteArray(1))).failure().reason) started("o6").let { - assertNotNull(it.accept(chunk("o6", 0, 0, ByteArray(4)))) + assertEquals(listOf(RaftWebViewShareSignal.Ack("o6")), it.accept(chunk("o6", 0, 0, ByteArray(4)))) // The empty middle file sends nothing. assertEquals(listOf(RaftWebViewShareSignal.Ack("o6")), it.accept(chunk("o6", 2, 0, ByteArray(2)))) assertEquals("chunk_order", it.accept(chunk("o6", 0, 1, ByteArray(1))).failure().reason)