diff --git a/composeApp/src/commonMain/composeResources/values/strings.xml b/composeApp/src/commonMain/composeResources/values/strings.xml index 10338751..88240528 100644 --- a/composeApp/src/commonMain/composeResources/values/strings.xml +++ b/composeApp/src/commonMain/composeResources/values/strings.xml @@ -254,6 +254,7 @@ Asked again just now. You can ask again in a few minutes. Read to the end of the list to sign. Recovery phrase + Recovery code Ready to sign Recents Reindex events diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/identity/DefaultIdentity.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/identity/DefaultIdentity.kt index 91d079c5..b7aa0d4a 100644 --- a/composeApp/src/commonMain/kotlin/mobi/giza/compose/identity/DefaultIdentity.kt +++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/identity/DefaultIdentity.kt @@ -7,6 +7,8 @@ import fr.acinq.phoenix.data.DecryptSeedResult import fr.acinq.phoenix.data.WalletId import fr.acinq.phoenix.managers.DataStoreManager import fr.acinq.phoenix.managers.NostrCredentialManager +import fr.acinq.phoenix.managers.RecoveryCodeManager +import fr.acinq.phoenix.data.DecryptRecoveryCodesResult import kotlinx.coroutines.flow.first import mobi.giza.compose.extensions.getGlobalPrefs @@ -48,7 +50,12 @@ object DefaultIdentity { } } - val stored = StoredIdentity.merge(wallets, credentials)[defaultId] + val codes = when (val result = RecoveryCodeManager.loadAndDecrypt(phoenixGlobal)) { + is DecryptRecoveryCodesResult.Success -> StoredIdentity.parseCodes(result.codes) + else -> emptyMap() + } + + val stored = StoredIdentity.merge(wallets, credentials, codes)[defaultId] ?: wallets[defaultId]?.let { StoredIdentity.mnemonic(it) } ?: return null @@ -61,6 +68,13 @@ object DefaultIdentity { userPrefs = dataStoreManager.loadUserPrefsForWallet(stored.id), internalPrefs = dataStoreManager.loadInternalPrefsForWallet(stored.id), ) + is StoredIdentity.RecoveryCode -> Identity.signing( + id = stored.id, + kind = IdentityKind.RecoveryCode, + nostrPrivateKey = stored.privateKey, + userPrefs = dataStoreManager.loadUserPrefsForWallet(stored.id), + internalPrefs = dataStoreManager.loadInternalPrefsForWallet(stored.id), + ) is StoredIdentity.NostrSecret -> Identity.signing( id = stored.id, kind = IdentityKind.NostrSecret, diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/identity/Identity.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/identity/Identity.kt index 305e47f4..5a832e1a 100644 --- a/composeApp/src/commonMain/kotlin/mobi/giza/compose/identity/Identity.kt +++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/identity/Identity.kt @@ -30,6 +30,13 @@ enum class IdentityKind { */ Mnemonic, + /** + * A [Mnemonic] whose words came from a recovery code the device also holds. To + * everything that reads `seed.dat` it is a phrase profile; the code is what a person + * wrote down, and what the backup screen shows. See docs/recovery-code-v3.md. + */ + RecoveryCode, + /** A bare nostr secret. Nothing else can be derived from it. */ NostrSecret, @@ -37,6 +44,10 @@ enum class IdentityKind { NostrPublic, } +/** A backup this device can show again: a phrase, or a code and the phrase it is. */ +val IdentityKind.hasBackup: Boolean + get() = this == IdentityKind.Mnemonic || this == IdentityKind.RecoveryCode + /** * The signing identity the app is running as -- or, for [IdentityKind.NostrPublic], * the identity it is looking at. diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/identity/IdentityWriter.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/identity/IdentityWriter.kt index 8ac43c92..da0f0360 100644 --- a/composeApp/src/commonMain/kotlin/mobi/giza/compose/identity/IdentityWriter.kt +++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/identity/IdentityWriter.kt @@ -8,10 +8,12 @@ import fr.acinq.phoenix.data.ElectrumConfig import fr.acinq.phoenix.data.WalletId import fr.acinq.phoenix.managers.DataStoreManager import fr.acinq.phoenix.managers.NostrCredentialManager +import fr.acinq.phoenix.managers.RecoveryCodeManager import fr.acinq.phoenix.managers.SeedManager import fr.acinq.phoenix.managers.nostrPrivateKey import fr.acinq.phoenix.managers.nostrPublicKeyHex import fr.acinq.phoenix.security.EncryptedNostrCredentials +import fr.acinq.phoenix.security.EncryptedRecoveryCodes import fr.acinq.phoenix.security.EncryptedSeed import fr.acinq.phoenix.security.NostrCredential import fr.acinq.phoenix.utils.preferences.GlobalPrefs @@ -22,6 +24,8 @@ import kotlinx.coroutines.IO import kotlinx.coroutines.delay import kotlinx.coroutines.launch import mobi.giza.compose.AppVersion +import mobi.giza.compose.identity.recoverycode.RecoveryCode +import mobi.giza.compose.identity.recoverycode.RecoveryCodeKeys import mobi.giza.compose.ui.view.model.WritingSeedState /** @@ -195,6 +199,86 @@ object IdentityWriter { } } + sealed class WriteRecoveryCodeResult { + /** The code is on the device, with its words and its key. [isNew] is false when it attached to a phrase profile already here. */ + data class Written(val id: WalletId, val isNew: Boolean) : WriteRecoveryCodeResult() + + /** This code is already on the device, under [id]. */ + data class AlreadyExists(val id: WalletId) : WriteRecoveryCodeResult() + + /** One of the three stores exists and could not be read; nothing was written. */ + data object CannotLoadKeys : WriteRecoveryCodeResult() + } + + /** + * Puts [code] on the device: its key in the credentials file, its 24 words in `seed.dat`, + * and the code in `recovery-codes.dat` -- in that order, the order [writeMnemonic] + * established with the code last, so that a crash between any two leaves something + * valid: a bare key the code derives, or a phrase profile the code attaches to the next + * time it is entered. See docs/recovery-code-v3.md, Phase 4. + * + * What is already here for the derived key decides what the write means, not whether + * it happens -- with one refusal, the same code twice: + * + * - nothing: a new profile; + * - a public entry: the read-only upgrade landing on a backup; + * - a bare secret: the key acquiring the code that derives it. The id changes to the + * words', so the bare key's preference files are deleted, as [writeMnemonic] does; + * - the code's words, no code: the code attached to the phrase profile it already is. + * Same id, same preferences, and nothing but the code is written. + */ + suspend fun writeRecoveryCode( + log: Logger, + phoenixGlobal: PhoenixGlobal, + globalPrefs: GlobalPrefs, + code: RecoveryCode, + isTorEnabled: Boolean, + customElectrumServer: ElectrumConfig.Custom?, + ): WriteRecoveryCodeResult { + log.d("writing recovery code to disk...") + val words = RecoveryCodeKeys.words(code) + val id = PhraseKeys.profileId(words) + val privateKey = PhraseKeys.nostrPrivateKey(words) + val publicKey = privateKey.nostrPublicKeyHex() + + val seeds = SeedManager.loadAndDecryptOrNull(phoenixGlobal)?.mapValues { it.value.words } + val credentials = NostrCredentialManager.loadAndDecryptOrNull(phoenixGlobal) + val codes = RecoveryCodeManager.loadAndDecryptOrNull(phoenixGlobal) + if (seeds == null || credentials == null || codes == null) { + log.e("could not load the existing keys, aborting...") + return WriteRecoveryCodeResult.CannotLoadKeys + } + if (codes[id] == code.canonical) { + log.i("attempting to import a recovery code that is already here, aborting...") + return WriteRecoveryCodeResult.AlreadyExists(id) + } + + val phraseHere = seeds.containsKey(id) + val existingEntry = credentials[publicKey] + if (existingEntry !is NostrCredential.Secret) { + NostrCredentialManager.writeToDisk( + phoenixGlobal, + EncryptedNostrCredentials.encrypt(credentials + (publicKey to NostrCredential.Secret(privateKey))), + ) + } + if (!phraseHere) { + SeedManager.writeSeedToDisk(phoenixGlobal, EncryptedSeed.V2.encrypt(seeds + (id to words)), overwrite = true) + } + RecoveryCodeManager.writeToDisk(phoenixGlobal, EncryptedRecoveryCodes.encrypt(codes + (id to code.canonical))) + + if (phraseHere) { + log.i("attached a recovery code to wallet=$id") + return WriteRecoveryCodeResult.Written(id, isNew = false) + } + if (existingEntry != null) { + log.i("the code's nostr key was here without a backup; it is now a profile with one") + DataStoreManager(phoenixGlobal.ctx, chain = PROFILE_CHAIN).deleteNodeUserPrefs(StoredIdentity.nostrPublic(publicKey).id) + } + prepareIdentity(phoenixGlobal, globalPrefs, id, isTorEnabled, customElectrumServer) + log.i("successfully wrote recovery code for wallet=$id") + return WriteRecoveryCodeResult.Written(id, isNew = true) + } + sealed class WriteNostrCredentialResult { data class Written(val id: WalletId) : WriteNostrCredentialResult() diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/identity/StoredIdentity.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/identity/StoredIdentity.kt index 9ddca818..094886ee 100644 --- a/composeApp/src/commonMain/kotlin/mobi/giza/compose/identity/StoredIdentity.kt +++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/identity/StoredIdentity.kt @@ -10,6 +10,8 @@ import fr.acinq.phoenix.data.WalletId import fr.acinq.phoenix.managers.nostrPrivateKey import fr.acinq.phoenix.managers.nostrPublicKeyHex import fr.acinq.phoenix.security.NostrCredential +import mobi.giza.compose.identity.recoverycode.RecoveryCodeKeys +import mobi.giza.compose.identity.recoverycode.RecoveryCode as Code /** * A profile this device holds something for, as listed before any of them is started. @@ -51,6 +53,23 @@ sealed interface StoredIdentity { override fun toString(): String = "StoredIdentity.Mnemonic(id=$id, npub=$nostrPublicKey, key=)" } + /** + * A [Mnemonic] whose 24 words a recovery code derives, and the code. Everything a + * phrase profile is, this is too -- same id, same key, same seed -- and the code is the + * one thing more: what the person wrote down, which the words cannot give back. Listed + * only when [code] derives [userWallet]'s words; see [merge]. + */ + data class RecoveryCode( + val userWallet: UserWallet, + val code: Code, + val privateKey: PrivateKey, + ) : StoredIdentity { + override val id: WalletId get() = userWallet.walletId + override val kind: IdentityKind get() = IdentityKind.RecoveryCode + override val nostrPublicKey: HexKey = privateKey.nostrPublicKeyHex() + override fun toString(): String = "StoredIdentity.RecoveryCode(id=$id, npub=$nostrPublicKey, key=)" + } + data class NostrSecret( override val id: WalletId, override val nostrPublicKey: HexKey, @@ -116,10 +135,18 @@ sealed interface StoredIdentity { * A seed with no credential at all -- the repair failed to write, or a crash fell * between the seed writer's two files -- is listed as it always was, with its key * derived from the words. A failed write must never hide a wallet. + * + * Last, [codes] are attached. A [Mnemonic] whose id has a code that derives its words + * becomes a [RecoveryCode]; a code that derives other words than the ones beside it + * is dropped with a log line, and the profile stays the phrase every build reads it + * as -- two files that disagree mean one is wrong, and `seed.dat` is the one every + * build trusts. A code with no seed at all attaches to nothing. See + * docs/recovery-code-v3.md, Phase 3. */ fun merge( wallets: Map, credentials: Map, + codes: Map = emptyMap(), ): Map { val walletsByPublicKey = wallets.values.associateBy { nostrPublicKeyOf(it.words) } val merged = LinkedHashMap() @@ -146,9 +173,33 @@ sealed interface StoredIdentity { merged[wallet.walletId] = mnemonic(wallet) } } + codes.forEach { (id, code) -> + val phrase = merged[id] as? Mnemonic ?: return@forEach + if (RecoveryCodeKeys.words(code) == phrase.userWallet.words) { + merged[id] = RecoveryCode(phrase.userWallet, code, phrase.privateKey) + } else { + log.w { "the recovery code for wallet=$id does not derive its words; listing it as its phrase" } + } + } return merged } + /** + * The codes `recovery-codes.dat` holds, parsed. A stored code that does not parse as a + * valid code -- a file edited by hand, a bug -- is dropped with a log line: it derives + * nothing, and its profile is still the phrase in `seed.dat`. + */ + fun parseCodes(stored: Map): Map = + stored.mapNotNull { (id, text) -> + when (val parsed = Code.parse(text)) { + is Code.Parse.Valid -> id to parsed.code + else -> { + log.w { "the stored recovery code for wallet=$id does not parse; ignoring it" } + null + } + } + }.toMap() + private val log = Logger.withTag("StoredIdentity") } } diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/composable/KeyRecoveryScreen.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/composable/KeyRecoveryScreen.kt index d558a638..155ca4df 100644 --- a/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/composable/KeyRecoveryScreen.kt +++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/composable/KeyRecoveryScreen.kt @@ -137,6 +137,7 @@ fun KeyRecoveryScreen( IdentityKind.NostrSecret, IdentityKind.NostrPublic -> stringResource(Res.string.these_are_your_keys_keep_them_safe_no_wallet) IdentityKind.Mnemonic, + IdentityKind.RecoveryCode, null -> stringResource(Res.string.these_are_your_keys_keep_them_safe_so_they) }, style = MaterialTheme.typography.bodyMedium, @@ -186,6 +187,7 @@ fun KeyRecoveryScreen( IdentityKind.NostrPublic -> Unit IdentityKind.Mnemonic, + IdentityKind.RecoveryCode, null -> KeyRecoveryOption( icon = Icons.Default.Spellcheck, title = stringResource(Res.string.recovery_phrase), diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/composable/SovereignWalletStartupScreen.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/composable/SovereignWalletStartupScreen.kt index 84126250..401d2555 100644 --- a/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/composable/SovereignWalletStartupScreen.kt +++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/composable/SovereignWalletStartupScreen.kt @@ -213,6 +213,15 @@ fun SovereignWalletStartupScreen( internalPrefs = dataStoreManager.loadInternalPrefsForWallet(identity.id), ) ) + is StoredIdentity.RecoveryCode -> sovereignWalletViewModel.setActiveIdentity( + Identity.signing( + id = identity.id, + kind = IdentityKind.RecoveryCode, + nostrPrivateKey = identity.privateKey, + userPrefs = dataStoreManager.loadUserPrefsForWallet(identity.id), + internalPrefs = dataStoreManager.loadInternalPrefsForWallet(identity.id), + ) + ) is StoredIdentity.NostrSecret -> sovereignWalletViewModel.setActiveIdentity( Identity.signing( id = identity.id, diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/composable/widgets/wallet/WalletsSelector.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/composable/widgets/wallet/WalletsSelector.kt index cde4c274..9f556ef2 100644 --- a/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/composable/widgets/wallet/WalletsSelector.kt +++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/composable/widgets/wallet/WalletsSelector.kt @@ -51,6 +51,7 @@ import fr.acinq.phoenix.utils.preferences.getByWalletIdOrDefault import mobi.giza.compose.extensions.hexToNpubHrp import mobi.giza.compose.resources.Res import mobi.giza.compose.resources.read_only +import mobi.giza.compose.resources.recovery_code import mobi.giza.compose.resources.recovery_phrase import org.jetbrains.compose.resources.stringResource import mobi.giza.compose.database.model.Profile @@ -195,6 +196,7 @@ private fun AvailableWalletView( } val held = when (identity) { is StoredIdentity.Mnemonic -> Res.string.recovery_phrase + is StoredIdentity.RecoveryCode -> Res.string.recovery_code is StoredIdentity.NostrPublic -> Res.string.read_only is StoredIdentity.NostrSecret -> null } diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/view/model/SovereignWalletViewModel.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/view/model/SovereignWalletViewModel.kt index 9e22ecc4..ee7b0f55 100644 --- a/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/view/model/SovereignWalletViewModel.kt +++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/view/model/SovereignWalletViewModel.kt @@ -20,6 +20,8 @@ import fr.acinq.phoenix.data.ListWalletState import fr.acinq.phoenix.data.UserWallet import fr.acinq.phoenix.data.WalletId import fr.acinq.phoenix.managers.NostrCredentialManager +import fr.acinq.phoenix.managers.RecoveryCodeManager +import fr.acinq.phoenix.data.DecryptRecoveryCodesResult import fr.acinq.phoenix.security.NostrCredential import fr.acinq.phoenix.managers.nostrPrivateKey import fr.acinq.phoenix.utils.preferences.GlobalPrefs @@ -277,7 +279,20 @@ class SovereignWalletViewModel( } } - val identities = StoredIdentity.merge(wallets, credentials) + // Read, never written, and never fatal: every profile with a code is also the + // phrase in seed.dat, so a codes file that cannot be read loses nothing but the + // code itself, which the backup screen reports when it is asked for. See + // docs/recovery-code-v3.md, Phase 4. + val codes = when (val result = RecoveryCodeManager.loadAndDecrypt(phoenixGlobal)) { + is DecryptRecoveryCodesResult.Success -> StoredIdentity.parseCodes(result.codes) + is DecryptRecoveryCodesResult.Failure.FileNotFound -> emptyMap() + is DecryptRecoveryCodesResult.Failure -> { + log.e { "cannot read the recovery codes file: $result; listing those profiles as their phrases" } + emptyMap() + } + } + + val identities = StoredIdentity.merge(wallets, credentials, codes) val metadataMap = getAvailableWalletsMeta(phoenixGlobal).first() identities.keys.forEach { walletId -> diff --git a/composeApp/src/jvmTest/kotlin/mobi/giza/compose/identity/IdentityWriterJvmTest.kt b/composeApp/src/jvmTest/kotlin/mobi/giza/compose/identity/IdentityWriterJvmTest.kt index 652d8096..6da6c7de 100644 --- a/composeApp/src/jvmTest/kotlin/mobi/giza/compose/identity/IdentityWriterJvmTest.kt +++ b/composeApp/src/jvmTest/kotlin/mobi/giza/compose/identity/IdentityWriterJvmTest.kt @@ -9,6 +9,7 @@ import fr.acinq.bitcoin.PrivateKey import fr.acinq.phoenix.PhoenixGlobal import fr.acinq.phoenix.data.WalletId import fr.acinq.phoenix.managers.NostrCredentialManager +import fr.acinq.phoenix.managers.RecoveryCodeManager import fr.acinq.phoenix.managers.SeedManager import fr.acinq.phoenix.managers.computePreferencePath import fr.acinq.phoenix.managers.nostrPublicKeyHex @@ -36,6 +37,8 @@ import kotlinx.coroutines.runBlocking import kotlinx.coroutines.test.resetMain import kotlinx.coroutines.test.setMain import kotlinx.coroutines.withTimeout +import mobi.giza.compose.identity.recoverycode.RecoveryCode +import mobi.giza.compose.identity.recoverycode.RecoveryCodeKeys import mobi.giza.compose.ui.view.model.WritingSeedState import okio.FileSystem import okio.SYSTEM @@ -323,4 +326,145 @@ class IdentityWriterJvmTest { credentials(), ) } + + // --- recovery codes (docs/recovery-code-v3.md, Phase 4) --- + + /** A fresh code, and what its 24 words derive. */ + private class Coded { + val code = RecoveryCode.generate() + val words = RecoveryCodeKeys.words(code) + val walletId = PhraseKeys.profileId(words) + val nostrKey = PhraseKeys.nostrPrivateKey(words) + val nostrPublicKey = nostrKey.nostrPublicKeyHex() + } + + private suspend fun writeCode(coded: Coded) = IdentityWriter.writeRecoveryCode( + log = log, + phoenixGlobal = phoenixGlobal, + globalPrefs = globalPrefs, + code = coded.code, + isTorEnabled = false, + customElectrumServer = null, + ) + + private fun codes() = RecoveryCodeManager.loadAndDecryptOrNull(phoenixGlobal) + + @Test + fun `a code writes its key, its 24 words and itself`() = runBlocking { + val coded = Coded() + + val result = assertIs(writeCode(coded)) + + assertEquals(coded.walletId, result.id) + assertTrue(result.isNew) + assertEquals(mapOf(coded.nostrPublicKey to NostrCredential.Secret(coded.nostrKey)), credentials()) + assertEquals(coded.words, seeds()?.get(coded.walletId)?.words) + assertEquals(mapOf(coded.walletId to coded.code.canonical), codes()) + assertTrue(FileSystem.SYSTEM.exists(computePreferencePath(phoenixGlobal.ctx, "userprefs_${result.id.nodeIdHash}.preferences_pb"))) + } + + @Test + fun `the same code twice is refused`() = runBlocking { + val coded = Coded() + writeCode(coded) + + assertEquals(coded.walletId, assertIs(writeCode(coded)).id) + assertEquals(1, codes()?.size) + } + + /** + * The words are a phrase, and the other writers already know what a phrase is: the + * code's words are a seed that is already here, its key is a wallet's, and forgetting + * it would only see it derived again. + */ + @Test + fun `a code profile is a phrase profile to the other writers`() = runBlocking { + val coded = Coded() + writeCode(coded) + + val words = coded.words + val outcome = CompletableDeferred>() + IdentityWriter.writeMnemonic( + log = log, phoenixGlobal = phoenixGlobal, globalPrefs = globalPrefs, + writingState = WritingSeedState.Init, viewModelScope = scope, mnemonics = words, + onWritingSeedError = { outcome.complete(Result.failure(IllegalStateException(it.toString()))) }, + onWritingSeedStateWriting = {}, isRestoringWallet = true, isTorEnabled = false, customElectrumServer = null, + onSeedWritten = { outcome.complete(Result.success(it)) }, + ) + val second = withTimeout(15_000) { outcome.await() } + assertTrue(second.exceptionOrNull()?.message?.contains("SeedAlreadyExists") == true, "$second") + + assertEquals(coded.walletId, assertIs(write(coded.nostrKey)).id) + assertIs( + IdentityWriter.forgetNostrCredential(log, phoenixGlobal, coded.walletId, coded.nostrPublicKey) + ) + } + + /** Signed in with the code's 24 words first, then with the code: one profile, the code attached. */ + @Test + fun `a code attaches to the phrase profile its words already made`() = runBlocking { + val coded = Coded() + val outcome = CompletableDeferred>() + IdentityWriter.writeMnemonic( + log = log, phoenixGlobal = phoenixGlobal, globalPrefs = globalPrefs, + writingState = WritingSeedState.Init, viewModelScope = scope, mnemonics = coded.words, + onWritingSeedError = { outcome.complete(Result.failure(IllegalStateException(it.toString()))) }, + onWritingSeedStateWriting = {}, isRestoringWallet = true, isTorEnabled = false, customElectrumServer = null, + onSeedWritten = { outcome.complete(Result.success(it)) }, + ) + assertEquals(coded.walletId, withTimeout(15_000) { outcome.await() }.getOrThrow()) + val prefs = computePreferencePath(phoenixGlobal.ctx, "userprefs_${coded.walletId.nodeIdHash}.preferences_pb") + assertTrue(FileSystem.SYSTEM.exists(prefs)) + + val result = assertIs(writeCode(coded)) + + assertEquals(coded.walletId, result.id) + assertFalse(result.isNew) + assertEquals(setOf(coded.walletId), seeds()?.keys) + assertEquals(mapOf(coded.walletId to coded.code.canonical), codes()) + assertTrue(FileSystem.SYSTEM.exists(prefs), "the phrase profile's preferences are kept") + } + + @Test + fun `the code of a key held as a bare secret attaches to it`() = runBlocking { + val coded = Coded() + write(coded.nostrKey) + val bareUserPrefs = userPrefsFile(StoredIdentity.nostrSecret(coded.nostrKey)) + assertTrue(FileSystem.SYSTEM.exists(bareUserPrefs)) + + val result = assertIs(writeCode(coded)) + + assertEquals(coded.walletId, result.id) + assertEquals(mapOf(coded.nostrPublicKey to NostrCredential.Secret(coded.nostrKey)), credentials()) + assertFalse(FileSystem.SYSTEM.exists(bareUserPrefs), "the bare key's preferences went with its id") + } + + @Test + fun `the code of a key held read-only attaches and the entry becomes a secret`() = runBlocking { + val coded = Coded() + writePublic(coded.nostrKey) + + assertIs(writeCode(coded)) + + assertEquals(mapOf(coded.nostrPublicKey to NostrCredential.Secret(coded.nostrKey)), credentials()) + } + + /** + * What an older build sees: no codes file. The profile is the phrase in seed.dat, with + * the same npub and the same id. + */ + @Test + fun `without the codes file a code profile lists as its phrase`() = runBlocking { + val coded = Coded() + writeCode(coded) + + val withCodes = StoredIdentity.merge( + seeds()!!, credentials()!!, StoredIdentity.parseCodes(codes()!!), + ) + val withoutCodes = StoredIdentity.merge(seeds()!!, credentials()!!) + + assertIs(withCodes[coded.walletId]) + val phrase = assertIs(withoutCodes[coded.walletId]) + assertEquals(coded.nostrPublicKey, phrase.nostrPublicKey) + } } diff --git a/composeApp/src/jvmTest/kotlin/mobi/giza/compose/identity/MultipleProfilesRoundTripJvmTest.kt b/composeApp/src/jvmTest/kotlin/mobi/giza/compose/identity/MultipleProfilesRoundTripJvmTest.kt index f88e7122..721af117 100644 --- a/composeApp/src/jvmTest/kotlin/mobi/giza/compose/identity/MultipleProfilesRoundTripJvmTest.kt +++ b/composeApp/src/jvmTest/kotlin/mobi/giza/compose/identity/MultipleProfilesRoundTripJvmTest.kt @@ -129,6 +129,11 @@ class MultipleProfilesRoundTripJvmTest { userPrefs = dataStoreManager.loadUserPrefsForWallet(stored.id), internalPrefs = dataStoreManager.loadInternalPrefsForWallet(stored.id), ) + is StoredIdentity.RecoveryCode -> Identity.signing( + id = stored.id, kind = IdentityKind.RecoveryCode, nostrPrivateKey = stored.privateKey, + userPrefs = dataStoreManager.loadUserPrefsForWallet(stored.id), + internalPrefs = dataStoreManager.loadInternalPrefsForWallet(stored.id), + ) is StoredIdentity.NostrSecret -> Identity.signing( id = stored.id, kind = IdentityKind.NostrSecret, nostrPrivateKey = stored.privateKey, userPrefs = dataStoreManager.loadUserPrefsForWallet(stored.id), diff --git a/composeApp/src/jvmTest/kotlin/mobi/giza/compose/identity/StoredIdentityJvmTest.kt b/composeApp/src/jvmTest/kotlin/mobi/giza/compose/identity/StoredIdentityJvmTest.kt index 15538faa..c1d8eca9 100644 --- a/composeApp/src/jvmTest/kotlin/mobi/giza/compose/identity/StoredIdentityJvmTest.kt +++ b/composeApp/src/jvmTest/kotlin/mobi/giza/compose/identity/StoredIdentityJvmTest.kt @@ -143,4 +143,64 @@ class StoredIdentityJvmTest { fun `the nsec form and the hex form name the same key`() { assertEquals(nip06PublicKey.toXonlyPublicKey().value.toHex(), nip06PublicKey) } + + // --- recovery codes (docs/recovery-code-v3.md, Phase 4) --- + + private val code = (mobi.giza.compose.identity.recoverycode.RecoveryCode.parse("LBZC-MYTK-E9P3-7C7B-AHJN-KX79-22CY-WAY7-K7QZ") + as mobi.giza.compose.identity.recoverycode.RecoveryCode.Parse.Valid).code + private val codeWords = mobi.giza.compose.identity.recoverycode.RecoveryCodeKeys.words(code) + private val codeWallet = UserWallet(walletId = PhraseKeys.profileId(codeWords), nodeId = "", words = codeWords) + + @Test + fun `a seed whose code derives its words is listed as a recovery code`() { + val merged = StoredIdentity.merge( + wallets = mapOf(codeWallet.walletId to codeWallet, wallet.walletId to wallet), + credentials = emptyMap(), + codes = mapOf(codeWallet.walletId to code), + ) + + assertEquals(2, merged.size) + val coded = assertIs(merged[codeWallet.walletId]) + assertEquals(code, coded.code) + assertEquals(IdentityKind.RecoveryCode, coded.kind) + assertEquals(StoredIdentity.nostrPublicKeyOf(codeWords), coded.nostrPublicKey) + assertIs(merged[wallet.walletId]) + } + + /** Two files that disagree: the words are what every build reads, so the words win. */ + @Test + fun `a code that does not derive the words beside it is dropped, and the phrase stays`() { + val merged = StoredIdentity.merge( + wallets = mapOf(wallet.walletId to wallet), + credentials = emptyMap(), + codes = mapOf(wallet.walletId to code), + ) + + assertIs(merged[wallet.walletId]) + } + + @Test + fun `a code with no seed attaches to nothing`() { + val merged = StoredIdentity.merge( + wallets = emptyMap(), + credentials = mapOf(bareKey.publicKey().xOnly().value.toHex() to NostrCredential.Secret(bareKey)), + codes = mapOf(codeWallet.walletId to code), + ) + + assertEquals(1, merged.size) + assertIs(merged.values.single()) + } + + @Test + fun `a stored code that does not parse is ignored`() { + val parsed = StoredIdentity.parseCodes( + mapOf( + codeWallet.walletId to code.canonical, + WalletId("12".repeat(20)) to "not a code", + WalletId("34".repeat(20)) to "LBZC-MYTK-E9P3-7C7B-AHJN-KX79-22CY-WAY7-K7QA", + ) + ) + + assertEquals(mapOf(codeWallet.walletId to code), parsed) + } }