Modern Apps git

← Modern-Apps.git

password: add totp codes

Commit
74b3ecf93ce18ed89fc5f6875ad7f4615fa39cfa
Author
Vayun <[email protected]>
When
2026-01-16 02:58 UTC (10 months ago)
Parents
b6d79ab

Diff

passwords/src/main/java/com/vayunmathur/passwords/ui/PasswordEditPage.kt
diff --git a/passwords/src/main/java/com/vayunmathur/passwords/ui/PasswordEditPage.kt b/passwords/src/main/java/com/vayunmathur/passwords/ui/PasswordEditPage.ktindex 6229b62dfc..47c304297a 100644--- a/passwords/src/main/java/com/vayunmathur/passwords/ui/PasswordEditPage.kt+++ b/passwords/src/main/java/com/vayunmathur/passwords/ui/PasswordEditPage.kt@@ -4,10 +4,14 @@ import androidx.compose.foundation.horizontalScroll import androidx.compose.foundation.layout.* import androidx.compose.foundation.rememberScrollState import androidx.compose.foundation.shape.RoundedCornerShape+import androidx.compose.foundation.text.KeyboardActions import androidx.compose.foundation.text.KeyboardOptions import androidx.compose.material3.* import androidx.compose.runtime.*+import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier+import androidx.compose.ui.platform.LocalFocusManager+import androidx.compose.ui.text.input.ImeAction import androidx.compose.ui.unit.dp import androidx.navigation3.runtime.NavBackStack import com.vayunmathur.library.ui.IconNavigation@@ -27,11 +31,22 @@ fun PasswordEditPage(backStack: NavBackStack<Route>, id: Long, viewModel: Databa     var userId by remember { mutableStateOf(pass.userId) }     var password by remember { mutableStateOf(pass.password) }     var totp by remember { mutableStateOf(pass.totpSecret ?: "") }-    var websitesText by remember { mutableStateOf(pass.websites.joinToString(",")) }+    // websites: maintain list and an input box for new site+    val websitesList = remember { mutableStateListOf<String>().apply { addAll(pass.websites) } }+    var websiteInput by remember { mutableStateOf("") }     var showPassword by remember { mutableStateOf(false) }      val snackbarHostState = remember { SnackbarHostState() }     val scope = rememberCoroutineScope()+    val focusManager = LocalFocusManager.current++    fun addWebsiteFromInput() {+        val candidate = websiteInput.trim()+        if (candidate.isNotEmpty() && !websitesList.contains(candidate)) {+            websitesList.add(candidate)+        }+        websiteInput = ""+    }      Scaffold(         topBar = {@@ -52,13 +67,12 @@ fun PasswordEditPage(backStack: NavBackStack<Route>, id: Long, viewModel: Databa                     return@FloatingActionButton                 } -                val websites = websitesText.split(',').map { it.trim() }.filter { it.isNotEmpty() }                 val newPass = pass.copy(                     name = name,                     userId = userId,                     password = password,                     totpSecret = totp.ifBlank { null },-                    websites = websites+                    websites = websitesList.toList()                 )                  if (pass.isNew()) {@@ -103,16 +117,38 @@ fun PasswordEditPage(backStack: NavBackStack<Route>, id: Long, viewModel: Databa              Card(shape = RoundedCornerShape(10.dp), modifier = Modifier.fillMaxWidth()) {                 Column(Modifier.padding(12.dp), verticalArrangement = Arrangement.spacedBy(8.dp)) {-                    OutlinedTextField(value = websitesText, onValueChange = { websitesText = it }, label = { Text("Websites (comma-separated)") }, modifier = Modifier.fillMaxWidth())+                    // Input for websites: pressing IME Done (Enter) adds to list+                    OutlinedTextField(+                        value = websiteInput,+                        onValueChange = { websiteInput = it },+                        label = { Text("Add website") },+                        modifier = Modifier.fillMaxWidth(),+                        keyboardOptions = KeyboardOptions(imeAction = ImeAction.Done),+                        keyboardActions = KeyboardActions(onDone = {+                            addWebsiteFromInput()+                            focusManager.clearFocus()+                        })+                    ) -                    // websites preview as simple chips (buttons)-                    val websites = websitesText.split(',').map { it.trim() }.filter { it.isNotEmpty() }-                    if (websites.isNotEmpty()) {+                    // websites preview as chips with remove X+                    if (websitesList.isNotEmpty()) {                         Row(Modifier                             .horizontalScroll(rememberScrollState())                             .padding(top = 4.dp), horizontalArrangement = Arrangement.spacedBy(8.dp)) {-                            for (w in websites) {-                                AssistChip(onClick = { /* maybe open or edit site */ }, label = { Text(w) })+                            for ((index, w) in websitesList.withIndex()) {+                                Surface(+                                    tonalElevation = 2.dp,+                                    shape = RoundedCornerShape(16.dp),+                                    modifier = Modifier.padding(vertical = 4.dp)+                                ) {+                                    Row(modifier = Modifier.padding(horizontal = 8.dp, vertical = 6.dp), verticalAlignment = Alignment.CenterVertically) {+                                        Text(w)+                                        Spacer(Modifier.width(8.dp))+                                        TextButton(onClick = { websitesList.removeAt(index) }, modifier = Modifier.size(28.dp)) {+                                            Text("✕")+                                        }+                                    }+                                }                             }                         }                     }
passwords/src/main/java/com/vayunmathur/passwords/ui/PasswordPage.kt
diff --git a/passwords/src/main/java/com/vayunmathur/passwords/ui/PasswordPage.kt b/passwords/src/main/java/com/vayunmathur/passwords/ui/PasswordPage.ktindex 0feb98458b..da0e8f0db1 100644--- a/passwords/src/main/java/com/vayunmathur/passwords/ui/PasswordPage.kt+++ b/passwords/src/main/java/com/vayunmathur/passwords/ui/PasswordPage.kt@@ -3,12 +3,14 @@ package com.vayunmathur.passwords.ui import android.content.ClipData import android.content.ClipboardManager import android.content.Context+import android.content.Intent import androidx.compose.foundation.background import androidx.compose.foundation.clickable import androidx.compose.foundation.layout.* import androidx.compose.foundation.shape.CircleShape import androidx.compose.foundation.shape.RoundedCornerShape import androidx.compose.material3.*+import androidx.compose.material3.CircularProgressIndicator import androidx.compose.runtime.* import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier@@ -19,11 +21,17 @@ import androidx.compose.ui.text.style.TextOverflow import androidx.compose.ui.unit.dp import androidx.navigation3.runtime.NavBackStack import com.vayunmathur.library.ui.IconEdit-import com.vayunmathur.library.ui.IconNavigation import com.vayunmathur.library.util.DatabaseViewModel import com.vayunmathur.passwords.Password import com.vayunmathur.passwords.Route import com.vayunmathur.passwords.R+import androidx.core.net.toUri+import com.vayunmathur.library.ui.IconNavigation+import kotlinx.coroutines.delay+import kotlinx.coroutines.launch+import javax.crypto.Mac+import javax.crypto.spec.SecretKeySpec+import kotlin.math.roundToLong  @OptIn(ExperimentalMaterial3Api::class) @Composable@@ -31,6 +39,9 @@ fun PasswordPage(backStack: NavBackStack<Route>, id: Long, viewModel: DatabaseVi     val password by viewModel.get<Password>(id)     val context = LocalContext.current     var showPassword by remember { mutableStateOf(false) }+    val snackbarHostState = remember { SnackbarHostState() }+    val scope = rememberCoroutineScope()+      Scaffold(         topBar = {@@ -46,6 +57,7 @@ fun PasswordPage(backStack: NavBackStack<Route>, id: Long, viewModel: DatabaseVi                 IconEdit()             }         },+        snackbarHost = { SnackbarHost(hostState = snackbarHostState) }     ) { paddingValues ->         Column(             Modifier@@ -60,6 +72,7 @@ fun PasswordPage(backStack: NavBackStack<Route>, id: Long, viewModel: DatabaseVi                 modifier = Modifier.fillMaxWidth()             ) {                 Row(Modifier.padding(16.dp), verticalAlignment = Alignment.CenterVertically) {+                    // Avatar with initial                     val initial = password.name.firstOrNull()?.uppercaseChar()?.toString() ?: "?"                     Box(                         Modifier@@ -81,7 +94,7 @@ fun PasswordPage(backStack: NavBackStack<Route>, id: Long, viewModel: DatabaseVi                 }             } -            // Password+            // Password card             Card(shape = RoundedCornerShape(8.dp), modifier = Modifier.fillMaxWidth()) {                 Column(Modifier.padding(12.dp)) {                     Text("Password", style = MaterialTheme.typography.titleMedium)@@ -111,12 +124,62 @@ fun PasswordPage(backStack: NavBackStack<Route>, id: Long, viewModel: DatabaseVi                 }             } -            // TOTP+            // TOTP card: show generated code and circular timer             Card(shape = RoundedCornerShape(8.dp), modifier = Modifier.fillMaxWidth()) {                 Column(Modifier.padding(12.dp)) {-                    Text("TOTP Secret", style = MaterialTheme.typography.titleMedium)+                    Text("TOTP", style = MaterialTheme.typography.titleMedium)                     Spacer(Modifier.height(8.dp))-                    Text(password.totpSecret ?: "(not configured)", style = MaterialTheme.typography.bodyMedium)++                    if (password.totpSecret.isNullOrBlank()) {+                        Text("(not configured)")+                    } else {+                        var currentCode by remember { mutableStateOf("") }+                        var progress by remember { mutableFloatStateOf(1f) }+                        var secondsRemaining by remember { mutableIntStateOf(30) }++                        LaunchedEffect(Unit) {+                            while (true) {+                                val nowMs = System.currentTimeMillis()+                                val nowSeconds = nowMs / 1000++                                // 1. Calculate the current 30s bucket (Time Step)+                                val timeStep = nowSeconds / 30++                                // 2. Generate code based on this bucket+                                currentCode = generateTotp(password.totpSecret!!, timeStep*30)++                                // 3. Calculate remaining time in this specific bucket+                                val millisIntoStep = nowMs % 30000+                                val millisRemaining = 30000 - millisIntoStep++                                secondsRemaining = (millisRemaining / 1000).toInt()+                                progress = millisRemaining / 30000f++                                // Tick frequently for a smooth progress bar+                                delay(50)+                            }+                        }++                        Row(verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.SpaceBetween, modifier = Modifier.fillMaxWidth()) {+                            Column {+                                Text(currentCode, style = MaterialTheme.typography.displayMedium)+                                Spacer(Modifier.height(4.dp))+                                Text("Refreshes in ${secondsRemaining} s", style = MaterialTheme.typography.bodySmall)+                            }++                            // Circular progress showing proportion of time remaining+                            Box(contentAlignment = Alignment.Center) {+                                CircularProgressIndicator({ progress }, Modifier.size(56.dp))+                                IconButton(onClick = {+                                    val clipboard = context.getSystemService(Context.CLIPBOARD_SERVICE) as ClipboardManager+                                    clipboard.setPrimaryClip(ClipData.newPlainText("totp", currentCode))+                                    scope.launch { snackbarHostState.showSnackbar("TOTP copied") }+                                }) {+                                    Icon(painterResource(R.drawable.content_copy_24px), contentDescription = "Copy TOTP")+                                }+                            }+                        }+                    }                 }             } @@ -131,7 +194,11 @@ fun PasswordPage(backStack: NavBackStack<Route>, id: Long, viewModel: DatabaseVi                         for (w in password.websites) {                             Row(verticalAlignment = Alignment.CenterVertically, modifier = Modifier                                 .fillMaxWidth()-                                .clickable { /* open link if desired */ }+                                .clickable {+                                    // open link+                                    val intent = Intent(Intent.ACTION_VIEW, w.toUri())+                                    context.startActivity(intent)+                                }                                 .padding(vertical = 6.dp)) {                                 Text(w, modifier = Modifier.weight(1f), style = MaterialTheme.typography.bodyMedium)                                 Icon(painterResource(R.drawable.link_24px), contentDescription = "Open site")@@ -142,4 +209,51 @@ fun PasswordPage(backStack: NavBackStack<Route>, id: Long, viewModel: DatabaseVi             }         }     }-}\ No newline at end of file+}++// TOTP implementation (RFC 6238) using HMAC-SHA1 and 6 digits+private fun base32Decode(data: String): ByteArray {+    val base32Chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZ234567"+    val clean = data.trim().replace("=", "").replace(" ", "").uppercase()+    val output = mutableListOf<Byte>()+    var buffer = 0+    var bitsLeft = 0+    for (c in clean) {+        val valC = base32Chars.indexOf(c)+        if (valC == -1) continue+        buffer = (buffer shl 5) or valC+        bitsLeft += 5+        if (bitsLeft >= 8) {+            bitsLeft -= 8+            output.add(((buffer shr bitsLeft) and 0xFF).toByte())+        }+    }+    return output.toByteArray()+}++private fun hotp(key: ByteArray, counter: Long, digits: Int = 6): String {+    val counterBytes = ByteArray(8)+    var c = counter+    for (i in 7 downTo 0) {+        counterBytes[i] = (c and 0xFF).toByte()+        c = c ushr 8+    }+    val mac = Mac.getInstance("HmacSHA1")+    val keySpec = SecretKeySpec(key, "RAW")+    mac.init(keySpec)+    val hash = mac.doFinal(counterBytes)+    val offset = (hash[hash.size - 1].toInt() and 0x0f)+    val binary = ((hash[offset].toInt() and 0x7f) shl 24) or+            ((hash[offset + 1].toInt() and 0xff) shl 16) or+            ((hash[offset + 2].toInt() and 0xff) shl 8) or+            (hash[offset + 3].toInt() and 0xff)+    val otp = binary % Math.pow(10.0, digits.toDouble()).toInt()+    return otp.toString().padStart(digits, '0')+}++private fun generateTotp(secret: String, epochSecond: Long): String {+    val key = base32Decode(secret)+    val timeStep = 30L+    val counter = epochSecond / timeStep+    return hotp(key, counter, 6)+}