communicate: Signal registration hCaptcha token flow
- Commit
866353c8ac1b6f44689742165684702b8a4c4c9b- Author
- vayun-mathur <[email protected]>
- When
- 2026-08-16 18:49 UTC (3 months ago)
- Parents
8388e69
Diff
communicate/src/main/java/com/vayunmathur/communicate/data/signal/registration/RegistrationHttpClient.kt
diff --git a/communicate/src/main/java/com/vayunmathur/communicate/data/signal/registration/RegistrationHttpClient.kt b/communicate/src/main/java/com/vayunmathur/communicate/data/signal/registration/RegistrationHttpClient.ktindex bc38fa3e5d..ea733146f4 100644--- a/communicate/src/main/java/com/vayunmathur/communicate/data/signal/registration/RegistrationHttpClient.kt+++ b/communicate/src/main/java/com/vayunmathur/communicate/data/signal/registration/RegistrationHttpClient.kt@@ -44,6 +44,9 @@ class RegistrationHttpClient(private val context: Context) { data class CodeResult(val status: String, val reason: String?, val raw: String) { val ok: Boolean get() = status == "sent" || status == "ok" || status == "200"++ /** Server asked for an hCaptcha token (requestedInformation contains "captcha"). */+ val needsCaptcha: Boolean get() = status == "captcha" } data class RegisterResult( val status: String, val aci: String?, val pni: String?, val reason: String?, val auth: SignalAuthData?, val raw: String,@@ -74,33 +77,75 @@ class RegistrationHttpClient(private val context: Context) { Log.e(TAG, "createVerificationSession failed", t) return CodeResult("error", t.message, t.message ?: "") }- // Persist session id so verifyCode can use it across process restarts.+ // Persist session id so submitCaptcha/verifyCode can use it across process restarts. SignalAuthData.save(context, auth.copy(verificationSessionId = create.id, phoneNumber = number)) - // 2) PATCH if server asks for pushChallenge/captcha.- // live-only: pushChallenge requires FCM token from Play Services + 5s EventBus latch (RegistrationRepository.requestAndVerifyPushToken); captcha requires hCaptcha token- if (create.requestedInformation.contains("pushChallenge") || create.requestedInformation.contains("captcha")) {- // Wire-correct PATCH construction; offline we have no FCM/captcha token so we send empty PATCH and surface reason.+ // 2) Server-requested challenges gate code delivery.+ // captcha: needs an hCaptcha token minted via the signalcaptchas.org WebView (see submitCaptcha + SignalCaptchaScreen).+ if (create.requestedInformation.contains("captcha") && !create.allowedToRequestCode) {+ return CodeResult("captcha", "captcha required", create.raw)+ }+ // pushChallenge is live-only: requires an FCM token from Play Services + EventBus latch (RegistrationRepository.requestAndVerifyPushToken).+ if (create.requestedInformation.contains("pushChallenge") && !create.allowedToRequestCode) { try { patchVerificationSession(create.id, pushToken = null, pushChallenge = null, captcha = null, mcc = null, mnc = null) } catch (t: Throwable) { Log.w(TAG, "patchVerificationSession (live-only) failed", t) }- if (create.requestedInformation.contains("pushChallenge") && !create.allowedToRequestCode) {- return CodeResult("error", "pushChallenge required (live-only: needs FCM pushToken)", create.raw)- }- if (create.requestedInformation.contains("captcha") && !create.allowedToRequestCode) {- return CodeResult("error", "captcha required (live-only: needs hCaptcha token)", create.raw)- }+ return CodeResult("error", "pushChallenge required (live-only: needs FCM pushToken)", create.raw) } // 3) POST /v1/verification/session/{id}/code {transport, client}+ return sendCode(create.id, transport)+ }++ /**+ * Submit a solved hCaptcha token to the current verification session, then continue to request the code.+ *+ * Signal-Android flow (RegistrationApi.submitCaptchaToken):+ * - WebView loads [CAPTCHA_URL]; on success it redirects to+ * `signalcaptcha://signal-hcaptcha.{sitekey}.registration.{token}`.+ * - The client strips the `signalcaptcha://` scheme and sends the remainder as the `captcha` field via+ * PATCH /v1/verification/session/{id} (UpdateVerificationSessionRequestBody).+ * - Once the session is no longer captcha-gated, request the SMS/voice code.+ *+ * [captchaToken] may be the raw `signalcaptcha://…` redirect URL or the already-stripped value; the scheme is+ * removed here so callers can pass either.+ */+ suspend fun submitCaptcha(e164: String, captchaToken: String, transport: String = "sms"): CodeResult {+ val number = e164.filter { it.isDigit() || it == '+' }+ val stored = SignalAuthData.load(context)+ ?: return CodeResult("error", "no_session", "missing verification session — request a code first")+ val sessionId = stored.verificationSessionId+ ?: return CodeResult("error", "no_session", "missing verification session — request a code first")+ val token = captchaToken.removePrefix(SIGNAL_CAPTCHA_SCHEME).ifBlank {+ return CodeResult("error", "empty_captcha", "empty captcha token")+ }+ // PATCH /v1/verification/session/{id} {captcha}+ val patched = try {+ patchVerificationSession(sessionId, pushToken = null, pushChallenge = null, captcha = token, mcc = null, mnc = null)+ } catch (t: Throwable) {+ Log.e(TAG, "submitCaptcha patch failed", t)+ return CodeResult("error", t.message, t.message ?: "")+ }+ // Keep the (possibly rotated) session id and number persisted for verifyCode.+ SignalAuthData.save(context, stored.copy(verificationSessionId = patched.id.ifEmpty { sessionId }, phoneNumber = number.ifEmpty { stored.phoneNumber }))+ if (patched.requestedInformation.contains("captcha") && !patched.allowedToRequestCode) {+ return CodeResult("captcha", "captcha rejected", patched.raw)+ }+ return sendCode(patched.id.ifEmpty { sessionId }, transport)+ }++ /** POST /v1/verification/session/{id}/code — shared by initial request and post-captcha retry. */+ private suspend fun sendCode(sessionId: String, transport: String): CodeResult { return try {- val codeResp = requestVerificationCode(create.id, transport)- if (!codeResp.allowedToRequestCode && codeResp.raw.contains("captcha", true)) {- CodeResult("error", "captcha required", codeResp.raw)- } else {- CodeResult("sent", null, codeResp.raw)+ val codeResp = requestVerificationCode(sessionId, transport)+ when {+ !codeResp.allowedToRequestCode && codeResp.requestedInformation.contains("captcha") ->+ CodeResult("captcha", "captcha required", codeResp.raw)+ !codeResp.allowedToRequestCode && codeResp.raw.contains("captcha", true) ->+ CodeResult("captcha", "captcha required", codeResp.raw)+ else -> CodeResult("sent", null, codeResp.raw) } } catch (t: Throwable) { Log.e(TAG, "requestVerificationCode failed", t)@@ -373,6 +418,16 @@ class RegistrationHttpClient(private val context: Context) { private const val VERIFICATION_SESSION_PATH = "/v1/verification/session" private const val VERIFICATION_CODE_PATH = "/v1/verification/session/%s/code" private const val REGISTRATION_PATH = "/v1/registration"++ /** hCaptcha challenge page (Signal-Android BuildConfig.SIGNAL_CAPTCHA_URL). */+ const val CAPTCHA_URL = "https://signalcaptchas.org/registration/generate.html"++ /**+ * Redirect scheme the captcha page hands back on success:+ * `signalcaptcha://signal-hcaptcha.{sitekey}.registration.{token}` (RegistrationConstants.SIGNAL_CAPTCHA_SCHEME).+ * The value after this prefix is submitted verbatim as the `captcha` field.+ */+ const val SIGNAL_CAPTCHA_SCHEME = "signalcaptcha://" } }
communicate/src/main/java/com/vayunmathur/communicate/ui/signal/SignalCaptchaScreen.kt
diff --git a/communicate/src/main/java/com/vayunmathur/communicate/ui/signal/SignalCaptchaScreen.kt b/communicate/src/main/java/com/vayunmathur/communicate/ui/signal/SignalCaptchaScreen.ktnew file mode 100644index 0000000000..58fd7b1c95--- /dev/null+++ b/communicate/src/main/java/com/vayunmathur/communicate/ui/signal/SignalCaptchaScreen.kt@@ -0,0 +1,57 @@+package com.vayunmathur.communicate.ui.signal++import android.annotation.SuppressLint+import android.view.ViewGroup+import android.webkit.WebView+import android.webkit.WebViewClient+import androidx.compose.foundation.layout.Box+import androidx.compose.foundation.layout.fillMaxSize+import androidx.compose.runtime.Composable+import androidx.compose.ui.Alignment+import androidx.compose.ui.Modifier+import androidx.compose.ui.viewinterop.AndroidView+import com.vayunmathur.communicate.data.signal.registration.RegistrationHttpClient++/**+ * WebView hCaptcha challenge for Signal registration.+ *+ * Mirrors Signal-Android's `CaptchaScreen`/`CaptchaFragment`: it loads+ * [RegistrationHttpClient.CAPTCHA_URL] (`signalcaptchas.org/registration/generate.html`), which completes+ * hCaptcha and redirects to `signalcaptcha://signal-hcaptcha.{sitekey}.registration.{token}`. We intercept that+ * redirect in [WebViewClient.shouldOverrideUrlLoading], strip the `signalcaptcha://` scheme, and hand the+ * remaining value to [onToken] — which is exactly what the server expects as the `captcha` field+ * (see [RegistrationHttpClient.submitCaptcha]).+ */+@SuppressLint("SetJavaScriptEnabled")+@Composable+fun SignalCaptchaWebView(+ onToken: (String) -> Unit,+ modifier: Modifier = Modifier,+) {+ Box(modifier = modifier.fillMaxSize(), contentAlignment = Alignment.Center) {+ AndroidView(+ modifier = Modifier.fillMaxSize(),+ factory = { ctx ->+ WebView(ctx).apply {+ layoutParams = ViewGroup.LayoutParams(+ ViewGroup.LayoutParams.MATCH_PARENT,+ ViewGroup.LayoutParams.MATCH_PARENT,+ )+ settings.javaScriptEnabled = true+ clearCache(true)+ webViewClient = object : WebViewClient() {+ @Deprecated("Deprecated in Java")+ override fun shouldOverrideUrlLoading(view: WebView, url: String): Boolean {+ if (url.startsWith(RegistrationHttpClient.SIGNAL_CAPTCHA_SCHEME)) {+ onToken(url.substring(RegistrationHttpClient.SIGNAL_CAPTCHA_SCHEME.length))+ return true+ }+ return false+ }+ }+ loadUrl(RegistrationHttpClient.CAPTCHA_URL)+ }+ },+ )+ }+}
communicate/src/main/java/com/vayunmathur/communicate/ui/signal/SignalRegistrationScreen.kt
diff --git a/communicate/src/main/java/com/vayunmathur/communicate/ui/signal/SignalRegistrationScreen.kt b/communicate/src/main/java/com/vayunmathur/communicate/ui/signal/SignalRegistrationScreen.ktindex 76691fc8de..484e717a0d 100644--- a/communicate/src/main/java/com/vayunmathur/communicate/ui/signal/SignalRegistrationScreen.kt+++ b/communicate/src/main/java/com/vayunmathur/communicate/ui/signal/SignalRegistrationScreen.kt@@ -39,7 +39,7 @@ import kotlinx.coroutines.withContext * * ⚠️ Registering as primary links Signal to this app — use a test number. */-private enum class RegStep { EnterNumber, EnterCode, Done }+private enum class RegStep { EnterNumber, Captcha, EnterCode, Done } @Composable fun SignalRegistrationScreen(@@ -57,6 +57,8 @@ fun SignalRegistrationScreen( var code by remember { mutableStateOf("") } var busy by remember { mutableStateOf(false) } var status by remember { mutableStateOf<String?>(null) }+ // Transport ("sms"/"voice") to resume after a captcha challenge is solved.+ var pendingTransport by remember { mutableStateOf("sms") } fun e164(): String = "+${cc.filter { it.isDigit() }}${number.filter { it.isDigit() }}" @@ -108,7 +110,10 @@ fun SignalRegistrationScreen( run { val r = withContext(Dispatchers.IO) { client.requestSmsCode(e164()) } status = "code: ${r.status}${r.reason?.let { " ($it)" } ?: ""}"- if (r.ok) step = RegStep.EnterCode+ when {+ r.needsCaptcha -> { pendingTransport = "sms"; step = RegStep.Captcha }+ r.ok -> step = RegStep.EnterCode+ } } }, ) { Text("Request SMS code") }@@ -118,7 +123,10 @@ fun SignalRegistrationScreen( run { val r = withContext(Dispatchers.IO) { client.requestVoiceCode(e164()) } status = "code: ${r.status}${r.reason?.let { " ($it)" } ?: ""}"- if (r.ok) step = RegStep.EnterCode+ when {+ r.needsCaptcha -> { pendingTransport = "voice"; step = RegStep.Captcha }+ r.ok -> step = RegStep.EnterCode+ } } }, ) { Text("Voice") }@@ -134,6 +142,30 @@ fun SignalRegistrationScreen( ) { Text("Check number (no SMS)") } } + RegStep.Captcha -> {+ Text(+ "Signal requires a captcha to continue. Complete the challenge below.",+ style = androidx.compose.material3.MaterialTheme.typography.bodySmall,+ )+ SignalCaptchaWebView(+ onToken = { token ->+ run {+ val r = withContext(Dispatchers.IO) { client.submitCaptcha(e164(), token, pendingTransport) }+ status = "code: ${r.status}${r.reason?.let { " ($it)" } ?: ""}"+ when {+ r.ok -> step = RegStep.EnterCode+ !r.needsCaptcha -> step = RegStep.EnterNumber+ }+ }+ },+ modifier = Modifier.fillMaxWidth().height(420.dp),+ )+ OutlinedButton(+ enabled = !busy,+ onClick = { step = RegStep.EnterNumber; status = null },+ ) { Text("Cancel") }+ }+ RegStep.EnterCode -> { OutlinedTextField( value = code,