From 12f08698ad368ffa19af65104654568d313a39e4 Mon Sep 17 00:00:00 2001 From: Matt Hills Date: Sun, 1 Nov 2026 09:17:18 -0500 Subject: [PATCH] Don't lock the locker while it's empty An empty locker (no documents and no folders) now opens straight away instead of showing the locked screen, on first use and after auto-lock. The catalog records a plaintext empty flag next to its ciphertext so this can be decided without the auth-bound key; nothing is decrypted on the flag's word, and catalogs from before the flag stay locked until saved. Showing the empty locker isn't an unlock: saving the first document or creating the first folder asks for fingerprint / PIN at that moment, and transfers, imports, exports and settings still ask first as before. Lock now is hidden and the auto-lock notification skipped while there's nothing to lock. --- .../com/mattintech/papercase/MainActivity.kt | 54 +++++++++++++++++-- .../com/mattintech/papercase/PapercaseApp.kt | 3 ++ .../papercase/auth/SessionManager.kt | 26 +++++++-- .../repository/SecureLockerRepository.kt | 36 +++++++++++++ .../locker/ui/AddDocumentActivity.kt | 17 ++++-- .../papercase/locker/ui/LockerActions.kt | 26 +++++++-- .../papercase/locker/ui/crop/CropActivity.kt | 2 +- .../papercase/auth/SessionManagerTest.kt | 52 ++++++++++++++++++ .../locker/repository/CatalogEmptyFlagTest.kt | 33 ++++++++++++ 9 files changed, 233 insertions(+), 16 deletions(-) create mode 100644 app/src/test/java/com/mattintech/papercase/locker/repository/CatalogEmptyFlagTest.kt diff --git a/app/src/main/java/com/mattintech/papercase/MainActivity.kt b/app/src/main/java/com/mattintech/papercase/MainActivity.kt index 0a929ad..631592b 100644 --- a/app/src/main/java/com/mattintech/papercase/MainActivity.kt +++ b/app/src/main/java/com/mattintech/papercase/MainActivity.kt @@ -356,6 +356,17 @@ class MainActivity : AppCompatActivity() { private fun getSessionTimeoutMs(): Long = prefs.lockerTimeoutMinutes * 60 * 1000L + /** A real unlock this session, so the locker key is usable. */ + private fun hasUnlockedSession(): Boolean = + isLockerUnlocked || SessionManager.isSessionValid(getSessionTimeoutMs()) + + /** + * Nothing in the locker, so it opens without asking to unlock. A document waiting to be opened + * (e.g. from a reminder) means there is something after all, so that still asks. + */ + private fun opensWithoutUnlock(): Boolean = + pendingOpenDocumentId == null && lockerRepository.isKnownEmpty() + override fun onNewIntent(intent: android.content.Intent) { super.onNewIntent(intent) setIntent(intent) @@ -371,11 +382,13 @@ class MainActivity : AppCompatActivity() { pendingOpenDocumentId = id if (isLockerUnlocked && binding.layoutLockerContent.visibility == View.VISIBLE) { openPendingDocument() - } else if (appAlreadyOpen) { + } else if (appAlreadyOpen || binding.layoutLockerContent.visibility == View.VISIBLE) { + // (Also when a fresh start opened a seemingly empty locker without unlocking: the + // document says otherwise, so ask now) binding.bottomNavigation.menu.findItem(R.id.nav_locker)?.isChecked = true showLockerTab(promptIfLocked = true) } - // On a fresh start the locker tab is already showing and asking to unlock + // On a fresh start the locker tab is otherwise already showing and asking to unlock return } @@ -877,6 +890,12 @@ class MainActivity : AppCompatActivity() { return } + // Empty locker: nothing to protect yet. Adding the first document or folder asks to unlock then. + if (opensWithoutUnlock()) { + displayLockerTab() + return + } + // No biometric / screen lock on this device: nothing to unlock with if (BiometricAuthHelper.checkBiometricAvailability(this) !is BiometricAuthHelper.BiometricStatus.Ready) { SessionManager.markAuthenticated() @@ -894,7 +913,11 @@ class MainActivity : AppCompatActivity() { val popup = androidx.appcompat.widget.PopupMenu(this, anchor) popup.menuInflater.inflate(R.menu.menu_toolbar_settings, popup.menu) popup.setForceShowIcon(true) - popup.menu.findItem(R.id.action_lock).isEnabled = isLockerUnlocked + popup.menu.findItem(R.id.action_lock).apply { + isEnabled = isLockerUnlocked + // An empty locker is never shown locked, so there's nothing to lock + isVisible = !lockerRepository.isKnownEmpty() + } popup.setOnMenuItemClickListener { item -> when (item.itemId) { R.id.action_transfer -> withLockerUnlocked("Unlock to transfer or back up") { showVaultTransferOptions() } @@ -935,7 +958,8 @@ class MainActivity : AppCompatActivity() { folders = emptyList() lockerAdapter.submitList(emptyList()) thumbnailLoader.clear() - if (binding.layoutSecureLocker.visibility == View.VISIBLE) showLockedLocker() + if (binding.layoutSecureLocker.visibility != View.VISIBLE) return + if (opensWithoutUnlock()) displayLockerTab() else showLockedLocker() } private fun promptLockerUnlock() { @@ -962,6 +986,12 @@ class MainActivity : AppCompatActivity() { binding.fabAddDocument.show() binding.tvToolbarTitle.text = "Locker" applyLockerLayout() + if (!hasUnlockedSession()) { + // Empty locker shown without an unlock: the key isn't usable, and there's nothing to + // decrypt, migrate or back up yet + loadSecureLockerDocuments() + return + } migrateLockerKeyIfNeeded() // The locker key is usable right now: bring the automatic backup snapshot up to date lifecycleScope.launch { AutoBackupManager.refreshIfNeeded(this@MainActivity) } @@ -1010,7 +1040,9 @@ class MainActivity : AppCompatActivity() { private fun handleLockerLocked() { lockLockerInPlace() - Toast.makeText(this, "Locker locked. Unlock again to continue.", Toast.LENGTH_SHORT).show() + if (!lockerRepository.isKnownEmpty()) { + Toast.makeText(this, "Locker locked. Unlock again to continue.", Toast.LENGTH_SHORT).show() + } } private fun showLockerKeyLostDialog() { @@ -1036,6 +1068,18 @@ class MainActivity : AppCompatActivity() { private fun loadSecureLockerDocuments() { lifecycleScope.launch { + if (!hasUnlockedSession() && lockerRepository.isKnownEmpty()) { + // Nothing to show, and reading the catalog would need an unlock + if (lockerRepository.isKeyLost()) { + // Android deleted the key (e.g. the screen lock was removed). Nothing was stored + // with it, so start a fresh locker instead of failing on the first save. + lockerRepository.resetAfterKeyLoss() + } + allDocuments = emptyList() + folders = emptyList() + renderLocker() + return@launch + } allDocuments = try { folders = lockerRepository.getFolders() lockerRepository.getAllDocuments() diff --git a/app/src/main/java/com/mattintech/papercase/PapercaseApp.kt b/app/src/main/java/com/mattintech/papercase/PapercaseApp.kt index f1becce..d3035ac 100644 --- a/app/src/main/java/com/mattintech/papercase/PapercaseApp.kt +++ b/app/src/main/java/com/mattintech/papercase/PapercaseApp.kt @@ -11,6 +11,7 @@ import com.mattintech.papercase.data.PreferencesManager import com.mattintech.papercase.locker.backup.AutoBackupManager import com.mattintech.papercase.locker.backup.DailyWorker import com.mattintech.papercase.locker.reminders.ReminderNotifier +import com.mattintech.papercase.locker.repository.SecureLockerRepository class PapercaseApp : Application() { @@ -29,6 +30,8 @@ class PapercaseApp : Application() { ClipboardSecurityManager.createNotificationChannel(this) ReminderNotifier.createChannel(this) SessionManager.init(this) + val lockerRepository = SecureLockerRepository(this) + SessionManager.isLockerEmpty = { lockerRepository.isKnownEmpty() } DailyWorker.schedule(this) getSharedPreferences(PreferencesManager.NAME, MODE_PRIVATE).registerOnSharedPreferenceChangeListener(settingsListener) diff --git a/app/src/main/java/com/mattintech/papercase/auth/SessionManager.kt b/app/src/main/java/com/mattintech/papercase/auth/SessionManager.kt index 0f1429b..ef875e4 100644 --- a/app/src/main/java/com/mattintech/papercase/auth/SessionManager.kt +++ b/app/src/main/java/com/mattintech/papercase/auth/SessionManager.kt @@ -53,6 +53,20 @@ object SessionManager { } } + /** + * Whether the locker has no documents or folders. An empty locker is never shown as locked, and + * locking it isn't announced. Set by PapercaseApp; defaults to not empty so nothing opens by mistake. + */ + var isLockerEmpty: () -> Boolean = { false } + + /** + * True when the locker can be shown without asking to unlock: after a recent unlock, or when + * there's nothing in it. This doesn't make the locker key usable; saving into an empty locker + * still needs an unlock first (see [isSessionValid]). + */ + fun canShowLocker(timeoutMs: Long = DEFAULT_TIMEOUT_MS): Boolean = + isSessionValid(timeoutMs) || isLockerEmpty() + private var isInForeground: Boolean = true private var backgroundTimestamp: Long = 0L private var appContext: Context? = null @@ -132,8 +146,7 @@ object SessionManager { if (backgroundTimestamp > 0L) { val elapsedInBackground = timeProvider() - backgroundTimestamp if (lastAuthTime > 0L && elapsedInBackground >= BACKGROUND_INACTIVITY_TIMEOUT_MS) { - lock() - appContext?.let { notifyLockerLocked(it) } + lockDueToInactivity() } backgroundTimestamp = 0L } @@ -161,11 +174,16 @@ object SessionManager { fun checkAndLockDueToInactivity() { if (!isInForeground && lastAuthTime > 0L) { - lock() - appContext?.let { notifyLockerLocked(it) } + lockDueToInactivity() } } + /** Ends the session; only tells the user when there was something to lock away. */ + private fun lockDueToInactivity() { + lock() + if (!isLockerEmpty()) appContext?.let { notifyLockerLocked(it) } + } + fun createNotificationChannel(context: Context) { val manager = context.getSystemService(Context.NOTIFICATION_SERVICE) as? NotificationManager ?: return diff --git a/app/src/main/java/com/mattintech/papercase/locker/repository/SecureLockerRepository.kt b/app/src/main/java/com/mattintech/papercase/locker/repository/SecureLockerRepository.kt index e9b1a63..3f65144 100644 --- a/app/src/main/java/com/mattintech/papercase/locker/repository/SecureLockerRepository.kt +++ b/app/src/main/java/com/mattintech/papercase/locker/repository/SecureLockerRepository.kt @@ -43,6 +43,20 @@ class SecureLockerRepository(private val context: Context) { } return map } + + /** + * Whether a catalog file says the locker has no documents and no folders. The flag sits next to + * the ciphertext so it can be read without the auth-bound key. Catalogs written before the flag + * existed count as not empty, so they stay locked until their next save. + */ + fun isEmptyCatalog(wrapperJson: String?): Boolean { + if (wrapperJson == null) return true + return runCatching { JSONObject(wrapperJson).optBoolean("empty", false) }.getOrDefault(false) + } + + // Last emptiness read, keyed by the catalog's size and time so it's only re-read after a write + @Volatile + private var emptyCache: Triple? = null } private val lockerDir = File(context.filesDir, "locker").apply { if (!exists()) mkdirs() } @@ -78,6 +92,26 @@ class SecureLockerRepository(private val context: Context) { /** True once the locker has been created on this device (even if it's now empty). */ fun exists(): Boolean = catalogFile.exists() + /** + * True when the locker has no documents or folders (or doesn't exist yet), so there's nothing to + * unlock. Read without decrypting. The flag isn't authenticated, but nothing is decrypted on its + * word: a wrong flag only shows an empty list, and saving still needs the key and the real catalog. + */ + fun isKnownEmpty(): Boolean { + if (!catalogFile.exists()) return true + val length = catalogFile.length() + val modified = catalogFile.lastModified() + emptyCache?.let { (l, m, empty) -> if (l == length && m == modified) return empty } + val empty = isEmptyCatalog(runCatching { catalogFile.readText() }.getOrDefault("{}")) + emptyCache = Triple(length, modified, empty) + return empty + } + + /** True when the catalog needs the auth-bound key but Android has deleted it. */ + fun isKeyLost(): Boolean = + catalogKeyVersion() == LockerKeystoreHelper.KEY_VERSION_AUTH_BOUND && + !LockerKeystoreHelper.hasKey(LockerKeystoreHelper.KEY_VERSION_AUTH_BOUND) + /** True when the locker still uses the key that works without authentication. */ fun needsAuthBoundMigration(): Boolean = isDeviceSecure() && catalogKeyVersion() == LockerKeystoreHelper.KEY_VERSION_LEGACY @@ -143,6 +177,8 @@ class SecureLockerRepository(private val context: Context) { put("ciphertext", cipherBase64) put("iv", ivBase64) put("keyVersion", version) + // Readable without the key, so an empty locker can be shown without unlocking + put("empty", catalog.documents.isEmpty() && catalog.folders.isEmpty()) } val tempFile = File(lockerDir, "catalog.enc.tmp") tempFile.writeText(wrapper.toString()) diff --git a/app/src/main/java/com/mattintech/papercase/locker/ui/AddDocumentActivity.kt b/app/src/main/java/com/mattintech/papercase/locker/ui/AddDocumentActivity.kt index c395f57..b7f4ee2 100644 --- a/app/src/main/java/com/mattintech/papercase/locker/ui/AddDocumentActivity.kt +++ b/app/src/main/java/com/mattintech/papercase/locker/ui/AddDocumentActivity.kt @@ -266,7 +266,8 @@ class AddDocumentActivity : AppCompatActivity() { override fun onResume() { super.onResume() - if (!SessionManager.isLockerUnlocked) { + // An empty locker opens without unlocking, so the first document can be filled in before it + if (!SessionManager.canShowLocker()) { finish() } } @@ -931,6 +932,14 @@ class AddDocumentActivity : AppCompatActivity() { val notes = binding.etNotes.text?.toString()?.trim().orEmpty() val docType = getSelectedDocumentType() + // First document in an empty locker: nothing was unlocked yet, and the locker key needs it now + if (!SessionManager.isLockerUnlocked && SessionManager.isLockerEmpty() && + BiometricAuthHelper.getDeviceSecurityLevel(this).isProtected + ) { + unlockAndRetrySave(subtitle = "Confirm it's you to add this document to your locker.") + return + } + binding.btnSaveDocument.isEnabled = false lifecycleScope.launch { @@ -1073,11 +1082,13 @@ class AddDocumentActivity : AppCompatActivity() { } } - private fun unlockAndRetrySave() { + private fun unlockAndRetrySave( + subtitle: String = "The locker locked while you were editing. Your changes are kept." + ) { BiometricAuthHelper.promptGeneralUnlock( activity = this, title = "Unlock to save", - subtitle = "The locker locked while you were editing. Your changes are kept.", + subtitle = subtitle, onSuccess = { SessionManager.markAuthenticated() validateAndSave() diff --git a/app/src/main/java/com/mattintech/papercase/locker/ui/LockerActions.kt b/app/src/main/java/com/mattintech/papercase/locker/ui/LockerActions.kt index fb7167d..18fdb37 100644 --- a/app/src/main/java/com/mattintech/papercase/locker/ui/LockerActions.kt +++ b/app/src/main/java/com/mattintech/papercase/locker/ui/LockerActions.kt @@ -289,13 +289,33 @@ class LockerActions( promptFolderName("New folder", "") { name -> val folder = Folder(name = name, parentId = parentId) // Saved before anything (like a move) uses it, so the two writes don't overlap - launch { - repository.saveFolder(folder) - onCreated(folder) + whenKeyUsable("Confirm it's you to create this folder") { + launch { + repository.saveFolder(folder) + onCreated(folder) + } } } } + /** + * An empty locker is shown without unlocking, so the first folder may be created before the + * locker key is usable. Ask for fingerprint / PIN then; otherwise just carry on. + */ + private fun whenKeyUsable(subtitle: String, action: () -> Unit) { + if (SessionManager.isLockerUnlocked || !BiometricAuthHelper.getDeviceSecurityLevel(activity).isProtected) return action() + BiometricAuthHelper.promptGeneralUnlock( + activity = activity, + title = "Unlock Locker", + subtitle = subtitle, + onSuccess = { + SessionManager.markAuthenticated() + action() + }, + onError = { _, _ -> } + ) + } + private fun promptFolderName(title: String, initial: String, onName: (String) -> Unit) { val input = DialogInput(activity, hint = "Folder name") input.editText.setText(initial) diff --git a/app/src/main/java/com/mattintech/papercase/locker/ui/crop/CropActivity.kt b/app/src/main/java/com/mattintech/papercase/locker/ui/crop/CropActivity.kt index 4460959..3a2c786 100644 --- a/app/src/main/java/com/mattintech/papercase/locker/ui/crop/CropActivity.kt +++ b/app/src/main/java/com/mattintech/papercase/locker/ui/crop/CropActivity.kt @@ -64,7 +64,7 @@ class CropActivity : AppCompatActivity() { override fun onResume() { super.onResume() - if (!SessionManager.isLockerUnlocked) finish() + if (!SessionManager.canShowLocker()) finish() } private fun finishWith(bitmap: Bitmap?) { diff --git a/app/src/test/java/com/mattintech/papercase/auth/SessionManagerTest.kt b/app/src/test/java/com/mattintech/papercase/auth/SessionManagerTest.kt index 4eb554f..b751fe1 100644 --- a/app/src/test/java/com/mattintech/papercase/auth/SessionManagerTest.kt +++ b/app/src/test/java/com/mattintech/papercase/auth/SessionManagerTest.kt @@ -2,6 +2,7 @@ package com.mattintech.papercase.auth import org.junit.Assert.assertFalse import org.junit.Assert.assertTrue +import org.junit.After import org.junit.Before import org.junit.Test @@ -14,6 +15,12 @@ class SessionManagerTest { fakeCurrentTime = 100_000L SessionManager.timeProvider = { fakeCurrentTime } SessionManager.lock() + SessionManager.isLockerEmpty = { false } + } + + @After + fun tearDown() { + SessionManager.isLockerEmpty = { false } } @Test @@ -111,4 +118,49 @@ class SessionManagerTest { SessionManager.keepAlive() assertFalse(SessionManager.isSessionValid()) } + + @Test + fun testLockedLockerWithDocuments_cannotBeShown() { + assertFalse(SessionManager.canShowLocker()) + } + + @Test + fun testEmptyLocker_canBeShownWithoutUnlock() { + SessionManager.isLockerEmpty = { true } + assertTrue(SessionManager.canShowLocker()) + // Showing it doesn't count as an unlock: saving into it still has to ask + assertFalse(SessionManager.isSessionValid()) + } + + @Test + fun testEmptyLocker_staysShowableAfterBackgroundTimeout() { + SessionManager.isLockerEmpty = { true } + SessionManager.markAuthenticated() + SessionManager.onAppEnteredBackground() + fakeCurrentTime += 31_000L + SessionManager.onAppEnteredForeground() + assertFalse("Session still ends", SessionManager.isLockerUnlocked) + assertTrue("Empty locker isn't shown locked", SessionManager.canShowLocker()) + } + + @Test + fun testFirstDocumentAdded_locksAgainAfterBackgroundTimeout() { + var empty = true + SessionManager.isLockerEmpty = { empty } + SessionManager.markAuthenticated() + empty = false + SessionManager.onAppEnteredBackground() + fakeCurrentTime += 31_000L + SessionManager.onAppEnteredForeground() + assertFalse(SessionManager.canShowLocker()) + } + + @Test + fun testEmptyLocker_validSessionStillExpires() { + SessionManager.isLockerEmpty = { true } + SessionManager.markAuthenticated() + fakeCurrentTime += SessionManager.MAX_AUTH_AGE_MS + 1 + assertFalse(SessionManager.isSessionValid()) + assertTrue(SessionManager.canShowLocker()) + } } diff --git a/app/src/test/java/com/mattintech/papercase/locker/repository/CatalogEmptyFlagTest.kt b/app/src/test/java/com/mattintech/papercase/locker/repository/CatalogEmptyFlagTest.kt new file mode 100644 index 0000000..3266ce5 --- /dev/null +++ b/app/src/test/java/com/mattintech/papercase/locker/repository/CatalogEmptyFlagTest.kt @@ -0,0 +1,33 @@ +package com.mattintech.papercase.locker.repository + +import org.junit.Assert.assertFalse +import org.junit.Assert.assertTrue +import org.junit.Test + +class CatalogEmptyFlagTest { + + @Test + fun noCatalogYet_isEmpty() { + assertTrue(SecureLockerRepository.isEmptyCatalog(null)) + } + + @Test + fun catalogFlaggedEmpty_isEmpty() { + assertTrue(SecureLockerRepository.isEmptyCatalog("""{"ciphertext":"x","iv":"y","keyVersion":2,"empty":true}""")) + } + + @Test + fun catalogFlaggedNotEmpty_isNotEmpty() { + assertFalse(SecureLockerRepository.isEmptyCatalog("""{"ciphertext":"x","iv":"y","keyVersion":2,"empty":false}""")) + } + + @Test + fun catalogFromBeforeTheFlag_staysLocked() { + assertFalse(SecureLockerRepository.isEmptyCatalog("""{"ciphertext":"x","iv":"y","keyVersion":2}""")) + } + + @Test + fun unreadableCatalog_staysLocked() { + assertFalse(SecureLockerRepository.isEmptyCatalog("not json")) + } +}