Modern Apps git
git clone https://git.maproj.org/Modern-Apps.git
translate ▾

Modern-Apps.git / communicate-dev / src / main / java / com / vayunmathur / communicate / data / signal / registration / RegistrationHttpClient.kt

RegistrationHttpClient.kt609 lines · 30.6 KiBRaw
1package com.vayunmathur.communicate.data.signal.registration
2
3import android.content.Context
4import android.util.Base64
5import com.vayunmathur.library.log.Log
6import com.vayunmathur.communicate.data.signal.SignalAuthData
7import com.vayunmathur.communicate.data.signal.transport.SignalTrust
8import com.vayunmathur.library.network.NetworkClient
9import org.json.JSONArray
10import org.json.JSONObject
11
12/**
13 * Signal registration — real verification-session flow.
14 *
15 * Grounded in:
16 * - PushServiceSocket.java: VERIFICATION_SESSION_PATH="/v1/verification/session",
17 * VERIFICATION_CODE_PATH="/v1/verification/session/%s/code", REGISTRATION_PATH="/v1/registration"
18 * - RegistrationApiV2.kt + VerificationSessionMetadataRequestBody.kt, UpdateVerificationSessionRequestBody.kt,
19 * RegistrationSessionRequestBody.kt, AccountAttributes.kt
20 * - libsignal/rust/net/src/env.rs DOMAIN_CONFIG_CHAT hostname "grpc.chat.signal.org" (WS) /
21 * service REST base "https://chat.signal.org" (uncensored) — see SignalServiceNetworkAccess.kt
22 *
23 * Flow:
24 * 1. POST /v1/verification/session {number,pushToken,pushTokenType,mcc,mnc} ->
25 * {id,allowedToRequestCode,requestedInformation,verified}
26 * 2. PATCH /v1/verification/session/{id} {pushChallenge|captcha,pushToken,...} when server requests it
27 * 3. POST /v1/verification/session/{id}/code {transport:"sms"|"voice",client:"android"} (+ Accept-Language)
28 * 4. PUT /v1/verification/session/{id}/code {code} -> verified=true
29 * 5. POST /v1/registration Authorization: Basic e164:password body RegistrationSessionRequestBody
30 * {sessionId, accountAttributes, aciIdentityKey/pniIdentityKey (base64-nopad IdentityKey.serialize 33B),
31 * aciSignedPreKey/pniSignedPreKey {keyId,publicKey,signature},
32 * aciPqLastResortPreKey/pniPqLastResortPreKey {keyId,publicKey (KEM 1569B 0x08||1568),signature},
33 * gcmToken null if fetchesMessages:true else {gcmRegistrationId,webSocketChannel:true},
34 * skipDeviceTransfer:true, requireAtomic:true}
35 * -> {uuid/aci, pni, storageCapable} or 423 RegistrationLock {timeRemaining, svr2Credentials, svr3Credentials}
36 * 423 RegistrationLock is live-only (requires SVR2/SVR3 + recoveryPassword/MasterKey.deriveRegistrationLock); keep
37 * wire-correct and return error.
38 *
39 * Uses :library:network NetworkClient (HttpURLConnection, no OkHttp/Ktor).
40 */
41class RegistrationHttpClient(private val context: Context) {
42
43 // Real service base — chat.signal.org (REST); WS uses grpc.chat.signal.org per env.rs DOMAIN_CONFIG_CHAT.
44 var baseUrl: String = baseOverrideForTest ?: "https://chat.signal.org"
45
46 var cdnUrl: String = "https://cdn.signal.org"
47
48 /** The result of requesting an SMS/voice verification code from the Signal service. */
49 data class CodeResult(val status: String, val reason: String?, val raw: String) {
50 val ok: Boolean get() = status == "sent" || status == "ok" || status == "200"
51
52 /** Server asked for an hCaptcha token (requestedInformation contains "captcha"). */
53 val needsCaptcha: Boolean get() = status == "captcha"
54 }
55 /** The result of submitting a Signal registration; carries the new ACI/PNI on success. */
56 data class RegisterResult(
57 val status: String,
58 val aci: String?,
59 val pni: String?,
60 val reason: String?,
61 val auth: SignalAuthData?,
62 val raw: String,
63 ) { val ok: Boolean get() = status == "ok" }
64 /** Whether a number is registered on Signal (whoami probe), plus the raw response. */
65 data class ExistResult(val exists: Boolean, val reason: String?, val raw: String)
66 /** A Signal registration session: what the service still needs before a code can be sent. */
67 data class SessionInfo(
68 val id: String,
69 val allowedToRequestCode: Boolean,
70 val requestedInformation: List<String>,
71 val verified: Boolean,
72 val nextSms: Int?,
73 val nextCall: Int?,
74 val raw: String,
75 )
76
77 suspend fun requestSmsCode(e164: String): CodeResult = requestCode(e164, "sms")
78 suspend fun requestVoiceCode(e164: String): CodeResult = requestCode(e164, "voice")
79
80 private suspend fun requestCode(e164: String, transport: String): CodeResult {
81 val number = e164.filter { it.isDigit() || it == '+' }
82 val auth = resolveScaffold(number)
83
84 // 1) POST /v1/verification/session
85 val create = try { createVerificationSession(
86 number,
87 pushToken = null,
88 mcc = null,
89 mnc = null) } catch (expected: Throwable) {
90 Log.error(TAG, "createVerificationSession failed", expected)
91 return CodeResult("error", expected.message, expected.message ?: "")
92 }
93 // Persist session id so submitCaptcha/verifyCode can use it across process restarts.
94 SignalAuthData.save(context, auth.copy(verificationSessionId = create.id, phoneNumber = number))
95
96 // 2) Server-requested challenges gate code delivery.
97 gateChallenges(create)?.let { return it }
98
99 // 3) POST /v1/verification/session/{id}/code {transport, client}
100 return sendCode(create.id, transport)
101 }
102
103 /** Resolve the auth scaffold, regenerating stale pre-registration material. */
104 private suspend fun resolveScaffold(number: String): SignalAuthData {
105 // Reuse the stored scaffold only if it belongs to this number AND is either an already-registered
106 // account (never clobber committed keys) or a still-valid pre-registration scaffold. A stale
107 // pre-registration scaffold — e.g. an old 32-byte unidentifiedAccessKey that the server rejects
108 // with HTTP 422 — is self-healed by regenerating fresh ephemeral registration keys for the SAME
109 // number, so the user does not need a new number or an app-data wipe.
110 val existing = SignalAuthData.load(context)
111 val reuseExisting = existing != null &&
112 existing.phoneNumber == number &&
113 existing.password.isNotEmpty() &&
114 (existing.registered || isValidPreRegScaffold(existing))
115 return if (reuseExisting) {
116 existing
117 } else {
118 if (existing != null && existing.phoneNumber == number && !existing.registered) {
119 Log.status(TAG, "Regenerating stale pre-registration scaffold for existing number (UAK/key refresh)")
120 }
121 SignalRegistrationKeys.generate(number).authScaffold.also { SignalAuthData.save(context, it) }
122 }
123 }
124
125 /** Challenge gates (captcha/pushChallenge); null when clear to send the code. */
126 private suspend fun gateChallenges(
127 create: SessionInfo,
128 ): CodeResult? {
129 // captcha: needs an hCaptcha token minted via the signalcaptchas.org WebView (see submitCaptcha +
130 // SignalCaptchaScreen).
131 if (create.requestedInformation.contains("captcha") && !create.allowedToRequestCode) {
132 return CodeResult("captcha", "captcha required", create.raw)
133 }
134 // pushChallenge is live-only: requires an FCM token from Play Services + EventBus latch
135 // (RegistrationRepository.requestAndVerifyPushToken).
136 if (create.requestedInformation.contains("pushChallenge") && !create.allowedToRequestCode) {
137 try {
138 patchVerificationSession(
139 create.id,
140 pushToken = null,
141 pushChallenge = null,
142 captcha = null,
143 mcc = null,
144 mnc = null)
145 } catch (expected: Throwable) {
146 Log.status(TAG, "patchVerificationSession (live-only) failed", expected)
147 }
148 return CodeResult("error", "pushChallenge required (live-only: needs FCM pushToken)", create.raw)
149 }
150 return null
151 }
152
153 /**
154 * Submit a solved hCaptcha token to the current verification session, then continue to request the code.
155 *
156 * Signal-Android flow (RegistrationApi.submitCaptchaToken):
157 * - WebView loads [CAPTCHA_URL]; on success it redirects to
158 * `signalcaptcha://signal-hcaptcha.{sitekey}.registration.{token}`.
159 * - The client strips the `signalcaptcha://` scheme and sends the remainder as the `captcha` field via
160 * PATCH /v1/verification/session/{id} (UpdateVerificationSessionRequestBody).
161 * - Once the session is no longer captcha-gated, request the SMS/voice code.
162 *
163 * [captchaToken] may be the raw `signalcaptcha://…` redirect URL or the already-stripped value; the scheme is
164 * removed here so callers can pass either.
165 */
166 suspend fun submitCaptcha(e164: String, captchaToken: String, transport: String = "sms"): CodeResult {
167 val number = e164.filter { it.isDigit() || it == '+' }
168 val stored = SignalAuthData.load(context)
169 ?: return CodeResult("error", "no_session", "missing verification session — request a code first")
170 val sessionId = stored.verificationSessionId
171 ?: return CodeResult("error", "no_session", "missing verification session — request a code first")
172 val token = captchaToken.removePrefix(SIGNAL_CAPTCHA_SCHEME).ifBlank {
173 return CodeResult("error", "empty_captcha", "empty captcha token")
174 }
175 // PATCH /v1/verification/session/{id} {captcha}
176 val patched = try {
177 patchVerificationSession(
178 sessionId,
179 pushToken = null,
180 pushChallenge = null,
181 captcha = token,
182 mcc = null,
183 mnc = null)
184 } catch (expected: Throwable) {
185 Log.error(TAG, "submitCaptcha patch failed", expected)
186 return CodeResult("error", expected.message, expected.message ?: "")
187 }
188 // Keep the (possibly rotated) session id and number persisted for verifyCode.
189 val rotated = stored.copy(
190 verificationSessionId = patched.id.ifEmpty { sessionId },
191 phoneNumber = number.ifEmpty { stored.phoneNumber },
192 )
193 SignalAuthData.save(context, rotated)
194 if (patched.requestedInformation.contains("captcha") && !patched.allowedToRequestCode) {
195 return CodeResult("captcha", "captcha rejected", patched.raw)
196 }
197 return sendCode(patched.id.ifEmpty { sessionId }, transport)
198 }
199
200 /** POST /v1/verification/session/{id}/code — shared by initial request and post-captcha retry. */
201 private suspend fun sendCode(sessionId: String, transport: String): CodeResult {
202 return try {
203 val codeResp = requestVerificationCode(sessionId, transport)
204 when {
205 !codeResp.allowedToRequestCode && codeResp.requestedInformation.contains("captcha") ->
206 CodeResult("captcha", "captcha required", codeResp.raw)
207 !codeResp.allowedToRequestCode && codeResp.raw.contains("captcha", true) ->
208 CodeResult("captcha", "captcha required", codeResp.raw)
209 else -> CodeResult("sent", null, codeResp.raw)
210 }
211 } catch (expected: Throwable) {
212 Log.error(TAG, "requestVerificationCode failed", expected)
213 CodeResult("error", expected.message, expected.message ?: "")
214 }
215 }
216
217 suspend fun verifyCode(code: String): RegisterResult {
218 val stored = SignalAuthData.load(context)
219 ?: return RegisterResult("error", null, null, "no_keys", null, "missing key scaffold")
220 val digits = code.filter { it.isDigit() }
221 val sessionId = stored.verificationSessionId
222 ?: return RegisterResult(
223 "error",
224 null,
225 null,
226 "no_session",
227 null,
228 "missing verification session — call requestSmsCode first")
229 // 4) PUT /v1/verification/session/{id}/code {code}
230 val verify = try { submitVerificationCode(sessionId, digits) } catch (expected: Throwable) {
231 Log.error(TAG, "submitVerificationCode failed", expected)
232 return RegisterResult("error", null, null, expected.message, null, expected.message ?: "")
233 }
234 if (!verify.verified) {
235 return RegisterResult("error", null, null, "code_not_verified", null, verify.raw)
236 }
237 // 5) POST /v1/registration with Basic e164:password + RegistrationSessionRequestBody
238 return try { submitRegistration(sessionId, stored) } catch (expected: Throwable) {
239 Log.error(TAG, "submitRegistration failed", expected)
240 RegisterResult("error", null, null, expected.message, null, expected.message ?: "")
241 }
242 }
243
244 // Real Signal has no GET /v1/accounts/exists/{e164}; CDSIv2 is authority for number->ACI.
245 // Post-auth use GET /v1/accounts/whoami.
246 // The number is not probed directly: post-auth whoami identifies by credentials, and pre-registration
247 // has no existence endpoint (CDSIv2 is the authority), so e164 only documents the caller's intent.
248 @Suppress("UnusedParameter")
249 suspend fun checkExists(e164: String): ExistResult {
250 val auth = SignalAuthData.load(context)
251 // If authenticated (registered), probe real endpoint GET /v1/accounts/whoami with Basic e164:password
252 if (auth != null && auth.registered && auth.password.isNotEmpty()) {
253 return try {
254 val basic = "Basic " + b64NoPad("${auth.phoneNumber}:${auth.password}".toByteArray(Charsets.UTF_8))
255 val resp = NetworkClient.performRequest(
256 "$baseUrl/v1/accounts/whoami",
257 method = "GET",
258 headers = mapOf("Authorization" to basic),
259 sslSocketFactory = SignalTrust.sslSocketFactory(context),
260 )
261 // whoami returns {number, aci, pni} when registered
262 ExistResult(resp.status == HTTP_OK, null, resp.body)
263 } catch (expected: Throwable) {
264 Log.error(TAG, "checkExists whoami failed", expected)
265 ExistResult(false, expected.message, expected.message ?: "")
266 }
267 }
268 // Pre-registration: no Signal endpoint to probe number existence; CDSIv2 discovery is the live-only authority.
269 return ExistResult(
270 false,
271 "live-only: use CDSIv2 POST https://cdsi.signal.org/v1/{mrenclave}/discovery after registration",
272 "")
273 }
274
275 // ---- Low-level verification-session calls ----
276
277 private suspend fun createVerificationSession(
278 number: String,
279 pushToken: String?,
280 mcc: String?,
281 mnc: String?): SessionInfo {
282 val body = JSONObject().apply {
283 put("number", number)
284 if (pushToken != null) {
285 put("pushToken", pushToken)
286 put("pushTokenType", "fcm")
287 }
288 if (mcc != null) put("mcc", mcc)
289 if (mnc != null) put("mnc", mnc)
290 }.toString()
291 val resp = NetworkClient.performRequest(
292 "$baseUrl$VERIFICATION_SESSION_PATH",
293 method = "POST",
294 headers = mapOf("Content-Type" to "application/json"),
295 body = body,
296 sslSocketFactory = SignalTrust.sslSocketFactory(context),
297 )
298 if (resp.status == HTTP_LOCKED) throw IllegalStateException(
299 "423 RegistrationLock (live-only: needs svr2Credentials/recoveryPassword)",
300 )
301 if (!resp.isSuccess) throw IllegalStateException("HTTP ${resp.status}: ${resp.body.take(ERROR_BODY_MAX_CHARS)}")
302 return parseSession(resp.body)
303 }
304
305 private suspend fun patchVerificationSession(
306 sessionId: String,
307 pushToken: String?,
308 pushChallenge: String?,
309 captcha: String?,
310 mcc: String?,
311 mnc: String?,
312 ): SessionInfo {
313 val body = JSONObject().apply {
314 if (captcha != null) put("captcha", captcha)
315 if (pushToken != null) {
316 put("pushToken", pushToken)
317 put("pushTokenType", "fcm")
318 }
319 if (pushChallenge != null) put("pushChallenge", pushChallenge)
320 if (mcc != null) put("mcc", mcc)
321 if (mnc != null) put("mnc", mnc)
322 }.toString()
323 val resp = NetworkClient.performRequest(
324 "$baseUrl$VERIFICATION_SESSION_PATH/$sessionId",
325 method = "PATCH",
326 headers = mapOf("Content-Type" to "application/json"),
327 body = body,
328 sslSocketFactory = SignalTrust.sslSocketFactory(context),
329 )
330 if (!resp.isSuccess) throw IllegalStateException("HTTP ${resp.status}: ${resp.body.take(ERROR_BODY_MAX_CHARS)}")
331 return parseSession(resp.body)
332 }
333
334 private suspend fun requestVerificationCode(sessionId: String, transport: String): SessionInfo {
335 val body = JSONObject().apply {
336 put("transport", transport) // "sms" | "voice"
337 put("client", "android") // or "android-2021-03" for SMS retriever
338 }.toString()
339 val resp = NetworkClient.performRequest(
340 "$baseUrl${String.format(VERIFICATION_CODE_PATH, sessionId)}",
341 method = "POST",
342 headers = mapOf(
343 "Content-Type" to "application/json",
344 "Accept-Language" to (java.util.Locale.getDefault().toLanguageTag()),
345 ),
346 body = body,
347 sslSocketFactory = SignalTrust.sslSocketFactory(context),
348 )
349 val failure = when {
350 resp.status == HTTP_LOCKED ->
351 IllegalStateException("423 RegistrationLock (live-only)")
352 resp.status == HTTP_RATE_LIMITED ->
353 IllegalStateException("429 rate limited: ${resp.body.take(ERROR_BODY_MAX_CHARS)}")
354 !resp.isSuccess ->
355 IllegalStateException("HTTP ${resp.status}: ${resp.body.take(ERROR_BODY_MAX_CHARS)}")
356 else -> null
357 }
358 if (failure != null) throw failure
359 return parseSession(resp.body)
360 }
361
362 private suspend fun submitVerificationCode(sessionId: String, code: String): SessionInfo {
363 val body = JSONObject().put("code", code).toString()
364 val resp = NetworkClient.performRequest(
365 "$baseUrl${String.format(VERIFICATION_CODE_PATH, sessionId)}",
366 method = "PUT",
367 headers = mapOf("Content-Type" to "application/json"),
368 body = body,
369 sslSocketFactory = SignalTrust.sslSocketFactory(context),
370 )
371 if (resp.status == HTTP_LOCKED) throw IllegalStateException("423 RegistrationLock (live-only)")
372 // Signal keys off session.verified, not strictly the HTTP code. A 409 whose body has verified:true means
373 // the code is already verified (idempotent) — mirror SubmitVerificationCodeResponseHandler, which maps that
374 // 409 to AlreadyVerifiedException and the app then proceeds to POST /v1/registration. So: if the parsed
375 // session is verified (on 200/204 or 409), treat it as success and continue the flow.
376 val session = parseSession(resp.body)
377 if (resp.isSuccess || session.verified) {
378 return session
379 }
380 throw IllegalStateException("HTTP ${resp.status}: ${resp.body.take(ERROR_BODY_MAX_CHARS)}")
381 }
382
383 private suspend fun submitRegistration(sessionId: String, auth: SignalAuthData): RegisterResult {
384 val password = auth.password.ifEmpty { return RegisterResult(
385 "error",
386 null,
387 null,
388 "missing_password",
389 null,
390 "no password") }
391 val e164 = auth.phoneNumber
392 val basic = "Basic " + b64NoPad("$e164:$password".toByteArray(Charsets.UTF_8))
393
394 val bodyJson = buildRegistrationBody(sessionId, auth)
395
396 val resp = NetworkClient.performRequest(
397 "$baseUrl$REGISTRATION_PATH",
398 method = "POST",
399 headers = mapOf(
400 "Content-Type" to "application/json",
401 "Authorization" to basic,
402 ),
403 body = bodyJson,
404 sslSocketFactory = SignalTrust.sslSocketFactory(context),
405 )
406 // 423 RegistrationLock — live-only: server returns {timeRemaining, svr2Credentials:{username,password},
407 // svr3Credentials} + recoveryPassword path
408 if (resp.status == HTTP_LOCKED) {
409 return RegisterResult(
410 "error",
411 null,
412 null,
413 "423 RegistrationLock (live-only: needs svr2Credentials/recoveryPassword via SVR2/SVR3)",
414 null,
415 resp.body)
416 }
417 if (!resp.isSuccess) {
418 Log.error(TAG, "submitRegistration HTTP ${resp.status}")
419 return RegisterResult("error", null, null, "HTTP ${resp.status}", null, resp.body)
420 }
421 return finalizeRegister(resp.body, auth)
422 }
423
424 /** The POST /v1/registration body: session, account attributes and ACI/PNI key material. */
425 private fun buildRegistrationBody(sessionId: String, auth: SignalAuthData): String {
426 // Identity keys: Base64-nopad(IdentityKey.serialize() 33B = 0x05||32)
427 val aciIdKey = auth.effectiveAciPublic().ifEmpty { auth.aciIdentityPublicKey }
428 val pniIdKey = auth.pniIdentityPublicKey.ifEmpty { auth.effectiveAciPublic() }
429 // Fallback: if PNI identity missing (legacy single-identity auth), reuse ACI identity wire-correctly but
430 // document live-only dual requirement
431 val pniIdentityWire = if (pniIdKey.isEmpty()) aciIdKey else pniIdKey
432
433 fun spkEntity(keyId: Int, pubB64: String, sigB64: String): JSONObject = JSONObject().apply {
434 put("keyId", keyId)
435 put("publicKey", pubB64.trimEnd('=')) // Base64-nopad per SignedPreKeyEntity
436 put("signature", sigB64.trimEnd('='))
437 }
438 fun kyberEntity(keyId: Int, pubB64: String, sigB64: String): JSONObject = JSONObject().apply {
439 put("keyId", keyId)
440 // KEM public serialize is 1569B = 0x08||1568; keep 0x08 tag intact for wire (see SignalPqPreKey)
441 put("publicKey", pubB64.trimEnd('='))
442 put("signature", sigB64.trimEnd('='))
443 }
444
445 return JSONObject().apply {
446 put("sessionId", sessionId)
447 // recoveryPassword is xor with sessionId — null here; live-only SVR re-registration uses recoveryPassword
448 // instead
449 put("accountAttributes", buildAccountAttributesJson(auth))
450 put("aciIdentityKey", aciIdKey.trimEnd('='))
451 put("pniIdentityKey", pniIdentityWire.trimEnd('='))
452 put(
453 "aciSignedPreKey",
454 spkEntity(auth.effectiveAciSignedId(), auth.effectiveAciSignedPub(), auth.effectiveAciSignedSig()))
455 // pniSignedPreKey — reuse ACI if missing legacy
456 val pniSpkId = if (auth.pniSignedPreKeyId != 0) auth.pniSignedPreKeyId else auth.effectiveAciSignedId()
457 val pniSpkPub = auth.pniSignedPreKeyPublic.ifEmpty { auth.effectiveAciSignedPub() }
458 val pniSpkSig = auth.pniSignedPreKeySignature.ifEmpty { auth.effectiveAciSignedSig() }
459 put("pniSignedPreKey", spkEntity(pniSpkId, pniSpkPub, pniSpkSig))
460 put(
461 "aciPqLastResortPreKey",
462 kyberEntity(auth.effectiveAciPqId(), auth.effectiveAciPqPub(), auth.effectiveAciPqSig()))
463 val pniPqId = if (auth.pniPqLastResortKeyId != 0) auth.pniPqLastResortKeyId else auth.effectiveAciPqId()
464 val pniPqPub = auth.pniPqLastResortPublic.ifEmpty { auth.effectiveAciPqPub() }
465 val pniPqSig = auth.pniPqLastResortSignature.ifEmpty { auth.effectiveAciPqSig() }
466 put("pniPqLastResortPreKey", kyberEntity(pniPqId, pniPqPub, pniPqSig))
467 // gcmToken: null if fetchesMessages:true (primary), else {gcmRegistrationId, webSocketChannel:true}
468 put("skipDeviceTransfer", true)
469 put("requireAtomic", true)
470 }.toString()
471 }
472
473 private fun buildAccountAttributesJson(auth: SignalAuthData): JSONObject {
474 // The account-attributes payload mirrors the signal service's
475 // AccountAttributes shape: a null signaling key, the registration and
476 // PNI registration ids, the 32-byte unidentified access key, the
477 // registration lock, an optional recovery password, message fetching
478 // enabled, the storage / timer / backfill / spqr / username-sync
479 // capabilities, phone-number discoverability, and the profile name.
480 val uakB64 = auth.unidentifiedAccessKey
481 val uakBytes = if (uakB64.isNotEmpty()) runCatching { Base64.decode(
482 uakB64,
483 Base64.NO_WRAP) }.getOrNull() else null
484 val caps = JSONObject().apply {
485 put("storage", true)
486 put("versionedExpirationTimer", true)
487 put("attachmentBackfill", true)
488 put("spqr", true)
489 put("usernameChangeSyncMessage", true)
490 }
491 return JSONObject().apply {
492 put("signalingKey", JSONObject.NULL)
493 put("registrationId", auth.effectiveAciRegId())
494 put(
495 "pniRegistrationId",
496 if (auth.pniRegistrationId != 0) auth.pniRegistrationId else auth.effectiveAciRegId())
497 put("fetchesMessages", true)
498 // AccountAttributes has no class-level @JsonInclude(NON_NULL): nullable fields serialize as explicit null.
499 put(
500 "registrationLock",
501 auth.registrationLock ?: JSONObject.NULL) // null until live SVR2 MasterKey.deriveRegistrationLock
502 put("recoveryPassword", JSONObject.NULL) // live-only SVR re-registration path; null for session-based reg
503 // Jackson serializes AccountAttributes.unidentifiedAccessKey (ByteArray) with its default variant =
504 // standard base64 WITH padding (MIME_NO_LINEFEEDS) — unlike the prekey material which is nopad.
505 if (uakBytes != null) put("unidentifiedAccessKey", b64Padded(uakBytes)) else put(
506 "unidentifiedAccessKey",
507 JSONObject.NULL)
508 put("unrestrictedUnidentifiedAccess", false)
509 put("discoverableByPhoneNumber", true)
510 put("capabilities", caps)
511 put("name", auth.profileName.ifEmpty { JSONObject.NULL })
512 // voice/video true by default in two-arg constructor
513 put("voice", true)
514 put("video", true)
515 }
516 }
517
518 private fun finalizeRegister(body: String, auth: SignalAuthData): RegisterResult {
519 val j = parse(body)
520 val status = j.optString("status", if (body.contains("\"uuid\"") || body.contains("\"aci\"")) "ok" else "error")
521 val aci = j.optStringOrNull("uuid") ?: j.optStringOrNull("aci") ?: j.optStringOrNull("number")
522 val pni = j.optStringOrNull("pni")
523 val updated = persistRegisteredAuth(j, body, auth, status, aci, pni)
524 val finalStatus = if (updated != null) "ok" else status
525 return RegisterResult(finalStatus, aci, pni, j.optStringOrNull("reason"), updated, body)
526 }
527
528 /** Persist the registered ACI/PNI onto [auth] when the response carries an account id. */
529 private fun persistRegisteredAuth(
530 j: JSONObject,
531 body: String,
532 auth: SignalAuthData,
533 status: String,
534 aci: String?,
535 pni: String?,
536 ): SignalAuthData? {
537 // VerifyAccountResponse fields: uuid/aci, pni, storageCapable, number, reregistration
538 val aciVal = j.optStringOrNull("uuid") ?: j.optStringOrNull("aci") ?: auth.aci
539 val ok = status == "ok" || (aciVal.isNotEmpty() && body.contains("\"uuid\""))
540 if (!ok && !j.has("uuid") && !j.has("aci")) return null
541 return auth.copy(
542 aci = aciVal.ifEmpty { aci ?: auth.aci },
543 pni = pni ?: auth.pni,
544 registered = true).also { SignalAuthData.save(context, it) }
545 }
546
547 private fun parseSession(body: String): SessionInfo {
548 val j = parse(body)
549 val id = j.optStringOrNull("id") ?: j.optStringOrNull("sessionId") ?: ""
550 val allowed = j.optBoolean("allowedToRequestCode", true)
551 val verified = j.optBoolean("verified", false)
552 val nextSms = j.optIntOrNull("nextSms")
553 val nextCall = j.optIntOrNull("nextCall")
554 val reqInfo = mutableListOf<String>()
555 val arr: JSONArray? = j.optJSONArray("requestedInformation")
556 if (arr != null) for (i in 0 until arr.length()) reqInfo.add(arr.optString(i))
557 return SessionInfo(id, allowed, reqInfo, verified, nextSms, nextCall, body)
558 }
559
560 private fun parse(body: String): JSONObject = try { JSONObject(body) } catch (_: Exception) { JSONObject() }
561
562 /**
563 * A reusable pre-registration scaffold must carry a valid unidentifiedAccessKey: the Signal server
564 * requires it to be EXACTLY 16 bytes (UnidentifiedAccess.deriveAccessKeyFrom trims to 16). An older
565 * scaffold with a 32-byte UAK is treated as stale so requestCode regenerates it for the same number.
566 */
567 private fun isValidPreRegScaffold(auth: SignalAuthData): Boolean {
568 val uak = auth.unidentifiedAccessKey
569 if (uak.isEmpty()) return false
570 val bytes = runCatching { Base64.decode(uak, Base64.NO_WRAP) }.getOrNull() ?: return false
571 return bytes.size == UUID_SIZE
572 }
573
574 /** HTTP status constants and logging tag for the Signal registration client. */
575 companion object {
576 /** Test seam: localhost base applied to new instances (e.g. Compose screens). */
577 var baseOverrideForTest: String? = null
578
579 private const val TAG = "SignalRegHttp"
580 private const val HTTP_OK = 200
581 private const val HTTP_LOCKED = 423
582 private const val HTTP_RATE_LIMITED = 429
583 /** How much of an error response body is quoted in an exception message. */
584 private const val ERROR_BODY_MAX_CHARS = 500
585 private const val UUID_SIZE = 16
586 private const val VERIFICATION_SESSION_PATH = "/v1/verification/session"
587 private const val VERIFICATION_CODE_PATH = "/v1/verification/session/%s/code"
588 private const val REGISTRATION_PATH = "/v1/registration"
589
590 /** hCaptcha challenge page (Signal-Android BuildConfig.SIGNAL_CAPTCHA_URL). */
591 const val CAPTCHA_URL = "https://signalcaptchas.org/registration/generate.html"
592
593 /**
594 * Redirect scheme the captcha page hands back on success:
595 * `signalcaptcha://signal-hcaptcha.{sitekey}.registration.{token}`
596 * (RegistrationConstants.SIGNAL_CAPTCHA_SCHEME).
597 * The value after this prefix is submitted verbatim as the `captcha` field.
598 */
599 const val SIGNAL_CAPTCHA_SCHEME = "signalcaptcha://"
600 }
601}
602
603private fun JSONObject.optStringOrNull(key: String): String? = if (has(key) && !isNull(key)) optString(key) else null
604private fun JSONObject.optBoolean(key: String, default: Boolean): Boolean = if (has(key) && !isNull(key)) optBoolean(
605 key,
606 default) else default
607private fun JSONObject.optIntOrNull(key: String): Int? = if (has(key) && !isNull(key)) optInt(key) else null
608private fun b64NoPad(bytes: ByteArray): String = Base64.encodeToString(bytes, Base64.NO_WRAP).trimEnd('=')
609private fun b64Padded(bytes: ByteArray): String = Base64.encodeToString(bytes, Base64.NO_WRAP)