Modern-Apps.git
Publicgit clone https://git.maproj.org/Modern-Apps.gitModern-Apps.git / communicate-dev / src / main / java / com / vayunmathur / communicate / data / whatsapp / registration / RegistrationHttpClient.kt
RegistrationHttpClient.kt604 lines · 26.6 KiBRaw
| 1 | package com.vayunmathur.communicate.data.whatsapp.registration |
| 2 | |
| 3 | import android.content.Context |
| 4 | import android.os.Build |
| 5 | import android.provider.Settings |
| 6 | import android.telephony.TelephonyManager |
| 7 | import com.vayunmathur.library.log.Log |
| 8 | import com.vayunmathur.communicate.data.whatsapp.WhatsAppAuthData |
| 9 | import com.vayunmathur.communicate.data.whatsapp.WhatsAppProtocol |
| 10 | import com.vayunmathur.library.network.NetworkClient |
| 11 | import org.json.JSONObject |
| 12 | import java.net.URLEncoder |
| 13 | |
| 14 | /** |
| 15 | * Speaks WhatsApp's primary-registration `/v2/ endpoints` protocol (own phone-number registration). |
| 16 | * |
| 17 | * Flow: [requestCode] (→ SMS/voice OTP) → [register] (with the OTP) → persisted [WhatsAppAuthData] |
| 18 | * with `new_jid`. [checkExist] probes state; [submitTwoFactor] handles the `/v2/security` PIN path. |
| 19 | * |
| 20 | * Parameter set + encodings are matched **exactly** to the pinned APK's `KotlinRegistrationBridge` + |
| 21 | * `C34244EyE` request builder (see [RegEncoding]) to avoid `bad_param`: |
| 22 | * - plain `A01`: cc, in, lg, lc, fdid, token, method, code |
| 23 | * - `A03` (UUID→16B→url-b64): expid |
| 24 | * - `A05` (percent-encoded raw bytes, stored pre-encoded): id, backup_token |
| 25 | * - `A00` ("true"/"false"): clicked_education_link, manage_call_permission, call_log_permission |
| 26 | * - `A04` (url-b64) E2E bundle: authkey, e_ident, e_keytype, e_regid, e_skey_id, e_skey_val, e_skey_sig |
| 27 | * |
| 28 | * Body is `application/x-www-form-urlencoded`. Default is the PLAIN body (the official client falls |
| 29 | * back to plain when its ENC layer fails, so the server accepts it); [useEncWrapper] adds ENC/H. |
| 30 | */ |
| 31 | class RegistrationHttpClient( |
| 32 | private val context: Context, |
| 33 | private val useEncWrapper: Boolean = false, |
| 34 | ) { |
| 35 | private val fingerprint = WhatsAppDeviceFingerprint.getOrCreate(context) |
| 36 | |
| 37 | /** Test seam: localhost base (without trailing slash) replacing the fixed endpoint. */ |
| 38 | internal var baseUrlForTest: String? = baseOverrideForTest |
| 39 | |
| 40 | // ------------------------------------------------------------------ results |
| 41 | |
| 42 | /** The result of requesting a WhatsApp verification code (status, method, retry-after). */ |
| 43 | data class CodeResult( |
| 44 | val status: String, val method: String?, val length: Int?, |
| 45 | val retryAfter: Long?, val reason: String?, val param: String?, val raw: String, |
| 46 | ) { val ok: Boolean get() = status == "sent" || status == "ok" } |
| 47 | |
| 48 | /** The result of a WhatsApp /v2/register attempt; carries the new JID on success. */ |
| 49 | data class RegisterResult( |
| 50 | val status: String, val newJid: String?, val login: String?, val serverTime: Long?, |
| 51 | val reason: String?, val param: String?, val auth: WhatsAppAuthData?, val raw: String, |
| 52 | ) { val ok: Boolean get() = status == "ok" } |
| 53 | |
| 54 | /** The result of a WhatsApp /v2/exist number check. */ |
| 55 | data class ExistResult(val status: String, val reason: String?, val param: String?, val raw: String) |
| 56 | |
| 57 | /** `/v2/consent` — over-18 self-declare / DOB / parent-verification consent (§3.12). */ |
| 58 | data class ConsentResult( |
| 59 | val status: String, val reason: String?, val pending: String?, val url: String?, val raw: String, |
| 60 | ) { val ok: Boolean get() = status == "ok" } |
| 61 | |
| 62 | /** `/v2/autoconf` — request the autoconf verifier / attribute list (§3.8). */ |
| 63 | data class AutoconfResult( |
| 64 | val status: String, val reason: String?, val registerStartMessage: String?, val raw: String, |
| 65 | ) { val ok: Boolean get() = status == "ok" || status == "sent" } |
| 66 | |
| 67 | /** `/v2/autoconf_verifier` — submit the encrypted verifier data (§3.9). */ |
| 68 | data class AutoconfVerifierResult(val status: String, val reason: String?, val raw: String) { |
| 69 | val ok: Boolean get() = status == "ok" |
| 70 | } |
| 71 | |
| 72 | /** `/v2/captcha_verify` — fraud-checkpoint code verification (§3.10). */ |
| 73 | data class CaptchaVerifyResult( |
| 74 | val status: String, val reason: String?, val violationType: String?, val appealToken: String?, val raw: String, |
| 75 | ) { val ok: Boolean get() = status == "verified" } |
| 76 | |
| 77 | /** `/v2/challenge` — email/oauth challenge step (§3.14). */ |
| 78 | data class ChallengeResult(val status: String, val reason: String?, val raw: String) { |
| 79 | val ok: Boolean get() = status == "ok" |
| 80 | } |
| 81 | |
| 82 | /** `/v2/client_log` — fire-and-forget onboarding funnel log (§3.6). */ |
| 83 | data class ClientLogResult(val status: String, val raw: String) { |
| 84 | val ok: Boolean get() = status == "ok" |
| 85 | } |
| 86 | |
| 87 | // ------------------------------------------------------------------ endpoints |
| 88 | |
| 89 | /** POST `/v2/code` — request an OTP. Generates + persists fresh key material first. */ |
| 90 | suspend fun requestCode(cc: String, number: String, method: String = "sms"): CodeResult { |
| 91 | val keys = RegistrationKeys.generate("$cc$number") |
| 92 | WhatsAppAuthData.save(context, keys.authScaffold) |
| 93 | |
| 94 | val p = RegParams() |
| 95 | p.a01("cc", cc) |
| 96 | p.a01("in", number) |
| 97 | p.addCommon() |
| 98 | p.addDevice() |
| 99 | // Token uses the NATIONAL number only (APK: ES2.A00.A01(app, $phoneNumber); $countryCode is |
| 100 | // a separate param, and server login = cc + in confirms `in`/$phoneNumber is national). |
| 101 | p.a01("token", RegistrationAttestation.computeToken(context, number)) |
| 102 | p.a01("method", method) |
| 103 | p.a00("clicked_education_link", false) |
| 104 | p.a00("manage_call_permission", false) |
| 105 | p.a00("call_log_permission", false) |
| 106 | p.addIntegrity(EndpointKind.CODE) |
| 107 | p.bundle(RegistrationKeys.bundleFields(keys.authScaffold)) |
| 108 | |
| 109 | val body = send("code", p) |
| 110 | val j = parse(body) |
| 111 | Log.error( |
| 112 | TAG, |
| 113 | "W2 code reason=${j.optStringOrNull("reason")} param=${j.optStringOrNull("param")}") |
| 114 | return CodeResult( |
| 115 | status = j.optString("status", "error"), |
| 116 | method = j.optStringOrNull("method"), |
| 117 | length = j.optIntOrNull("length"), |
| 118 | retryAfter = j.optLongOrNull("retry_after"), |
| 119 | reason = j.optStringOrNull("reason"), |
| 120 | param = j.optStringOrNull("param"), |
| 121 | raw = body, |
| 122 | ) |
| 123 | } |
| 124 | |
| 125 | /** POST `/v2/register` — submit the OTP and finalize the primary line. */ |
| 126 | suspend fun register(cc: String, number: String, code: String): RegisterResult { |
| 127 | val auth = WhatsAppAuthData.load(context) |
| 128 | ?: return RegisterResult("error", null, null, null, "no_keys", null, null, "missing key scaffold") |
| 129 | val p = RegParams() |
| 130 | p.a01("cc", cc) |
| 131 | p.a01("in", number) |
| 132 | p.addCommon() |
| 133 | p.addDevice() |
| 134 | p.a01("code", code.filter { it.isDigit() }) |
| 135 | p.addIntegrity(EndpointKind.REGISTER) |
| 136 | p.bundle(RegistrationKeys.bundleFields(auth)) |
| 137 | |
| 138 | val body = send("register", p) |
| 139 | return finalizeRegister(body, auth) |
| 140 | } |
| 141 | |
| 142 | /** POST `/v2/security` — submit the account's 2FA PIN when register returns `security_code`. */ |
| 143 | suspend fun submitTwoFactor(cc: String, number: String, pin: String): RegisterResult { |
| 144 | val auth = WhatsAppAuthData.load(context) |
| 145 | ?: return RegisterResult("error", null, null, null, "no_keys", null, null, "missing key scaffold") |
| 146 | val p = RegParams() |
| 147 | p.a01("cc", cc) |
| 148 | p.a01("in", number) |
| 149 | p.addCommon() |
| 150 | p.addDevice() |
| 151 | p.a01("code", pin.filter { it.isDigit() }) |
| 152 | p.bundle(RegistrationKeys.bundleFields(auth)) |
| 153 | |
| 154 | val body = send("security", p) |
| 155 | return finalizeRegister(body, auth) |
| 156 | } |
| 157 | |
| 158 | /** POST `/v2/exist` — probe whether the number is already registered on this key material. */ |
| 159 | suspend fun checkExist(cc: String, number: String): ExistResult { |
| 160 | val auth = WhatsAppAuthData.load(context) |
| 161 | val p = RegParams() |
| 162 | p.a01("cc", cc) |
| 163 | p.a01("in", number) |
| 164 | p.addCommon() |
| 165 | p.addDevice() |
| 166 | // Bug fix (w2.md §3.1): /v2/exist REQUIRES `token`; it was previously omitted. |
| 167 | p.a01("token", RegistrationAttestation.computeToken(context, number)) |
| 168 | p.addIntegrity(EndpointKind.EXIST) |
| 169 | if (auth != null) p.bundle(RegistrationKeys.bundleFields(auth)) |
| 170 | val body = send("exist", p) |
| 171 | val j = parse(body) |
| 172 | Log.error( |
| 173 | TAG, |
| 174 | "W2 exist reason=${j.optStringOrNull("reason")} param=${j.optStringOrNull("param")}") |
| 175 | return ExistResult( |
| 176 | j.optString("status", "error"), |
| 177 | j.optStringOrNull("reason"), |
| 178 | j.optStringOrNull("param"), |
| 179 | body) |
| 180 | } |
| 181 | |
| 182 | /** |
| 183 | * POST `/v2/consent` (§3.12). Records the age/consent decision. Needs the E2E encryption bundle |
| 184 | * (`/v2/consent` is in the proto-2.0 encryption list, §2.1). [consentContext] is one of |
| 185 | * `app_store_age|dob|parent_verification|consent`. |
| 186 | */ |
| 187 | suspend fun consent( |
| 188 | cc: String, |
| 189 | number: String, |
| 190 | consentContext: String, |
| 191 | dob: String? = null, |
| 192 | ageLowerBound: Int? = null, |
| 193 | consentDecision: String? = null, |
| 194 | consentId: String? = null, |
| 195 | consentVersion: String? = null, |
| 196 | securityCode: String? = null, |
| 197 | ): ConsentResult { |
| 198 | val auth = WhatsAppAuthData.load(context) |
| 199 | val p = RegParams() |
| 200 | p.a01("cc", cc) |
| 201 | p.a01("in", number) |
| 202 | p.addCommon() |
| 203 | p.addDevice() |
| 204 | if (auth != null) p.bundle(RegistrationKeys.bundleFields(auth)) |
| 205 | p.a01("context", consentContext) |
| 206 | p.a02("dob", dob) |
| 207 | if (ageLowerBound != null) p.a01("age_lower_bound", ageLowerBound.toString()) |
| 208 | p.a02("consent_decision", consentDecision) |
| 209 | p.a02("consent_id", consentId) |
| 210 | p.a02("consent_version", consentVersion) |
| 211 | p.a02("security_code", securityCode) |
| 212 | val body = send("consent", p) |
| 213 | val j = parse(body) |
| 214 | return ConsentResult( |
| 215 | status = j.optString("status", "error"), |
| 216 | reason = j.optStringOrNull("reason"), |
| 217 | pending = j.optStringOrNull("pending"), |
| 218 | url = j.optStringOrNull("url"), |
| 219 | raw = body, |
| 220 | ) |
| 221 | } |
| 222 | |
| 223 | /** |
| 224 | * POST `/v2/autoconf` (§3.8). Requests the autoconf verifier / attribute list. No E2E bundle |
| 225 | * (autoconf is not in the §2.1 encryption list). [consent] is `1` or `2`. |
| 226 | */ |
| 227 | suspend fun autoconf( |
| 228 | cc: String, |
| 229 | number: String, |
| 230 | consent: Int, |
| 231 | clientCapabilities: String? = null, |
| 232 | consentShown: Boolean, |
| 233 | createVerifier: Boolean, |
| 234 | ): AutoconfResult { |
| 235 | val p = RegParams() |
| 236 | p.a01("cc", cc) |
| 237 | p.a01("in", number) |
| 238 | p.addCommon() |
| 239 | p.addDevice() |
| 240 | p.a01("consent", consent.toString()) |
| 241 | p.a02("client_capabilities", clientCapabilities) |
| 242 | p.a00("consent_shown", consentShown) |
| 243 | p.a00("create_verifier", createVerifier) |
| 244 | val body = send("autoconf", p) |
| 245 | val j = parse(body) |
| 246 | return AutoconfResult( |
| 247 | status = j.optString("status", "error"), |
| 248 | reason = j.optStringOrNull("reason"), |
| 249 | registerStartMessage = j.optStringOrNull("register_start_message"), |
| 250 | raw = body, |
| 251 | ) |
| 252 | } |
| 253 | |
| 254 | /** |
| 255 | * POST `/v2/autoconf_verifier` (§3.9). Submits the encrypted verifier data. |
| 256 | * [registrationMethod]: 0 token, 2 wa_old, 3 email, 4 flash, 5 sms. |
| 257 | */ |
| 258 | suspend fun autoconfVerifier( |
| 259 | cc: String, |
| 260 | number: String, |
| 261 | code: String, |
| 262 | encryptedVerifierData: String, |
| 263 | registrationMethod: Int, |
| 264 | ): AutoconfVerifierResult { |
| 265 | val p = RegParams() |
| 266 | p.a01("cc", cc) |
| 267 | p.a01("in", number) |
| 268 | p.addCommon() |
| 269 | p.addDevice() |
| 270 | p.a01("code", code.filter { it.isDigit() }) |
| 271 | p.a01("encrypted_verifier_data", encryptedVerifierData) |
| 272 | p.a01("registration_method", registrationMethod.toString()) |
| 273 | val body = send("autoconf_verifier", p) |
| 274 | val j = parse(body) |
| 275 | return AutoconfVerifierResult(j.optString("status", "error"), j.optStringOrNull("reason"), body) |
| 276 | } |
| 277 | |
| 278 | /** |
| 279 | * POST `/v2/captcha_verify` (§3.10). Verifies a fraud-checkpoint code. Needs only `authkey` from |
| 280 | * the E2E bundle (per §3.10), not the full `e_*` set. |
| 281 | */ |
| 282 | suspend fun captchaVerify(cc: String, number: String, fraudCheckpointCode: String): CaptchaVerifyResult { |
| 283 | val auth = WhatsAppAuthData.load(context) |
| 284 | val p = RegParams() |
| 285 | p.a01("cc", cc) |
| 286 | p.a01("in", number) |
| 287 | p.addCommon() |
| 288 | p.addDevice() |
| 289 | if (auth != null) { |
| 290 | RegistrationKeys.bundleFields(auth)["authkey"]?.let { p.bundle(mapOf("authkey" to it)) } |
| 291 | } |
| 292 | p.a01("fraud_checkpoint_code", fraudCheckpointCode) |
| 293 | val body = send("captcha_verify", p) |
| 294 | val j = parse(body) |
| 295 | return CaptchaVerifyResult( |
| 296 | status = j.optString("status", "error"), |
| 297 | reason = j.optStringOrNull("reason"), |
| 298 | violationType = j.optStringOrNull("violation_type"), |
| 299 | appealToken = j.optStringOrNull("appeal_token"), |
| 300 | raw = body, |
| 301 | ) |
| 302 | } |
| 303 | |
| 304 | /** |
| 305 | * POST `/v2/challenge` (§3.14). Email/OAuth challenge step. No E2E bundle. |
| 306 | * [challengeType]: `email_enter|email_verify`. |
| 307 | */ |
| 308 | suspend fun challenge( |
| 309 | cc: String, |
| 310 | number: String, |
| 311 | challengeType: String, |
| 312 | email: String? = null, |
| 313 | oauthToken: String? = null, |
| 314 | code: String? = null, |
| 315 | ): ChallengeResult { |
| 316 | val p = RegParams() |
| 317 | p.a01("cc", cc) |
| 318 | p.a01("in", number) |
| 319 | p.addCommon() |
| 320 | p.addDevice() |
| 321 | p.a01("challenge_type", challengeType) |
| 322 | p.a02("email", email) |
| 323 | p.a02("oauth_token", oauthToken) |
| 324 | p.a02("code", code) |
| 325 | val body = send("challenge", p) |
| 326 | val j = parse(body) |
| 327 | return ChallengeResult(j.optString("status", "error"), j.optStringOrNull("reason"), body) |
| 328 | } |
| 329 | |
| 330 | /** |
| 331 | * POST `/v2/client_log` (§3.6). Fire-and-forget onboarding funnel log; no encryption/integrity, |
| 332 | * only `lg,lc,rc` + `cc?/in?` + the error context/type. Always returns `ok` server-side. |
| 333 | */ |
| 334 | suspend fun clientLog( |
| 335 | errorContext: String, |
| 336 | errorType: String, |
| 337 | cc: String? = null, |
| 338 | number: String? = null, |
| 339 | ): ClientLogResult { |
| 340 | val p = RegParams() |
| 341 | p.a02("cc", cc) |
| 342 | p.a02("in", number) |
| 343 | p.a01("lg", context.resources.configuration.locales[0].language.ifEmpty { "en" }) |
| 344 | p.a01("lc", context.resources.configuration.locales[0].country.ifEmpty { "US" }) |
| 345 | p.a01("rc", "0") |
| 346 | p.a01("client_error_context", errorContext) |
| 347 | p.a01("client_error_type", errorType) |
| 348 | val body = send("client_log", p) |
| 349 | val j = parse(body) |
| 350 | return ClientLogResult(j.optString("status", "error"), body) |
| 351 | } |
| 352 | |
| 353 | // ------------------------------------------------------------------ internals |
| 354 | |
| 355 | private fun finalizeRegister(body: String, auth: WhatsAppAuthData): RegisterResult { |
| 356 | val j = parse(body) |
| 357 | val status = j.optString("status", "error") |
| 358 | val newJid = j.optStringOrNull("new_jid") |
| 359 | val login = j.optStringOrNull("login") |
| 360 | val lid = j.optStringOrNull("lid") |
| 361 | // Success may omit `new_jid` (e.g. type:"existing" re-registration); the server returns the |
| 362 | // phone in `login`, so derive the JID from it. Registration is complete whenever status==ok. |
| 363 | val updated = if (status == "ok") { |
| 364 | val wid = when { |
| 365 | newJid != null -> normalizeJid(newJid) |
| 366 | login != null -> "[email protected]" |
| 367 | else -> auth.wid |
| 368 | } |
| 369 | auth.copy( |
| 370 | wid = wid, |
| 371 | lid = lid?.let { if (it.contains("@")) it else "$it@lid" } ?: auth.lid, |
| 372 | serverTime = j.optLongOrNull("server_time") ?: 0L, |
| 373 | registered = true, |
| 374 | loggedInAt = System.currentTimeMillis() / MS_PER_SECOND, |
| 375 | ).also { WhatsAppAuthData.save(context, it) } |
| 376 | } else { |
| 377 | null |
| 378 | } |
| 379 | val reason = j.optStringOrNull("reason") |
| 380 | val param = j.optStringOrNull("param") |
| 381 | if (status != "ok") Log.error(TAG, "W2 register reason=$reason param=$param") |
| 382 | return RegisterResult( |
| 383 | status = status, |
| 384 | newJid = newJid ?: login?.let { "[email protected]" }, |
| 385 | login = login, |
| 386 | serverTime = j.optLongOrNull("server_time"), |
| 387 | reason = reason, |
| 388 | param = param, |
| 389 | auth = updated, |
| 390 | raw = body, |
| 391 | ) |
| 392 | } |
| 393 | |
| 394 | /** |
| 395 | * Mirrors `C34244EyE`: values are stored either PLAIN (A00/A01/A02/A03/A04) or PRE-ENCODED via |
| 396 | * percent-encoding (A05, tracked in [raw]). At query build the raw values are appended as-is; all |
| 397 | * others are URL-encoded — exactly as the APK's request transform does. |
| 398 | */ |
| 399 | private inner class RegParams { |
| 400 | val map = LinkedHashMap<String, String>() |
| 401 | val raw = HashSet<String>() |
| 402 | |
| 403 | fun a00(key: String, value: Boolean) { map[key] = if (value) "true" else "false" } |
| 404 | fun a01(key: String, value: String) { map[key] = value } |
| 405 | fun a02(key: String, value: String?) { if (value != null) map[key] = value } |
| 406 | fun a03(key: String, uuid: String) { map[key] = RegEncoding.b64Url(RegEncoding.uuidToBytes(uuid)) } |
| 407 | fun a05(key: String, bytes: ByteArray) { map[key] = RegEncoding.percentEncode(bytes); raw.add(key) } |
| 408 | fun bundle(fields: Map<String, String>) { map.putAll(fields) } // already url-b64 (A04), non-raw |
| 409 | |
| 410 | fun addCommon() { |
| 411 | a01("lg", context.resources.configuration.locales[0].language.ifEmpty { "en" }) |
| 412 | a01("lc", context.resources.configuration.locales[0].country.ifEmpty { "US" }) |
| 413 | a01("fdid", fingerprint.fdid) |
| 414 | a03("expid", fingerprint.expid) |
| 415 | a05("id", fingerprint.recoveryToken) |
| 416 | a05("backup_token", fingerprint.backupToken) |
| 417 | } |
| 418 | |
| 419 | /** |
| 420 | * Common/device params added by the APK's `F4L` layer (merged via `A06(map)`). Confirmed |
| 421 | * against the native param-key table in libwhatsappmerged.so AND by decompiling `LX/F4L;` |
| 422 | * (A0I/A0M/A0P/A0G) from the installed com.whatsapp 2.26.29.73: WhatsApp does NOT send a |
| 423 | * `platform` form param — the server derives platform from the User-Agent — and it does NOT |
| 424 | * send any `gpia`/`aid`/`_gi`/`_gp`/`_ge`/`_ga`/`_gs`/`t`/`db` params in the no-Play path |
| 425 | * (`gpia` is added only when Play Integrity is available; see [SEND_INTEGRITY_SIGNALS]). The |
| 426 | * fields below are the real F4L device fingerprint the official no-Play request carries. |
| 427 | */ |
| 428 | fun addDevice() { |
| 429 | val tm = runCatching { context.getSystemService(TelephonyManager::class.java) }.getOrNull() |
| 430 | val netOp = tm?.networkOperator.orEmpty() |
| 431 | val simOp = tm?.simOperator.orEmpty() |
| 432 | a01("mcc", if (netOp.length >= MCC_LENGTH) netOp.substring(0, MCC_LENGTH) else "000") |
| 433 | a01("mnc", if (netOp.length > MCC_LENGTH) netOp.substring(MCC_LENGTH) else "000") |
| 434 | a01("sim_mcc", if (simOp.length >= MCC_LENGTH) simOp.substring(0, MCC_LENGTH) else "000") |
| 435 | a01("sim_mnc", if (simOp.length > MCC_LENGTH) simOp.substring(MCC_LENGTH) else "000") |
| 436 | a01("network_radio_type", "1") |
| 437 | a01("simnum", "1") |
| 438 | a01("hasinrc", "0") |
| 439 | a01("pid", android.os.Process.myPid().toString()) |
| 440 | a01("rc", "0") |
| 441 | // Honest device fingerprint the official no-Play /v2 request includes (RE of LX/F4L; |
| 442 | // A0G/A0M/A0P). All standard, non-Play, non-attestation signals. |
| 443 | a01("network_operator_name", tm?.networkOperatorName.orEmpty()) |
| 444 | a01("sim_operator_name", tm?.simOperatorName.orEmpty()) |
| 445 | a01("airplane_mode_on", airplaneModeOn()) |
| 446 | a01("device_ram", deviceRamBytes()) |
| 447 | } |
| 448 | |
| 449 | private fun airplaneModeOn(): String = runCatching { |
| 450 | if (Settings.Global.getInt(context.contentResolver, Settings.Global.AIRPLANE_MODE_ON, 0) != 0) "1" else "0" |
| 451 | }.getOrDefault("0") |
| 452 | |
| 453 | private fun deviceRamBytes(): String = runCatching { |
| 454 | val am = context.getSystemService(Context.ACTIVITY_SERVICE) as android.app.ActivityManager |
| 455 | val mi = android.app.ActivityManager.MemoryInfo() |
| 456 | am.getMemoryInfo(mi) |
| 457 | mi.totalMem.toString() |
| 458 | }.getOrDefault("0") |
| 459 | |
| 460 | fun query(): String = map.entries.joinToString("&") { (k, v) -> |
| 461 | val encoded = if (k in raw) v else URLEncoder.encode(v, "UTF-8") |
| 462 | "$k=$encoded" |
| 463 | } |
| 464 | |
| 465 | /** |
| 466 | * Add the per-endpoint device-integrity signals (w2.md §2.3/§3.1-3.3, Phase B 2e) from |
| 467 | * [RegistrationIntegrity]. `gpia`/`_gg` (Play Integrity) and `recaptcha` are never sent — |
| 468 | * they are signed by Google / bound to the official Play-installed WhatsApp and cannot be |
| 469 | * forged by this client. |
| 470 | * |
| 471 | * OFF by default (see [SEND_INTEGRITY_SIGNALS]): DEVICE-CONFIRMED that sending ANY integrity |
| 472 | * blob — even with official static values (`_gi` package=com.whatsapp + official base.apk |
| 473 | * hash, official `_gp`) — trips WhatsApp's attestation gate and returns |
| 474 | * `status:fail reason:blocked` ("couldn't verify you're using the official WhatsApp app"). |
| 475 | * The last verified-live `status:ok` sent NO integrity signals, so we match that. The |
| 476 | * official-valued builder is retained (dormant) for recoverability; when the switch is off |
| 477 | * this method is a no-op. |
| 478 | * |
| 479 | * Inclusion per endpoint (only if the switch is turned on): |
| 480 | * - EXIST: aid,_gi,_gp,_ge,_ga,_gs,db (+profile_name; no t) |
| 481 | * - CODE: aid,_gi,_gp,_ge,_ga,_gs,t,hasav |
| 482 | * - REGISTER: aid,_gi,_gp,_ge,_ga,_gs,t |
| 483 | */ |
| 484 | fun addIntegrity(kind: EndpointKind) { |
| 485 | if (!SEND_INTEGRITY_SIGNALS) return |
| 486 | val s = runCatching { RegistrationIntegrity.collect(context) }.getOrNull() ?: return |
| 487 | if (s.aid.isNotEmpty()) a01("aid", s.aid) |
| 488 | a02("_gi", s.gi) |
| 489 | a01("_gp", s.gp) |
| 490 | a01("_ge", s.ge) |
| 491 | a01("_ga", s.ga) |
| 492 | a01("_gs", s.gs) |
| 493 | when (kind) { |
| 494 | EndpointKind.EXIST -> { |
| 495 | a01("db", s.db) |
| 496 | WhatsAppAuthData.load(context)?.profileName?.takeIf { it.isNotEmpty() } |
| 497 | ?.let { a01("profile_name", it) } |
| 498 | } |
| 499 | EndpointKind.CODE -> { |
| 500 | a01("t", RegistrationIntegrity.tField(s.tSeconds)) |
| 501 | a01("hasav", "0") // 0 = can't read SMS (we never read the user's SMS inbox) |
| 502 | } |
| 503 | EndpointKind.REGISTER -> { |
| 504 | a01("t", RegistrationIntegrity.tField(s.tSeconds)) |
| 505 | } |
| 506 | } |
| 507 | } |
| 508 | } |
| 509 | |
| 510 | private suspend fun send(path: String, params: RegParams): String { |
| 511 | val query = params.query() |
| 512 | val body = if (useEncWrapper) { |
| 513 | val encv = RegistrationAttestation.encryptQueryString(query) |
| 514 | if (encv != null) { |
| 515 | val h = RegistrationAttestation.signWithAttestation(encv, fingerprint.attestationKey) |
| 516 | "ENC=${URLEncoder.encode(encv, "UTF-8")}&H=${URLEncoder.encode(h, "UTF-8")}" |
| 517 | } else { |
| 518 | query |
| 519 | } |
| 520 | } else { |
| 521 | query |
| 522 | } |
| 523 | |
| 524 | val headers = mapOf( |
| 525 | "User-Agent" to userAgent(), |
| 526 | "Content-Type" to "application/x-www-form-urlencoded", |
| 527 | "Accept" to "text/json", |
| 528 | ) |
| 529 | return try { |
| 530 | val resp = NetworkClient.performRequest( |
| 531 | url = baseUrlForTest?.let { "$it/$path" } ?: WhatsAppRegistrationConstants.endpoint(path), |
| 532 | method = "POST", |
| 533 | headers = headers, |
| 534 | body = body, |
| 535 | useSystemTrust = true, |
| 536 | ) |
| 537 | Log.status(TAG, "/v2/$path -> ${resp.status}") |
| 538 | resp.body |
| 539 | } catch (expected: Throwable) { |
| 540 | Log.error(TAG, "/v2/$path request failed", expected) |
| 541 | """{"status":"error","reason":"network:${expected.message}"}""" |
| 542 | } |
| 543 | } |
| 544 | |
| 545 | /** |
| 546 | * `WhatsApp/<ver> Android/<osrel> Device/<manufacturer>-<model>` — byte-for-byte the official |
| 547 | * app's registration UA (decompiled `X/C09990d9.A01`, com.whatsapp 2.26.29.73): app name |
| 548 | * "WhatsApp", version, "Android"/osRelease, "Device/"manufacturer-model, with a trailing |
| 549 | * empty token (`Voip.REJECT_REASON_DECLINED == ""`). Each device token (osRelease, manufacturer, |
| 550 | * model) is sanitized with WhatsApp's exact regex `[^,.\w\-()]` → "_" (NOT just spaces). The |
| 551 | * server derives `platform` from this UA. |
| 552 | */ |
| 553 | private fun userAgent(): String { |
| 554 | val san = Regex("[^,.\\w()\\-]") |
| 555 | val os = san.replace(Build.VERSION.RELEASE.orEmpty(), "_") |
| 556 | val mfr = san.replace(Build.MANUFACTURER.orEmpty(), "_") |
| 557 | val model = san.replace(Build.MODEL.orEmpty(), "_") |
| 558 | return "WhatsApp/${WhatsAppProtocol.WA_VERSION_NAME} Android/$os Device/$mfr-$model" |
| 559 | } |
| 560 | |
| 561 | private fun parse(body: String): JSONObject = try { |
| 562 | JSONObject(body) |
| 563 | } catch (_: Exception) { |
| 564 | JSONObject().put("status", "error").put("reason", "unparseable") |
| 565 | } |
| 566 | |
| 567 | private fun normalizeJid(jid: String): String = |
| 568 | if (jid.contains("@")) jid else "[email protected]" |
| 569 | |
| 570 | /** Endpoint and logging constants for the WhatsApp registration client. */ |
| 571 | companion object { |
| 572 | private const val TAG = "WARegHttp" |
| 573 | |
| 574 | /** Test seam applied to new instances (e.g. those a Compose screen remembers). */ |
| 575 | var baseOverrideForTest: String? = null |
| 576 | |
| 577 | /** |
| 578 | * Master switch for the Phase-B device-integrity signals |
| 579 | * (`aid`,`_gi`,`_gp`,`_ge`,`_ga`,`_gs`,`t`,`hasav`,`db`,`profile_name`). |
| 580 | * |
| 581 | * OFF — DEVICE-CONFIRMED: sending the integrity blob, even with the OFFICIAL WhatsApp static |
| 582 | * values, trips WhatsApp's attestation gate and returns `status:fail reason:blocked` (the |
| 583 | * "couldn't verify you're using the official WhatsApp app" screen), because that gate is |
| 584 | * backed by a Play-Integrity / reCAPTCHA-Enterprise proof that is Google-signed / bound to |
| 585 | * the official Play app and cannot be forged. So the default request sends NO integrity |
| 586 | * signals at all, matching the last verified-live `status:ok` param set (baseline 33dd602). |
| 587 | * The official-valued builder in [RegistrationIntegrity] is kept dormant for recoverability. |
| 588 | */ |
| 589 | private const val SEND_INTEGRITY_SIGNALS = false |
| 590 | private const val MS_PER_SECOND = 1000L |
| 591 | private const val MCC_LENGTH = 3 |
| 592 | } |
| 593 | |
| 594 | /** WAMSYS endpoint kinds that carry per-endpoint integrity params (w2.md §3.1-3.3). */ |
| 595 | private enum class EndpointKind { EXIST, CODE, REGISTER } |
| 596 | } |
| 597 | |
| 598 | // -- small JSONObject null-safe helpers -- |
| 599 | private fun JSONObject.optStringOrNull(key: String): String? = |
| 600 | if (has(key) && !isNull(key)) optString(key) else null |
| 601 | private fun JSONObject.optIntOrNull(key: String): Int? = |
| 602 | if (has(key) && !isNull(key)) optInt(key) else null |
| 603 | private fun JSONObject.optLongOrNull(key: String): Long? = |
| 604 | if (has(key) && !isNull(key)) optLong(key) else null |