Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

3 changes: 2 additions & 1 deletion apps/android-app/src/main/AndroidManifest.xml
Original file line number Diff line number Diff line change
Expand Up @@ -57,7 +57,8 @@
<activity
android:name=".session.FireCloudflareChallengeActivity"
android:exported="false"
android:launchMode="singleTop" />
android:launchMode="singleTop"
android:theme="@style/Theme.Fire.ChallengeSheet" />
<activity
android:name=".ui.webview.FireInAppWebViewActivity"
android:exported="false" />
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ import android.content.Context
import com.fire.app.core.image.FireImageLoader
import com.fire.app.core.theme.FireColors
import com.fire.app.push.FirePushNotificationDispatcher
import com.fire.app.session.FireForegroundActivity
import com.fire.app.ui.topicdetail.BookmarkReminderScheduler
import com.google.android.material.color.DynamicColors
import kotlinx.coroutines.CoroutineScope
Expand All @@ -30,6 +31,7 @@ class FireApplication : Application() {
FireImageLoader.initialize(this)
BookmarkReminderScheduler.createNotificationChannel(this)
FirePushNotificationDispatcher.createNotificationChannel(this)
registerActivityLifecycleCallbacks(FireForegroundActivity.callbacks)
}

override fun onTerminate() {
Expand Down
65 changes: 64 additions & 1 deletion apps/android-app/src/main/java/com/fire/app/MainActivity.kt
Original file line number Diff line number Diff line change
Expand Up @@ -10,22 +10,29 @@ import androidx.core.view.updatePadding
import androidx.lifecycle.DefaultLifecycleObserver
import androidx.lifecycle.LifecycleOwner
import androidx.lifecycle.ProcessLifecycleOwner
import androidx.appcompat.app.AlertDialog
import androidx.lifecycle.lifecycleScope
import androidx.navigation.NavController
import androidx.navigation.NavOptions
import androidx.navigation.fragment.NavHostFragment
import com.fire.app.databinding.ActivityMainBinding
import com.fire.app.session.FireBrowserTransportPrompt
import com.fire.app.session.FireSessionRecoveryPolicy
import com.fire.app.session.FireCfClearanceRefreshService
import com.fire.app.session.FireSessionStoreRepository
import com.fire.app.session.FireStateObserverRepository
import com.fire.app.session.FireWebViewCookieActionSupport
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
import uniffi.fire_uniffi_session.SessionState

class MainActivity : AppCompatActivity() {

private lateinit var binding: ActivityMainBinding
private var hasLatchedAskEnableBrowserTransport = false
private var isAskEnableDialogVisible = false
private var latestSessionSnapshot: SessionState? = null

override fun onCreate(savedInstanceState: Bundle?) {
enableEdgeToEdge()
Expand All @@ -50,10 +57,21 @@ class MainActivity : AppCompatActivity() {
ProcessLifecycleOwner.get().lifecycle.addObserver(object : DefaultLifecycleObserver {
override fun onStart(owner: LifecycleOwner) {
FireCfClearanceRefreshService.get(this@MainActivity).setSceneActive(true)
lifecycleScope.launch {
runCatching {
FireSessionStoreRepository.get(this@MainActivity).noteAppForegrounded()
}
presentAskEnableBrowserTransportIfNeeded(latestSessionSnapshot)
}
}

override fun onStop(owner: LifecycleOwner) {
FireCfClearanceRefreshService.get(this@MainActivity).setSceneActive(false)
lifecycleScope.launch {
runCatching {
FireSessionStoreRepository.get(this@MainActivity).noteAppBackgrounded()
}
}
}
})
lifecycleScope.launch {
Expand Down Expand Up @@ -176,8 +194,15 @@ class MainActivity : AppCompatActivity() {
}.getOrDefault(false)
}
FireStateObserverRepository.sessionSnapshots.collect { snapshot ->
latestSessionSnapshot = snapshot
val suppressLoginRecovery = FireSessionRecoveryPolicy.suppressesHostLoginRecovery(
snapshot.recovery,
)
if (!suppressLoginRecovery) {
presentAskEnableBrowserTransportIfNeeded(snapshot)
}
val isAuthenticated = snapshot.readiness.canReadAuthenticatedApi
if (wasAuthenticated && !isAuthenticated) {
if (!suppressLoginRecovery && wasAuthenticated && !isAuthenticated) {
FireWebViewCookieActionSupport.clearIdentityCookies()
if (navController.currentDestination?.id != R.id.onboardingFragment) {
val options = NavOptions.Builder()
Expand All @@ -197,6 +222,44 @@ class MainActivity : AppCompatActivity() {
}
}

private fun presentAskEnableBrowserTransportIfNeeded(snapshot: SessionState?) {
val kind = snapshot?.let(FireBrowserTransportPrompt::signalKind)
if (!FireBrowserTransportPrompt.shouldPresent(kind, hasLatchedAskEnableBrowserTransport)) {
hasLatchedAskEnableBrowserTransport = FireBrowserTransportPrompt.nextLatch(kind)
return
}
if (isFinishing || isDestroyed || !lifecycle.currentState.isAtLeast(androidx.lifecycle.Lifecycle.State.STARTED)) {
return
}
if (isAskEnableDialogVisible) {
return
}
hasLatchedAskEnableBrowserTransport = true
isAskEnableDialogVisible = true
AlertDialog.Builder(this)
.setTitle(R.string.browser_transport_prompt_title)
.setMessage(R.string.browser_transport_prompt_message)
.setPositiveButton(R.string.browser_transport_prompt_enable) { _, _ ->
lifecycleScope.launch {
runCatching {
FireSessionStoreRepository.get(this@MainActivity)
.enableBrowserTransportForSession()
}
}
}
.setNegativeButton(R.string.browser_transport_prompt_decline) { _, _ ->
lifecycleScope.launch {
runCatching {
FireSessionStoreRepository.get(this@MainActivity).declineBrowserTransport()
}
}
}
.setOnDismissListener {
isAskEnableDialogVisible = false
}
.show()
}

private fun handleSignedOutLaunch(navController: NavController) {
val entry = intent?.getStringExtra(EXTRA_ONBOARDING_ENTRY) ?: return
if (entry.isBlank()) return
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -43,6 +43,10 @@ object FireRenderPresentation {
is RenderUiSegmentState.Onebox -> {
FireRichTextBlock.Text(listOf(mapOnebox(segment.card)))
}
is RenderUiSegmentState.Quote -> {
val nodes = segment.nodes.map(::mapNode)
if (nodes.isEmpty()) null else FireRichTextBlock.Text(nodes)
}
null -> null
}
}
Expand All @@ -63,6 +67,7 @@ object FireRenderPresentation {
return (0u until handle.segmentCount()).flatMap { index ->
when (val segment = handle.segment(index)) {
is RenderUiSegmentState.Rich -> segment.nodes.map(::mapNode)
is RenderUiSegmentState.Quote -> segment.nodes.map(::mapNode)
else -> emptyList()
}
}
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,106 @@
package com.fire.app.session

import android.content.Context
import android.os.Handler
import android.os.Looper
import android.webkit.CookieManager
import android.webkit.WebView
import java.util.concurrent.CountDownLatch
import java.util.concurrent.TimeUnit
import org.json.JSONObject
import uniffi.fire_uniffi_session.BrowserHttpException
import uniffi.fire_uniffi_session.BrowserHttpHandler
import uniffi.fire_uniffi_session.BrowserHttpHeaderState
import uniffi.fire_uniffi_session.BrowserHttpRequestState
import uniffi.fire_uniffi_session.BrowserHttpResponseState

class FireBrowserHttpHandler(
context: Context,
) : BrowserHttpHandler {
private val appContext = context.applicationContext

override fun executeBrowserHttp(request: BrowserHttpRequestState): BrowserHttpResponseState {
val latch = CountDownLatch(1)
var result: BrowserHttpResponseState? = null
var error: String? = null
Handler(Looper.getMainLooper()).post {
val webView = WebView(appContext)
CookieManager.getInstance().setAcceptCookie(true)
val headerObject = request.headers.joinToString(",") { header ->
"\"${header.name.jsonEscape()}\":\"${header.value.jsonEscape()}\""
}
val script = """
(async () => {
try {
const res = await fetch("${request.url.jsonEscape()}", {
method: "${request.method.jsonEscape()}",
headers: {$headerObject},
body: ${requestBodyLiteral(request)},
credentials: "include"
});
const buffer = await res.arrayBuffer();
const body = Array.from(new Uint8Array(buffer));
const headers = [];
res.headers.forEach((value, name) => headers.push({name, value}));
return JSON.stringify({status: res.status, headers, body});
} catch (error) {
return JSON.stringify({error: String(error)});
}
})()
""".trimIndent()
webView.evaluateJavascript(script) { raw ->
try {
val json = JSONObject(raw.trim('"').replace("\\\"", "\""))
if (json.has("error")) {
error = json.optString("error")
} else {
val headers = mutableListOf<BrowserHttpHeaderState>()
val headerArray = json.optJSONArray("headers")
if (headerArray != null) {
for (index in 0 until headerArray.length()) {
val item = headerArray.optJSONObject(index) ?: continue
headers += BrowserHttpHeaderState(
name = item.optString("name"),
value = item.optString("value"),
)
}
}
val bodyArray = json.optJSONArray("body")
val body = if (bodyArray == null) {
byteArrayOf()
} else {
ByteArray(bodyArray.length()) { bodyArray.optInt(it).toByte() }
}
result = BrowserHttpResponseState(
status = json.optInt("status", 502).toUShort(),
headers = headers,
body = body,
)
}
} catch (thrown: Exception) {
error = thrown.message
} finally {
latch.countDown()
}
}
}
latch.await((request.timeoutMs + 2_000u).toLong(), TimeUnit.MILLISECONDS)
return result ?: throw BrowserHttpException.Failed(
details = error ?: "browser fetch failed",
)
}
}

private fun requestBodyLiteral(request: BrowserHttpRequestState): String {
val body = request.body ?: return "undefined"
if (body.isEmpty()) return "undefined"
val encoded = android.util.Base64.encodeToString(
body.map { it.toByte() }.toByteArray(),
android.util.Base64.NO_WRAP,
)
return "Uint8Array.from(atob(\"${encoded.jsonEscape()}\"), c => c.charCodeAt(0))"
}

private fun String.jsonEscape(): String {
return replace("\\", "\\\\").replace("\"", "\\\"")
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
package com.fire.app.session

import uniffi.fire_uniffi_session.AuthRuntimeSignalKindState
import uniffi.fire_uniffi_session.SessionState

object FireBrowserTransportPrompt {
fun shouldPresent(kind: AuthRuntimeSignalKindState?, alreadyLatched: Boolean): Boolean {
return kind == AuthRuntimeSignalKindState.ASK_ENABLE_BROWSER_TRANSPORT && !alreadyLatched
}

fun nextLatch(kind: AuthRuntimeSignalKindState?): Boolean {
return kind == AuthRuntimeSignalKindState.ASK_ENABLE_BROWSER_TRANSPORT
}

fun signalKind(snapshot: SessionState): AuthRuntimeSignalKindState? {
return snapshot.lastAuthRuntimeSignal?.kind
}
}
Loading
Loading