diff --git a/change-logs/1.28.0/changesets/webview-share-files.md b/change-logs/1.28.0/changesets/webview-share-files.md new file mode 100644 index 0000000000..ba0854fb93 --- /dev/null +++ b/change-logs/1.28.0/changesets/webview-share-files.md @@ -0,0 +1,20 @@ +--- +type: added +area: artifacts +platforms: + - android +pull_request: 5120 +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/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 f158c61635..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 @@ -158,6 +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 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 @@ -842,7 +846,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 +1113,181 @@ internal class RaftAndroidSandboxWebView( } } + /** + * 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 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) { session.accept(raw) } + } + + /** + * 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, + rearmExpiry: Boolean = false, + work: () -> List? + ) { + runCatching { + RaftWebViewShareIo.execute { + val signals = runCatching(work).getOrElse { runCatching { session.abortAll("internal") }.getOrDefault(emptyList()) } + 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) } + } + + 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. 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, + delayMs: Long = RaftWebViewShareIdleTimeoutMs + 1_000L + ) { + shareExpiryCheck?.let { shareMainHandler.removeCallbacks(it) } + val check = + Runnable { + shareExpiryCheck = null + if (!destroyed && shareSession === session) runShareIo(session, rearmExpiry = true) { session.expire() } + } + shareExpiryCheck = check + shareMainHandler.postDelayed(check, delayMs) + } + + 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 { + 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 { + checkNotNull(folder) { "share folder" } + val uris = + ArrayList( + request.files.map { file -> + val target = java.io.File(folder, file.name) + 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 = + 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]) + } 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}") + discardShareFolder(folder) + settleShare(request.id, "AbortError") + } + } + + private fun settleShare(id: String, errorName: String?) { + if (destroyed) return + 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) || @@ -1118,6 +1298,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( @@ -1129,22 +1310,23 @@ internal class RaftAndroidSandboxWebView( ) { if (destroyed || !isMainFrame || sourceOrigin.toString() != originRule) return val raw = message.data ?: 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 + // A share message goes to the share thread whole; this (UI) thread neither parses nor decodes it. + if (raftWebViewIsShareMessage(raw)) { + acceptShareMessage(session, raw) + return } - events.onDownloadRequested?.invoke(result) + handleDownloadMessage(raw) } } WebViewCompat.addWebMessageListener(webView, RaftWebViewDownloadPortName, setOf(originRule), listener) downloadMessageListener = listener + shareSession = session downloadNameScriptHandler = - WebViewCompat.addDocumentStartJavaScript(webView, RaftWebViewDownloadNameHookScript, setOf(originRule)) + WebViewCompat.addDocumentStartJavaScript( + webView, + RaftWebViewDownloadNameHookScript + "\n" + raftWebViewShareShimScript(), + setOf(originRule) + ) }.onFailure { Log.w(LOG_TAG, "download_support unavailable", it) } } @@ -1156,6 +1338,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.close() } + } } private fun removeHostMessageListener() { @@ -1368,3 +1557,100 @@ 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 const val RaftWebViewShareExpiryRecheckMs: Long = 10_000L + +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() }) + + 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 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) + + @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 new file mode 100644 index 0000000000..15a014305d --- /dev/null +++ b/compose/shared/src/commonMain/kotlin/build/raft/app/RaftWebViewShare.kt @@ -0,0 +1,386 @@ +package build.raft.app + +import build.raft.app.compat.json.JSONObject +import build.raft.app.downloads.RaftShareFileName +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, 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;" + + "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,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||f.length>$RaftWebViewShareMaxFiles)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(){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');};" + + "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 + +/** 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, + val title: String, + val text: String, + val url: String, + val files: List, +) + +/** 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) + + /** Share [id] failed or was given up: drop what was written. Unknown ids are fine. */ + fun discard(id: String) +} + +/** + * 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 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 = + 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, + val url: String, + val names: List, + val types: List, + val sizes: List, + var lastMessageAt: Long, + ) { + val received = LongArray(sizes.size) + val nextChunk = IntArray(sizes.size) + var nextFile = 0 + } + + private val pending = LinkedHashMap() + + 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 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 out + if (share.sizes.indices.any { share.received[it] != share.sizes[it] }) { + 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)) + } + } + "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, out: MutableList) { + pending.remove(id) + discard(id) + out += RaftWebViewShareSignal.Failed(id, "DataError", reason) + } + + private fun discard(id: String) { + runCatching { sink.discard(id) } + } +} + +/** + * 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 = 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 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 new file mode 100644 index 0000000000..350addc815 --- /dev/null +++ b/compose/shared/src/commonTest/kotlin/build/raft/app/RaftWebViewShareTest.kt @@ -0,0 +1,365 @@ +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.assertFalse +import kotlin.test.assertIs +import kotlin.test.assertNotNull +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")) + } + + @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 = + 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)) } + }, + ) + + 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 streamsTwoFilesToTheSinkAndDeduplicatesNames() { + val receiver = receiver() + val a = "第一个".encodeToByteArray() + val b = byteArrayOf(1, 2, 3) + assertEquals( + emptyList(), + receiver.accept(start("s1", Triple("周报.md", "text/markdown", a.size.toLong()), Triple("周报.md", "text/markdown", b.size.toLong()))), + ) + 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(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")) + } + + @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 + 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 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)))) + 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" }) + 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 { + 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)))) + 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 { + 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) + } + // 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 + fun textOnlyShareText() { + assertEquals("hi\nhttps://x.y", raftWebViewShareText("t", "hi", "https://x.y")) + assertEquals("t", raftWebViewShareText("t", "", "")) + } +}