Privacy-first password manager with built-in email aliasing. Fully encrypted and self-hostable.
Cleanup todos and refactor detekt issues (#520)
Leendert de Borst665662982c8b
diff --git a/.vscode/AliasVault.code-workspace b/.vscode/AliasVault.code-workspaceindex d2c26c908..65f6f2853 100644--- a/.vscode/AliasVault.code-workspace+++ b/.vscode/AliasVault.code-workspace@@ -23,5 +23,7 @@"path": "../shared"}],- "settings": {}+ "settings": {+ "java.configuration.updateBuildConfiguration": "interactive"+ }}diff --git a/apps/mobile-app/android/app/build.gradle b/apps/mobile-app/android/app/build.gradleindex fe79766f5..93d9285b4 100644--- a/apps/mobile-app/android/app/build.gradle+++ b/apps/mobile-app/android/app/build.gradle@@ -276,7 +276,8 @@ task lintCheck {// Add a task dependency to make ktlint run before buildtasks.named("preBuild") {- dependsOn("ktlintCheck")+ dependsOn("lintFormat")+ dependsOn("lintCheck")}// Ensure codegen completes before ktlint tasks rundiff --git a/apps/mobile-app/android/app/src/main/java/net/aliasvault/app/MainActivity.kt b/apps/mobile-app/android/app/src/main/java/net/aliasvault/app/MainActivity.ktindex dbea3d245..52df95594 100644--- a/apps/mobile-app/android/app/src/main/java/net/aliasvault/app/MainActivity.kt+++ b/apps/mobile-app/android/app/src/main/java/net/aliasvault/app/MainActivity.kt@@ -1,8 +1,6 @@package net.aliasvault.appimport android.content.res.Configuration-import android.os.Buildimport android.os.Bundle-import android.util.Logimport android.view.WindowInsetsControllerimport androidx.core.content.ContextCompatimport com.facebook.react.ReactActivity@@ -16,9 +14,6 @@ import expo.modules.splashscreen.SplashScreenManager* The main activity of the app.*/class MainActivity : ReactActivity() {- companion object {- private const val TAG = "MainActivity"- }/*** Called when the activity is created.@@ -52,55 +47,34 @@ class MainActivity : ReactActivity() {}/**- * Configure system bars (status bar and navigation bar) colors and appearance- * based on current theme (light/dark mode)+ * Configure system bars (status bar and navigation bar) colors and appearance based on current theme (light/dark mode).*/private fun configureSystemBars() {val isDarkMode = (resources.configuration.uiMode and Configuration.UI_MODE_NIGHT_MASK) == Configuration.UI_MODE_NIGHT_YES- Log.d(TAG, "Configuring system bars - isDarkMode: $isDarkMode")window.apply {if (isDarkMode) {// Dark mode: black background with light iconsval bgColor = ContextCompat.getColor(context, R.color.av_background)- Log.d(TAG, "Setting dark mode colors - bgColor: ${String.format("#%06X", 0xFFFFFF and bgColor)}")statusBarColor = bgColornavigationBarColor = bgColor- if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {- // Android 11+ (API 30+): Use WindowInsetsController- insetsController?.apply {- setSystemBarsAppearance(- 0, // Light icons/text- WindowInsetsController.APPEARANCE_LIGHT_STATUS_BARS or WindowInsetsController.APPEARANCE_LIGHT_NAVIGATION_BARS,- )- }- } else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {- // Android 8-10 (API 26-29): Use deprecated flags- @Suppress("DEPRECATION")- decorView.systemUiVisibility = decorView.systemUiVisibility and- android.view.View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR.inv() and- android.view.View.SYSTEM_UI_FLAG_LIGHT_NAVIGATION_BAR.inv()+ insetsController?.apply {+ setSystemBarsAppearance(+ 0, // Light icons/text+ WindowInsetsController.APPEARANCE_LIGHT_STATUS_BARS or WindowInsetsController.APPEARANCE_LIGHT_NAVIGATION_BARS,+ )}} else {// Light mode: light gray background with dark iconsstatusBarColor = ContextCompat.getColor(context, R.color.av_background)navigationBarColor = ContextCompat.getColor(context, R.color.av_background)- if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {- // Android 11+ (API 30+): Use WindowInsetsController- insetsController?.apply {- setSystemBarsAppearance(- WindowInsetsController.APPEARANCE_LIGHT_STATUS_BARS or WindowInsetsController.APPEARANCE_LIGHT_NAVIGATION_BARS,- WindowInsetsController.APPEARANCE_LIGHT_STATUS_BARS or WindowInsetsController.APPEARANCE_LIGHT_NAVIGATION_BARS,- )- }- } else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {- // Android 8-10 (API 26-29): Use deprecated flags- @Suppress("DEPRECATION")- decorView.systemUiVisibility = decorView.systemUiVisibility or- android.view.View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR or- android.view.View.SYSTEM_UI_FLAG_LIGHT_NAVIGATION_BAR+ insetsController?.apply {+ setSystemBarsAppearance(+ WindowInsetsController.APPEARANCE_LIGHT_STATUS_BARS or WindowInsetsController.APPEARANCE_LIGHT_NAVIGATION_BARS,+ WindowInsetsController.APPEARANCE_LIGHT_STATUS_BARS or WindowInsetsController.APPEARANCE_LIGHT_NAVIGATION_BARS,+ )}}}diff --git a/apps/mobile-app/android/app/src/main/java/net/aliasvault/app/components/LoadingIndicator.kt b/apps/mobile-app/android/app/src/main/java/net/aliasvault/app/components/LoadingIndicator.ktindex 96a74235f..c2dffbc23 100644--- a/apps/mobile-app/android/app/src/main/java/net/aliasvault/app/components/LoadingIndicator.kt+++ b/apps/mobile-app/android/app/src/main/java/net/aliasvault/app/components/LoadingIndicator.kt@@ -46,14 +46,14 @@ class LoadingIndicator @JvmOverloads constructor(}/**- * Set the loading message text+ * Set the loading message text.*/fun setMessage(message: String) {loadingMessage.text = message}/**- * Start the pulsing animation on the dots+ * Start the pulsing animation on the dots.*/fun startAnimation() {// Stop any existing animations@@ -70,7 +70,7 @@ class LoadingIndicator @JvmOverloads constructor(}/**- * Stop the pulsing animation+ * Stop the pulsing animation.*/fun stopAnimation() {animators.forEach { it.cancel() }@@ -78,7 +78,7 @@ class LoadingIndicator @JvmOverloads constructor(}/**- * Start the pulsing animation on a single dot with a delay+ * Start the pulsing animation on a single dot with a delay.*/private fun startDotAnimation(dot: View, delayMillis: Long): ObjectAnimator {val animator = ObjectAnimator.ofFloat(dot, "alpha", 0.3f, 1.0f).apply {diff --git a/apps/mobile-app/android/app/src/main/java/net/aliasvault/app/credentialprovider/AliasVaultCredentialProviderService.kt b/apps/mobile-app/android/app/src/main/java/net/aliasvault/app/credentialprovider/AliasVaultCredentialProviderService.ktindex 234c49444..978854bac 100644--- a/apps/mobile-app/android/app/src/main/java/net/aliasvault/app/credentialprovider/AliasVaultCredentialProviderService.kt+++ b/apps/mobile-app/android/app/src/main/java/net/aliasvault/app/credentialprovider/AliasVaultCredentialProviderService.kt@@ -19,6 +19,7 @@ import androidx.credentials.provider.CreateEntryimport androidx.credentials.provider.CredentialProviderServiceimport androidx.credentials.provider.ProviderClearCredentialStateRequestimport androidx.credentials.provider.PublicKeyCredentialEntry+import net.aliasvault.app.utils.Helpersimport net.aliasvault.app.vaultstore.VaultStoreimport net.aliasvault.app.vaultstore.getPasskeysForRpIdimport net.aliasvault.app.vaultstore.passkey.PasskeyHelper@@ -37,22 +38,24 @@ class AliasVaultCredentialProviderService : CredentialProviderService() {companion object {private const val TAG = "AliasVaultCredProvider"- // Intent extras for authentication+ /** Intent extra key for passing the passkey request JSON. */const val EXTRA_REQUEST_JSON = "request_json"++ /** Intent extra key for passing the relying party ID. */const val EXTRA_RP_ID = "rp_id"++ /** Intent extra key for passing the passkey ID. */const val EXTRA_PASSKEY_ID = "passkey_id"}/**- * Called when the system needs to display available credentials for authentication+ * Called when the system needs to display available credentials for authentication.*/override fun onBeginGetCredentialRequest(request: BeginGetCredentialRequest,cancellationSignal: CancellationSignal,callback: OutcomeReceiver<BeginGetCredentialResponse, GetCredentialException>,) {- Log.d(TAG, "onBeginGetCredentialRequest called")-try {// Get vault store instanceval vaultStore = VaultStore.getExistingInstance()@@ -75,7 +78,6 @@ class AliasVaultCredentialProviderService : CredentialProviderService() {}}- Log.d(TAG, "Returning ${credentialEntries.size} credential entries")callback.onResult(BeginGetCredentialResponse(credentialEntries = credentialEntries))} catch (e: Exception) {Log.e(TAG, "Error in onBeginGetCredentialRequest", e)@@ -84,7 +86,7 @@ class AliasVaultCredentialProviderService : CredentialProviderService() {}/**- * Process a passkey credential option and return matching credential entries+ * Process a passkey credential option and return matching credential entries.*/private fun processPasskeyOption(option: BeginGetPublicKeyCredentialOption,@@ -101,8 +103,6 @@ class AliasVaultCredentialProviderService : CredentialProviderService() {return emptyList()}- Log.d(TAG, "Looking for passkeys for RP ID: $rpId")-// Query vault for matching passkeysval db = try {val dbField = VaultStore::class.java.getDeclaredField("dbConnection")@@ -120,12 +120,6 @@ class AliasVaultCredentialProviderService : CredentialProviderService() {// Get passkeys for this RP IDval passkeys = vaultStore.getPasskeysForRpId(rpId, db)- Log.d(TAG, "Found ${passkeys.size} passkeys for $rpId")-- // Debug: Log each passkey ID- passkeys.forEach { passkey ->- Log.d(TAG, "Passkey found: ID=${passkey.id}, DisplayName=${passkey.displayName}, RpId=${passkey.rpId}")- }// Filter by allowCredentials if specifiedval allowCredentials = requestObj.optJSONArray("allowCredentials")@@ -141,18 +135,13 @@ class AliasVaultCredentialProviderService : CredentialProviderService() {passkeys.filter { passkey ->val passkeyIdBytes = PasskeyHelper.guidToBytes(passkey.id.toString())- val passkeyIdB64 = android.util.Base64.encodeToString(- passkeyIdBytes,- android.util.Base64.URL_SAFE or android.util.Base64.NO_WRAP or android.util.Base64.NO_PADDING,- )+ val passkeyIdB64 = Helpers.bytesToBase64url(passkeyIdBytes)allowedIds.contains(passkeyIdB64)}} else {passkeys}- Log.d(TAG, "After filtering: ${filteredPasskeys.size} passkeys")-// Convert to CredentialEntry objectsreturn filteredPasskeys.map { passkey ->createPasskeyEntry(passkey, option, requestJson)@@ -164,15 +153,13 @@ class AliasVaultCredentialProviderService : CredentialProviderService() {}/**- * Create a PublicKeyCredentialEntry for a passkey+ * Create a PublicKeyCredentialEntry for a passkey.*/private fun createPasskeyEntry(passkey: net.aliasvault.app.vaultstore.models.Passkey,option: BeginGetPublicKeyCredentialOption,requestJson: String,): PublicKeyCredentialEntry {- Log.d(TAG, "Creating passkey entry for ID=${passkey.id}, DisplayName=${passkey.displayName}")-// Create intent for PasskeyAuthenticationActivityval intent = Intent(this, PasskeyAuthenticationActivity::class.java).apply {putExtra(EXTRA_REQUEST_JSON, requestJson)@@ -181,8 +168,6 @@ class AliasVaultCredentialProviderService : CredentialProviderService() {passkey.userHandle?.let { putExtra("user_handle", it) }}- Log.d(TAG, "Intent created with passkey ID: ${passkey.id}")-val pendingIntent = PendingIntent.getActivity(this,passkey.id.hashCode(),@@ -204,15 +189,13 @@ class AliasVaultCredentialProviderService : CredentialProviderService() {}/**- * Called when the system needs to display available accounts for credential creation+ * Called when the system needs to display available accounts for credential creation.*/override fun onBeginCreateCredentialRequest(request: BeginCreateCredentialRequest,cancellationSignal: CancellationSignal,callback: OutcomeReceiver<BeginCreateCredentialResponse, CreateCredentialException>,) {- Log.d(TAG, "onBeginCreateCredentialRequest called")-val response: BeginCreateCredentialResponse? = processCreateCredentialRequest(request)if (response != null) {callback.onResult(response)@@ -222,12 +205,11 @@ class AliasVaultCredentialProviderService : CredentialProviderService() {}/**- * Process create credential request+ * Process create credential request.*/private fun processCreateCredentialRequest(request: BeginCreateCredentialRequest,): BeginCreateCredentialResponse? {- // Get vault store instanceval vaultStore = VaultStore.getExistingInstance()if (vaultStore == null) {Log.w(TAG, "VaultStore not initialized for passkey creation")@@ -248,7 +230,7 @@ class AliasVaultCredentialProviderService : CredentialProviderService() {}/**- * Handle passkey creation query+ * Handle passkey creation query.*/private fun handleCreatePasskeyQuery(request: BeginCreatePublicKeyCredentialRequest,@@ -267,9 +249,6 @@ class AliasVaultCredentialProviderService : CredentialProviderService() {val userObj = requestObj.optJSONObject("user")val userName = userObj?.optString("name") ?: ""val userDisplayName = userObj?.optString("displayName") ?: userName- val userIdB64 = userObj?.optString("id") ?: ""-- Log.d(TAG, "Creating passkey for RP: $rpId ($rpName), user: $userName")val createEntries = mutableListOf<CreateEntry>()@@ -290,7 +269,6 @@ class AliasVaultCredentialProviderService : CredentialProviderService() {createEntries.add(entry)}- Log.d(TAG, "Returning ${createEntries.size} create entries")return BeginCreateCredentialResponse(createEntries)} catch (e: Exception) {Log.e(TAG, "Error handling passkey create query", e)@@ -299,11 +277,10 @@ class AliasVaultCredentialProviderService : CredentialProviderService() {}/**- * Create a PendingIntent for passkey registration+ * Create a PendingIntent for passkey registration.* The intent doesn't need any extras - all data is available via providerRequest.callingRequest*/private fun createNewPendingIntent(rpId: String): PendingIntent {- // Create intent for PasskeyRegistrationActivityval intent = Intent(this, PasskeyRegistrationActivity::class.java)return PendingIntent.getActivity(@@ -322,7 +299,6 @@ class AliasVaultCredentialProviderService : CredentialProviderService() {// Called when user signs out or clears credential state// For AliasVault, we don't need to do anything here as credentials// are managed through the main app- Log.d(TAG, "onClearCredentialStateRequest called")callback.onResult(null)}}diff --git a/apps/mobile-app/android/app/src/main/java/net/aliasvault/app/credentialprovider/PasskeyAuthenticationActivity.kt b/apps/mobile-app/android/app/src/main/java/net/aliasvault/app/credentialprovider/PasskeyAuthenticationActivity.ktindex 39108061e..28fb6bd21 100644--- a/apps/mobile-app/android/app/src/main/java/net/aliasvault/app/credentialprovider/PasskeyAuthenticationActivity.kt+++ b/apps/mobile-app/android/app/src/main/java/net/aliasvault/app/credentialprovider/PasskeyAuthenticationActivity.kt@@ -6,6 +6,7 @@ import android.os.Bundleimport android.util.Logimport androidx.credentials.provider.PendingIntentHandlerimport androidx.credentials.provider.ProviderGetCredentialRequest+import net.aliasvault.app.utils.Helpersimport net.aliasvault.app.vaultstore.VaultStoreimport net.aliasvault.app.vaultstore.getPasskeyByIdimport net.aliasvault.app.vaultstore.passkey.PasskeyAuthenticator@@ -57,7 +58,7 @@ class PasskeyAuthenticationActivity : Activity() {}/**- * Process the passkey authentication request and generate assertion+ * Process the passkey authentication request and generate assertion.*/private fun processAuthenticationRequest(providerRequest: ProviderGetCredentialRequest) {try {@@ -180,14 +181,14 @@ class PasskeyAuthenticationActivity : Activity() {}/**- * Build clientDataJSON for WebAuthn if the caller didn't provide it+ * Build clientDataJSON for WebAuthn if the caller didn't provide it.*/private fun buildClientDataJson(challenge: String, origin: String): String {return """{"type":"webauthn.get","challenge":"$challenge","origin":"$origin","crossOrigin":false}"""}/**- * Compute SHA-256 hash+ * Compute SHA-256 hash.*/private fun sha256(data: ByteArray): ByteArray {val digest = MessageDigest.getInstance("SHA-256")@@ -195,7 +196,7 @@ class PasskeyAuthenticationActivity : Activity() {}/**- * Extract PRF extension inputs from request+ * Extract PRF extension inputs from request.*/private fun extractPrfInputs(requestObj: JSONObject): PasskeyAuthenticator.PrfInputs? {try {@@ -208,10 +209,12 @@ class PasskeyAuthenticationActivity : Activity() {if (firstB64.isEmpty()) return nullval secondB64 = eval.optString("second")- val first = base64urlDecode(firstB64)- val second = if (secondB64.isNotEmpty()) base64urlDecode(secondB64) else null-- Log.d(TAG, "PRF extension requested with ${if (second != null) "two" else "one"} salt(s)")+ val first = Helpers.base64urlDecode(firstB64)+ val second = if (secondB64.isNotEmpty()) {+ Helpers.base64urlDecode(secondB64)+ } else {+ null+ }return PasskeyAuthenticator.PrfInputs(first, second)} catch (e: Exception) {@@ -221,34 +224,7 @@ class PasskeyAuthenticationActivity : Activity() {}/**- * Decode base64url string to bytes- */- private fun base64urlDecode(base64url: String): ByteArray {- var base64 = base64url- .replace('-', '+')- .replace('_', '/')-- // Add padding if needed- val remainder = base64.length % 4- if (remainder > 0) {- base64 += "=".repeat(4 - remainder)- }-- return android.util.Base64.decode(base64, android.util.Base64.NO_WRAP)- }-- /**- * Encode bytes to base64url string- */- private fun base64urlEncode(data: ByteArray): String {- return android.util.Base64.encodeToString(- data,- android.util.Base64.URL_SAFE or android.util.Base64.NO_WRAP or android.util.Base64.NO_PADDING,- )- }-- /**- * Build PublicKeyCredential response from PasskeyAuthenticator assertion result+ * Build PublicKeyCredential response from PasskeyAuthenticator assertion result.** @param assertion The assertion result from PasskeyAuthenticator.getAssertion* @param clientDataJson Optional clientDataJSON string. If null, clientDataJSON will be@@ -258,10 +234,10 @@ class PasskeyAuthenticationActivity : Activity() {assertion: PasskeyAuthenticator.PasskeyAssertionResult,clientDataJson: String?,): androidx.credentials.GetCredentialResponse {- val credentialIdB64 = base64urlEncode(assertion.credentialId)- val signatureB64 = base64urlEncode(assertion.signature)- val authDataB64 = base64urlEncode(assertion.authenticatorData)- val userHandleB64 = assertion.userHandle?.let { base64urlEncode(it) }+ val credentialIdB64 = Helpers.bytesToBase64url(assertion.credentialId)+ val signatureB64 = Helpers.bytesToBase64url(assertion.signature)+ val authDataB64 = Helpers.bytesToBase64url(assertion.authenticatorData)+ val userHandleB64 = assertion.userHandle?.let { Helpers.bytesToBase64url(it) }val responseObj = JSONObject().apply {put("id", credentialIdB64)@@ -275,7 +251,7 @@ class PasskeyAuthenticationActivity : Activity() {// Only include clientDataJSON if we built it ourselves// When Chrome provides clientDataHash, omit this fieldclientDataJson?.let {- put("clientDataJSON", base64urlEncode(it.toByteArray(Charsets.UTF_8)))+ put("clientDataJSON", Helpers.bytesToBase64url(it.toByteArray(Charsets.UTF_8)))}put("authenticatorData", authDataB64)put("signature", signatureB64)@@ -293,8 +269,8 @@ class PasskeyAuthenticationActivity : Activity() {put("results",JSONObject().apply {- put("first", base64urlEncode(it.first))- it.second?.let { second -> put("second", base64urlEncode(second)) }+ put("first", Helpers.bytesToBase64url(it.first))+ it.second?.let { second -> put("second", Helpers.bytesToBase64url(second)) }},)},diff --git a/apps/mobile-app/android/app/src/main/java/net/aliasvault/app/credentialprovider/PasskeyFormFragment.kt b/apps/mobile-app/android/app/src/main/java/net/aliasvault/app/credentialprovider/PasskeyFormFragment.ktindex 69b4eca22..88f2de42f 100644--- a/apps/mobile-app/android/app/src/main/java/net/aliasvault/app/credentialprovider/PasskeyFormFragment.kt+++ b/apps/mobile-app/android/app/src/main/java/net/aliasvault/app/credentialprovider/PasskeyFormFragment.kt@@ -21,6 +21,10 @@ import kotlinx.coroutines.launchimport kotlinx.coroutines.withContextimport net.aliasvault.app.Rimport net.aliasvault.app.components.LoadingIndicator+import net.aliasvault.app.credentialprovider.models.PasskeyRegistrationViewModel+import net.aliasvault.app.exceptions.PasskeyOperationException+import net.aliasvault.app.exceptions.VaultOperationException+import net.aliasvault.app.utils.Helpersimport net.aliasvault.app.vaultstore.PasskeyWithCredentialInfoimport net.aliasvault.app.vaultstore.VaultStoreimport net.aliasvault.app.vaultstore.createCredentialWithPasskey@@ -34,7 +38,7 @@ import java.util.Dateimport java.util.UUID/**- * Fragment for passkey creation/replacement form+ * Fragment for passkey creation/replacement form.*/class PasskeyFormFragment : Fragment() {@@ -43,6 +47,9 @@ class PasskeyFormFragment : Fragment() {private const val ARG_IS_REPLACE = "is_replace"private const val ARG_PASSKEY_ID = "passkey_id"+ /**+ * Create a new instance of PasskeyFormFragment.+ */fun newInstance(isReplace: Boolean, passkeyId: String?): PasskeyFormFragment {return PasskeyFormFragment().apply {arguments = Bundle().apply {@@ -84,7 +91,7 @@ class PasskeyFormFragment : Fragment() {// Initialize servicesvaultStore = VaultStore.getExistingInstance()- ?: throw Exception("VaultStore not initialized")+ ?: throw VaultOperationException("VaultStore not initialized")webApiService = WebApiService(requireContext())}@@ -200,7 +207,7 @@ class PasskeyFormFragment : Fragment() {}/**- * Create a new passkey flow+ * Create a new passkey flow.*/private suspend fun createPasskeyFlow(displayName: String) = withContext(Dispatchers.IO) {try {@@ -224,9 +231,7 @@ class PasskeyFormFragment : Fragment() {showLoading(getString(R.string.passkey_creating))}- Log.d(TAG, "Creating passkey for RP: ${viewModel.rpId}, user: ${viewModel.userName}")-- // Extract favicon (optional)+ // Try to extract favicon from the website URL if possiblevar logo: ByteArray? = nulltry {logo = webApiService.extractFavicon("https://${viewModel.rpId}")@@ -239,22 +244,12 @@ class PasskeyFormFragment : Fragment() {val passkeyId = UUID.randomUUID()val credentialId = PasskeyHelper.guidToBytes(passkeyId.toString())- // Use clientDataHash from the request- val requestClientDataHash = viewModel.clientDataHash- if (requestClientDataHash == null) {- throw Exception("Client data hash not available")- }-// Parse request to get challenge (for building response clientDataJSON later)val requestObj = JSONObject(viewModel.requestJson)val challenge = requestObj.optString("challenge", "")// Use origin from the request- val requestOrigin = viewModel.origin- if (requestOrigin == null) {- throw Exception("Origin not available")- }- Log.d(TAG, "Using origin from request: $requestOrigin")+ val requestOrigin = viewModel.origin ?: throw PasskeyOperationException("Origin not available")// Extract PRF inputs if presentval prfInputs = extractPrfInputs(requestObj)@@ -263,7 +258,6 @@ class PasskeyFormFragment : Fragment() {// Create the passkey using PasskeyAuthenticatorval passkeyResult = PasskeyAuthenticator.createPasskey(credentialId = credentialId,- clientDataHash = requestClientDataHash,rpId = viewModel.rpId,userId = viewModel.userId,userName = viewModel.userName,@@ -295,7 +289,6 @@ class PasskeyFormFragment : Fragment() {showLoading(getString(R.string.passkey_saving))}- Log.d(TAG, "Saving passkey to vault...")vaultStore.createCredentialWithPasskey(rpId = viewModel.rpId,userName = viewModel.userName,@@ -303,7 +296,6 @@ class PasskeyFormFragment : Fragment() {passkey = passkey,logo = logo,)- Log.d(TAG, "Passkey saved successfully")// Step 4: Upload vault changes to serverwithContext(Dispatchers.Main) {@@ -322,13 +314,12 @@ class PasskeyFormFragment : Fragment() {}// Build response- val credentialIdB64 = base64urlEncode(credentialId)- val attestationObjectB64 = base64urlEncode(passkeyResult.attestationObject)+ val credentialIdB64 = Helpers.bytesToBase64url(credentialId)+ val attestationObjectB64 = Helpers.bytesToBase64url(passkeyResult.attestationObject)// Rebuild clientDataJSON for the response (needed for the credential response)- val clientDataJson =- """{"type":"webauthn.create","challenge":"$challenge","origin":"$requestOrigin","crossOrigin":false}"""- val clientDataJsonB64 = base64urlEncode(clientDataJson.toByteArray(Charsets.UTF_8))+ val clientDataJson = buildClientDataJson(challenge, requestOrigin)+ val clientDataJsonB64 = Helpers.bytesToBase64url(clientDataJson.toByteArray(Charsets.UTF_8))val responseJson = JSONObject().apply {put("id", credentialIdB64)@@ -340,15 +331,15 @@ class PasskeyFormFragment : Fragment() {JSONObject().apply {put("clientDataJSON", clientDataJsonB64)put("attestationObject", attestationObjectB64)- put("authenticatorData", base64urlEncode(passkeyResult.authenticatorData))+ put("authenticatorData", Helpers.bytesToBase64url(passkeyResult.authenticatorData))put("transports",org.json.JSONArray().apply {put("internal")},)- put("publicKey", base64urlEncode(passkeyResult.publicKeyDER))- put("publicKeyAlgorithm", -7) // ES256, required for Chrome CredManHelper. Firefox doesn't need this.+ put("publicKey", Helpers.bytesToBase64url(passkeyResult.publicKeyDER))+ put("publicKeyAlgorithm", -7)},)@@ -365,9 +356,9 @@ class PasskeyFormFragment : Fragment() {put("results",JSONObject().apply {- put("first", base64urlEncode(prfResults.first))+ put("first", Helpers.bytesToBase64url(prfResults.first))prfResults.second?.let {- put("second", base64urlEncode(it))+ put("second", Helpers.bytesToBase64url(it))}},)@@ -388,12 +379,8 @@ class PasskeyFormFragment : Fragment() {hideLoading()val resultIntent = Intent()try {- Log.d(TAG, "Setting credential response...")PendingIntentHandler.setCreateCredentialResponse(resultIntent, response)- Log.d(TAG, "Credential response set successfully")-requireActivity().setResult(Activity.RESULT_OK, resultIntent)- Log.d(TAG, "Result set to RESULT_OK, finishing activity")requireActivity().finish()} catch (e: Exception) {Log.e(TAG, "Error setting credential response", e)@@ -409,7 +396,7 @@ class PasskeyFormFragment : Fragment() {}/**- * Replace an existing passkey flow+ * Replace an existing passkey flow.*/private suspend fun replacePasskeyFlow(displayName: String, passkeyToReplace: PasskeyWithCredentialInfo) = withContext(Dispatchers.IO) {try {@@ -433,8 +420,6 @@ class PasskeyFormFragment : Fragment() {showLoading(getString(R.string.passkey_replacing))}- Log.d(TAG, "Replacing passkey ${passkeyToReplace.passkey.id} for RP: ${viewModel.rpId}")-// Extract favicon (optional)var logo: ByteArray? = nulltry {@@ -448,21 +433,12 @@ class PasskeyFormFragment : Fragment() {val newPasskeyId = UUID.randomUUID()val credentialId = PasskeyHelper.guidToBytes(newPasskeyId.toString())- // Use clientDataHash from the request- val requestClientDataHash = viewModel.clientDataHash- if (requestClientDataHash == null) {- throw Exception("Client data hash not available")- }-// Parse request to get challengeval requestObj = JSONObject(viewModel.requestJson)val challenge = requestObj.optString("challenge", "")// Use origin from the request- val requestOrigin = viewModel.origin- if (requestOrigin == null) {- throw Exception("Origin not available")- }+ val requestOrigin = viewModel.origin ?: throw PasskeyOperationException("Origin not available")// Extract PRF inputs if presentval prfInputs = extractPrfInputs(requestObj)@@ -471,7 +447,6 @@ class PasskeyFormFragment : Fragment() {// Create the new passkey using PasskeyAuthenticatorval passkeyResult = PasskeyAuthenticator.createPasskey(credentialId = credentialId,- clientDataHash = requestClientDataHash,rpId = viewModel.rpId,userId = viewModel.userId,userName = viewModel.userName,@@ -503,7 +478,7 @@ class PasskeyFormFragment : Fragment() {showLoading(getString(R.string.passkey_saving))}- val db = vaultStore.database ?: throw Exception("Vault not unlocked")+ val db = vaultStore.database ?: throw VaultOperationException("Vault not unlocked")db.beginTransaction()try {vaultStore.replacePasskey(@@ -516,8 +491,6 @@ class PasskeyFormFragment : Fragment() {// Commit transaction and persist to encrypted vault filevaultStore.commitTransaction()-- Log.d(TAG, "Passkey replaced successfully")} catch (e: Exception) {db.endTransaction()throw e@@ -540,12 +513,11 @@ class PasskeyFormFragment : Fragment() {}// Build response (same as create flow)- val credentialIdB64 = base64urlEncode(credentialId)- val attestationObjectB64 = base64urlEncode(passkeyResult.attestationObject)+ val credentialIdB64 = Helpers.bytesToBase64url(credentialId)+ val attestationObjectB64 = Helpers.bytesToBase64url(passkeyResult.attestationObject)- val clientDataJson =- """{"type":"webauthn.create","challenge":"$challenge","origin":"$requestOrigin","crossOrigin":false}"""- val clientDataJsonB64 = base64urlEncode(clientDataJson.toByteArray(Charsets.UTF_8))+ val clientDataJson = buildClientDataJson(challenge, requestOrigin)+ val clientDataJsonB64 = Helpers.bytesToBase64url(clientDataJson.toByteArray(Charsets.UTF_8))val responseJson = JSONObject().apply {put("id", credentialIdB64)@@ -557,20 +529,24 @@ class PasskeyFormFragment : Fragment() {JSONObject().apply {put("clientDataJSON", clientDataJsonB64)put("attestationObject", attestationObjectB64)- put("authenticatorData", base64urlEncode(passkeyResult.authenticatorData))+ put("authenticatorData", Helpers.bytesToBase64url(passkeyResult.authenticatorData))put("transports",org.json.JSONArray().apply {put("internal")},)- put("publicKey", base64urlEncode(passkeyResult.publicKeyDER))+ put("publicKey", Helpers.bytesToBase64url(passkeyResult.publicKeyDER))put("publicKeyAlgorithm", -7)},)// Add PRF extension results if present- val prfResults = if (enablePrf) passkeyResult.prfResults else null+ val prfResults = if (enablePrf) {+ passkeyResult.prfResults+ } else {+ null+ }if (prfResults != null) {put("clientExtensionResults",@@ -582,9 +558,9 @@ class PasskeyFormFragment : Fragment() {put("results",JSONObject().apply {- put("first", base64urlEncode(prfResults.first))+ put("first", Helpers.bytesToBase64url(prfResults.first))prfResults.second?.let {- put("second", base64urlEncode(it))+ put("second", Helpers.bytesToBase64url(it))}},)@@ -597,20 +573,14 @@ class PasskeyFormFragment : Fragment() {}}- Log.d(TAG, "Response JSON: ${responseJson.toString(2)}")-val response = CreatePublicKeyCredentialResponse(responseJson.toString())withContext(Dispatchers.Main) {hideLoading()val resultIntent = Intent()try {- Log.d(TAG, "Setting credential response...")PendingIntentHandler.setCreateCredentialResponse(resultIntent, response)- Log.d(TAG, "Credential response set successfully")-requireActivity().setResult(Activity.RESULT_OK, resultIntent)- Log.d(TAG, "Result set to RESULT_OK, finishing activity")requireActivity().finish()} catch (e: Exception) {Log.e(TAG, "Error setting credential response", e)@@ -626,7 +596,8 @@ class PasskeyFormFragment : Fragment() {}/**- * Extract PRF extension inputs from request+ * Extract PRF extension inputs from request.+ * Note: PRF needs to be fully tested, we did not get PRF eval in the request from CredMan so far.*/private fun extractPrfInputs(requestObj: JSONObject): PasskeyAuthenticator.PrfInputs? {try {@@ -638,10 +609,13 @@ class PasskeyFormFragment : Fragment() {if (firstB64.isEmpty()) return nullval secondB64 = eval.optString("second")- val first = base64urlDecode(firstB64)- val second = if (secondB64.isNotEmpty()) base64urlDecode(secondB64) else null+ val first = Helpers.base64urlDecode(firstB64)+ val second = if (secondB64.isNotEmpty()) {+ Helpers.base64urlDecode(secondB64)+ } else {+ null+ }- Log.d(TAG, "PRF extension requested")return PasskeyAuthenticator.PrfInputs(first, second)} catch (e: Exception) {Log.w(TAG, "Error extracting PRF inputs", e)@@ -650,30 +624,10 @@ class PasskeyFormFragment : Fragment() {}/**- * Encode bytes to base64url string+ * Build clientDataJSON for WebAuthn create request.*/- private fun base64urlEncode(data: ByteArray): String {- return android.util.Base64.encodeToString(- data,- android.util.Base64.URL_SAFE or android.util.Base64.NO_WRAP or android.util.Base64.NO_PADDING,- )- }-- /**- * Decode base64url string to bytes- */- private fun base64urlDecode(base64url: String): ByteArray {- var base64 = base64url- .replace('-', '+')- .replace('_', '/')-- // Add padding if needed- val remainder = base64.length % 4- if (remainder > 0) {- base64 += "=".repeat(4 - remainder)- }-- return android.util.Base64.decode(base64, android.util.Base64.NO_WRAP)+ private fun buildClientDataJson(challenge: String, origin: String): String {+ return """{"type":"webauthn.create","challenge":"$challenge","origin":"$origin","crossOrigin":false}"""}/**diff --git a/apps/mobile-app/android/app/src/main/java/net/aliasvault/app/credentialprovider/PasskeyRegistrationActivity.kt b/apps/mobile-app/android/app/src/main/java/net/aliasvault/app/credentialprovider/PasskeyRegistrationActivity.ktindex 0165623f8..4499ad027 100644--- a/apps/mobile-app/android/app/src/main/java/net/aliasvault/app/credentialprovider/PasskeyRegistrationActivity.kt+++ b/apps/mobile-app/android/app/src/main/java/net/aliasvault/app/credentialprovider/PasskeyRegistrationActivity.kt@@ -7,6 +7,9 @@ import androidx.credentials.CreatePublicKeyCredentialRequestimport androidx.credentials.provider.PendingIntentHandlerimport androidx.fragment.app.FragmentActivityimport net.aliasvault.app.R+import net.aliasvault.app.credentialprovider.models.PasskeyRegistrationViewModel+import net.aliasvault.app.exceptions.VaultOperationException+import net.aliasvault.app.utils.Helpersimport net.aliasvault.app.vaultstore.VaultStoreimport net.aliasvault.app.vaultstore.getPasskeysWithCredentialInfoimport org.json.JSONObject@@ -34,14 +37,10 @@ class PasskeyRegistrationActivity : FragmentActivity() {override fun onCreate(savedInstanceState: Bundle?) {super.onCreate(savedInstanceState)- Log.d(TAG, "PasskeyRegistrationActivity onCreate called")-try {// Initialize VaultStorevaultStore = VaultStore.getExistingInstance()- ?: throw Exception("VaultStore not initialized")-- Log.d(TAG, "VaultStore initialized")+ ?: throw VaultOperationException("VaultStore not initialized")// Retrieve provider requestval providerRequest = PendingIntentHandler.retrieveProviderCreateCredentialRequest(intent)@@ -51,8 +50,6 @@ class PasskeyRegistrationActivity : FragmentActivity() {return}- Log.d(TAG, "Provider request retrieved successfully")-// Extract parameters from providerRequest.callingRequestval createRequest = providerRequest.callingRequestif (createRequest !is CreatePublicKeyCredentialRequest) {@@ -66,10 +63,6 @@ class PasskeyRegistrationActivity : FragmentActivity() {viewModel.clientDataHash = createRequest.clientDataHashviewModel.origin = createRequest.origin- Log.d(TAG, "Request JSON: ${viewModel.requestJson}")- Log.d(TAG, "Origin: ${viewModel.origin}")- Log.d(TAG, "ClientDataHash length: ${viewModel.clientDataHash?.size}")-// Parse request JSON to extract RP ID and user infoval requestObj = JSONObject(viewModel.requestJson)@@ -83,8 +76,6 @@ class PasskeyRegistrationActivity : FragmentActivity() {viewModel.userDisplayName = userObj?.optString("displayName")?.takeIf { it.isNotEmpty() }val userIdB64 = userObj?.optString("id")- Log.d(TAG, "Parameters: rpId=${viewModel.rpId}, userName=${viewModel.userName}, userDisplayName=${viewModel.userDisplayName}")-if (viewModel.rpId.isEmpty() || viewModel.requestJson.isEmpty()) {Log.e(TAG, "Missing required parameters")finish()@@ -94,7 +85,7 @@ class PasskeyRegistrationActivity : FragmentActivity() {// Decode user ID from base64urlviewModel.userId = if (!userIdB64.isNullOrEmpty()) {try {- base64urlDecode(userIdB64)+ Helpers.base64urlDecode(userIdB64)} catch (e: Exception) {Log.w(TAG, "Failed to decode user ID", e)null@@ -112,7 +103,6 @@ class PasskeyRegistrationActivity : FragmentActivity() {userId = viewModel.userId,db = db,)- Log.d(TAG, "Found ${viewModel.existingPasskeys.size} existing passkeys for rpId=${viewModel.rpId}")}// Set content view with fragment container@@ -136,7 +126,7 @@ class PasskeyRegistrationActivity : FragmentActivity() {}/**- * Show selection fragment when there are existing passkeys+ * Show selection fragment when there are existing passkeys.*/private fun showSelectionFragment() {val fragment = PasskeySelectionFragment()@@ -146,7 +136,7 @@ class PasskeyRegistrationActivity : FragmentActivity() {}/**- * Show form fragment for creating or replacing a passkey+ * Show form fragment for creating or replacing a passkey.*/private fun showFormFragment(isReplace: Boolean, passkeyId: String?) {val fragment = PasskeyFormFragment.newInstance(isReplace, passkeyId)@@ -154,21 +144,4 @@ class PasskeyRegistrationActivity : FragmentActivity() {.replace(R.id.fragmentContainer, fragment).commit()}-- /**- * Decode base64url string to bytes- */- private fun base64urlDecode(base64url: String): ByteArray {- var base64 = base64url- .replace('-', '+')- .replace('_', '/')-- // Add padding if needed- val remainder = base64.length % 4- if (remainder > 0) {- base64 += "=".repeat(4 - remainder)- }-- return android.util.Base64.decode(base64, android.util.Base64.NO_WRAP)- }}diff --git a/apps/mobile-app/android/app/src/main/java/net/aliasvault/app/credentialprovider/PasskeySelectionFragment.kt b/apps/mobile-app/android/app/src/main/java/net/aliasvault/app/credentialprovider/PasskeySelectionFragment.ktindex 09217bec5..062ed8c9f 100644--- a/apps/mobile-app/android/app/src/main/java/net/aliasvault/app/credentialprovider/PasskeySelectionFragment.kt+++ b/apps/mobile-app/android/app/src/main/java/net/aliasvault/app/credentialprovider/PasskeySelectionFragment.kt@@ -10,10 +10,11 @@ import androidx.fragment.app.Fragmentimport androidx.fragment.app.activityViewModelsimport com.google.android.material.button.MaterialButtonimport net.aliasvault.app.R+import net.aliasvault.app.credentialprovider.models.PasskeyRegistrationViewModel/**- * Fragment that shows the passkey selection screen- * Displays options to create new or replace existing passkeys+ * Fragment that shows the passkey selection screen.+ * Displays options to create new or replace existing passkeys.*/class PasskeySelectionFragment : Fragment() {diff --git a/apps/mobile-app/android/app/src/main/java/net/aliasvault/app/credentialprovider/PasskeyRegistrationViewModel.kt b/apps/mobile-app/android/app/src/main/java/net/aliasvault/app/credentialprovider/models/PasskeyRegistrationViewModel.ktsimilarity index 55%rename from apps/mobile-app/android/app/src/main/java/net/aliasvault/app/credentialprovider/PasskeyRegistrationViewModel.ktrename to apps/mobile-app/android/app/src/main/java/net/aliasvault/app/credentialprovider/models/PasskeyRegistrationViewModel.ktindex 81d19a048..c9cae6c42 100644--- a/apps/mobile-app/android/app/src/main/java/net/aliasvault/app/credentialprovider/PasskeyRegistrationViewModel.kt+++ b/apps/mobile-app/android/app/src/main/java/net/aliasvault/app/credentialprovider/models/PasskeyRegistrationViewModel.kt@@ -1,37 +1,62 @@-package net.aliasvault.app.credentialprovider+package net.aliasvault.app.credentialprovider.modelsimport androidx.lifecycle.ViewModelimport net.aliasvault.app.vaultstore.PasskeyWithCredentialInfoimport java.util.UUID/**- * ViewModel to share passkey registration state between fragments+ * ViewModel to share passkey registration state between fragments.*/class PasskeyRegistrationViewModel : ViewModel() {- // Request data+ /** The passkey request JSON string from the relying party. */var requestJson: String = ""++ /** The client data hash for passkey creation. */var clientDataHash: ByteArray? = null++ /** The origin URL of the passkey request. */var origin: String? = null++ /** The relying party identifier. */var rpId: String = ""++ /** The username for the passkey. */var userName: String? = null++ /** The user display name for the passkey. */var userDisplayName: String? = null++ /** The user ID as a byte array. */var userId: ByteArray? = null- // State+ /** List of existing passkeys for the relying party. */var existingPasskeys: List<PasskeyWithCredentialInfo> = emptyList()++ /** The passkey selected to be replaced, if any. */var selectedPasskeyToReplace: PasskeyWithCredentialInfo? = null++ /** Whether the user is in replace mode (true) or create new mode (false). */var isReplaceMode: Boolean = false+ /**+ * Called when the user selects to create a new passkey.+ */fun onCreateNewSelected() {isReplaceMode = falseselectedPasskeyToReplace = null}+ /**+ * Called when the user selects to replace an existing passkey.+ */fun onReplaceSelected(passkeyInfo: PasskeyWithCredentialInfo) {isReplaceMode = trueselectedPasskeyToReplace = passkeyInfo}+ /**+ * Get a passkey by its ID from the existing passkeys list.+ */fun getPasskeyById(id: UUID): PasskeyWithCredentialInfo? {return existingPasskeys.firstOrNull { it.passkey.id == id }}diff --git a/apps/mobile-app/android/app/src/main/java/net/aliasvault/app/exceptions/AliasVaultAndroidException.kt b/apps/mobile-app/android/app/src/main/java/net/aliasvault/app/exceptions/AliasVaultAndroidException.ktnew file mode 100644index 000000000..cef79dbe3--- /dev/null+++ b/apps/mobile-app/android/app/src/main/java/net/aliasvault/app/exceptions/AliasVaultAndroidException.kt@@ -0,0 +1,60 @@+package net.aliasvault.app.exceptions++/**+ * Base exception class for AliasVault Android application errors.+ *+ * This custom exception replaces generic Exception usage throughout the Android codebase+ * to provide more specific error handling and improve code quality.+ */+open class AliasVaultAndroidException : Exception {+ /**+ * Constructs an exception with a detail message.+ */+ constructor(message: String) : super(message)++ /**+ * Constructs an exception with a detail message and a cause.+ */+ constructor(message: String, cause: Throwable) : super(message, cause)++ /**+ * Constructs an exception with a cause.+ */+ constructor(cause: Throwable) : super(cause)+}++/**+ * Exception thrown when vault operations fail.+ */+class VaultOperationException : AliasVaultAndroidException {+ constructor(message: String) : super(message)+ constructor(message: String, cause: Throwable) : super(message, cause)+ constructor(cause: Throwable) : super(cause)+}++/**+ * Exception thrown when passkey operations fail.+ */+class PasskeyOperationException : AliasVaultAndroidException {+ constructor(message: String) : super(message)+ constructor(message: String, cause: Throwable) : super(message, cause)+ constructor(cause: Throwable) : super(cause)+}++/**+ * Exception thrown when cryptographic operations fail.+ */+class CryptoOperationException : AliasVaultAndroidException {+ constructor(message: String) : super(message)+ constructor(message: String, cause: Throwable) : super(message, cause)+ constructor(cause: Throwable) : super(cause)+}++/**+ * Exception thrown when data serialization/deserialization fails.+ */+class SerializationException : AliasVaultAndroidException {+ constructor(message: String) : super(message)+ constructor(message: String, cause: Throwable) : super(message, cause)+ constructor(cause: Throwable) : super(cause)+}diff --git a/apps/mobile-app/android/app/src/main/java/net/aliasvault/app/nativevaultmanager/NativeVaultManager.kt b/apps/mobile-app/android/app/src/main/java/net/aliasvault/app/nativevaultmanager/NativeVaultManager.ktindex c473cf9e7..66cecc7cc 100644--- a/apps/mobile-app/android/app/src/main/java/net/aliasvault/app/nativevaultmanager/NativeVaultManager.kt+++ b/apps/mobile-app/android/app/src/main/java/net/aliasvault/app/nativevaultmanager/NativeVaultManager.kt@@ -860,14 +860,13 @@ class NativeVaultManager(reactContext: ReactApplicationContext) :// MARK: - WebAPI Configuration/**- * Set the API URL+ * Set the API URL.* @param url The API URL to set* @param promise The promise to resolve*/@ReactMethodoverride fun setApiUrl(url: String, promise: Promise) {try {- // TODO: Implement when WebApiService is completewebApiService.setApiUrl(url)promise.resolve(null)} catch (e: Exception) {@@ -877,13 +876,12 @@ class NativeVaultManager(reactContext: ReactApplicationContext) :}/**- * Get the API URL- * @param promise The promise to resolve+ * Get the API URL.+ * @param promise The promise to resolve.*/@ReactMethodoverride fun getApiUrl(promise: Promise) {try {- // TODO: Implement when WebApiService is completeval apiUrl = webApiService.getApiUrl()promise.resolve(apiUrl)} catch (e: Exception) {@@ -895,15 +893,14 @@ class NativeVaultManager(reactContext: ReactApplicationContext) :// MARK: - WebAPI Token Management/**- * Set both access and refresh tokens- * @param accessToken The access token- * @param refreshToken The refresh token- * @param promise The promise to resolve+ * Set both access and refresh tokens.+ * @param accessToken The access token.+ * @param refreshToken The refresh token.+ * @param promise The promise to resolve.*/@ReactMethodoverride fun setAuthTokens(accessToken: String, refreshToken: String, promise: Promise) {try {- // TODO: Implement when WebApiService is completewebApiService.setAuthTokens(accessToken, refreshToken)promise.resolve(null)} catch (e: Exception) {@@ -913,13 +910,12 @@ class NativeVaultManager(reactContext: ReactApplicationContext) :}/**- * Get the access token- * @param promise The promise to resolve+ * Get the access token.+ * @param promise The promise to resolve.*/@ReactMethodoverride fun getAccessToken(promise: Promise) {try {- // TODO: Implement when WebApiService is completeval accessToken = webApiService.getAccessToken()promise.resolve(accessToken)} catch (e: Exception) {@@ -929,13 +925,12 @@ class NativeVaultManager(reactContext: ReactApplicationContext) :}/**- * Clear both access and refresh tokens- * @param promise The promise to resolve+ * Clear both access and refresh tokens.+ * @param promise The promise to resolve.*/@ReactMethodoverride fun clearAuthTokens(promise: Promise) {try {- // TODO: Implement when WebApiService is completewebApiService.clearAuthTokens()promise.resolve(null)} catch (e: Exception) {@@ -945,14 +940,11 @@ class NativeVaultManager(reactContext: ReactApplicationContext) :}/**- * Revoke tokens via WebAPI (called when logging out)- * @param promise The promise to resolve+ * Revoke tokens via WebAPI (called when logging out).+ * @param promise The promise to resolve.*/@ReactMethodoverride fun revokeTokens(promise: Promise) {- // TODO: Implement when WebApiService is complete- // This should call webApiService.revokeTokens() which is an async suspend function- // For now, we'll use a coroutine scope to handle itCoroutineScope(Dispatchers.IO).launch {try {webApiService.revokeTokens()@@ -971,13 +963,13 @@ class NativeVaultManager(reactContext: ReactApplicationContext) :// MARK: - WebAPI Request Execution/**- * Execute a WebAPI request- * @param method The HTTP method- * @param endpoint The API endpoint- * @param body The request body (nullable)- * @param headers The request headers as JSON string- * @param requiresAuth Whether authentication is required- * @param promise The promise to resolve+ * Execute a WebAPI request.+ * @param method The HTTP method.+ * @param endpoint The API endpoint.+ * @param body The request body (nullable).+ * @param headers The request headers as JSON string.+ * @param requiresAuth Whether authentication is required.+ * @param promise The promise to resolve.*/@ReactMethodoverride fun executeWebApiRequest(@@ -989,7 +981,6 @@ class NativeVaultManager(reactContext: ReactApplicationContext) :promise: Promise,) {try {- // TODO: Implement when WebApiService is complete// Parse headers from JSON stringval headersMap = mutableMapOf<String, String>()val headersJson = JSONObject(headers)@@ -1022,22 +1013,22 @@ class NativeVaultManager(reactContext: ReactApplicationContext) :}/**- * Register credential identities (Android stub - not yet implemented)- * @param promise The promise to resolve+ * Register credential identities in the Native Autofill API cache.+ * @param promise The promise to resolve.*/@ReactMethodoverride fun registerCredentialIdentities(promise: Promise) {- // TODO: Implement Android credential identity registration- Log.d(TAG, "registerCredentialIdentities: Not yet implemented on Android")+ // Not required for Android as Android autofill queries AliasVault for credentials in realtime+ // and does not implement caching (in comparison to iOS which does).promise.resolve(null)}// MARK: - Username Management/**- * Set the username- * @param username The username to set- * @param promise The promise to resolve+ * Set the username.+ * @param username The username to set.+ * @param promise The promise to resolve.*/@ReactMethodoverride fun setUsername(username: String, promise: Promise) {@@ -1051,8 +1042,8 @@ class NativeVaultManager(reactContext: ReactApplicationContext) :}/**- * Get the username- * @param promise The promise to resolve+ * Get the username.+ * @param promise The promise to resolve.*/@ReactMethodoverride fun getUsername(promise: Promise) {@@ -1066,8 +1057,8 @@ class NativeVaultManager(reactContext: ReactApplicationContext) :}/**- * Clear the username- * @param promise The promise to resolve+ * Clear the username.+ * @param promise The promise to resolve.*/@ReactMethodoverride fun clearUsername(promise: Promise) {@@ -1083,9 +1074,9 @@ class NativeVaultManager(reactContext: ReactApplicationContext) :// MARK: - Offline Mode Management/**- * Set offline mode flag- * @param isOffline Whether app is offline- * @param promise The promise to resolve+ * Set offline mode flag.+ * @param isOffline Whether app is offline.+ * @param promise The promise to resolve.*/@ReactMethodoverride fun setOfflineMode(isOffline: Boolean, promise: Promise) {@@ -1099,8 +1090,8 @@ class NativeVaultManager(reactContext: ReactApplicationContext) :}/**- * Get offline mode flag- * @param promise The promise to resolve+ * Get offline mode flag.+ * @param promise The promise to resolve.*/@ReactMethodoverride fun getOfflineMode(promise: Promise) {@@ -1116,8 +1107,8 @@ class NativeVaultManager(reactContext: ReactApplicationContext) :// MARK: - Vault Sync and Mutate/**- * Check if a new vault version is available on the server- * @param promise The promise to resolve with object containing isNewVersionAvailable and newRevision+ * Check if a new vault version is available on the server.+ * @param promise The promise to resolve with object containing isNewVersionAvailable and newRevision.*/@ReactMethodoverride fun isNewVaultVersionAvailable(promise: Promise) {@@ -1146,9 +1137,9 @@ class NativeVaultManager(reactContext: ReactApplicationContext) :}/**- * Download and store the vault from the server- * @param newRevision The new revision number to download- * @param promise The promise to resolve+ * Download and store the vault from the server.+ * @param newRevision The new revision number to download.+ * @param promise The promise to resolve.*/@ReactMethodoverride fun downloadVault(newRevision: Double, promise: Promise) {@@ -1168,8 +1159,8 @@ class NativeVaultManager(reactContext: ReactApplicationContext) :}/**- * Mutate vault (upload changes to server)- * @param promise The promise to resolve+ * Mutate vault (upload changes to server).+ * @param promise The promise to resolve.*/@ReactMethodoverride fun mutateVault(promise: Promise) {diff --git a/apps/mobile-app/android/app/src/main/java/net/aliasvault/app/utils/Helpers.kt b/apps/mobile-app/android/app/src/main/java/net/aliasvault/app/utils/Helpers.ktnew file mode 100644index 000000000..64b0d5fc4--- /dev/null+++ b/apps/mobile-app/android/app/src/main/java/net/aliasvault/app/utils/Helpers.kt@@ -0,0 +1,37 @@+package net.aliasvault.app.utils++/**+ * Helpers+ * -------------------------+ * Utility class for helper methods.+ */+object Helpers {+ /**+ * Encode bytes to base64url string.+ */+ @JvmStatic+ fun bytesToBase64url(data: ByteArray): String {+ return android.util.Base64.encodeToString(+ data,+ android.util.Base64.URL_SAFE or android.util.Base64.NO_WRAP or android.util.Base64.NO_PADDING,+ )+ }++ /**+ * Decode base64url string to bytes.+ */+ @JvmStatic+ fun base64urlDecode(base64url: String): ByteArray {+ var base64 = base64url+ .replace('-', '+')+ .replace('_', '/')++ // Add padding if needed+ val remainder = base64.length % 4+ if (remainder > 0) {+ base64 += "=".repeat(4 - remainder)+ }++ return android.util.Base64.decode(base64, android.util.Base64.NO_WRAP)+ }+}diff --git a/apps/mobile-app/android/app/src/main/java/net/aliasvault/app/vaultstore/AppInfo.kt b/apps/mobile-app/android/app/src/main/java/net/aliasvault/app/vaultstore/AppInfo.ktindex 1c88c7b28..e404f9d6a 100644--- a/apps/mobile-app/android/app/src/main/java/net/aliasvault/app/vaultstore/AppInfo.kt+++ b/apps/mobile-app/android/app/src/main/java/net/aliasvault/app/vaultstore/AppInfo.kt@@ -1,8 +1,8 @@package net.aliasvault.app.vaultstore/**- * Application configuration constants- * This file contains version requirements and other app-wide configuration values+ * Application configuration constants.+ * This file contains version requirements and other app-wide configuration values.*/object AppInfo {/**diff --git a/apps/mobile-app/android/app/src/main/java/net/aliasvault/app/vaultstore/VaultStore.kt b/apps/mobile-app/android/app/src/main/java/net/aliasvault/app/vaultstore/VaultStore.ktindex 9406c6999..32e61ba34 100644--- a/apps/mobile-app/android/app/src/main/java/net/aliasvault/app/vaultstore/VaultStore.kt+++ b/apps/mobile-app/android/app/src/main/java/net/aliasvault/app/vaultstore/VaultStore.kt@@ -9,6 +9,8 @@ import android.util.Logimport com.lambdapioneer.argon2kt.Argon2Ktimport com.lambdapioneer.argon2kt.Argon2Modeimport com.lambdapioneer.argon2kt.Argon2Version+import net.aliasvault.app.exceptions.SerializationException+import net.aliasvault.app.exceptions.VaultOperationExceptionimport net.aliasvault.app.vaultstore.interfaces.CredentialOperationCallbackimport net.aliasvault.app.vaultstore.interfaces.CryptoOperationCallbackimport net.aliasvault.app.vaultstore.keystoreprovider.KeystoreOperationCallback@@ -107,8 +109,8 @@ class VaultStore(private var dbConnection: SQLiteDatabase? = null/**- * Internal accessor for database connection- * Used by extension functions to access the database+ * Internal accessor for database connection.+ * Used by extension functions to access the database.*/internal val database: SQLiteDatabase?get() = dbConnection@@ -259,9 +261,7 @@ class VaultStore(* @return The derived key as a ByteArray*/fun deriveKeyFromPassword(password: String, salt: String, encryptionType: String, encryptionSettings: String): ByteArray {- if (encryptionType != "Argon2Id") {- throw IllegalArgumentException("Unsupported encryption type: $encryptionType")- }+ require(encryptionType == "Argon2Id") { "Unsupported encryption type: $encryptionType" }// Parse encryption settings JSONval settings = JSONObject(encryptionSettings)@@ -1033,6 +1033,7 @@ class VaultStore()for (format in formats) {+ @Suppress("SwallowedException")try {return format.parse(normalizedDate)} catch (e: Exception) {@@ -1206,7 +1207,7 @@ class VaultStore(} catch (e: Exception) {Log.e(TAG, "Failed to decode status response", e)Log.e(TAG, "Response body: '${statusResponse.body}'")- throw VaultSyncError.ParseError("Failed to decode status response: ${e.message}")+ throw VaultSyncError.ParseError("Failed to decode status response: ${e.message}", e)}if (!status.clientVersionSupported) {@@ -1226,15 +1227,17 @@ class VaultStore(return}+ @Suppress("SwallowedException")try {val json = org.json.JSONObject(keyDerivationParams)val salt = json.optString("salt", "")if (srpSalt.isNotEmpty() && srpSalt != salt) {throw VaultSyncError.PasswordChanged()}+ } catch (e: VaultSyncError.PasswordChanged) {+ throw e} catch (e: Exception) {- if (e is VaultSyncError.PasswordChanged) throw e- // Ignore parsing errors+ // Ignore generic parsing errors}}@@ -1251,14 +1254,14 @@ class VaultStore(requiresAuth = true,)} catch (e: Exception) {- throw Exception("Network error: ${e.message}", e)+ throw VaultOperationException("Network error: ${e.message}", e)}if (vaultResponse.statusCode != 200) {if (vaultResponse.statusCode == 401) {- throw Exception("Session expired")+ throw VaultOperationException("Session expired")}- throw Exception("Server unavailable: ${vaultResponse.statusCode}")+ throw VaultOperationException("Server unavailable: ${vaultResponse.statusCode}")}val vault = parseVaultResponse(vaultResponse.body)@@ -1315,7 +1318,7 @@ class VaultStore()} catch (e: Exception) {Log.e(TAG, "Failed to decode vault response", e)- throw Exception("Failed to decode vault response: ${e.message}")+ throw SerializationException("Failed to decode vault response: ${e.message}", e)}}@@ -1325,9 +1328,9 @@ class VaultStore(private fun validateVaultStatus(status: Int) {when (status) {0 -> return- 1 -> throw Exception("Vault merge required")- 2 -> throw Exception("Vault outdated")- else -> throw Exception("Unknown vault status: $status")+ 1 -> throw VaultOperationException("Vault merge required")+ 2 -> throw VaultOperationException("Vault outdated")+ else -> throw VaultOperationException("Unknown vault status: $status")}}@@ -1343,10 +1346,10 @@ class VaultStore(val encryptedDb = getEncryptedDatabase()val username = getUsername()- ?: throw Exception("Username not found")+ ?: throw VaultOperationException("Username not found")if (!isVaultUnlocked()) {- throw Exception("Vault must be unlocked to prepare for upload")+ throw VaultOperationException("Vault must be unlocked to prepare for upload")}// Get all credentials@@ -1370,6 +1373,7 @@ class VaultStore(val dbVersion = getDatabaseVersion()// Get app version+ @Suppress("SwallowedException")val version = try {val context = storageProvider as? net.aliasvault.app.vaultstore.storageprovider.AndroidStorageProviderval pm = context?.javaClass?.getDeclaredField("context")?.get(context) as? android.content.Context@@ -1439,7 +1443,7 @@ class VaultStore(if (response.statusCode != 200) {Log.e(TAG, "Server rejected vault upload with status ${response.statusCode}")- throw Exception("Server returned error: ${response.statusCode}")+ throw VaultOperationException("Server returned error: ${response.statusCode}")}// Parse response@@ -1451,7 +1455,7 @@ class VaultStore()} catch (e: Exception) {Log.e(TAG, "Failed to parse vault upload response", e)- throw Exception("Failed to parse vault upload response: ${e.message}")+ throw SerializationException("Failed to parse vault upload response: ${e.message}", e)}// Check vault response status@@ -1462,9 +1466,9 @@ class VaultStore(setOfflineMode(false)return true}- 1 -> throw Exception("Vault merge required")- 2 -> throw Exception("Vault is outdated, please sync first")- else -> throw Exception("Failed to upload vault")+ 1 -> throw VaultOperationException("Vault merge required")+ 2 -> throw VaultOperationException("Vault is outdated, please sync first")+ else -> throw VaultOperationException("Failed to upload vault")}} catch (e: Exception) {Log.e(TAG, "Error mutating vault", e)diff --git a/apps/mobile-app/android/app/src/main/java/net/aliasvault/app/vaultstore/VaultStorePasskey.kt b/apps/mobile-app/android/app/src/main/java/net/aliasvault/app/vaultstore/VaultStorePasskey.ktindex 37c22d0d9..019e86692 100644--- a/apps/mobile-app/android/app/src/main/java/net/aliasvault/app/vaultstore/VaultStorePasskey.kt+++ b/apps/mobile-app/android/app/src/main/java/net/aliasvault/app/vaultstore/VaultStorePasskey.kt@@ -29,7 +29,7 @@ import java.util.UUIDprivate const val TAG = "VaultStorePasskey"/**- * Minimum date definition for default values+ * Minimum date definition for default values.*/private val MIN_DATE: Date = Calendar.getInstance(TimeZone.getTimeZone("UTC")).apply {set(Calendar.YEAR, 1)@@ -42,7 +42,7 @@ private val MIN_DATE: Date = Calendar.getInstance(TimeZone.getTimeZone("UTC")).a}.time/**- * Get a passkey by its credential ID (the WebAuthn credential ID, not the parent Credential UUID)+ * Get a passkey by its credential ID (the WebAuthn credential ID, not the parent Credential UUID).*/fun VaultStore.getPasskeyByCredentialId(credentialId: ByteArray, db: SQLiteDatabase): Passkey? {// Convert credentialId bytes to UUID string for lookup@@ -72,7 +72,7 @@ fun VaultStore.getPasskeyByCredentialId(credentialId: ByteArray, db: SQLiteDatab}/**- * Get all passkeys for a credential+ * Get all passkeys for a credential.*/fun VaultStore.getPasskeysForCredential(credentialId: UUID, db: SQLiteDatabase): List<Passkey> {val query = """@@ -98,7 +98,7 @@ fun VaultStore.getPasskeysForCredential(credentialId: UUID, db: SQLiteDatabase):}/**- * Get all passkeys for a specific relying party identifier (RP ID)+ * Get all passkeys for a specific relying party identifier (RP ID).*/fun VaultStore.getPasskeysForRpId(rpId: String, db: SQLiteDatabase): List<Passkey> {val query = """@@ -124,17 +124,20 @@ fun VaultStore.getPasskeysForRpId(rpId: String, db: SQLiteDatabase): List<Passke}/**- * Data class to hold passkey with credential info+ * Data class to hold passkey with credential info.*/data class PasskeyWithCredentialInfo(+ /** The passkey. */val passkey: Passkey,+ /** The service name from the credential. */val serviceName: String?,+ /** The username from the credential. */val username: String?,)/**- * Get passkeys with credential info for a specific rpId and optionally username- * Used for finding existing passkeys that might be replaced during registration+ * Get passkeys with credential info for a specific rpId and optionally username.+ * Used for finding existing passkeys that might be replaced during registration.*/fun VaultStore.getPasskeysWithCredentialInfo(rpId: String,@@ -187,7 +190,7 @@ fun VaultStore.getPasskeysWithCredentialInfo(}/**- * Insert a new passkey into the database+ * Insert a new passkey into the database.*/fun VaultStore.insertPasskey(passkey: Passkey, db: SQLiteDatabase) {val insert = """@@ -218,8 +221,8 @@ fun VaultStore.insertPasskey(passkey: Passkey, db: SQLiteDatabase) {}/**- * Create a new credential with an associated passkey- * This method handles the database transaction internally+ * Create a new credential with an associated passkey.+ * This method handles the database transaction internally.*/fun VaultStore.createCredentialWithPasskey(rpId: String,@@ -228,7 +231,7 @@ fun VaultStore.createCredentialWithPasskey(passkey: Passkey,logo: ByteArray? = null,): Credential {- val db = database ?: throw IllegalStateException("Vault not unlocked")+ val db = database ?: error("Vault not unlocked")db.beginTransaction()try {@@ -348,8 +351,8 @@ fun VaultStore.createCredentialWithPasskey(}/**- * Replace an existing passkey with a new one- * This deletes the old passkey and creates a new one with the same credential+ * Replace an existing passkey with a new one.+ * This deletes the old passkey and creates a new one with the same credential.*/fun VaultStore.replacePasskey(oldPasskeyId: UUID,@@ -413,7 +416,7 @@ fun VaultStore.replacePasskey(}/**- * Get a passkey by its ID+ * Get a passkey by its ID.*/fun VaultStore.getPasskeyById(passkeyId: UUID, db: SQLiteDatabase): Passkey? {val query = """@@ -438,7 +441,7 @@ fun VaultStore.getPasskeyById(passkeyId: UUID, db: SQLiteDatabase): Passkey? {}/**- * Parse a passkey row from database query+ * Parse a passkey row from database query.*/private fun parsePasskeyRow(cursor: Cursor): Passkey? {try {@@ -487,8 +490,8 @@ private fun parsePasskeyRow(cursor: Cursor): Passkey? {}/**- * Format a date for database insertion- * Format: yyyy-MM-dd HH:mm:ss+ * Format a date for database insertion.+ * Format: yyyy-MM-dd HH:mm:ss.*/private fun formatDateForDatabase(date: Date): String {val formatter = SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.US)@@ -497,8 +500,8 @@ private fun formatDateForDatabase(date: Date): String {}/**- * Parse a date string from the database- * Format: yyyy-MM-dd HH:mm:ss+ * Parse a date string from the database.+ * Format: yyyy-MM-dd HH:mm:ss.*/private fun parseDateString(dateString: String): Date? {return try {@@ -512,11 +515,26 @@ private fun parseDateString(dateString: String): Date? {}/**- * VaultStore passkey-specific errors+ * VaultStore passkey-specific errors.*/sealed class VaultStorePasskeyError(message: String) : Exception(message) {+ /**+ * Error indicating vault is not unlocked.+ */class VaultNotUnlocked(message: String) : VaultStorePasskeyError(message)++ /**+ * Error indicating passkey was not found.+ */class PasskeyNotFound(message: String) : VaultStorePasskeyError(message)++ /**+ * Error indicating credential was not found.+ */class CredentialNotFound(message: String) : VaultStorePasskeyError(message)++ /**+ * Error indicating a database operation failure.+ */class DatabaseError(message: String) : VaultStorePasskeyError(message)}diff --git a/apps/mobile-app/android/app/src/main/java/net/aliasvault/app/vaultstore/VaultSyncError.kt b/apps/mobile-app/android/app/src/main/java/net/aliasvault/app/vaultstore/VaultSyncError.ktindex 5c7538349..380d57a34 100644--- a/apps/mobile-app/android/app/src/main/java/net/aliasvault/app/vaultstore/VaultSyncError.kt+++ b/apps/mobile-app/android/app/src/main/java/net/aliasvault/app/vaultstore/VaultSyncError.kt@@ -12,35 +12,127 @@ package net.aliasvault.app.vaultstore*/sealed class VaultSyncError(message: String, cause: Throwable? = null) : Exception(message, cause) {// Authentication errors- class AuthenticationFailed(message: String = "Authentication failed") : VaultSyncError(message)- class SessionExpired(message: String = "Session expired") : VaultSyncError(message)- class PasswordChanged(message: String = "Password has changed") : VaultSyncError(message)+ /**+ * Error indicating authentication failed.+ */+ class AuthenticationFailed(+ message: String = "Authentication failed",+ cause: Throwable? = null,+ ) : VaultSyncError(message, cause)++ /**+ * Error indicating session expired.+ */+ class SessionExpired(+ message: String = "Session expired",+ cause: Throwable? = null,+ ) : VaultSyncError(message, cause)++ /**+ * Error indicating password has changed.+ */+ class PasswordChanged(+ message: String = "Password has changed",+ cause: Throwable? = null,+ ) : VaultSyncError(message, cause)// Network/connectivity errors- class ServerUnavailable(val statusCode: Int, message: String = "Server unavailable (status: $statusCode)") :- VaultSyncError(message)- class NetworkError(val underlyingError: Throwable) :- VaultSyncError("Network error: ${underlyingError.message}", underlyingError)- class Timeout(message: String = "Request timeout") : VaultSyncError(message)+ /**+ * Error indicating server unavailable.+ */+ class ServerUnavailable(+ /** The HTTP status code. */+ val statusCode: Int,+ message: String = "Server unavailable (status: $statusCode)",+ cause: Throwable? = null,+ ) : VaultSyncError(message, cause)++ /**+ * Error indicating network error.+ */+ class NetworkError(+ /** The underlying error. */+ val underlyingError: Throwable,+ ) : VaultSyncError("Network error: ${underlyingError.message}", underlyingError)++ /**+ * Error indicating request timeout.+ */+ class Timeout(+ message: String = "Request timeout",+ cause: Throwable? = null,+ ) : VaultSyncError(message, cause)// Version/compatibility errors- class ClientVersionNotSupported(message: String = "Client version not supported") : VaultSyncError(message)- class ServerVersionNotSupported(message: String = "Server version not supported") : VaultSyncError(message)- class VaultVersionIncompatible(message: String = "Vault version incompatible") : VaultSyncError(message)+ /**+ * Error indicating client version not supported.+ */+ class ClientVersionNotSupported(+ message: String = "Client version not supported",+ cause: Throwable? = null,+ ) : VaultSyncError(message, cause)++ /**+ * Error indicating server version not supported.+ */+ class ServerVersionNotSupported(+ message: String = "Server version not supported",+ cause: Throwable? = null,+ ) : VaultSyncError(message, cause)++ /**+ * Error indicating vault version incompatible.+ */+ class VaultVersionIncompatible(+ message: String = "Vault version incompatible",+ cause: Throwable? = null,+ ) : VaultSyncError(message, cause)// Vault status errors- class VaultMergeRequired(message: String = "Vault merge required") : VaultSyncError(message)- class VaultOutdated(message: String = "Vault outdated") : VaultSyncError(message)+ /**+ * Error indicating vault merge required.+ */+ class VaultMergeRequired(+ message: String = "Vault merge required",+ cause: Throwable? = null,+ ) : VaultSyncError(message, cause)++ /**+ * Error indicating vault outdated.+ */+ class VaultOutdated(+ message: String = "Vault outdated",+ cause: Throwable? = null,+ ) : VaultSyncError(message, cause)// Decryption errors- class VaultDecryptFailed(message: String = "Failed to decrypt vault") : VaultSyncError(message)+ /**+ * Error indicating failed to decrypt vault.+ */+ class VaultDecryptFailed(+ message: String = "Failed to decrypt vault",+ cause: Throwable? = null,+ ) : VaultSyncError(message, cause)// Generic errors- class UnknownError(message: String) : VaultSyncError("Unknown error: $message")- class ParseError(message: String) : VaultSyncError("Parse error: $message")+ /**+ * Error indicating unknown error.+ */+ class UnknownError(+ message: String,+ cause: Throwable? = null,+ ) : VaultSyncError("Unknown error: $message", cause)++ /**+ * Error indicating parse error.+ */+ class ParseError(+ message: String,+ cause: Throwable? = null,+ ) : VaultSyncError("Parse error: $message", cause)/**- * Get the error code string for React Native bridge+ * Get the error code string for React Native bridge.*/val code: Stringget() = when (this) {diff --git a/apps/mobile-app/android/app/src/main/java/net/aliasvault/app/vaultstore/models/Passkey.kt b/apps/mobile-app/android/app/src/main/java/net/aliasvault/app/vaultstore/models/Passkey.ktindex 3ab684a7c..b9d4383a6 100644--- a/apps/mobile-app/android/app/src/main/java/net/aliasvault/app/vaultstore/models/Passkey.kt+++ b/apps/mobile-app/android/app/src/main/java/net/aliasvault/app/vaultstore/models/Passkey.kt@@ -4,70 +4,70 @@ import java.util.Dateimport java.util.UUID/**- * Passkey model representing a WebAuthn credential- * Linked to a parent Credential for UI display (service name, logo, etc.)+ * Passkey model representing a WebAuthn credential.+ * Linked to a parent Credential for UI display (service name, logo, etc.).** This is a Kotlin port of the iOS Swift implementation:* - Reference: apps/mobile-app/ios/VaultModels/Passkey.swift*/data class Passkey(/**- * Passkey record ID which is also the WebAuthn credential ID+ * Passkey record ID which is also the WebAuthn credential ID.*/val id: UUID,/**- * Parent Credential UUID (AliasVault internal ID)+ * Parent Credential UUID (AliasVault internal ID).*/val parentCredentialId: UUID,/**- * Relying party identifier (domain)+ * Relying party identifier (domain).*/val rpId: String,/**- * User ID/handle from RP (optional)+ * User ID/handle from RP (optional).*/val userHandle: ByteArray?,/**- * User-visible identifier (typically email)+ * User-visible identifier (typically email).*/val userName: String?,/**- * JWK format (JSON), encrypted in storage+ * JWK format (JSON), encrypted in storage.*/val publicKey: ByteArray,/**- * JWK format (JSON), encrypted in storage+ * JWK format (JSON), encrypted in storage.*/val privateKey: ByteArray,/**- * PRF secret (32 bytes) if extension enabled+ * PRF secret (32 bytes) if extension enabled.*/val prfKey: ByteArray?,/**- * User-facing name for this passkey+ * User-facing name for this passkey.*/val displayName: String,/**- * The creation date of the passkey+ * The creation date of the passkey.*/val createdAt: Date,/**- * The update date of the passkey+ * The update date of the passkey.*/val updatedAt: Date,/**- * Whether the passkey is deleted+ * Whether the passkey is deleted.*/val isDeleted: Boolean,) {diff --git a/apps/mobile-app/android/app/src/main/java/net/aliasvault/app/vaultstore/passkey/PasskeyAuthenticator.kt b/apps/mobile-app/android/app/src/main/java/net/aliasvault/app/vaultstore/passkey/PasskeyAuthenticator.ktindex 9542619a2..cb83aae5f 100644--- a/apps/mobile-app/android/app/src/main/java/net/aliasvault/app/vaultstore/passkey/PasskeyAuthenticator.kt+++ b/apps/mobile-app/android/app/src/main/java/net/aliasvault/app/vaultstore/passkey/PasskeyAuthenticator.kt@@ -1,5 +1,6 @@package net.aliasvault.app.vaultstore.passkey+import net.aliasvault.app.utils.Helpersimport org.json.JSONObjectimport java.security.KeyPairGeneratorimport java.security.MessageDigest@@ -36,7 +37,7 @@ import javax.crypto.spec.SecretKeySpec*/object PasskeyAuthenticator {- /** AliasVault AAGUID: a11a5vau-9f32-4b8c-8c5d-2f7d13e8c942 */+ /** AliasVault AAGUID: a11a5vau-9f32-4b8c-8c5d-2f7d13e8c942. */private val AAGUID = byteArrayOf(0xa1.toByte(), 0x1a, 0x5f, 0xaa.toByte(), 0x9f.toByte(), 0x32, 0x4b, 0x8c.toByte(),0x8c.toByte(), 0x5d, 0x2f, 0x7d, 0x13, 0xe8.toByte(), 0xc9.toByte(), 0x42,@@ -45,14 +46,13 @@ object PasskeyAuthenticator {// MARK: - Public API/**- * Create a new passkey (registration)- * Returns credential data ready for Android to return to the RP, plus storage data+ * Create a new passkey (registration).+ * Returns credential data ready for Android to return to the RP, plus storage data.*/@JvmStatic@Suppress("LongParameterList")fun createPasskey(credentialId: ByteArray,- clientDataHash: ByteArray,rpId: String,userId: ByteArray?,userName: String?,@@ -135,8 +135,8 @@ object PasskeyAuthenticator {}/**- * Create an assertion (authentication)- * Returns assertion data ready for Android to return to the RP+ * Create an assertion (authentication).+ * Returns assertion data ready for Android to return to the RP.*/@JvmStatic@Suppress("LongParameterList")@@ -202,7 +202,7 @@ object PasskeyAuthenticator {// MARK: - Key Management/**- * Export public key as JWK format (JSON)+ * Export public key as JWK format (JSON).*/private fun exportPublicKeyAsJWK(publicKey: ECPublicKey): ByteArray {val w = publicKey.w@@ -220,8 +220,8 @@ object PasskeyAuthenticator {}/**- * Export private key as JWK format (JSON)- * Note: We need the KeyPair to properly export both public and private components+ * Export private key as JWK format (JSON).+ * Note: We need the KeyPair to properly export both public and private components.*/private fun exportPrivateKeyAsJWK(privateKey: ECPrivateKey, publicKey: ECPublicKey): ByteArray {val w = publicKey.w@@ -241,8 +241,8 @@ object PasskeyAuthenticator {}/**- * Import private key from JWK format- * Uses ECPrivateKeySpec to avoid Android Keystore issues+ * Import private key from JWK format.+ * Uses ECPrivateKeySpec to avoid Android Keystore issues.*/private fun importPrivateKeyFromJWK(jwkData: ByteArray): ECPrivateKey {val jwkString = String(jwkData, Charsets.UTF_8)@@ -253,7 +253,7 @@ object PasskeyAuthenticator {?: throw PasskeyError.InvalidJWK("Missing 'd' parameter in JWK")// Decode base64url to bytes- val dBytes = base64urlToBytes(dBase64url)+ val dBytes = Helpers.base64urlDecode(dBase64url)// Convert to BigInteger (d parameter is the private key value)val d = java.math.BigInteger(1, dBytes)@@ -272,28 +272,11 @@ object PasskeyAuthenticator {return keyFactory.generatePrivate(privKeySpec) as ECPrivateKey}- /**- * Decode base64url string to bytes- */- private fun base64urlToBytes(base64url: String): ByteArray {- var base64 = base64url- .replace('-', '+')- .replace('_', '/')-- // Add padding if needed- val remainder = base64.length % 4- if (remainder > 0) {- base64 += "=".repeat(4 - remainder)- }-- return android.util.Base64.decode(base64, android.util.Base64.NO_WRAP)- }-// MARK: - CBOR Encoding/**- * Build COSE EC2 public key for ES256- * CBOR map: {1: 2, 3: -7, -1: 1, -2: x, -3: y}+ * Build COSE EC2 public key for ES256.+ * CBOR map: {1: 2, 3: -7, -1: 1, -2: x, -3: y}.*/private fun buildCoseEc2Es256(publicKey: ECPublicKey): ByteArray {val w = publicKey.w@@ -312,8 +295,8 @@ object PasskeyAuthenticator {}/**- * Build attestation object with "none" format- * CBOR map: {fmt: "none", attStmt: {}, authData: <bytes>}+ * Build attestation object with "none" format.+ * CBOR map: {fmt: "none", attStmt: {}, authData: <bytes>}.*/private fun buildAttestationObjectNone(authenticatorData: ByteArray): ByteArray {return byteArrayOf(@@ -328,7 +311,7 @@ object PasskeyAuthenticator {}/**- * Encode a string as CBOR text+ * Encode a string as CBOR text.*/private fun cborText(text: String): ByteArray {val bytes = text.toByteArray(Charsets.UTF_8)@@ -344,7 +327,7 @@ object PasskeyAuthenticator {}/**- * Encode bytes as CBOR byte string+ * Encode bytes as CBOR byte string.*/private fun cborBytes(bytes: ByteArray): ByteArray {return when {@@ -361,8 +344,8 @@ object PasskeyAuthenticator {// MARK: - PRF Extension/**- * Evaluate PRF (hmac-secret extension)- * Implements: HMAC-SHA256(prfSecret, SHA-256("WebAuthn PRF\x00" || salt))+ * Evaluate PRF (hmac-secret extension).+ * Implements: HMAC-SHA256(prfSecret, SHA-256("WebAuthn PRF\x00" || salt)).*/private fun evaluatePrf(secret: ByteArray, salt: ByteArray): ByteArray {// Step 1: Domain separation - hash salt with "WebAuthn PRF\x00" prefix@@ -398,18 +381,33 @@ object PasskeyAuthenticator {// MARK: - Supporting Types+ /**+ * Result of passkey creation containing all data needed for registration and storage.+ */data class PasskeyCreationResult(+ /** The unique credential identifier. */val credentialId: ByteArray,+ /** The authenticator data bytes. */val authenticatorData: ByteArray,+ /** The attestation object in CBOR format. */val attestationObject: ByteArray,- val publicKey: ByteArray, // JWK format- val publicKeyDER: ByteArray, // DER/SPKI format for Chrome- val privateKey: ByteArray, // JWK format+ /** The public key in JWK format. */+ val publicKey: ByteArray,+ /** The public key in DER/SPKI format for Chrome. */+ val publicKeyDER: ByteArray,+ /** The private key in JWK format. */+ val privateKey: ByteArray,+ /** The relying party identifier. */val rpId: String,+ /** The user identifier. */val userId: ByteArray?,+ /** The username. */val userName: String?,+ /** The user display name. */val userDisplayName: String?,+ /** The PRF secret for hmac-secret extension. */val prfSecret: ByteArray?,+ /** The PRF evaluation results if requested. */val prfResults: PrfResults?,) {override fun equals(other: Any?): Boolean {@@ -457,11 +455,19 @@ object PasskeyAuthenticator {}}+ /**+ * Result of passkey assertion containing authentication data.+ */data class PasskeyAssertionResult(+ /** The credential identifier. */val credentialId: ByteArray,+ /** The authenticator data bytes. */val authenticatorData: ByteArray,+ /** The signature in DER format. */val signature: ByteArray,+ /** The user handle. */val userHandle: ByteArray?,+ /** The PRF evaluation results if requested. */val prfResults: PrfResults?,) {override fun equals(other: Any?): Boolean {@@ -492,8 +498,13 @@ object PasskeyAuthenticator {}}+ /**+ * PRF extension input values for evaluation.+ */data class PrfInputs(+ /** The first PRF input salt. */val first: ByteArray?,+ /** The optional second PRF input salt. */val second: ByteArray?,) {override fun equals(other: Any?): Boolean {@@ -521,8 +532,13 @@ object PasskeyAuthenticator {}}+ /**+ * PRF extension evaluation results.+ */data class PrfResults(+ /** The first PRF output. */val first: ByteArray,+ /** The optional second PRF output. */val second: ByteArray?,) {override fun equals(other: Any?): Boolean {@@ -547,11 +563,33 @@ object PasskeyAuthenticator {}}+ /**+ * Base class for passkey-related errors.+ */sealed class PasskeyError(message: String) : Exception(message) {+ /**+ * Error indicating an invalid public key.+ */class InvalidPublicKey(message: String) : PasskeyError(message)++ /**+ * Error indicating an invalid private key.+ */class InvalidPrivateKey(message: String) : PasskeyError(message)++ /**+ * Error indicating an invalid JWK format.+ */class InvalidJWK(message: String) : PasskeyError(message)++ /**+ * Error indicating an invalid signature.+ */class InvalidSignature(message: String) : PasskeyError(message)++ /**+ * Error indicating CBOR encoding failure.+ */class CborEncodingFailed(message: String) : PasskeyError(message)}}diff --git a/apps/mobile-app/android/app/src/main/java/net/aliasvault/app/vaultstore/passkey/PasskeyHelper.kt b/apps/mobile-app/android/app/src/main/java/net/aliasvault/app/vaultstore/passkey/PasskeyHelper.ktindex 7e8fc22c1..2b0dba79b 100644--- a/apps/mobile-app/android/app/src/main/java/net/aliasvault/app/vaultstore/passkey/PasskeyHelper.kt+++ b/apps/mobile-app/android/app/src/main/java/net/aliasvault/app/vaultstore/passkey/PasskeyHelper.kt@@ -15,8 +15,8 @@ package net.aliasvault.app.vaultstore.passkeyobject PasskeyHelper {/**- * Convert GUID string to byte array- * Example: "3f2504e0-4f89-11d3-9a0c-0305e82c3301" → ByteArray(16 bytes)+ * Convert GUID string to byte array.+ * Example: "3f2504e0-4f89-11d3-9a0c-0305e82c3301" → ByteArray(16 bytes).*/@JvmStaticfun guidToBytes(guid: String): ByteArray {@@ -33,8 +33,8 @@ object PasskeyHelper {}/**- * Convert byte array to GUID string (uppercase)- * Example: ByteArray(16 bytes) → "3F2504E0-4F89-11D3-9A0C-0305E82C3301"+ * Convert byte array to GUID string (uppercase).+ * Example: ByteArray(16 bytes) → "3F2504E0-4F89-11D3-9A0C-0305E82C3301".*/@JvmStaticfun bytesToGuid(bytes: ByteArray): String {@@ -57,8 +57,8 @@ object PasskeyHelper {}/**- * Convert byte array to Base64URL encoding- * Base64URL uses - instead of + and _ instead of /, and omits padding+ * Convert byte array to Base64URL encoding.+ * Base64URL uses - instead of + and _ instead of /, and omits padding.*/@JvmStaticfun bytesToBase64url(bytes: ByteArray): String {diff --git a/apps/mobile-app/android/app/src/main/java/net/aliasvault/app/webapi/WebApiService.kt b/apps/mobile-app/android/app/src/main/java/net/aliasvault/app/webapi/WebApiService.ktindex 8dccee886..dbc7abf56 100644--- a/apps/mobile-app/android/app/src/main/java/net/aliasvault/app/webapi/WebApiService.kt+++ b/apps/mobile-app/android/app/src/main/java/net/aliasvault/app/webapi/WebApiService.kt@@ -13,11 +13,14 @@ import java.net.HttpURLConnectionimport java.net.URL/**- * Response object from a WebAPI request containing status code, body, and headers+ * Response object from a WebAPI request containing status code, body, and headers.*/data class WebApiResponse(+ /** The HTTP status code of the response. */val statusCode: Int,+ /** The response body as a string. */val body: String,+ /** The response headers as a map of key-value pairs. */val headers: Map<String, String>,)@@ -40,21 +43,21 @@ class WebApiService(private val context: Context) {// MARK: - Configuration Management/**- * Set the API URL+ * Set the API URL.*/fun setApiUrl(url: String) {sharedPreferences.edit().putString(API_URL_KEY, url).apply()}/**- * Get the API URL+ * Get the API URL.*/fun getApiUrl(): String {return sharedPreferences.getString(API_URL_KEY, DEFAULT_API_URL) ?: DEFAULT_API_URL}/**- * Get the base URL with /v1/ appended+ * Get the base URL with /v1/ appended.*/private fun getBaseUrl(): String {val apiUrl = getApiUrl()@@ -65,7 +68,7 @@ class WebApiService(private val context: Context) {// MARK: - Token Management/**- * Set both access and refresh tokens+ * Set both access and refresh tokens.*/fun setAuthTokens(accessToken: String, refreshToken: String) {sharedPreferences.edit()@@ -75,21 +78,21 @@ class WebApiService(private val context: Context) {}/**- * Get the access token+ * Get the access token.*/fun getAccessToken(): String? {return sharedPreferences.getString(ACCESS_TOKEN_KEY, null)}/**- * Get the refresh token+ * Get the refresh token.*/private fun getRefreshToken(): String? {return sharedPreferences.getString(REFRESH_TOKEN_KEY, null)}/**- * Clear both access and refresh tokens+ * Clear both access and refresh tokens.*/fun clearAuthTokens() {sharedPreferences.edit()@@ -101,7 +104,7 @@ class WebApiService(private val context: Context) {// MARK: - HTTP Request Execution/**- * Execute a WebAPI request with support for authentication and token refresh+ * Execute a WebAPI request with support for authentication and token refresh.*/suspend fun executeRequest(method: String,@@ -163,7 +166,7 @@ class WebApiService(private val context: Context) {}/**- * Execute a raw HTTP request without token refresh logic+ * Execute a raw HTTP request without token refresh logic.*/private suspend fun executeRawRequest(method: String,@@ -174,8 +177,6 @@ class WebApiService(private val context: Context) {val baseUrl = getBaseUrl()val urlString = "$baseUrl$endpoint"- Log.d(TAG, "Executing $method request to $urlString")-var connection: HttpURLConnection? = nulltry {val url = URL(urlString)@@ -226,8 +227,6 @@ class WebApiService(private val context: Context) {}}- Log.d(TAG, "Response status: $statusCode")-WebApiResponse(statusCode = statusCode,body = responseBody,@@ -242,7 +241,7 @@ class WebApiService(private val context: Context) {}/**- * Refresh the access token using the refresh token+ * Refresh the access token using the refresh token.*/private suspend fun refreshAccessToken(): String? = withContext(Dispatchers.IO) {val refreshToken = getRefreshToken()@@ -289,8 +288,6 @@ class WebApiService(private val context: Context) {// Update stored tokenssetAuthTokens(accessToken = newToken, refreshToken = newRefreshToken)-- Log.d(TAG, "Token refresh successful")newToken} catch (e: Exception) {Log.e(TAG, "Token refresh failed", e)@@ -301,7 +298,7 @@ class WebApiService(private val context: Context) {// MARK: - Helper Methods/**- * Get the client version header value+ * Get the client version header value.*/private fun getClientVersionHeader(): String {return try {@@ -316,8 +313,8 @@ class WebApiService(private val context: Context) {}/**- * Extract favicon from a website URL- * Returns the favicon image as a byte array, or null if extraction fails+ * Extract favicon from a website URL.+ * Returns the favicon image as a byte array, or null if extraction fails.*/suspend fun extractFavicon(url: String): ByteArray? = withContext(Dispatchers.IO) {try {@@ -360,7 +357,7 @@ class WebApiService(private val context: Context) {// MARK: - Token Revocation/**- * Revoke tokens via WebAPI (called when logging out)+ * Revoke tokens via WebAPI (called when logging out).*/suspend fun revokeTokens() = withContext(Dispatchers.IO) {try {diff --git a/apps/mobile-app/android/detekt.yml b/apps/mobile-app/android/detekt.ymlindex 87b447a8a..ac793efe4 100644--- a/apps/mobile-app/android/detekt.yml+++ b/apps/mobile-app/android/detekt.yml@@ -14,19 +14,22 @@ complexity:constructorThreshold: 6TooManyFunctions:active: true- thresholdInFiles: 40- thresholdInClasses: 40- thresholdInInterfaces: 40- thresholdInObjects: 40+ thresholdInFiles: 60+ thresholdInClasses: 60+ thresholdInInterfaces: 60+ thresholdInObjects: 60CyclomaticComplexMethod:active: true- threshold: 26+ threshold: 30NestedBlockDepth:active: truethreshold: 5LongMethod:active: true- threshold: 120+ threshold: 170+ LargeClass:+ active: true+ threshold: 1600ComplexCondition:active: truethreshold: 6@@ -48,13 +51,19 @@ style:maxLineLength: 160ReturnCount:active: true- max: 6+ max: 8MagicNumber:active: falseThrowsCount:active: true- max: 3+ max: 8exceptions:TooGenericExceptionCaught:- active: false\ No newline at end of file+ active: false+ TooGenericExceptionThrown:+ active: true+ exceptionNames:+ - Throwable+ - Error+ - RuntimeExceptiondiff --git a/apps/mobile-app/hooks/useVaultMutate.ts b/apps/mobile-app/hooks/useVaultMutate.tsindex 407b16b10..a17ea20e8 100644--- a/apps/mobile-app/hooks/useVaultMutate.ts+++ b/apps/mobile-app/hooks/useVaultMutate.ts@@ -46,7 +46,6 @@ export function useVaultMutate() : {/*** Prepare vault for password change operation.- * TODO: Move this to native layer as well when implementing native password change support.*/const prepareVaultForPasswordChange = useCallback(async (): Promise<Vault> => {const currentRevision = await NativeVaultManager.getCurrentVaultRevisionNumber();