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
24 changes: 24 additions & 0 deletions apps/android-app/src/main/AndroidManifest.xml
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,30 @@
android:scheme="fire"
android:host="profile" />
</intent-filter>
<intent-filter>
<action android:name="android.intent.action.VIEW" />
<category android:name="android.intent.category.DEFAULT" />
<category android:name="android.intent.category.BROWSABLE" />
<data
android:scheme="discourse"
android:host="auth_redirect" />
</intent-filter>
<intent-filter>
<action android:name="android.intent.action.VIEW" />
<category android:name="android.intent.category.DEFAULT" />
<category android:name="android.intent.category.BROWSABLE" />
<data
android:scheme="fire"
android:host="qr-login" />
</intent-filter>
<intent-filter>
<action android:name="android.intent.action.VIEW" />
<category android:name="android.intent.category.DEFAULT" />
<category android:name="android.intent.category.BROWSABLE" />
<data
android:scheme="fluxdo"
android:host="qr-login" />
</intent-filter>
</activity>
<activity
android:name=".ui.topicdetail.TopicDetailActivity"
Expand Down
24 changes: 24 additions & 0 deletions apps/android-app/src/main/java/com/fire/app/MainActivity.kt
Original file line number Diff line number Diff line change
Expand Up @@ -47,6 +47,7 @@ class MainActivity : AppCompatActivity() {

configureBottomNavigation(navController)
handleWidgetDeepLink(navController)
handleAuthOrQrDeepLink(intent)
bindCloudflareRefreshLifecycle()
bindSessionExpiryObserver(navController)

Expand Down Expand Up @@ -118,6 +119,29 @@ class MainActivity : AppCompatActivity() {
handleSignedOutLaunch(navController)
}

override fun onNewIntent(intent: android.content.Intent) {
super.onNewIntent(intent)
setIntent(intent)
handleAuthOrQrDeepLink(intent)
}

private fun handleAuthOrQrDeepLink(intent: android.content.Intent?) {
val uri = intent?.data ?: return
val scheme = uri.scheme?.lowercase() ?: return
val host = uri.host?.lowercase()
lifecycleScope.launch {
val store = FireSessionStoreRepository.get(this@MainActivity)
when {
scheme == "discourse" && host == "auth_redirect" -> {
runCatching { store.handleUserApiKeyAuthRedirect(uri.toString()) }
}
(scheme == "fire" || scheme == "fluxdo") && host == "qr-login" -> {
runCatching { store.loginWithQrPayload(uri.toString()) }
}
}
}
}

private fun handleWidgetDeepLink(navController: NavController) {
val uri = intent?.data ?: return
if (uri.scheme != "fire") return
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -108,6 +108,7 @@ object FireErrorClassifier {
"cooldown" -> "Cloudflare 验证暂时冷却中,请稍后重试或手动验证"
"cancelled" -> "已取消 Cloudflare 验证"
"background_suppressed" -> "后台请求遇到 Cloudflare 验证,请在页面中手动验证"
"manual_required" -> "需要手动完成 Cloudflare 验证"
"failed" -> "Cloudflare 验证未完成,请重试"
else -> "需要完成 Cloudflare 验证"
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -49,19 +49,29 @@ class FireCloudflareChallengeActivity : ComponentActivity() {
super.onCreate(savedInstanceState)
pendingToken = intent.getStringExtra(EXTRA_PENDING_TOKEN).orEmpty()
targetUrl = intent.getStringExtra(EXTRA_TARGET_URL).orEmpty()
val hidden = intent.getBooleanExtra(EXTRA_HIDDEN, false)
if (pendingToken.isBlank() || targetUrl.isBlank()) {
finishWithResult(cancelledResult(userCancelled = false))
return
}

if (hidden) {
window.setLayout(2, 2)
setShowWhenLocked(false)
}
setContentView(R.layout.activity_cloudflare_challenge)
applySystemBarInsets()
webView = findViewById(R.id.challenge_webview)
progressBar = findViewById(R.id.challenge_progress)
completionOverlay = findViewById(R.id.challenge_completion_overlay)
findViewById<TextView>(R.id.challenge_close).setOnClickListener {
val closeButton = findViewById<TextView>(R.id.challenge_close)
closeButton.setOnClickListener {
finishWithResult(cancelledResult(userCancelled = true))
}
if (hidden) {
closeButton.visibility = View.GONE
progressBar.visibility = View.GONE
}

val cookieManager = CookieManager.getInstance()
val baselineCookies = collectRelevantCookies()
Expand Down Expand Up @@ -489,6 +499,7 @@ class FireCloudflareChallengeActivity : ComponentActivity() {
companion object {
const val EXTRA_PENDING_TOKEN = "fire.pending_token"
const val EXTRA_TARGET_URL = "fire.target_url"
const val EXTRA_HIDDEN = "fire.hidden"

private const val CHALLENGE_PLATFORM_PATH = "/cdn-cgi/challenge-platform/"
private val RELEVANT_COOKIE_NAMES = setOf("_t", "_forum_session", "cf_clearance", "_cfuvid")
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -149,10 +149,6 @@ class FireCloudflareChallengeRuntimeHandler(
override fun completeCloudflareChallenge(
request: CloudflareChallengeRequestState,
): CloudflareChallengeResultState {
if (!request.isForeground) {
return softChallengeResult(userCancelled = false)
}
// Only the owner of the gate presents UI. Concurrent requests wait here.
return FireCloudflareChallengePresentationGate.runExclusive {
ui.present(request)
}
Expand Down Expand Up @@ -185,12 +181,6 @@ class FireCloudflareChallengeCoordinator(
fun completeSynchronously(
request: CloudflareChallengeRequestState,
): CloudflareChallengeResultState {
// Background/silent traffic must not steal focus. Rust only starts a new
// challenge for foreground requests; keep a host-side defensive gate.
if (!request.isForeground) {
return cancelledResult(userCancelled = false)
}

FireCfClearanceRefreshService.get(context).beginManualChallenge("manual_challenge_start")
try {
return presentChallenge(request)
Expand All @@ -215,6 +205,7 @@ class FireCloudflareChallengeCoordinator(
FireCloudflareChallengeActivity.EXTRA_TARGET_URL,
challengeUrl(request.originUrl),
)
putExtra(FireCloudflareChallengeActivity.EXTRA_HIDDEN, !request.isForeground)
}
(host ?: context).startActivity(intent)

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -20,17 +20,47 @@ object FireCloudflareRecovery {
if (!isCloudflareChallenge(error)) {
throw error
}
val recovered = completeManualVerification(
context = context,
sessionStore = sessionStore,
operation = operation,
originUrl = originUrl,
)
if (!recovered) {
throw error
when (recoveryAction(reason(error))) {
RecoveryAction.WaitThenRetry -> {
awaitInProgressQuietPeriod()
work()
}
RecoveryAction.Rethrow -> throw error
}
}
}

enum class RecoveryAction {
WaitThenRetry,
Rethrow,
}

fun recoveryAction(reason: String): RecoveryAction {
return if (reason == "in_progress") RecoveryAction.WaitThenRetry else RecoveryAction.Rethrow
}

suspend fun awaitInProgressQuietPeriod(
appearTimeoutMs: Long = 2_000,
presentationTimeoutMs: Long = 120_000,
settleMs: Long = 500,
) {
val started = System.currentTimeMillis()
while (
!FireCloudflareChallengePresentationGate.isPresentationInFlight &&
System.currentTimeMillis() - started < appearTimeoutMs
) {
kotlinx.coroutines.delay(50)
}
if (FireCloudflareChallengePresentationGate.isPresentationInFlight) {
val waitStarted = System.currentTimeMillis()
while (
FireCloudflareChallengePresentationGate.isPresentationInFlight &&
System.currentTimeMillis() - waitStarted < presentationTimeoutMs
) {
kotlinx.coroutines.delay(50)
}
work()
}
kotlinx.coroutines.delay(settleMs)
}

suspend fun completeManualVerification(
Expand All @@ -39,6 +69,7 @@ object FireCloudflareRecovery {
operation: String = "manual.verify",
originUrl: String = "https://linux.do/",
): Boolean = withContext(Dispatchers.IO) {
runCatching { sessionStore.beginManualCloudflareChallenge() }
val epoch = runCatching { sessionStore.currentSessionEpoch() }.getOrDefault(0u)
val result = FireCloudflareChallengeCoordinator(context.applicationContext)
.completeSynchronously(
Expand Down Expand Up @@ -116,5 +147,6 @@ object FireCloudflareRecovery {
"failed",
"background_suppressed",
"required",
"manual_required",
)
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
package com.fire.app.session

import android.webkit.CookieManager
import uniffi.fire_uniffi_session.SessionCandidateCookiesState
import uniffi.fire_uniffi_session.SessionCandidateHandler

class FireSessionCandidateRuntimeHandler(
private val sessionStore: FireSessionStore,
) : SessionCandidateHandler {
override fun sessionCandidateCookies(): SessionCandidateCookiesState {
val header = runCatching {
val url = sessionStore.cachedBaseUrl() ?: "https://linux.do"
CookieManager.getInstance().getCookie(url)
}.getOrNull()
val pairs = header
?.split(';')
?.mapNotNull { part ->
val trimmed = part.trim()
val separator = trimmed.indexOf('=')
if (separator <= 0) {
null
} else {
trimmed.substring(0, separator) to trimmed.substring(separator + 1)
}
}
.orEmpty()
return SessionCandidateCookiesState(
tToken = pairs.lastOrNull { it.first == "_t" && it.second.isNotBlank() }?.second,
forumSession = pairs.lastOrNull { it.first == "_forum_session" && it.second.isNotBlank() }?.second,
)
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -184,6 +184,18 @@ class FireSessionStore(
core.session().unregisterCookieSelfHealingHandler()
}

fun registerSessionCandidateHandler(handler: uniffi.fire_uniffi_session.SessionCandidateHandler) {
core.session().registerSessionCandidateHandler(handler)
}

fun registerUserApiKeyCryptoHandler(handler: uniffi.fire_uniffi_session.UserApiKeyCryptoHandler) {
core.session().registerUserApiKeyCryptoHandler(handler)
}

fun cachedBaseUrl(): String {
return runCatching { core.session().baseUrl() }.getOrDefault("https://linux.do")
}

suspend fun restorePersistedSessionIfAvailable(): SessionState? = withContext(Dispatchers.IO) {
if (!sessionFile.exists()) {
return@withContext null
Expand Down Expand Up @@ -268,6 +280,14 @@ class FireSessionStore(
core.session().noteCloudflareClearanceRejected()
}

suspend fun clearCloudflareCooldown() = withContext(Dispatchers.Default) {
core.session().clearCloudflareCooldown()
}

suspend fun beginManualCloudflareChallenge(): Boolean = withContext(Dispatchers.Default) {
core.session().beginManualCloudflareChallenge()
}

suspend fun finalizeLoginReady(): SessionState = withContext(Dispatchers.Default) {
val state = core.session().finalizeLoginReady()
persistCurrentSession()
Expand Down Expand Up @@ -342,8 +362,41 @@ class FireSessionStore(
state
}

suspend fun recordFingerprintDone() = withContext(Dispatchers.Default) {
core.session().recordFingerprintDone()
suspend fun recordFingerprintDone(
cookies: List<PlatformCookieState> = emptyList(),
) = withContext(Dispatchers.Default) {
core.session().recordFingerprintDone(cookies)
persistCurrentSession()
}

suspend fun handleUserApiKeyAuthRedirect(uri: String) = withContext(Dispatchers.Default) {
core.session().handleUserApiKeyAuthRedirect(uri).also { persistCurrentSession() }
}

suspend fun loginWithQrPayload(raw: String) = withContext(Dispatchers.Default) {
core.session().loginWithQrPayload(raw).also { persistCurrentSession() }
}

suspend fun buildUserApiKeyAuthorizeUrl(
publicKeyPem: String,
clientId: String,
) = withContext(Dispatchers.Default) {
core.session().buildUserApiKeyAuthorizeUrl(publicKeyPem, clientId, null)
}

suspend fun createQrLoginPayload(
publicKeyPem: String,
clientId: String,
username: String? = null,
) = withContext(Dispatchers.Default) {
core.session().createQrLoginPayload(publicKeyPem, clientId, username)
}

fun encodeQrLoginPayload(
payload: uniffi.fire_uniffi_session.QrLoginPayloadState,
scheme: String = "fire",
): String {
return core.session().encodeQrLoginPayload(payload, scheme)
}

suspend fun persistCurrentSession() = withContext(Dispatchers.IO) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -15,13 +15,39 @@ object FireSessionStoreRepository {
private var challengeHandler: FireCloudflareChallengeRuntimeHandler? = null
@Volatile
private var cookieSelfHealingHandler: FireCookieSelfHealingRuntimeHandler? = null
@Volatile
private var sessionCandidateHandler: FireSessionCandidateRuntimeHandler? = null
@Volatile
private var userApiKeyCryptoHandler: FireUserApiKeyCryptoRuntimeHandler? = null

suspend fun get(context: Context): FireSessionStore = withContext(Dispatchers.IO) {
getOrCreateBlocking(context.applicationContext)
}

fun getIfInitialized(): FireSessionStore? = shared

suspend fun startUserApiKeyLogin(context: Context) {
val store = get(context)
val crypto = userApiKeyCrypto(context)
store.registerUserApiKeyCryptoHandler(crypto)
val authorize = store.buildUserApiKeyAuthorizeUrl(
publicKeyPem = crypto.publicKeyPem(),
clientId = crypto.clientId(),
)
val intent = android.content.Intent(
android.content.Intent.ACTION_VIEW,
android.net.Uri.parse(authorize.url),
).addFlags(android.content.Intent.FLAG_ACTIVITY_NEW_TASK)
context.startActivity(intent)
}

fun userApiKeyCrypto(context: Context): FireUserApiKeyCryptoRuntimeHandler {
getOrCreateBlocking(context.applicationContext)
return userApiKeyCryptoHandler ?: FireUserApiKeyCryptoRuntimeHandler(context.applicationContext).also {
userApiKeyCryptoHandler = it
}
}

private fun getOrCreateBlocking(context: Context): FireSessionStore {
val startedAt = SystemClock.elapsedRealtime()
shared?.let { store ->
Expand All @@ -44,6 +70,14 @@ object FireSessionStoreRepository {
cookieSelfHealingHandler = FireCookieSelfHealingRuntimeHandler(store)
}
cookieSelfHealingHandler?.let(store::registerCookieSelfHealingHandler)
if (sessionCandidateHandler == null) {
sessionCandidateHandler = FireSessionCandidateRuntimeHandler(store)
}
sessionCandidateHandler?.let(store::registerSessionCandidateHandler)
if (userApiKeyCryptoHandler == null) {
userApiKeyCryptoHandler = FireUserApiKeyCryptoRuntimeHandler(context.applicationContext)
}
userApiKeyCryptoHandler?.let(store::registerUserApiKeyCryptoHandler)
val refresh = FireCfClearanceRefreshService.get(context.applicationContext)
refresh.bind(store)
// snapshot() is suspend; callers (e.g. MainActivity / login) update
Expand Down
Loading
Loading