passwords: split two over-limit files for release lint
- Commit
61d50e733973f786dec88136c3ae28416c43e1dc- Author
- Vayun Mathur <[email protected]>
- When
- 2026-11-22 14:05 UTC (13 days ago)
- Parents
efebb9b
lintVitalRelease blocked the release build: KdbxSyncEngine was 819 lines (limit 800) and PasskeyAuthActivity 394 (350 for ui). The sync runner half (native codec, SAF document, runKdbxSync overloads, atomic write) moves verbatim to KdbxSyncRunner.kt (engine 683), and the passkey create ceremony moves to PasskeyCreateFlow.kt (activity 277); public API and call sites unchanged, no lint config touched. Verified: passwords compileDevKotlin, lintVitalRelease and testDevUnitTest all pass.
Diff
passwords/src/main/java/com/vayunmathur/passwords/sync/KdbxSyncEngine.kt
diff --git a/passwords/src/main/java/com/vayunmathur/passwords/sync/KdbxSyncEngine.kt b/passwords/src/main/java/com/vayunmathur/passwords/sync/KdbxSyncEngine.ktindex 12db377b38..aa47cce4ef 100644--- a/passwords/src/main/java/com/vayunmathur/passwords/sync/KdbxSyncEngine.kt+++ b/passwords/src/main/java/com/vayunmathur/passwords/sync/KdbxSyncEngine.kt@@ -1,8 +1,5 @@ package com.vayunmathur.passwords.sync -import android.content.Context-import android.net.Uri-import androidx.core.net.toUri import androidx.room3.withWriteTransaction import com.vayunmathur.passwords.data.Passkey import com.vayunmathur.passwords.data.PasskeyDao@@ -13,12 +10,7 @@ import com.vayunmathur.passwords.data.PasswordRepository import com.vayunmathur.passwords.data.SyncSnapshot import com.vayunmathur.passwords.data.SyncSnapshotDao import com.vayunmathur.passwords.data.newSyncId-import com.vayunmathur.passwords.util.KdbxNative-import kotlinx.coroutines.CancellationException import kotlinx.coroutines.flow.Flow-import org.json.JSONArray-import org.json.JSONObject-import java.io.File import java.io.FileNotFoundException import java.io.IOException @@ -689,130 +681,3 @@ private class Plan<T>( val quarantineIds: List<String>, ) -/** Singleton holding native kdbx codec state and operations. */-object NativeKdbxCodec : KdbxCodec {- override fun read(password: String, bytes: ByteArray): List<Map<String, String>>? {- val json = KdbxNative.nativeImport(password, bytes) ?: return null- val array = JSONArray(json)- return (0 until array.length()).map { i ->- val entry = array.getJSONObject(i)- buildMap { for (key in entry.keys()) put(key, entry.getString(key)) }- }- }-- override fun write(password: String, entries: List<Map<String, String>>): ByteArray? {- val array = JSONArray()- for (entry in entries) array.put(JSONObject(entry as Map<*, *>))- return KdbxNative.nativeExport(password, array.toString())- }-}--/** Saf Kdbx Document: a context implementation for saf kdbx document. */-class SafKdbxDocument(private val context: Context, private val uri: Uri) : KdbxDocument {- override fun read(): ByteArray =- context.contentResolver.openInputStream(uri)?.use { it.readBytes() }- ?: throw FileNotFoundException("Cannot open $uri")-- override fun write(bytes: ByteArray) {- context.contentResolver.openOutputStream(uri, "wt")?.use { it.write(bytes) }- ?: throw FileNotFoundException("Cannot write $uri")- }-}--/** Runs a sync from the persisted settings, recording the outcome for the settings screen. */-suspend fun runKdbxSync(context: Context, db: PasswordDatabase): KdbxSyncResult {- if (!KdbxSyncSettings.enabled(context)) return KdbxSyncResult.NotConfigured- val uri = KdbxSyncSettings.documentUri(context) ?: return KdbxSyncResult.NotConfigured- val passwordHelper = KdbxPasswordHelper(context)- if (!passwordHelper.isKeyGenerated()) return KdbxSyncResult.NotConfigured-- val result = runSyncCatching {- KdbxSyncEngine(db, NativeKdbxCodec).sync(- document = SafKdbxDocument(context, uri.toUri()),- vaultPassword = passwordHelper.getPassphrase(),- onBackup = { previous -> writeBytesAtomically(File(context.filesDir, BACKUP_FILE_NAME), previous) },- )- }-- when (result) {- is KdbxSyncResult.Success -> {- // A successful sync clears any prior quarantine: the file now- // provably holds every baselined id (live or tombstoned).- KdbxSyncSettings.clearQuarantine(context)- KdbxSyncSettings.recordSuccess(context)- }- KdbxSyncResult.NotConfigured -> Unit- is KdbxSyncResult.Quarantined ->- KdbxSyncSettings.recordQuarantine(context, KdbxSyncSettings.QUARANTINE_FOREIGN_DELETE)- else -> KdbxSyncSettings.recordFailure(context, result.errorCode())- }- return result-}--private suspend fun runSyncCatching(block: suspend () -> KdbxSyncResult): KdbxSyncResult {- return try {- block()- } catch (expected: CancellationException) {- throw expected- } catch (expected: Exception) {- // Any transport/codec failure (SAF IOException on a cloud-backed- // document, Room failure, codec crash) aborts the sync: the engine- // mutates nothing until re-encode + verify, so abort is always safe.- // Never let an exception escape as a partial merge.- KdbxSyncResult.Error(expected.message ?: expected.javaClass.simpleName)- }-}--/** Repository-based overload — preferred; avoids direct PasswordDatabase access. */-suspend fun runKdbxSync(context: Context, repository: PasswordRepository): KdbxSyncResult {- if (!KdbxSyncSettings.enabled(context)) return KdbxSyncResult.NotConfigured- val uri = KdbxSyncSettings.documentUri(context) ?: return KdbxSyncResult.NotConfigured- val passwordHelper = KdbxPasswordHelper(context)- if (!passwordHelper.isKeyGenerated()) return KdbxSyncResult.NotConfigured-- val result = runSyncCatching {- KdbxSyncEngine(repository, NativeKdbxCodec).sync(- document = SafKdbxDocument(context, uri.toUri()),- vaultPassword = passwordHelper.getPassphrase(),- onBackup = { previous -> writeBytesAtomically(File(context.filesDir, BACKUP_FILE_NAME), previous) },- )- }-- when (result) {- is KdbxSyncResult.Success -> {- // A successful sync clears any prior quarantine: the file now- // provably holds every baselined id (live or tombstoned).- KdbxSyncSettings.clearQuarantine(context)- KdbxSyncSettings.recordSuccess(context)- }- KdbxSyncResult.NotConfigured -> Unit- is KdbxSyncResult.Quarantined ->- KdbxSyncSettings.recordQuarantine(context, KdbxSyncSettings.QUARANTINE_FOREIGN_DELETE)- else -> KdbxSyncSettings.recordFailure(context, result.errorCode())- }- return result-}--private const val BACKUP_FILE_NAME = "kdbx-sync-backup.kdbx"--/**- * Write [bytes] to [target] via tmp file + rename, so a crash mid-backup never leaves a- * torn KDBX backup in place of the last good one. Same shape as `AndroidFileBlobStore.put`- * (library/everysync-core): temp in the same directory, rename, delete+rename fallback- * where rename cannot replace, temp always cleaned up. (No `FileFiles.writeBytes` exists- * in library/ — verified, it does not do this.)- */-private fun writeBytesAtomically(target: File, bytes: ByteArray) {- val dir = target.parentFile- if (dir != null) dir.mkdirs()- val tmp = File.createTempFile("kdbx-backup-", ".tmp", dir)- try {- tmp.writeBytes(bytes)- if (!tmp.renameTo(target)) {- target.delete()- tmp.renameTo(target)- }- } finally {- if (tmp.exists()) tmp.delete()- }-}
passwords/src/main/java/com/vayunmathur/passwords/sync/KdbxSyncRunner.kt
diff --git a/passwords/src/main/java/com/vayunmathur/passwords/sync/KdbxSyncRunner.kt b/passwords/src/main/java/com/vayunmathur/passwords/sync/KdbxSyncRunner.ktnew file mode 100644index 0000000000..d0ea867337--- /dev/null+++ b/passwords/src/main/java/com/vayunmathur/passwords/sync/KdbxSyncRunner.kt@@ -0,0 +1,142 @@+package com.vayunmathur.passwords.sync++import android.content.Context+import android.net.Uri+import androidx.core.net.toUri+import com.vayunmathur.passwords.data.PasswordDatabase+import com.vayunmathur.passwords.data.PasswordRepository+import com.vayunmathur.passwords.util.KdbxNative+import kotlinx.coroutines.CancellationException+import org.json.JSONArray+import org.json.JSONObject+import java.io.File+import java.io.FileNotFoundException+import java.io.IOException++/** Singleton holding native kdbx codec state and operations. */+object NativeKdbxCodec : KdbxCodec {+ override fun read(password: String, bytes: ByteArray): List<Map<String, String>>? {+ val json = KdbxNative.nativeImport(password, bytes) ?: return null+ val array = JSONArray(json)+ return (0 until array.length()).map { i ->+ val entry = array.getJSONObject(i)+ buildMap { for (key in entry.keys()) put(key, entry.getString(key)) }+ }+ }++ override fun write(password: String, entries: List<Map<String, String>>): ByteArray? {+ val array = JSONArray()+ for (entry in entries) array.put(JSONObject(entry as Map<*, *>))+ return KdbxNative.nativeExport(password, array.toString())+ }+}++/** Saf Kdbx Document: a context implementation for saf kdbx document. */+class SafKdbxDocument(private val context: Context, private val uri: Uri) : KdbxDocument {+ override fun read(): ByteArray =+ context.contentResolver.openInputStream(uri)?.use { it.readBytes() }+ ?: throw FileNotFoundException("Cannot open $uri")++ override fun write(bytes: ByteArray) {+ context.contentResolver.openOutputStream(uri, "wt")?.use { it.write(bytes) }+ ?: throw FileNotFoundException("Cannot write $uri")+ }+}++/** Runs a sync from the persisted settings, recording the outcome for the settings screen. */+suspend fun runKdbxSync(context: Context, db: PasswordDatabase): KdbxSyncResult {+ if (!KdbxSyncSettings.enabled(context)) return KdbxSyncResult.NotConfigured+ val uri = KdbxSyncSettings.documentUri(context) ?: return KdbxSyncResult.NotConfigured+ val passwordHelper = KdbxPasswordHelper(context)+ if (!passwordHelper.isKeyGenerated()) return KdbxSyncResult.NotConfigured++ val result = runSyncCatching {+ KdbxSyncEngine(db, NativeKdbxCodec).sync(+ document = SafKdbxDocument(context, uri.toUri()),+ vaultPassword = passwordHelper.getPassphrase(),+ onBackup = { previous -> writeBytesAtomically(File(context.filesDir, BACKUP_FILE_NAME), previous) },+ )+ }++ when (result) {+ is KdbxSyncResult.Success -> {+ // A successful sync clears any prior quarantine: the file now+ // provably holds every baselined id (live or tombstoned).+ KdbxSyncSettings.clearQuarantine(context)+ KdbxSyncSettings.recordSuccess(context)+ }+ KdbxSyncResult.NotConfigured -> Unit+ is KdbxSyncResult.Quarantined ->+ KdbxSyncSettings.recordQuarantine(context, KdbxSyncSettings.QUARANTINE_FOREIGN_DELETE)+ else -> KdbxSyncSettings.recordFailure(context, result.errorCode())+ }+ return result+}++private suspend fun runSyncCatching(block: suspend () -> KdbxSyncResult): KdbxSyncResult {+ return try {+ block()+ } catch (expected: CancellationException) {+ throw expected+ } catch (expected: Exception) {+ // Any transport/codec failure (SAF IOException on a cloud-backed+ // document, Room failure, codec crash) aborts the sync: the engine+ // mutates nothing until re-encode + verify, so abort is always safe.+ // Never let an exception escape as a partial merge.+ KdbxSyncResult.Error(expected.message ?: expected.javaClass.simpleName)+ }+}++/** Repository-based overload — preferred; avoids direct PasswordDatabase access. */+suspend fun runKdbxSync(context: Context, repository: PasswordRepository): KdbxSyncResult {+ if (!KdbxSyncSettings.enabled(context)) return KdbxSyncResult.NotConfigured+ val uri = KdbxSyncSettings.documentUri(context) ?: return KdbxSyncResult.NotConfigured+ val passwordHelper = KdbxPasswordHelper(context)+ if (!passwordHelper.isKeyGenerated()) return KdbxSyncResult.NotConfigured++ val result = runSyncCatching {+ KdbxSyncEngine(repository, NativeKdbxCodec).sync(+ document = SafKdbxDocument(context, uri.toUri()),+ vaultPassword = passwordHelper.getPassphrase(),+ onBackup = { previous -> writeBytesAtomically(File(context.filesDir, BACKUP_FILE_NAME), previous) },+ )+ }++ when (result) {+ is KdbxSyncResult.Success -> {+ // A successful sync clears any prior quarantine: the file now+ // provably holds every baselined id (live or tombstoned).+ KdbxSyncSettings.clearQuarantine(context)+ KdbxSyncSettings.recordSuccess(context)+ }+ KdbxSyncResult.NotConfigured -> Unit+ is KdbxSyncResult.Quarantined ->+ KdbxSyncSettings.recordQuarantine(context, KdbxSyncSettings.QUARANTINE_FOREIGN_DELETE)+ else -> KdbxSyncSettings.recordFailure(context, result.errorCode())+ }+ return result+}++private const val BACKUP_FILE_NAME = "kdbx-sync-backup.kdbx"++/**+ * Write [bytes] to [target] via tmp file + rename, so a crash mid-backup never leaves a+ * torn KDBX backup in place of the last good one. Same shape as `AndroidFileBlobStore.put`+ * (library/everysync-core): temp in the same directory, rename, delete+rename fallback+ * where rename cannot replace, temp always cleaned up. (No `FileFiles.writeBytes` exists+ * in library/ — verified, it does not do this.)+ */+private fun writeBytesAtomically(target: File, bytes: ByteArray) {+ val dir = target.parentFile+ if (dir != null) dir.mkdirs()+ val tmp = File.createTempFile("kdbx-backup-", ".tmp", dir)+ try {+ tmp.writeBytes(bytes)+ if (!tmp.renameTo(target)) {+ target.delete()+ tmp.renameTo(target)+ }+ } finally {+ if (tmp.exists()) tmp.delete()+ }+}
passwords/src/main/java/com/vayunmathur/passwords/ui/PasskeyAuthActivity.kt
diff --git a/passwords/src/main/java/com/vayunmathur/passwords/ui/PasskeyAuthActivity.kt b/passwords/src/main/java/com/vayunmathur/passwords/ui/PasskeyAuthActivity.ktindex 9392f733ce..c23c095ac7 100644--- a/passwords/src/main/java/com/vayunmathur/passwords/ui/PasskeyAuthActivity.kt+++ b/passwords/src/main/java/com/vayunmathur/passwords/ui/PasskeyAuthActivity.kt@@ -6,7 +6,6 @@ import android.content.Intent import android.os.Bundle import android.util.Base64 import com.vayunmathur.library.log.Log-import androidx.credentials.CreatePublicKeyCredentialRequest import androidx.credentials.GetPublicKeyCredentialOption import androidx.credentials.PublicKeyCredential import androidx.credentials.exceptions.GetCredentialUnknownException@@ -17,7 +16,6 @@ import com.vayunmathur.library.biometric.unlockDatabaseWithBiometrics import com.vayunmathur.library.util.DatabaseHelper import com.vayunmathur.passwords.platform.cable.WebAuthnAuthenticator import com.vayunmathur.passwords.data.PasswordRepository-import com.vayunmathur.passwords.domain.Cbor import com.vayunmathur.passwords.platform.PasskeyCredentialService import com.vayunmathur.passwords.platform.PasskeyUtils import com.vayunmathur.passwords.platform.buildGetCredentialResponse@@ -26,7 +24,6 @@ import kotlinx.coroutines.CancellationException import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.launch import kotlinx.coroutines.withContext-import org.json.JSONArray import org.json.JSONObject import java.security.MessageDigest @@ -69,7 +66,7 @@ class PasskeyAuthActivity : FragmentActivity() { lifecycleScope.launch { try { when (flow) {- FLOW_CREATE -> handleCreate()+ FLOW_CREATE -> handlePasskeyCreate(repository) FLOW_GET -> handleGet() FLOW_PASSWORD -> handlePassword() FLOW_UNLOCK -> handleUnlock()@@ -102,119 +99,6 @@ class PasskeyAuthActivity : FragmentActivity() { } } - private suspend fun handleCreate() {- val request = PendingIntentHandler.retrieveProviderCreateCredentialRequest(intent) ?: run {- Log.error(TAG, "No create credential request in intent")- setResult(RESULT_CANCELED)- return- }- val publicKeyRequest = request.callingRequest as? CreatePublicKeyCredentialRequest ?: run {- Log.error(TAG, "Request is not a PublicKeyCredentialRequest")- setResult(RESULT_CANCELED)- return- }-- val json = JSONObject(publicKeyRequest.requestJson)- val rp = json.getJSONObject("rp")- val rpId = rp.getString("id")- val rpName = rp.optString("name", rpId)- val user = json.getJSONObject("user")- val userId = user.getString("id")- val userName = user.optString("name", "")- val userDisplayName = user.optString("displayName", userName)- val challenge = json.getString("challenge")-- // This authenticator only makes ES256 keys. Honouring a request that- // does not offer alg -7 would persist a credential the relying party- // then rejects; refuse before anything is generated or stored.- if (!PasskeyUtils.supportsEs256(json)) {- Log.error(TAG, "Create request offers no ES256 in pubKeyCredParams")- setResult(RESULT_CANCELED)- return- }- // excludeCredentials names credentials the relying party already has:- // creating (and, via the shared helper, silently replacing) one of- // them must not happen.- val excludedIds = PasskeyUtils.credentialDescriptorIds(json, "excludeCredentials")- if (excludedIds.isNotEmpty()) {- val excluded = withContext(Dispatchers.IO) { repository.getPasskeysByRpId(rpId) }.any { stored ->- excludedIds.any { PasskeyUtils.credentialIdsMatch(stored.credentialId, it) }- }- if (excluded) {- Log.error(TAG, "Create request excludes an existing credential for rpId=$rpId")- setResult(RESULT_CANCELED)- return- }- }-- // Privileged browsers provide clientDataHash directly- val callingAppInfo = request.callingAppInfo- val privilegedOrigin = PasskeyUtils.getPrivilegedOrigin(callingAppInfo, applicationContext)- val isPrivileged = privilegedOrigin != null- val origin = privilegedOrigin ?: PasskeyUtils.getAndroidOrigin(callingAppInfo)- Log.dev(TAG, "Create passkey for rpId=$rpId, origin=$origin, privileged=$isPrivileged")-- // Generate the credential and persist it; both transports share this.- val created = withContext(Dispatchers.IO) {- WebAuthnAuthenticator.createCredential(- rpId = rpId,- rpName = rpName,- // The request JSON carries the user handle already base64url-encoded; the shared- // helper works in raw bytes and re-encodes when storing.- userId = PasskeyUtils.decodeB64Url(userId),- userName = userName,- userDisplayName = userDisplayName,- aaguid = PasskeyUtils.SAME_DEVICE_AAGUID,- store = repository,- )- }- val credentialIdB64 = PasskeyUtils.encodeB64Url(created.credentialId)-- // WebAuthn wraps the authenticator data in an attestationObject. Over CTAP the browser- // builds this itself from the response fields, which is why the helper returns neither.- val attestationObject = Cbor.encode(linkedMapOf<String, Any>(- "fmt" to "none",- "attStmt" to emptyMap<Any, Any>(),- "authData" to created.authenticatorData,- ))-- // For privileged browsers: use placeholder clientDataJSON (browser replaces it)- // For Android apps: build our own clientDataJSON- val clientDataJsonB64 = if (isPrivileged) {- b64Url("<placeholder>".toByteArray())- } else {- val clientDataJson = JSONObject().apply {- put("type", "webauthn.create")- put("challenge", challenge)- put("origin", origin)- put("crossOrigin", false)- }.toString()- b64Url(clientDataJson.toByteArray())- }-- val responseJson = JSONObject().apply {- put("id", credentialIdB64)- put("rawId", credentialIdB64)- put("type", "public-key")- put("authenticatorAttachment", "platform")- put("response", JSONObject().apply {- put("clientDataJSON", clientDataJsonB64)- put("attestationObject", b64Url(attestationObject))- put("transports", JSONArray(listOf("internal", "hybrid")))- put("publicKeyAlgorithm", -7)- put("publicKey", b64Url(created.publicKeySpki))- put("authenticatorData", b64Url(created.authenticatorData))- })- put("clientExtensionResults", JSONObject())- }.toString()-- Log.dev(TAG, "Passkey created successfully for rpId=$rpId, credId=$credentialIdB64")- val credentialResponse = androidx.credentials.CreatePublicKeyCredentialResponse(responseJson)- val result = Intent()- PendingIntentHandler.setCreateCredentialResponse(result, credentialResponse)- setResult(RESULT_OK, result)- }- private suspend fun handleGet() { val providerRequest = PendingIntentHandler.retrieveProviderGetCredentialRequest(intent) ?: run { Log.error(TAG, "No get credential request in intent")
passwords/src/main/java/com/vayunmathur/passwords/ui/PasskeyCreateFlow.kt
diff --git a/passwords/src/main/java/com/vayunmathur/passwords/ui/PasskeyCreateFlow.kt b/passwords/src/main/java/com/vayunmathur/passwords/ui/PasskeyCreateFlow.ktnew file mode 100644index 0000000000..7aa31d6bba--- /dev/null+++ b/passwords/src/main/java/com/vayunmathur/passwords/ui/PasskeyCreateFlow.kt@@ -0,0 +1,130 @@+package com.vayunmathur.passwords.ui++import android.app.Activity+import android.content.Intent+import androidx.credentials.CreatePublicKeyCredentialRequest+import androidx.credentials.provider.PendingIntentHandler+import com.vayunmathur.library.log.Log+import com.vayunmathur.passwords.data.PasswordRepository+import com.vayunmathur.passwords.domain.Cbor+import com.vayunmathur.passwords.platform.PasskeyUtils+import com.vayunmathur.passwords.platform.cable.WebAuthnAuthenticator+import kotlinx.coroutines.Dispatchers+import kotlinx.coroutines.withContext+import org.json.JSONArray+import org.json.JSONObject++private const val TAG = "PasskeyAuthActivity"++internal suspend fun PasskeyAuthActivity.handlePasskeyCreate(repository: PasswordRepository) {+ val request = PendingIntentHandler.retrieveProviderCreateCredentialRequest(intent) ?: run {+ Log.error(TAG, "No create credential request in intent")+ setResult(Activity.RESULT_CANCELED)+ return+ }+ val publicKeyRequest = request.callingRequest as? CreatePublicKeyCredentialRequest ?: run {+ Log.error(TAG, "Request is not a PublicKeyCredentialRequest")+ setResult(Activity.RESULT_CANCELED)+ return+ }++ val json = JSONObject(publicKeyRequest.requestJson)+ val rp = json.getJSONObject("rp")+ val rpId = rp.getString("id")+ val rpName = rp.optString("name", rpId)+ val user = json.getJSONObject("user")+ val userId = user.getString("id")+ val userName = user.optString("name", "")+ val userDisplayName = user.optString("displayName", userName)+ val challenge = json.getString("challenge")++ // This authenticator only makes ES256 keys. Honouring a request that+ // does not offer alg -7 would persist a credential the relying party+ // then rejects; refuse before anything is generated or stored.+ if (!PasskeyUtils.supportsEs256(json)) {+ Log.error(TAG, "Create request offers no ES256 in pubKeyCredParams")+ setResult(Activity.RESULT_CANCELED)+ return+ }+ // excludeCredentials names credentials the relying party already has:+ // creating (and, via the shared helper, silently replacing) one of+ // them must not happen.+ val excludedIds = PasskeyUtils.credentialDescriptorIds(json, "excludeCredentials")+ if (excludedIds.isNotEmpty()) {+ val excluded = withContext(Dispatchers.IO) { repository.getPasskeysByRpId(rpId) }.any { stored ->+ excludedIds.any { PasskeyUtils.credentialIdsMatch(stored.credentialId, it) }+ }+ if (excluded) {+ Log.error(TAG, "Create request excludes an existing credential for rpId=$rpId")+ setResult(Activity.RESULT_CANCELED)+ return+ }+ }++ // Privileged browsers provide clientDataHash directly+ val callingAppInfo = request.callingAppInfo+ val privilegedOrigin = PasskeyUtils.getPrivilegedOrigin(callingAppInfo, applicationContext)+ val isPrivileged = privilegedOrigin != null+ val origin = privilegedOrigin ?: PasskeyUtils.getAndroidOrigin(callingAppInfo)+ Log.dev(TAG, "Create passkey for rpId=$rpId, origin=$origin, privileged=$isPrivileged")++ // Generate the credential and persist it; both transports share this.+ val created = withContext(Dispatchers.IO) {+ WebAuthnAuthenticator.createCredential(+ rpId = rpId,+ rpName = rpName,+ // The request JSON carries the user handle already base64url-encoded; the shared+ // helper works in raw bytes and re-encodes when storing.+ userId = PasskeyUtils.decodeB64Url(userId),+ userName = userName,+ userDisplayName = userDisplayName,+ aaguid = PasskeyUtils.SAME_DEVICE_AAGUID,+ store = repository,+ )+ }+ val credentialIdB64 = PasskeyUtils.encodeB64Url(created.credentialId)++ // WebAuthn wraps the authenticator data in an attestationObject. Over CTAP the browser+ // builds this itself from the response fields, which is why the helper returns neither.+ val attestationObject = Cbor.encode(linkedMapOf<String, Any>(+ "fmt" to "none",+ "attStmt" to emptyMap<Any, Any>(),+ "authData" to created.authenticatorData,+ ))++ // For privileged browsers: use placeholder clientDataJSON (browser replaces it)+ // For Android apps: build our own clientDataJSON+ val clientDataJsonB64 = if (isPrivileged) {+ PasskeyUtils.encodeB64Url("<placeholder>".toByteArray())+ } else {+ val clientDataJson = JSONObject().apply {+ put("type", "webauthn.create")+ put("challenge", challenge)+ put("origin", origin)+ put("crossOrigin", false)+ }.toString()+ PasskeyUtils.encodeB64Url(clientDataJson.toByteArray())+ }++ val responseJson = JSONObject().apply {+ put("id", credentialIdB64)+ put("rawId", credentialIdB64)+ put("type", "public-key")+ put("authenticatorAttachment", "platform")+ put("response", JSONObject().apply {+ put("clientDataJSON", clientDataJsonB64)+ put("attestationObject", PasskeyUtils.encodeB64Url(attestationObject))+ put("transports", JSONArray(listOf("internal", "hybrid")))+ put("publicKeyAlgorithm", -7)+ put("publicKey", PasskeyUtils.encodeB64Url(created.publicKeySpki))+ put("authenticatorData", PasskeyUtils.encodeB64Url(created.authenticatorData))+ })+ put("clientExtensionResults", JSONObject())+ }.toString()++ Log.dev(TAG, "Passkey created successfully for rpId=$rpId, credId=$credentialIdB64")+ val credentialResponse = androidx.credentials.CreatePublicKeyCredentialResponse(responseJson)+ val result = Intent()+ PendingIntentHandler.setCreateCredentialResponse(result, credentialResponse)+ setResult(Activity.RESULT_OK, result)+}