diff --git a/composeApp/src/commonMain/composeResources/values/strings.xml b/composeApp/src/commonMain/composeResources/values/strings.xml index 88240528..77fff79b 100644 --- a/composeApp/src/commonMain/composeResources/values/strings.xml +++ b/composeApp/src/commonMain/composeResources/values/strings.xml @@ -453,23 +453,29 @@ Ask again A password-protected key (ncryptsec) is not supported yet. Decrypt it in the app it came from and paste the nsec. - Enter a recovery phrase or an nsec to sign in. + Enter a recovery code, a recovery phrase or an nsec to sign in. Paste Recognised as a nostr secret key. Recognised as a recovery phrase. Giza keeps no wallet. Restoring the phrase here brings back the profile it signs as, and nothing else. Recognised as a public key. You will see this profile and the people it follows; messages stay closed and nothing can be sent. Paste the nsec later to open it. - Recovery phrase, nsec or npub + Recovery code, phrase, nsec or npub Sign in with a recovery phrase, an nsec, or an npub to look around Signed in Signing you in… - That is not a recovery phrase or a nostr key. + That is not a recovery code, a recovery phrase or a nostr key. That nostr secret key is not valid. That recovery phrase is not valid. Check each word and the order. The key could not be saved on this device. Whatever you paste stays on this device. Giza checks it, shows you the profile it opens, and writes nothing until you confirm. This key is already on this device. - Twelve words, nsec1… or npub1… + LB… code, twelve words, nsec1… or npub1… + Recognised as a recovery code. + That is not a recovery code. Check that it has nine blocks of four. + There's a typo in this code. Check each block. + That is an older eight-block code. Giza only uses nine-block recovery codes. + Block %1$d, character %2$d looks wrong. Did you mean %3$s? + Use this code Use a different key You are signing in as diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/identity/CredentialParser.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/identity/CredentialParser.kt index 124fd814..1956c764 100644 --- a/composeApp/src/commonMain/kotlin/mobi/giza/compose/identity/CredentialParser.kt +++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/identity/CredentialParser.kt @@ -8,6 +8,9 @@ import fr.acinq.bitcoin.PrivateKey import fr.acinq.bitcoin.XonlyPublicKey import fr.acinq.phoenix.managers.nostrPublicKeyHex import fr.acinq.phoenix.utils.MnemonicLanguage +import mobi.giza.compose.identity.recoverycode.RecoveryCode as Code +import mobi.giza.compose.identity.recoverycode.RecoveryCodeKeys +import mobi.giza.compose.identity.recoverycode.RecoveryCodeProblem /** * What a user pasted into the sign-in field, once it has been recognised. @@ -26,6 +29,17 @@ sealed interface SignInCredential { override fun toString(): String = "RecoveryPhrase(npub=$nostrPublicKey, words=***)" } + /** + * A nine-block recovery code: a 24-word phrase in another notation, and the nostr key + * its words derive. See docs/recovery-code-v3.md. + */ + data class RecoveryCode( + val code: Code, + override val nostrPublicKey: HexKey, + ) : SignInCredential { + override fun toString(): String = "RecoveryCode(npub=$nostrPublicKey, code=***)" + } + /** A bare nostr secret. No wallet comes with it. */ data class NostrSecret( val privateKey: PrivateKey, @@ -57,6 +71,18 @@ enum class CredentialProblem { /** An ncryptsec (NIP-49). Decrypting one is a follow-on; say so rather than fail opaquely. */ EncryptedKey, + /** Shaped like a recovery code, and not one: the wrong length, or a symbol no code has. */ + InvalidRecoveryCode, + + /** + * A recovery code with a typo: well formed, and its ninth block disagrees. With a + * suggestion when exactly one symbol explains it -- see [CredentialParser.Result.Refused]. + */ + RecoveryCodeTypo, + + /** A recovery code of an older, eight-block version. Giza only makes nine-block codes. */ + UnsupportedRecoveryCode, + /** An identity with this nostr public key is already on the device, as a wallet or a key. */ AlreadyOnThisDevice, @@ -67,9 +93,9 @@ enum class CredentialProblem { /** * Recognises a pasted credential. Pure, so it can be pinned row by row. * - * A user does not choose an input type; they paste what they have. The three accepted - * shapes are unambiguous -- words have spaces, keys do not, and a bech32 prefix says - * which key -- and the one refused shape is named for what it is rather than lumped in + * A user does not choose an input type; they paste what they have. The four accepted + * shapes are unambiguous -- a recovery code is eight or nine blocks of four, words are + * twelve or more and have spaces, keys do not, and a bech32 prefix says which key -- and the one refused shape is named for what it is rather than lumped in * with garbage, because a user who pasted an ncryptsec did something reasonable and * should be told what to do instead. * @@ -84,15 +110,34 @@ object CredentialParser { sealed interface Result { data class Recognised(val credential: SignInCredential) : Result - data class Refused(val problem: CredentialProblem) : Result + /** + * @param suggestion for [CredentialProblem.RecoveryCodeTypo], the one code a single + * symbol away, when there is exactly one. A suggestion and nothing more: it becomes + * the input only when a person accepts it, because two typos can sit one symbol + * from somebody else's code. + */ + data class Refused(val problem: CredentialProblem, val suggestion: Code.Parse.Typo? = null) : Result } private val hex64 = Regex("[0-9a-f]{64}") + /** + * Eight or nine groups of four letters or digits, apart by dashes or whitespace, or one + * run of 32 or 36: the shapes of a recovery code as typed, copied or pasted. Nothing else + * this field reads has them -- a phrase has 12 to 24 words of three to eight letters, a + * key a prefix or 64 characters -- so an input of this shape is a code, and its problems + * are a code's problems. + */ + private val recoveryCodeShape = Regex("[A-Za-z0-9]{4}(?:[\\s-]+[A-Za-z0-9]{4}){7,8}|[A-Za-z0-9]{32}|[A-Za-z0-9]{36}") + fun parse(raw: String): Result { val text = raw.trim() if (text.isEmpty()) return Result.Refused(CredentialProblem.Empty) + // Before the words: a code typed by hand arrives as `LBZC MYTK …` as often as with + // dashes, and would otherwise read as a phrase that failed its checksum. + if (recoveryCodeShape.matches(text)) return recoveryCode(text) + // Whitespace anywhere inside means words. Not lower-cased: the wordlist already // is, and a capitalised word is a paste artefact worth showing rather than fixing. val words = text.split(Regex("\\s+")) @@ -117,6 +162,17 @@ object CredentialParser { Result.Refused(CredentialProblem.InvalidPhrase) } + private fun recoveryCode(text: String): Result = when (val parsed = Code.parse(text)) { + is Code.Parse.Valid -> Result.Recognised( + SignInCredential.RecoveryCode(parsed.code, StoredIdentity.nostrPublicKeyOf(RecoveryCodeKeys.words(parsed.code))) + ) + is Code.Parse.Typo -> Result.Refused(CredentialProblem.RecoveryCodeTypo, suggestion = parsed) + is Code.Parse.Invalid -> Result.Refused( + if (parsed.problem == RecoveryCodeProblem.Checksum) CredentialProblem.RecoveryCodeTypo else CredentialProblem.InvalidRecoveryCode + ) + is Code.Parse.UnsupportedVersion -> Result.Refused(CredentialProblem.UnsupportedRecoveryCode) + } + private fun nsec(token: String): Result { val bytes = runCatching { val (hrp, data) = Bech32.decodeBytes(token) diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/composable/SignInScreen.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/composable/SignInScreen.kt index 46b9fdeb..5abde064 100644 --- a/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/composable/SignInScreen.kt +++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/composable/SignInScreen.kt @@ -14,6 +14,7 @@ import androidx.compose.foundation.verticalScroll import androidx.compose.material.icons.Icons import androidx.compose.material.icons.filled.ContentPaste import androidx.compose.material.icons.filled.Key +import androidx.compose.material.icons.filled.Password import androidx.compose.material.icons.filled.Spellcheck import androidx.compose.material.icons.filled.Visibility import androidx.compose.material3.Button @@ -21,6 +22,7 @@ import androidx.compose.material3.ExperimentalMaterial3Api import androidx.compose.material3.Icon import androidx.compose.material3.IconButton import androidx.compose.material3.MaterialTheme +import androidx.compose.material3.OutlinedButton import androidx.compose.material3.Scaffold import androidx.compose.material3.SnackbarHost import androidx.compose.material3.Surface @@ -41,6 +43,13 @@ import mobi.giza.compose.resources.Res import mobi.giza.compose.resources.a_password_protected_key_ncryptsec_is_not import mobi.giza.compose.resources.enter_a_recovery_phrase_or_an_nsec_to_sign_in import mobi.giza.compose.resources.next +import mobi.giza.compose.resources.block_character_looks_wrong_did_you_mean +import mobi.giza.compose.resources.recognised_as_a_recovery_code +import mobi.giza.compose.resources.that_is_an_older_eight_block_code +import mobi.giza.compose.resources.that_is_not_a_recovery_code_check_it_has_nine_blocks +import mobi.giza.compose.resources.there_s_a_typo_in_this_code_check_each_block +import mobi.giza.compose.resources.use_this_code +import mobi.giza.compose.identity.recoverycode.RecoveryCode import mobi.giza.compose.resources.paste import mobi.giza.compose.resources.recognised_as_a_nostr_secret_key_no_wallet import mobi.giza.compose.resources.recognised_as_a_public_key_you_will_see @@ -103,6 +112,7 @@ fun SignInToProfileScreen( onWritten: (WalletId) -> Unit, onError: (WritingSeedState.Error) -> Unit, ) -> Unit, + writeRecoveryCode: suspend (RecoveryCode) -> IdentityWriter.WriteRecoveryCodeResult, onNavigateBack: () -> Unit, /** * The tail: re-list, select, go to startup. Also what "switch to it" does when the key @@ -117,6 +127,7 @@ fun SignInToProfileScreen( writeNostrKey = writeNostrKey, writeNostrPublicKey = writeNostrPublicKey, writeRecoveryPhrase = writeRecoveryPhrase, + writeRecoveryCode = writeRecoveryCode, ) ) @@ -182,6 +193,7 @@ fun SignInToProfileScreen( private fun InputPrompt(viewModel: SignInToProfileViewModel) { val field = viewModel.signInToProfileFormState.textFieldForm.textFieldState val problem = viewModel.inputProblem.value + val suggestion = viewModel.typoSuggestion.value val clipboardManager = LocalClipboardManager.current Column( @@ -201,7 +213,7 @@ private fun InputPrompt(viewModel: SignInToProfileViewModel) { modifier = Modifier.fillMaxWidth(), state = field, isError = problem != null, - supportingText = problem?.let { { Text(text = problemMessage(it)) } }, + supportingText = problem?.let { { Text(text = problemMessage(it, suggestion)) } }, // Two lines shows a whole phrase without scrolling and an nsec on one; four is // room for a phrase pasted with line breaks. lineLimits = TextFieldLineLimits.MultiLine(minHeightInLines = 2, maxHeightInLines = 4), @@ -229,6 +241,22 @@ private fun InputPrompt(viewModel: SignInToProfileViewModel) { }, ) + // A located typo is offered, never applied: two typos can sit one symbol from + // somebody else's code, so the corrected code becomes the input only on this press, + // and the confirm step still shows the npub it derives before anything is written. + if (suggestion != null) { + Text( + text = suggestion.suggested.canonical, + style = MaterialTheme.typography.bodyLarge.copy(fontFamily = FontFamily.Monospace), + ) + OutlinedButton( + modifier = Modifier.align(Alignment.End), + onClick = { viewModel.acceptSuggestion() }, + ) { + Text(text = stringResource(Res.string.use_this_code)) + } + } + Button( modifier = Modifier.align(Alignment.End), onClick = { viewModel.recognise() }, @@ -283,6 +311,13 @@ private fun Confirm( style = MaterialTheme.typography.bodyMedium, ) } + is SignInCredential.RecoveryCode -> { + Icon(Icons.Default.Password, contentDescription = Decorative) + Text( + text = stringResource(Res.string.recognised_as_a_recovery_code), + style = MaterialTheme.typography.bodyMedium, + ) + } is SignInCredential.NostrSecret -> { Icon(Icons.Default.Key, contentDescription = Decorative) Text( @@ -317,14 +352,33 @@ private fun Confirm( } } -/** Each refusal is a sentence that says what to do instead, not a code. */ +/** + * Each refusal is a sentence that says what to do instead, not a code. A recovery code with + * one located typo says where, and what the symbol should be. + */ @Composable -private fun problemMessage(problem: CredentialProblem): String = stringResource( +private fun problemMessage(problem: CredentialProblem, suggestion: RecoveryCode.Parse.Typo? = null): String = + if (problem == CredentialProblem.RecoveryCodeTypo && suggestion != null) { + stringResource( + Res.string.block_character_looks_wrong_did_you_mean, + suggestion.block, + suggestion.character, + suggestion.suggestedSymbol.toString(), + ) + } else { + problemMessageOf(problem) + } + +@Composable +private fun problemMessageOf(problem: CredentialProblem): String = stringResource( when (problem) { CredentialProblem.Empty -> Res.string.enter_a_recovery_phrase_or_an_nsec_to_sign_in CredentialProblem.NotRecognised -> Res.string.that_is_not_a_recovery_phrase_or_a_nostr_key CredentialProblem.InvalidPhrase -> Res.string.that_recovery_phrase_is_not_valid_check CredentialProblem.InvalidKey -> Res.string.that_nostr_secret_key_is_not_valid + CredentialProblem.InvalidRecoveryCode -> Res.string.that_is_not_a_recovery_code_check_it_has_nine_blocks + CredentialProblem.RecoveryCodeTypo -> Res.string.there_s_a_typo_in_this_code_check_each_block + CredentialProblem.UnsupportedRecoveryCode -> Res.string.that_is_an_older_eight_block_code CredentialProblem.EncryptedKey -> Res.string.a_password_protected_key_ncryptsec_is_not CredentialProblem.AlreadyOnThisDevice -> Res.string.this_key_is_already_on_this_device CredentialProblem.CouldNotWrite -> Res.string.the_key_could_not_be_saved_on_this_device @@ -343,6 +397,7 @@ private fun SignInToProfileScreenPreview() { writeNostrKey = { IdentityWriter.WriteNostrCredentialResult.CannotLoadKeys }, writeNostrPublicKey = { IdentityWriter.WriteNostrCredentialResult.CannotLoadKeys }, writeRecoveryPhrase = { _, _, onError -> onError(WritingSeedState.Error.CannotLoadSeedMap) }, + writeRecoveryCode = { IdentityWriter.WriteRecoveryCodeResult.CannotLoadKeys }, onNavigateBack = {}, onSignedIn = {}, ) diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/composable/navigation/GizaNavHost.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/composable/navigation/GizaNavHost.kt index c3291e2f..c5bcb0f1 100644 --- a/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/composable/navigation/GizaNavHost.kt +++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/composable/navigation/GizaNavHost.kt @@ -715,6 +715,7 @@ fun GizaNavHost( onSeedWriteError = onError, ) }, + writeRecoveryCode = { code -> sovereignWalletViewModel.writeRecoveryCode(code) }, onNavigateBack = { navController.popBackStack() }, diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/view/model/SignInToProfileViewModel.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/view/model/SignInToProfileViewModel.kt index cbbb74a1..12275769 100644 --- a/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/view/model/SignInToProfileViewModel.kt +++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/view/model/SignInToProfileViewModel.kt @@ -24,6 +24,8 @@ import mobi.giza.compose.identity.SignInCredential import mobi.giza.compose.repository.NostrRepository import mobi.giza.compose.ui.view.state.SignInToProfileUIState import mobi.giza.compose.ui.view.state.form.SignInToProfileFormState +import mobi.giza.compose.identity.recoverycode.RecoveryCode +import androidx.compose.foundation.text.input.setTextAndPlaceCursorAtEnd /** * Signs in with something the user already has: a recovery phrase, an nsec, or -- to @@ -51,6 +53,7 @@ class SignInToProfileViewModel( onWritten: (WalletId) -> Unit, onError: (WritingSeedState.Error) -> Unit, ) -> Unit, + private val writeRecoveryCode: suspend (RecoveryCode) -> IdentityWriter.WriteRecoveryCodeResult, val signInToProfileFormState: SignInToProfileFormState = SignInToProfileFormState(), ) : ViewModel() { @@ -66,6 +69,7 @@ class SignInToProfileViewModel( onWritten: (WalletId) -> Unit, onError: (WritingSeedState.Error) -> Unit, ) -> Unit, + writeRecoveryCode: suspend (RecoveryCode) -> IdentityWriter.WriteRecoveryCodeResult, ): ViewModelProvider.Factory = viewModelFactory { initializer { SignInToProfileViewModel( @@ -73,6 +77,7 @@ class SignInToProfileViewModel( writeNostrKey = writeNostrKey, writeNostrPublicKey = writeNostrPublicKey, writeRecoveryPhrase = writeRecoveryPhrase, + writeRecoveryCode = writeRecoveryCode, ) } } @@ -85,17 +90,38 @@ class SignInToProfileViewModel( /** Why the field's contents were refused, shown as its supporting text; null when they were not. */ val inputProblem: MutableState = mutableStateOf(null) + /** + * For a recovery code with one wrong symbol, the code it is one symbol away from; null + * otherwise. Shown beside the field, and applied only by [acceptSuggestion]. + */ + val typoSuggestion: MutableState = mutableStateOf(null) + /** Reads the field and either moves to [SignInToProfileUIState.Confirm] or marks the field. */ fun recognise() { when (val result = CredentialParser.parse(signInToProfileFormState.textFieldForm.textFieldState.text.toString())) { - is CredentialParser.Result.Refused -> inputProblem.value = result.problem + is CredentialParser.Result.Refused -> { + inputProblem.value = result.problem + typoSuggestion.value = result.suggestion + } is CredentialParser.Result.Recognised -> { inputProblem.value = null + typoSuggestion.value = null uiState.value = SignInToProfileUIState.Confirm(result.credential) } } } + /** + * The person accepted the suggested correction: the field becomes the corrected code and + * is read again, so the confirm step -- the npub it derives -- still stands between the + * suggestion and the disk. + */ + fun acceptSuggestion() { + val suggestion = typoSuggestion.value ?: return + signInToProfileFormState.textFieldForm.textFieldState.setTextAndPlaceCursorAtEnd(suggestion.suggested.canonical) + recognise() + } + /** Back to the field, keeping what was typed. */ fun useADifferentKey() { uiState.value = SignInToProfileUIState.InputPrompt @@ -134,6 +160,19 @@ class SignInToProfileViewModel( is SignInCredential.NostrPublicKey -> write("nostr public key") { writeNostrPublicKey(credential.nostrPublicKey) } + is SignInCredential.RecoveryCode -> try { + when (val result = writeRecoveryCode(credential.code)) { + is IdentityWriter.WriteRecoveryCodeResult.Written -> Outcome.SignedIn(result.id) + is IdentityWriter.WriteRecoveryCodeResult.AlreadyExists -> Outcome.Failed(CredentialProblem.AlreadyOnThisDevice, alreadyHere = result.id) + is IdentityWriter.WriteRecoveryCodeResult.CannotLoadKeys -> Outcome.Failed(CredentialProblem.CouldNotWrite) + } + } catch (e: CancellationException) { + throw e + } catch (e: Exception) { + logger.e("could not write the recovery code", e) + Outcome.Failed(CredentialProblem.CouldNotWrite) + } + is SignInCredential.RecoveryPhrase -> { // Callback-shaped writer, awaited: the seed writer drives WritingSeedState and // reports through two callbacks, exactly one of which fires. 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 ee7b0f55..fcbe1bcf 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 @@ -38,6 +38,7 @@ import mobi.giza.compose.identity.Identity import mobi.giza.compose.identity.IdentityWriter import mobi.giza.compose.identity.SeedCredentials import mobi.giza.compose.identity.StoredIdentity +import mobi.giza.compose.identity.recoverycode.RecoveryCode sealed class WritingSeedState { data object Init : WritingSeedState() @@ -435,6 +436,17 @@ class SovereignWalletViewModel( customElectrumServer = customElectrumServer.value, ) + /** Writes a recovery code, its words and its key, with the same options. See [IdentityWriter.writeRecoveryCode]. */ + suspend fun writeRecoveryCode(code: RecoveryCode): IdentityWriter.WriteRecoveryCodeResult = + IdentityWriter.writeRecoveryCode( + log = log, + phoenixGlobal = phoenixGlobal, + globalPrefs = getGlobalPrefs(), + code = code, + isTorEnabled = isTorEnabled.value, + customElectrumServer = customElectrumServer.value, + ) + /** Writes a public key as a read-only identity, with the same options. */ suspend fun writeNostrPublicKey(nostrPublicKey: HexKey): IdentityWriter.WriteNostrCredentialResult = IdentityWriter.writeNostrPublicKey( diff --git a/composeApp/src/jvmTest/kotlin/mobi/giza/compose/identity/AddProfileFromInsideJvmTest.kt b/composeApp/src/jvmTest/kotlin/mobi/giza/compose/identity/AddProfileFromInsideJvmTest.kt index c8b7dc89..08211d80 100644 --- a/composeApp/src/jvmTest/kotlin/mobi/giza/compose/identity/AddProfileFromInsideJvmTest.kt +++ b/composeApp/src/jvmTest/kotlin/mobi/giza/compose/identity/AddProfileFromInsideJvmTest.kt @@ -95,6 +95,7 @@ class AddProfileFromInsideJvmTest { writeNostrKey = { key -> sovereign.writeNostrKey(key) }, writeNostrPublicKey = { pubkey -> sovereign.writeNostrPublicKey(pubkey) }, writeRecoveryPhrase = { _, _, onError -> onError(mobi.giza.compose.ui.view.model.WritingSeedState.Error.CannotLoadSeedMap) }, + writeRecoveryCode = { mobi.giza.compose.identity.IdentityWriter.WriteRecoveryCodeResult.CannotLoadKeys }, ) private fun activated(stored: StoredIdentity.NostrSecret): Identity { diff --git a/composeApp/src/jvmTest/kotlin/mobi/giza/compose/identity/CredentialParserJvmTest.kt b/composeApp/src/jvmTest/kotlin/mobi/giza/compose/identity/CredentialParserJvmTest.kt index 437baf96..7db5c06c 100644 --- a/composeApp/src/jvmTest/kotlin/mobi/giza/compose/identity/CredentialParserJvmTest.kt +++ b/composeApp/src/jvmTest/kotlin/mobi/giza/compose/identity/CredentialParserJvmTest.kt @@ -138,4 +138,67 @@ class CredentialParserJvmTest { assertNull(CredentialParser.npubOrNull(input), "for '$input'") } } + + // --- recovery codes (docs/recovery-code-v3.md, Phase 5) --- + + private val code = "LBZC-MYTK-E9P3-7C7B-AHJN-KX79-22CY-WAY7-K7QZ" + /** RecoveryCodeKeysTest's pinned npub for [code]. */ + private val codePublicKey = "ece2bc031552ccd5062f6fb933f7e00187e6391df2b81fe0a83e697a7589b89f" + + @Test + fun `a recovery code, typed any way, is the same code`() { + for (input in listOf(code, code.lowercase(), code.replace('-', ' '), code.replace("-", ""), " $code\n", code.replace("-", " "))) { + val credential = assertIs(recognised(input), "for '$input'") + assertEquals(code, credential.code.canonical, "for '$input'") + assertEquals(codePublicKey, credential.nostrPublicKey, "for '$input'") + } + } + + @Test + fun `one wrong symbol is a typo, with the one code it could be`() { + val result = assertIs(CredentialParser.parse("LBTP-WJRN-FXBT-U8KT-ZP5P-AQN9-XK3J-K3CV-2TB5")) + assertEquals(CredentialProblem.RecoveryCodeTypo, result.problem) + val suggestion = result.suggestion ?: error("no suggestion") + assertEquals(5, suggestion.block) + assertEquals(2, suggestion.character) + assertEquals("LBTP-WJRN-FXBT-U8KT-Z45P-AQN9-XK3J-K3CV-2TB5", suggestion.suggested.canonical) + } + + /** + * Two typos: refused as a typo, and with no suggestion -- or, where two errors happen to + * sit one symbol from another valid code, with a suggestion that is *not* the original. + * That second case is why a suggestion is never applied without a press. + */ + @Test + fun `two wrong symbols are a typo without the original as a suggestion`() { + val result = assertIs(CredentialParser.parse("LBTP-RJRN-FXBT-U8KT-Z45P-AQN9-XK33-K3CV-2TB5")) + assertEquals(CredentialProblem.RecoveryCodeTypo, result.problem) + assertNotEquals("LBTP-WJRN-FXBT-U8KT-Z45P-AQN9-XK3J-K3CV-2TB5", result.suggestion?.suggested?.canonical) + } + + @Test + fun `an older code is named for what it is`() { + assertEquals(CredentialProblem.UnsupportedRecoveryCode, refused("LA2Q-48Z3-25JR-S5JB-5SUS-HXHJ-RCMM-8YUA")) + assertEquals(CredentialProblem.UnsupportedRecoveryCode, refused("R52Q-48Z3-25JR-S5JB-5SUS-HXHJ-RCMM-8YUA")) + } + + @Test + fun `the shape of a code that is not one is refused as a code`() { + assertEquals(CredentialProblem.InvalidRecoveryCode, refused("LBZC-MOTK-OOOO-7C7B-AHJN-KX79-22CY-WAY7-K7QZ")) + assertEquals(CredentialProblem.InvalidRecoveryCode, refused("ABCD EFGH JKLM NPQR STUV WXYZ 2345 7899")) + } + + /** Twelve groups is a phrase, however short its words: only eight or nine is a code. */ + @Test + fun `twelve four-letter words are still a phrase`() { + assertEquals(CredentialProblem.InvalidPhrase, refused("able acid also area army atom aunt auto away baby back bake")) + } + + /** The code's 24 words are a phrase, and the same person. */ + @Test + fun `a code's words are the code's key`() { + val parsed = assertIs(recognised(code)) + val words = mobi.giza.compose.identity.recoverycode.RecoveryCodeKeys.words(parsed.code).joinToString(" ") + assertEquals(codePublicKey, assertIs(recognised(words)).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 721af117..ad8c84aa 100644 --- a/composeApp/src/jvmTest/kotlin/mobi/giza/compose/identity/MultipleProfilesRoundTripJvmTest.kt +++ b/composeApp/src/jvmTest/kotlin/mobi/giza/compose/identity/MultipleProfilesRoundTripJvmTest.kt @@ -191,6 +191,7 @@ class MultipleProfilesRoundTripJvmTest { writeNostrKey = { key -> sovereign.writeNostrKey(key) }, writeNostrPublicKey = { pubkey -> sovereign.writeNostrPublicKey(pubkey) }, writeRecoveryPhrase = { _, _, onError -> onError(WritingSeedState.Error.CannotLoadSeedMap) }, + writeRecoveryCode = { mobi.giza.compose.identity.IdentityWriter.WriteRecoveryCodeResult.CannotLoadKeys }, ) // A, from a phrase: both files written, listed once with a wallet attached. diff --git a/composeApp/src/jvmTest/kotlin/mobi/giza/compose/identity/NpubPreviewRoundTripJvmTest.kt b/composeApp/src/jvmTest/kotlin/mobi/giza/compose/identity/NpubPreviewRoundTripJvmTest.kt index 300cc152..6d3a5760 100644 --- a/composeApp/src/jvmTest/kotlin/mobi/giza/compose/identity/NpubPreviewRoundTripJvmTest.kt +++ b/composeApp/src/jvmTest/kotlin/mobi/giza/compose/identity/NpubPreviewRoundTripJvmTest.kt @@ -117,6 +117,7 @@ class NpubPreviewRoundTripJvmTest { writeNostrKey = { key -> IdentityWriter.writeNostrKey(log, phoenixGlobal, globalPrefs, key, isTorEnabled = false, customElectrumServer = null) }, writeNostrPublicKey = { pubkey -> IdentityWriter.writeNostrPublicKey(log, phoenixGlobal, globalPrefs, pubkey, isTorEnabled = false, customElectrumServer = null) }, writeRecoveryPhrase = { _, _, onError -> onError(mobi.giza.compose.ui.view.model.WritingSeedState.Error.CannotLoadSeedMap) }, + writeRecoveryCode = { mobi.giza.compose.identity.IdentityWriter.WriteRecoveryCodeResult.CannotLoadKeys }, ) private fun listed() = StoredIdentity.merge( diff --git a/composeApp/src/jvmTest/kotlin/mobi/giza/compose/ui/view/model/SignInToProfileViewModelJvmTest.kt b/composeApp/src/jvmTest/kotlin/mobi/giza/compose/ui/view/model/SignInToProfileViewModelJvmTest.kt index a750bf7a..dfee3087 100644 --- a/composeApp/src/jvmTest/kotlin/mobi/giza/compose/ui/view/model/SignInToProfileViewModelJvmTest.kt +++ b/composeApp/src/jvmTest/kotlin/mobi/giza/compose/ui/view/model/SignInToProfileViewModelJvmTest.kt @@ -10,6 +10,10 @@ import mobi.giza.compose.identity.IdentityWriter import mobi.giza.compose.identity.SignInCredential import mobi.giza.compose.identity.StoredIdentity import mobi.giza.compose.repository.NostrRepository +import mobi.giza.compose.identity.recoverycode.RecoveryCode +import mobi.giza.compose.ui.view.state.SignInToProfileUIState +import androidx.compose.foundation.text.input.setTextAndPlaceCursorAtEnd +import kotlin.test.assertIs import kotlin.test.Test import kotlin.test.assertEquals @@ -49,11 +53,13 @@ class SignInToProfileViewModelJvmTest { nostrKeyOutcome: () -> IdentityWriter.WriteNostrCredentialResult = { IdentityWriter.WriteNostrCredentialResult.Written(id) }, publicKeyOutcome: () -> IdentityWriter.WriteNostrCredentialResult = { IdentityWriter.WriteNostrCredentialResult.Written(id) }, seedOutcome: ((WalletId) -> Unit, (WritingSeedState.Error) -> Unit) -> Unit = { onWritten, _ -> onWritten(id) }, + codeOutcome: () -> IdentityWriter.WriteRecoveryCodeResult = { IdentityWriter.WriteRecoveryCodeResult.Written(id, isNew = true) }, ) = SignInToProfileViewModel( nostrRepository = recorder, writeNostrKey = { recorder.effects += "writeNostrKey"; nostrKeyOutcome() }, writeNostrPublicKey = { recorder.effects += "writeNostrPublicKey"; publicKeyOutcome() }, writeRecoveryPhrase = { _, onWritten, onError -> recorder.effects += "writeRecoveryPhrase"; seedOutcome(onWritten, onError) }, + writeRecoveryCode = { recorder.effects += "writeRecoveryCode"; codeOutcome() }, ) @Test @@ -142,4 +148,57 @@ class SignInToProfileViewModelJvmTest { fun `both credentials of one key plant the same account`() { assertEquals(StoredIdentity.nostrPublicKeyOf(words), nostrSecret.nostrPublicKey) } + + // --- recovery codes (docs/recovery-code-v3.md, Phase 5) --- + + private val code = (RecoveryCode.parse("LBZC-MYTK-E9P3-7C7B-AHJN-KX79-22CY-WAY7-K7QZ") as RecoveryCode.Parse.Valid).code + private val recoveryCode = SignInCredential.RecoveryCode(code, publicKey) + + @Test + fun `a recovery code goes through the code writer and plants the same account`() = runBlocking { + val recorder = Recorder() + + val outcome = viewModel(recorder).commit(recoveryCode) + + assertEquals(SignInToProfileViewModel.Outcome.SignedIn(id), outcome) + assertEquals(listOf("writeRecoveryCode", "signInToProfile:$publicKey"), recorder.effects) + } + + @Test + fun `a code already on the device is the same refusal`() = runBlocking { + val recorder = Recorder() + + val outcome = viewModel(recorder, codeOutcome = { IdentityWriter.WriteRecoveryCodeResult.AlreadyExists(alreadyHere) }).commit(recoveryCode) + + assertEquals(SignInToProfileViewModel.Outcome.Failed(CredentialProblem.AlreadyOnThisDevice, alreadyHere), outcome) + assertEquals(listOf("writeRecoveryCode"), recorder.effects) + } + + /** + * A typo is offered and not applied: the field keeps what was typed and the screen stays + * on the field until the suggestion is accepted, and accepting it goes to the confirm + * step -- where the npub is shown -- rather than straight to a write. + */ + @Test + fun `a located typo waits for a press, and the press goes to the confirm step`() { + val recorder = Recorder() + val viewModel = viewModel(recorder) + val field = viewModel.signInToProfileFormState.textFieldForm.textFieldState + val typed = "LBTP-WJRN-FXBT-U8KT-ZP5P-AQN9-XK3J-K3CV-2TB5" + field.setTextAndPlaceCursorAtEnd(typed) + + viewModel.recognise() + + assertEquals(CredentialProblem.RecoveryCodeTypo, viewModel.inputProblem.value) + assertEquals(typed, field.text.toString()) + assertIs(viewModel.uiState.value) + + viewModel.acceptSuggestion() + + assertEquals("LBTP-WJRN-FXBT-U8KT-Z45P-AQN9-XK3J-K3CV-2TB5", field.text.toString()) + val confirm = assertIs(viewModel.uiState.value) + assertIs(confirm.credential) + assertEquals(null, viewModel.typoSuggestion.value) + assertEquals(emptyList(), recorder.effects, "nothing written by accepting a suggestion") + } }