diff --git a/.gitmodules b/.gitmodules index 3c2343b8..0f775bbb 100644 --- a/.gitmodules +++ b/.gitmodules @@ -1,3 +1,4 @@ [submodule "lightning-kmp-app"] path = lightning-kmp-app url = https://github.com/kngako/lightning-kmp-app.git + branch = master diff --git a/composeApp/src/commonMain/composeResources/values/strings.xml b/composeApp/src/commonMain/composeResources/values/strings.xml index 3793df7e..32f2d50a 100644 --- a/composeApp/src/commonMain/composeResources/values/strings.xml +++ b/composeApp/src/commonMain/composeResources/values/strings.xml @@ -264,7 +264,13 @@ This will be shown when people open your profile. This will be the display name for this chat room. This will be the display name for your profile and also important for search. - This will give you read only access to the profile. + Read only + Messages need the secret key. This profile is read only: you can see it and the people it follows, but nothing here can be opened or sent. + Sign in with the nsec + Sign out of this profile? + Use a different key? + This device holds no key for %1$s, so there is nothing to lose. The profile stays on the relays, and you can sign in again any time. + Could not sign out. Please try again. This will give you write access to the profile. Curare broadcasts what you publish to a distributed set of relays, so it stays decentralised. Translate chunk @@ -648,13 +654,13 @@ Copied the raw JSON A password-protected key (ncryptsec) is not supported yet. Decrypt it in the app it came from and paste the nsec. - An npub is a public key. Curare needs the secret key, the nsec, to sign as you. Enter a recovery phrase or an nsec to sign in. Paste Recognised as a nostr secret key. No wallet comes with it. Recognised as a recovery phrase. It also restores the wallet. - Recovery phrase or nsec - Sign in with a recovery phrase or an nsec + 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 + 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. @@ -663,7 +669,7 @@ The key could not be saved on this device. Whatever you paste stays on this device. Curare checks it, shows you the profile it opens, and writes nothing until you confirm. This key is already on this device. - Twelve words, or nsec1… + Twelve words, nsec1… or npub1… Use a different key You are signing in as diff --git a/composeApp/src/commonMain/kotlin/to/curare/compose/database/dao/NostrDao.kt b/composeApp/src/commonMain/kotlin/to/curare/compose/database/dao/NostrDao.kt index ceac30fb..27326810 100644 --- a/composeApp/src/commonMain/kotlin/to/curare/compose/database/dao/NostrDao.kt +++ b/composeApp/src/commonMain/kotlin/to/curare/compose/database/dao/NostrDao.kt @@ -445,6 +445,17 @@ abstract class NostrDao( return@let } + if (activeKeyPair.privKey == null) { + // Addressed to us, and we cannot open it: a read-only identity. Keep the + // event and the wrap, as the branch above does for wraps addressed to + // someone else; the key that opens this one may be signed in later. Without + // this, the unseal below would run with a key nobody has and throw, and + // the throw would take the event with it. + logger.d("GiftWrap ${nostrEvent.id} is addressed to us, but this identity holds no key") + + return@let + } + giftWrapMessage.decryptGiftWrapSeal( activeKeyPair ).let { giftWrapSeal -> diff --git a/composeApp/src/commonMain/kotlin/to/curare/compose/database/repository/DatabaseNostrRepository.kt b/composeApp/src/commonMain/kotlin/to/curare/compose/database/repository/DatabaseNostrRepository.kt index 80d18225..dd9706d4 100644 --- a/composeApp/src/commonMain/kotlin/to/curare/compose/database/repository/DatabaseNostrRepository.kt +++ b/composeApp/src/commonMain/kotlin/to/curare/compose/database/repository/DatabaseNostrRepository.kt @@ -258,6 +258,17 @@ class DatabaseNostrRepository( override suspend fun signInToProfile( publicKey: HexKey ) { + // Idempotent by pubkey. Until the read-only kind, nothing called this twice for + // one key -- the writers refused a second sign-in before it got here. Pasting the + // nsec of a key held read-only is the first path that signs in a pubkey whose + // account already exists, and a second placeholder would be two kind-0 rows for + // one pubkey: two accounts disagreeing about which is this one, the failure + // `setUpProfileForExistingKey`'s own comment describes. + if (database.unsignedNostrEventDao().getLocalAccounts().any { it.unsignedNostrEvent?.pubKey == publicKey }) { + logger.d("signInToProfile: $publicKey already has an account here, nothing to plant") + return + } + val profileEventTemplate = MetadataEvent.createNew() saveUnsignedNostrEvent( diff --git a/composeApp/src/commonMain/kotlin/to/curare/compose/identity/CredentialParser.kt b/composeApp/src/commonMain/kotlin/to/curare/compose/identity/CredentialParser.kt index 12095dd8..94cfb288 100644 --- a/composeApp/src/commonMain/kotlin/to/curare/compose/identity/CredentialParser.kt +++ b/composeApp/src/commonMain/kotlin/to/curare/compose/identity/CredentialParser.kt @@ -2,16 +2,18 @@ package to.curare.compose.identity import com.vitorpamplona.quartz.nip01Core.core.HexKey import com.vitorpamplona.quartz.nip19Bech32.bech32.Bech32 +import fr.acinq.bitcoin.ByteVector32 import fr.acinq.bitcoin.MnemonicCode import fr.acinq.bitcoin.PrivateKey +import fr.acinq.bitcoin.XonlyPublicKey import fr.acinq.phoenix.managers.nostrPublicKeyHex import fr.acinq.phoenix.utils.MnemonicLanguage /** * What a user pasted into the sign-in field, once it has been recognised. * - * Both carry the nostr public key, because the confirm step shows it and the duplicate - * check compares it. Neither prints its secret. + * All three carry the nostr public key, because the confirm step shows it and the + * duplicate check compares it. None prints a secret. */ sealed interface SignInCredential { val nostrPublicKey: HexKey @@ -31,6 +33,11 @@ sealed interface SignInCredential { ) : SignInCredential { override fun toString(): String = "NostrSecret(npub=$nostrPublicKey, key=)" } + + /** A bare nostr public key. Nothing can be signed with it: a profile to look at. */ + data class NostrPublicKey( + override val nostrPublicKey: HexKey, + ) : SignInCredential } /** Why an input was not accepted. The screen turns each into a sentence. */ @@ -44,12 +51,9 @@ enum class CredentialProblem { /** Words, but the checksum or the wordlist says no: a wrong word, or one out of order. */ InvalidPhrase, - /** An nsec or hex that does not decode to a valid secp256k1 secret. */ + /** An nsec or hex that does not decode to a valid secp256k1 secret, or an npub that does not decode to a point on the curve. */ InvalidKey, - /** An npub. A public key cannot sign, and every write path here assumes a key that can. */ - PublicKeyOnly, - /** An ncryptsec (NIP-49). Decrypting one is a follow-on; say so rather than fail opaquely. */ EncryptedKey, @@ -63,11 +67,18 @@ 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 two accepted - * shapes are unambiguous -- words have spaces, keys do not -- and the two refused - * shapes are named for what they are rather than lumped in with garbage, because a - * user who pasted an npub or an ncryptsec did something reasonable and should be told - * what to do instead. + * 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 + * with garbage, because a user who pasted an ncryptsec did something reasonable and + * should be told what to do instead. + * + * **Hex stays a secret.** A private key and an x-only public key are both thirty-two + * bytes, and sixty-four hex characters cannot say which. The confirm step shows the + * derived npub, so a public key pasted as hex is visible for what it is; guessing -- + * "not a valid secret, so try it as a public key" -- would never fire when it mattered, + * since an x coordinate is, with overwhelming probability, also a valid scalar. An npub + * has to arrive as an npub. */ object CredentialParser { @@ -91,7 +102,7 @@ object CredentialParser { // prefix is how a key arrives from a link. val token = text.removePrefix("nostr:").lowercase() return when { - token.startsWith("npub1") -> Result.Refused(CredentialProblem.PublicKeyOnly) + token.startsWith("npub1") -> npub(token) token.startsWith("ncryptsec1") -> Result.Refused(CredentialProblem.EncryptedKey) token.startsWith("nsec1") -> nsec(token) hex64.matches(token) -> secret(runCatching { PrivateKey.fromHex(token) }.getOrNull()) @@ -119,4 +130,21 @@ object CredentialParser { if (privateKey == null || !privateKey.isValid()) return Result.Refused(CredentialProblem.InvalidKey) return Result.Recognised(SignInCredential.NostrSecret(privateKey, privateKey.nostrPublicKeyHex())) } + + /** + * Thirty-two bytes under the `npub` prefix that name a point on the curve -- the + * counterpart of the `isValid()` a secret is checked with, since not every x + * coordinate has a point above it. + */ + private fun npub(token: String): Result { + val bytes = runCatching { + val (hrp, data) = Bech32.decodeBytes(token) + require(hrp == "npub") { "not an npub" } + require(data.size == 32) { "not an x-only key" } + data + }.getOrNull() ?: return Result.Refused(CredentialProblem.InvalidKey) + val xOnly = XonlyPublicKey(ByteVector32(bytes)) + if (!xOnly.publicKey.isValid()) return Result.Refused(CredentialProblem.InvalidKey) + return Result.Recognised(SignInCredential.NostrPublicKey(xOnly.value.toHex())) + } } diff --git a/composeApp/src/commonMain/kotlin/to/curare/compose/identity/ForgetIdentity.kt b/composeApp/src/commonMain/kotlin/to/curare/compose/identity/ForgetIdentity.kt new file mode 100644 index 00000000..eee1c545 --- /dev/null +++ b/composeApp/src/commonMain/kotlin/to/curare/compose/identity/ForgetIdentity.kt @@ -0,0 +1,50 @@ +package to.curare.compose.identity + +import to.curare.compose.repository.NostrRepository + +/** + * Takes an identity off the device: the credential out of the file, its preference + * files deleted, its metadata hidden, its account rows gone -- in that order, so a + * failure partway leaves the credential on disk rather than an identity the selector + * lists but nothing can open. The caller then re-lists and clears the active identity. + * + * Lifted out of `NostrSecretViewModel.forgetKey`, where it was written for an nsec, so + * that the two exits a read-only identity has -- sign out, and *use a different key* on + * the not-found screen -- run the same sequence rather than a copy of it. The first step + * is the same call for both credential kinds since the credentials file; only a mnemonic + * identity is refused, because removing a seed is a wallet question this does not + * answer. + * + * The two writers are injected as functions so the sequence can be pinned in a test + * without a key store, as the nsec view model's already is. + */ +object ForgetIdentity { + + sealed interface Outcome { + /** The device no longer holds anything for the identity. */ + data object Forgotten : Outcome + + /** A mnemonic identity: its key is in the seed, and this does not remove seeds. */ + data object NotACredential : Outcome + + /** The credentials file could not be read; nothing was changed. */ + data object CannotForget : Outcome + } + + suspend fun forget( + identity: Identity, + nostrRepository: NostrRepository, + forgetNostrCredential: suspend (Identity) -> IdentityWriter.ForgetNostrCredentialResult, + hideIdentityMetadata: suspend (Identity) -> Unit, + ): Outcome = when (forgetNostrCredential(identity)) { + is IdentityWriter.ForgetNostrCredentialResult.Forgotten -> { + hideIdentityMetadata(identity) + // The kind 0 that made it a local account, and anything queued that can now + // never be signed. Published events and the profile cache stay. + nostrRepository.forgetLocalAccount(identity.nostrPublicKey) + Outcome.Forgotten + } + is IdentityWriter.ForgetNostrCredentialResult.NotACredential -> Outcome.NotACredential + is IdentityWriter.ForgetNostrCredentialResult.CannotLoadKeys -> Outcome.CannotForget + } +} diff --git a/composeApp/src/commonMain/kotlin/to/curare/compose/identity/Identity.kt b/composeApp/src/commonMain/kotlin/to/curare/compose/identity/Identity.kt index 09e676ce..b2598030 100644 --- a/composeApp/src/commonMain/kotlin/to/curare/compose/identity/Identity.kt +++ b/composeApp/src/commonMain/kotlin/to/curare/compose/identity/Identity.kt @@ -1,12 +1,15 @@ package to.curare.compose.identity import com.vitorpamplona.quartz.nip01Core.core.HexKey +import com.vitorpamplona.quartz.nip01Core.core.hexToByteArray +import com.vitorpamplona.quartz.nip01Core.crypto.KeyPair import fr.acinq.bitcoin.Crypto import fr.acinq.bitcoin.PrivateKey import fr.acinq.bitcoin.XonlyPublicKey import fr.acinq.bitcoin.byteVector import fr.acinq.phoenix.PhoenixBusiness import fr.acinq.phoenix.data.WalletId +import fr.acinq.phoenix.managers.nostrPublicKeyHex import fr.acinq.phoenix.utils.preferences.InternalPrefs import fr.acinq.phoenix.utils.preferences.UserPrefs @@ -16,7 +19,8 @@ import fr.acinq.phoenix.utils.preferences.UserPrefs * The distinction is not cosmetic: the nostr key is a BIP32 leaf of the seed at * `m/44'/1237'/0'/0/0`, and that derivation runs one way. Twelve words yield the * key and a wallet; a bare key yields nothing further, so an identity made from - * one can never grow a node behind it. See docs/nsec-sign-in.md. + * one can never grow a node behind it; and a bare public key yields nothing at all, + * not even a signature. See docs/nsec-sign-in.md and docs/npub-sign-in.md. */ enum class IdentityKind { /** Twelve words. The nostr key is derived from them, and so is a wallet. */ @@ -24,10 +28,14 @@ enum class IdentityKind { /** A bare nostr secret. Nothing else can be derived from it. */ NostrSecret, + + /** A bare nostr public key. Nothing can be signed, opened or derived from it. */ + NostrPublic, } /** - * The signing identity the app is running as. + * The signing identity the app is running as -- or, for [IdentityKind.NostrPublic], + * the identity it is looking at. * * This is what every consumer of "the active user" reads, in place of reaching * through the wallet -- `business.walletManager.keyManager.value.nostrPrivateKey()` @@ -37,34 +45,114 @@ enum class IdentityKind { * Marmot bundle password is `hash160` of it. None of them can tell where it came * from, and after this type none of them need to. * + * [nostrPublicKey] is a field rather than a derivation because a read-only identity + * has nothing to derive it from. The two checks in `init` keep the field and the key + * from disagreeing, which a data class would otherwise happily allow; [signing] and + * [readOnly] are the two ways to get one built without tripping them. + * * @param id keys the per-identity preference files and the wallet metadata. For a * [IdentityKind.Mnemonic] identity it is the hash160 of the node id, as it always - * was; for a [IdentityKind.NostrSecret] identity it is the hash160 of the x-only - * public key ([toWalletId]). Same shape, so nothing downstream can tell the kinds - * apart by the id -- the kind is here, where it can be asked. + * was; for the two bare kinds it is the hash160 of the x-only public key + * ([toWalletId]) -- the *same* id whether the device holds the secret or only the + * public key, which is what lets a read-only identity become a signing one and keep + * its preferences. Same shape as a wallet's, so nothing downstream can tell the + * kinds apart by the id -- the kind is here, where it can be asked. + * @param nostrPrivateKey null only for [IdentityKind.NostrPublic]. * @param business the running node. Non-null only for [IdentityKind.Mnemonic]. */ data class Identity( val id: WalletId, val kind: IdentityKind, - val nostrPrivateKey: PrivateKey, - val userPrefs: UserPrefs, - val internalPrefs: InternalPrefs, - val business: PhoenixBusiness?, -) { /** - * X-only, hex -- the form every nostr call site wants. Computed once. + * X-only, hex -- the form every nostr call site wants. * * Not `publicKey().toHex()`: that is the 33-byte compressed encoding, sixty-six * hex characters, and it is what the library's own `nostrPublicKey()` returns. * Nostr keys are the 32-byte x coordinate. */ - val nostrPublicKey: HexKey = nostrPrivateKey.publicKey().xOnly().value.toHex() + val nostrPublicKey: HexKey, + val nostrPrivateKey: PrivateKey?, + val userPrefs: UserPrefs, + val internalPrefs: InternalPrefs, + val business: PhoenixBusiness?, +) { + /** + * What the notary, the pumps and every write entrance ask. + * + * A property of the identity rather than `nostrPrivateKey != null` repeated at each + * site, so that a signer that holds no local key -- a remote one, some day -- has + * one place to answer *true*. + */ + val canSign: Boolean get() = nostrPrivateKey != null + + init { + require((nostrPrivateKey == null) == (kind == IdentityKind.NostrPublic)) { + "identity kind $kind and its key disagree about whether there is one" + } + require(nostrPrivateKey == null || nostrPrivateKey.nostrPublicKeyHex() == nostrPublicKey) { + "identity key does not derive the public key it was given" + } + } /** The key must never reach a log. `data class` would print it. */ override fun toString(): String = "Identity(id=$id, kind=$kind, key=)" + + companion object { + /** An identity that holds its secret: the public key is derived, never supplied. */ + fun signing( + id: WalletId, + kind: IdentityKind, + nostrPrivateKey: PrivateKey, + userPrefs: UserPrefs, + internalPrefs: InternalPrefs, + business: PhoenixBusiness?, + ): Identity { + require(kind != IdentityKind.NostrPublic) { "a read-only identity has no secret to sign with" } + return Identity( + id = id, + kind = kind, + nostrPublicKey = nostrPrivateKey.nostrPublicKeyHex(), + nostrPrivateKey = nostrPrivateKey, + userPrefs = userPrefs, + internalPrefs = internalPrefs, + business = business, + ) + } + + /** An identity the device holds only the public key of. No secret, no node. */ + fun readOnly( + id: WalletId, + nostrPublicKey: HexKey, + userPrefs: UserPrefs, + internalPrefs: InternalPrefs, + ): Identity = Identity( + id = id, + kind = IdentityKind.NostrPublic, + nostrPublicKey = nostrPublicKey, + nostrPrivateKey = null, + userPrefs = userPrefs, + internalPrefs = internalPrefs, + business = null, + ) + } } +/** + * The one place a quartz [KeyPair] is built from an identity. + * + * With a secret, quartz recomputes the public key from it and the second argument is a + * cross-check. Without one it is quartz's read-only constructor, which its own source + * comments as "this is a read-only account". What it must never be is + * `KeyPair(privKey = null)` with nothing else: that is quartz's *make me a new key*, and + * a read-only pair forwarded into it would try to open the user's gift wraps with a key + * nobody has, fail, and look in the logs like a decryption failure. This helper exists so + * that the trap has one place to be avoided. + */ +fun Identity.toKeyPair(): KeyPair = KeyPair( + privKey = nostrPrivateKey?.value?.toByteArray(), + pubKey = nostrPublicKey.hexToByteArray(), +) + /** * The [WalletId] of an identity that has no node id to hash. * diff --git a/composeApp/src/commonMain/kotlin/to/curare/compose/identity/IdentityWriter.kt b/composeApp/src/commonMain/kotlin/to/curare/compose/identity/IdentityWriter.kt index 61ea936b..b6887369 100644 --- a/composeApp/src/commonMain/kotlin/to/curare/compose/identity/IdentityWriter.kt +++ b/composeApp/src/commonMain/kotlin/to/curare/compose/identity/IdentityWriter.kt @@ -11,12 +11,13 @@ import fr.acinq.phoenix.data.ElectrumConfig import fr.acinq.phoenix.data.WalletId import fr.acinq.phoenix.managers.DataStoreManager import fr.acinq.phoenix.managers.NodeParamsManager -import fr.acinq.phoenix.managers.NostrKeyManager +import fr.acinq.phoenix.managers.NostrCredentialManager import fr.acinq.phoenix.managers.SeedManager import fr.acinq.phoenix.managers.nostrPrivateKey import fr.acinq.phoenix.managers.nostrPublicKeyHex -import fr.acinq.phoenix.security.EncryptedNostrKeys +import fr.acinq.phoenix.security.EncryptedNostrCredentials import fr.acinq.phoenix.security.EncryptedSeed +import fr.acinq.phoenix.security.NostrCredential import fr.acinq.phoenix.utils.preferences.GlobalPrefs import kotlinx.coroutines.CoroutineExceptionHandler import kotlinx.coroutines.CoroutineScope @@ -28,8 +29,8 @@ import to.curare.compose.AppVersion import to.curare.compose.ui.view.model.WritingSeedState /** - * Puts a new identity's secret on disk, one function per kind, and prepares the - * per-identity preferences both kinds read. + * Puts a new identity on disk, one function per kind, and prepares the per-identity + * preferences every kind reads. * * [writeMnemonic] was an `expect` with three byte-identical actuals -- android, jvm, ios -- * using nothing but commonMain: SeedManager, EncryptedSeed, LocalKeyManager, @@ -37,19 +38,24 @@ import to.curare.compose.ui.view.model.WritingSeedState * differ and nothing does now, so it is one function here, and the second writer sits * next to it rather than being triplicated in turn. * - * Both refuse a duplicate **by nostr public key**, not only by id. A wallet and an + * All three refuse a duplicate **by nostr public key**, not only by id. A wallet and an * imported key can be the same npub under different ids -- one is hash160 of the node * key, the other hash160 of the nostr key -- and the database is keyed by pubkey, so two * identities for one pubkey would share every row and disagree about which is active. + * + * With one exception, which is the point of the credentials file: a public key already + * here read-only is not a duplicate of the secret that signs as it. The device does not + * have that secret, and refusing it would be false. [writeNostrKey] replaces the entry + * in one write; [writeMnemonic] has to span two files and says which goes first. */ object IdentityWriter { - /** The nostr public keys of every identity already on this device, or null if a store could not be read. */ - private fun knownNostrPublicKeys(phoenixGlobal: PhoenixGlobal): Set? { - val wallets = SeedManager.loadAndDecryptOrNull(phoenixGlobal) ?: return null - val nostrKeys = NostrKeyManager.loadAndDecryptOrNull(phoenixGlobal) ?: return null - return StoredIdentity.merge(wallets, nostrKeys).values.map { it.nostrPublicKey }.toSet() - } + /** What the seed store says, or null if it could not be read. */ + private fun seedPublicKeys(phoenixGlobal: PhoenixGlobal): Set? = + SeedManager.loadAndDecryptOrNull(phoenixGlobal) + ?.values + ?.map { StoredIdentity.nostrPublicKeyOf(it.words) } + ?.toSet() /** * Creates the preference files a new id needs and records the choices made before @@ -107,8 +113,8 @@ object IdentityWriter { val existingSeeds = SeedManager.loadAndDecryptOrNull(phoenixGlobal)?.map { it.key to it.value.words }?.toMap() - // Null when nostr-keys.dat exists and cannot be read; an empty map when it is absent. - val existingNostrKeys = NostrKeyManager.loadAndDecryptOrNull(phoenixGlobal) + // Null when nostr-credentials.dat exists and cannot be read; an empty map when it is absent. + val existingCredentials = NostrCredentialManager.loadAndDecryptOrNull(phoenixGlobal) val seed = MnemonicCode.toSeed(mnemonics, "").toByteVector() val keyManager = LocalKeyManager(seed, NodeParamsManager.chain, NodeParamsManager.remoteSwapInXpub) @@ -116,7 +122,7 @@ object IdentityWriter { val newNostrPublicKey = keyManager.nostrPrivateKey().nostrPublicKeyHex() when { - existingSeeds == null || existingNostrKeys == null -> { + existingSeeds == null || existingCredentials == null -> { log.e("could not load the existing seed map, aborting...") onWritingSeedError.invoke( WritingSeedState.Error.CannotLoadSeedMap @@ -130,7 +136,7 @@ object IdentityWriter { ) return@launch } - existingNostrKeys.containsKey(newNostrPublicKey) -> { + existingCredentials[newNostrPublicKey] is NostrCredential.Secret -> { // The same npub is already here as a bare key. The id check above cannot // see that -- different hash, different key -- so it is asked by pubkey. log.i("attempting to import a seed whose nostr key is already here, aborting...") @@ -140,6 +146,18 @@ object IdentityWriter { return@launch } else -> { + if (existingCredentials[newNostrPublicKey] is NostrCredential.Public) { + // The npub is here read-only, and the words that sign as it have just + // been pasted: an upgrade, across two files. The credential goes + // first, then the seed. A crash between the two loses the read-only + // identity, which the npub pasted again restores; the reverse order + // would leave one npub listed twice under two ids. + log.i("the seed's nostr key is here read-only; replacing it with the wallet") + NostrCredentialManager.writeToDisk( + phoenixGlobal, + EncryptedNostrCredentials.encrypt(existingCredentials - newNostrPublicKey), + ) + } val newSeedMap = existingSeeds + (newWalletId to mnemonics) val encrypted = EncryptedSeed.V2.encrypt(newSeedMap) SeedManager.writeSeedToDisk(phoenixGlobal, encrypted, overwrite = true) @@ -160,21 +178,28 @@ object IdentityWriter { } } - sealed class WriteNostrKeyResult { - data class Written(val id: WalletId) : WriteNostrKeyResult() + sealed class WriteNostrCredentialResult { + data class Written(val id: WalletId) : WriteNostrCredentialResult() - /** An identity with this nostr public key is already on the device, as a wallet or as a key. */ - data object AlreadyExists : WriteNostrKeyResult() + /** + * An identity with this nostr public key is already on the device and holds at least + * what was pasted: a wallet or a secret, for either input; a public key, for an npub. + */ + data object AlreadyExists : WriteNostrCredentialResult() /** One of the two stores exists and could not be read; nothing was written. */ - data object CannotLoadKeys : WriteNostrKeyResult() + data object CannotLoadKeys : WriteNostrCredentialResult() } /** - * Adds [privateKey] to `nostr-keys.dat` and prepares its preferences. Suspending and - * result-shaped rather than callback-shaped: nothing was built around a state machine - * for it, and the caller is a coroutine already. Throws on an I/O or key store failure - * during the write, as [writeMnemonic]'s handler would have caught. + * Adds [privateKey] to `nostr-credentials.dat` as a secret and prepares its + * preferences. Suspending and result-shaped rather than callback-shaped: nothing was + * built around a state machine for it, and the caller is a coroutine already. Throws + * on an I/O or key store failure during the write, as [writeMnemonic]'s handler would + * have caught. + * + * A public entry for the same key is the one thing that is not a duplicate: the entry + * becomes a secret one, in a single write, under the id it already had. */ suspend fun writeNostrKey( log: Logger, @@ -183,65 +208,112 @@ object IdentityWriter { privateKey: PrivateKey, isTorEnabled: Boolean, customElectrumServer: ElectrumConfig.Custom?, - ): WriteNostrKeyResult { + ): WriteNostrCredentialResult { log.d("writing nostr key to disk...") val stored = StoredIdentity.nostrSecret(privateKey) - val known = knownNostrPublicKeys(phoenixGlobal) - val existingNostrKeys = NostrKeyManager.loadAndDecryptOrNull(phoenixGlobal) - if (known == null || existingNostrKeys == null) { + val seeds = seedPublicKeys(phoenixGlobal) + val existing = NostrCredentialManager.loadAndDecryptOrNull(phoenixGlobal) + if (seeds == null || existing == null) { log.e("could not load the existing keys, aborting...") - return WriteNostrKeyResult.CannotLoadKeys + return WriteNostrCredentialResult.CannotLoadKeys } - if (stored.nostrPublicKey in known) { + if (stored.nostrPublicKey in seeds || existing[stored.nostrPublicKey] is NostrCredential.Secret) { log.i("attempting to import a nostr key that is already here, aborting...") - return WriteNostrKeyResult.AlreadyExists + return WriteNostrCredentialResult.AlreadyExists } + val upgrading = existing[stored.nostrPublicKey] is NostrCredential.Public - val encrypted = EncryptedNostrKeys.encrypt(existingNostrKeys + (stored.nostrPublicKey to privateKey)) - NostrKeyManager.writeToDisk(phoenixGlobal, encrypted) - log.i("successfully imported nostr key for identity=${stored.id}") + val encrypted = EncryptedNostrCredentials.encrypt( + existing + (stored.nostrPublicKey to NostrCredential.Secret(privateKey)) + ) + NostrCredentialManager.writeToDisk(phoenixGlobal, encrypted) + if (upgrading) { + log.i("read-only identity=${stored.id} now holds its key") + } else { + log.i("successfully imported nostr key for identity=${stored.id}") + } prepareIdentity(phoenixGlobal, globalPrefs, stored.id, isTorEnabled, customElectrumServer) - return WriteNostrKeyResult.Written(stored.id) - } - - sealed class ForgetNostrKeyResult { - data object Forgotten : ForgetNostrKeyResult() - - /** The key is not in `nostr-keys.dat`: a mnemonic identity's key lives in the seed, and removing a seed is a wallet question. */ - data object NotABareKey : ForgetNostrKeyResult() - - data object CannotLoadKeys : ForgetNostrKeyResult() + return WriteNostrCredentialResult.Written(stored.id) } /** - * The inverse of [writeNostrKey]: removes the key from `nostr-keys.dat` and deletes - * the identity's preference files. The profile stays on the relays, and the same key - * can be signed in again. Only for a bare key -- see [ForgetNostrKeyResult.NotABareKey]. + * Adds [nostrPublicKey] to `nostr-credentials.dat` as a public entry -- an identity + * the device can look at and not sign as -- and prepares its preferences. Refused if + * the device already holds anything at all for the key, since anything is more than + * this. */ - suspend fun forgetNostrKey( + suspend fun writeNostrPublicKey( + log: Logger, + phoenixGlobal: PhoenixGlobal, + globalPrefs: GlobalPrefs, + nostrPublicKey: HexKey, + isTorEnabled: Boolean, + customElectrumServer: ElectrumConfig.Custom?, + ): WriteNostrCredentialResult { + log.d("writing nostr public key to disk...") + val stored = StoredIdentity.nostrPublic(nostrPublicKey) + + val seeds = seedPublicKeys(phoenixGlobal) + val existing = NostrCredentialManager.loadAndDecryptOrNull(phoenixGlobal) + if (seeds == null || existing == null) { + log.e("could not load the existing keys, aborting...") + return WriteNostrCredentialResult.CannotLoadKeys + } + if (stored.nostrPublicKey in seeds || existing.containsKey(stored.nostrPublicKey)) { + log.i("attempting to add a public key the device already holds something for, aborting...") + return WriteNostrCredentialResult.AlreadyExists + } + + NostrCredentialManager.writeToDisk( + phoenixGlobal, + EncryptedNostrCredentials.encrypt(existing + (stored.nostrPublicKey to NostrCredential.Public)), + ) + log.i("added read-only identity=${stored.id}") + + prepareIdentity(phoenixGlobal, globalPrefs, stored.id, isTorEnabled, customElectrumServer) + + return WriteNostrCredentialResult.Written(stored.id) + } + + sealed class ForgetNostrCredentialResult { + data object Forgotten : ForgetNostrCredentialResult() + + /** The key is not in `nostr-credentials.dat`: a mnemonic identity's key lives in the seed, and removing a seed is a wallet question. */ + data object NotACredential : ForgetNostrCredentialResult() + + data object CannotLoadKeys : ForgetNostrCredentialResult() + } + + /** + * The inverse of [writeNostrKey] and [writeNostrPublicKey] alike: removes the entry, + * whichever kind it is, from `nostr-credentials.dat` and deletes the identity's + * preference files. The profile stays on the relays, and the same key can be signed + * in again. Only for a credential -- see [ForgetNostrCredentialResult.NotACredential]. + */ + suspend fun forgetNostrCredential( log: Logger, phoenixGlobal: PhoenixGlobal, id: WalletId, nostrPublicKey: HexKey, - ): ForgetNostrKeyResult { - val existing = NostrKeyManager.loadAndDecryptOrNull(phoenixGlobal) + ): ForgetNostrCredentialResult { + val existing = NostrCredentialManager.loadAndDecryptOrNull(phoenixGlobal) if (existing == null) { log.e("could not load the existing keys, aborting...") - return ForgetNostrKeyResult.CannotLoadKeys + return ForgetNostrCredentialResult.CannotLoadKeys } if (!existing.containsKey(nostrPublicKey)) { - log.i("asked to forget a key that is not a bare key on this device") - return ForgetNostrKeyResult.NotABareKey + log.i("asked to forget a key that is not a credential on this device") + return ForgetNostrCredentialResult.NotACredential } - NostrKeyManager.writeToDisk(phoenixGlobal, EncryptedNostrKeys.encrypt(existing - nostrPublicKey)) - log.i("forgot nostr key for identity=$id") + NostrCredentialManager.writeToDisk(phoenixGlobal, EncryptedNostrCredentials.encrypt(existing - nostrPublicKey)) + log.i("forgot nostr credential for identity=$id") DataStoreManager(phoenixGlobal.ctx, chain = NodeParamsManager.chain).deleteNodeUserPrefs(id) - return ForgetNostrKeyResult.Forgotten + return ForgetNostrCredentialResult.Forgotten } } diff --git a/composeApp/src/commonMain/kotlin/to/curare/compose/identity/StoredIdentity.kt b/composeApp/src/commonMain/kotlin/to/curare/compose/identity/StoredIdentity.kt index 0490f59b..47fa9b81 100644 --- a/composeApp/src/commonMain/kotlin/to/curare/compose/identity/StoredIdentity.kt +++ b/composeApp/src/commonMain/kotlin/to/curare/compose/identity/StoredIdentity.kt @@ -1,5 +1,6 @@ package to.curare.compose.identity +import co.touchlab.kermit.Logger import com.vitorpamplona.quartz.nip01Core.core.HexKey import fr.acinq.bitcoin.ByteVector32 import fr.acinq.bitcoin.MnemonicCode @@ -12,14 +13,16 @@ import fr.acinq.phoenix.data.WalletId import fr.acinq.phoenix.managers.NodeParamsManager import fr.acinq.phoenix.managers.nostrPrivateKey import fr.acinq.phoenix.managers.nostrPublicKeyHex +import fr.acinq.phoenix.security.NostrCredential /** - * An identity this device holds the secret for, as listed before any of them is started. + * An identity this device holds something for, as listed before any of them is started. * - * Two stores feed this -- `seed.dat` for wallets, `nostr-keys.dat` for bare keys -- and - * the startup screen wants one list. The nostr public key is on both kinds because it - * is the one thing they have in common and the one thing a duplicate check has to - * compare: a wallet and an imported key can be the *same* npub under different ids. + * Two stores feed this -- `seed.dat` for wallets, `nostr-credentials.dat` for bare keys + * and bare public keys -- and the startup screen wants one list. The nostr public key + * is on every kind because it is the one thing they have in common and the one thing a + * duplicate check has to compare: a wallet and an imported key can be the *same* npub + * under different ids. * * On what this holds: `SovereignWalletViewModel.availableWallets` has always carried * decrypted words for the view model's life, because starting the node needs them. @@ -49,6 +52,17 @@ sealed interface StoredIdentity { override fun toString(): String = "StoredIdentity.NostrSecret(id=$id, npub=$nostrPublicKey, key=)" } + /** + * A public key the device holds nothing else for. Its id is the one its secret would + * have, so that pasting the nsec later keeps the preferences and metadata. + */ + data class NostrPublic( + override val id: WalletId, + override val nostrPublicKey: HexKey, + ) : StoredIdentity { + override val kind: IdentityKind get() = IdentityKind.NostrPublic + } + companion object { /** * The nostr public key a wallet's words derive. `SeedManager.loadAndDecrypt` has @@ -73,24 +87,53 @@ sealed interface StoredIdentity { ) } + fun nostrPublic(publicKeyHex: HexKey): NostrPublic = NostrPublic( + id = publicKeyHex.toXonlyPublicKey().toWalletId(), + nostrPublicKey = publicKeyHex, + ) + /** - * One map from the two stores. [nostrKeys] is keyed by x-only public key hex, as - * `nostr-keys.dat` is; the id of each is derived from that key, so a stored key - * whose map key disagrees with its own public key is dropped here too, though - * `EncryptedNostrKeys` refuses such a file before it gets this far. + * One map from the two stores. [credentials] is keyed by x-only public key hex, as + * `nostr-credentials.dat` is; a secret's id is derived from its own key, so a + * stored secret whose map key disagrees with its public key is dropped here too, + * though `EncryptedNostrCredentials` refuses such a file before it gets this far. + * + * One entry per public key is the credentials file's own invariant, so there is no + * precedence between credentials to decide. There is one between a seed and a + * credential, for the one upgrade that has to span both files -- a recovery phrase + * pasted over a public credential, which `IdentityWriter.writeMnemonic` performs as + * two writes: a `Public` whose public key a seed derives is dropped, with a log line, + * and the next write repairs the file. A *secret* for a seed's key is kept, as it + * always was: two ids for one npub is a duplicate the writers refuse, not a state + * the listing hides. */ fun merge( wallets: Map, - nostrKeys: Map, + credentials: Map, ): Map { val merged = LinkedHashMap() wallets.values.forEach { userWallet -> merged[userWallet.walletId] = mnemonic(userWallet) } - nostrKeys.forEach { (publicKeyHex, privateKey) -> - val stored = nostrSecret(privateKey) - if (stored.nostrPublicKey == publicKeyHex) merged[stored.id] = stored + val seedPublicKeys = merged.values.map { it.nostrPublicKey }.toSet() + credentials.forEach { (publicKeyHex, credential) -> + when (credential) { + is NostrCredential.Secret -> { + val stored = nostrSecret(credential.privateKey) + if (stored.nostrPublicKey == publicKeyHex) merged[stored.id] = stored + } + is NostrCredential.Public -> { + if (publicKeyHex in seedPublicKeys) { + log.w { "public credential for a key a seed already derives; listing the wallet only" } + } else { + val stored = runCatching { nostrPublic(publicKeyHex) }.getOrNull() + if (stored != null) merged[stored.id] = stored + } + } + } } return merged } + + private val log = Logger.withTag("StoredIdentity") } } diff --git a/composeApp/src/commonMain/kotlin/to/curare/compose/ui/composable/ActiveProfileScreen.kt b/composeApp/src/commonMain/kotlin/to/curare/compose/ui/composable/ActiveProfileScreen.kt index e0de958d..717a587c 100644 --- a/composeApp/src/commonMain/kotlin/to/curare/compose/ui/composable/ActiveProfileScreen.kt +++ b/composeApp/src/commonMain/kotlin/to/curare/compose/ui/composable/ActiveProfileScreen.kt @@ -50,6 +50,7 @@ import to.curare.compose.ui.view.model.ActiveProfileViewModel import to.curare.compose.ui.view.state.ActiveProfileUIState import com.vitorpamplona.quartz.nip01Core.core.HexKey import com.vitorpamplona.quartz.nip01Core.metadata.MetadataEvent +import to.curare.compose.ui.composable.widgets.LocalCanSign import to.curare.compose.ui.theme.spacing import curare.composeapp.generated.resources.Res import org.jetbrains.compose.resources.stringResource @@ -61,6 +62,16 @@ import curare.composeapp.generated.resources.profile import curare.composeapp.generated.resources.key_recovery import curare.composeapp.generated.resources.share_profile import curare.composeapp.generated.resources.sign_out +import curare.composeapp.generated.resources.sign_out_of_this_profile_question +import curare.composeapp.generated.resources.could_not_sign_out_please_try_again +import to.curare.compose.identity.Identity +import to.curare.compose.identity.IdentityWriter +import to.curare.compose.ui.composable.widgets.dialogs.SignOutOfReadOnlyDialog +import to.curare.compose.ui.composable.widgets.rememberNotifier +import to.curare.compose.ui.view.model.SignOutViewModel +import kotlinx.coroutines.flow.StateFlow +import androidx.compose.runtime.collectAsState +import androidx.compose.runtime.rememberCoroutineScope import curare.composeapp.generated.resources.something_went_wrong import curare.composeapp.generated.resources.we_couldn_t_find_the_local_profile_please import to.curare.compose.ui.composable.widgets.ErrorState @@ -82,8 +93,42 @@ fun ActiveProfileScreen( onNavigateBack: () -> Unit, onNavigateToRoute: (Route) -> Unit, nostrRepository: NostrRepository, + // Sign out is real for a read-only identity only -- there is nothing on the device + // to lose -- and these are what it takes. Null where the screen is composed without + // an identity to sign out of (previews, tests), in which case the button keeps its + // pending route for every kind. + signOut: SignOutDependencies? = null, ) { + // Whether this identity can sign, which decides which rows below exist. + val canSign = LocalCanSign.current + + val signOutViewModel: SignOutViewModel? = signOut?.let { + viewModel( + factory = SignOutViewModel.factory( + activeIdentityStateFlow = it.activeIdentityStateFlow, + nostrRepository = nostrRepository, + forgetNostrCredential = it.forgetNostrCredential, + hideIdentityMetadata = it.hideIdentityMetadata, + ), + ) + } + val signOutState = signOutViewModel?.state?.collectAsState()?.value + if (signOutViewModel != null && signOut != null && signOutState is SignOutViewModel.State.Confirming) { + SignOutOfReadOnlyDialog( + title = Res.string.sign_out_of_this_profile_question, + nostrPublicKey = signOutViewModel.nostrPublicKey, + onConfirm = { signOutViewModel.signOut(onSignedOut = signOut.onSignedOut) }, + onDismiss = { signOutViewModel.cancel() }, + ) + } + // The failure is short and needs no action: the button is still there to try again. + val notify = rememberNotifier(rememberCoroutineScope()) + val couldNotSignOut = stringResource(Res.string.could_not_sign_out_please_try_again) + LaunchedEffect(signOutState) { + if (signOutState is SignOutViewModel.State.Failed) notify(couldNotSignOut) + } + val activeProfileViewModel: ActiveProfileViewModel = viewModel( factory = ActiveProfileViewModel.factory( nostrEventId = nostrEventId, @@ -226,7 +271,10 @@ fun ActiveProfileScreen( } } - item { + // Key packages are signed, and there is nothing to recover for + // an identity the device holds no secret for: neither row for a + // read-only identity. + if (canSign) item { TextButton( onClick = { onNavigateToRoute.invoke( @@ -279,7 +327,7 @@ fun ActiveProfileScreen( } - item { + if (canSign) item { TextButton( onClick = { onNavigateToRoute.invoke( @@ -332,14 +380,26 @@ fun ActiveProfileScreen( // destructive action. It now matches how leaving and // deleting a group are already treated in // ChatRoomDetailScreen: a TextButton in the error colour. + // + // For a read-only identity it does what its colour has been + // promising: a confirmation naming the npub, then the + // identity leaves the device. For the other two kinds it + // keeps routing to the pending screen -- removing a seed is + // a wallet question, and an nsec has its own forget under + // key recovery. TextButton( colors = ButtonDefaults.textButtonColors( contentColor = MaterialTheme.colorScheme.error ), + enabled = signOutState !is SignOutViewModel.State.InProgress, onClick = { - onNavigateToRoute.invoke( - ImplementationPendingRoute("Sign out") - ) + if (!canSign && signOutViewModel != null) { + signOutViewModel.askToSignOut() + } else { + onNavigateToRoute.invoke( + ImplementationPendingRoute("Sign out") + ) + } } ) { Icon( @@ -380,6 +440,19 @@ fun ActiveProfileScreen( } } +/** + * What signing out of a read-only identity needs, bundled so that the screen's parameter + * list gains one line rather than four, and so a caller that has none of them passes + * nothing rather than three lambdas that throw. + */ +class SignOutDependencies( + val activeIdentityStateFlow: StateFlow, + val forgetNostrCredential: suspend (Identity) -> IdentityWriter.ForgetNostrCredentialResult, + val hideIdentityMetadata: suspend (Identity) -> Unit, + /** The nav host's tail: re-list, and clear the active identity so startup shows the selector or Landing. */ + val onSignedOut: () -> Unit, +) + @ConformancePreviews @Composable private fun UnannouncedProfileScreenPreview() { diff --git a/composeApp/src/commonMain/kotlin/to/curare/compose/ui/composable/HomeScreen.kt b/composeApp/src/commonMain/kotlin/to/curare/compose/ui/composable/HomeScreen.kt index 55a69c03..a8b3053f 100644 --- a/composeApp/src/commonMain/kotlin/to/curare/compose/ui/composable/HomeScreen.kt +++ b/composeApp/src/commonMain/kotlin/to/curare/compose/ui/composable/HomeScreen.kt @@ -13,6 +13,7 @@ import androidx.compose.foundation.pager.HorizontalPager import androidx.compose.foundation.pager.rememberPagerState import androidx.compose.material.icons.Icons import androidx.compose.material.icons.filled.Add +import androidx.compose.material.icons.filled.Lock import androidx.compose.material3.Icon import androidx.compose.material3.ExperimentalMaterial3Api import androidx.compose.material3.ExperimentalMaterial3ExpressiveApi @@ -24,6 +25,7 @@ import androidx.compose.material3.Scaffold import androidx.compose.material3.Surface import androidx.compose.material3.Tab import androidx.compose.material3.Text +import androidx.compose.material3.TextButton import androidx.compose.material3.TopAppBar import androidx.compose.material3.rememberModalBottomSheetState import androidx.compose.runtime.Composable @@ -45,6 +47,7 @@ import to.curare.compose.database.model.intermdiate.LocalProfileWithFollowing import to.curare.compose.repository.ChatRepository import to.curare.compose.repository.NostrRepository import to.curare.compose.ui.composable.navigation.routes.Route +import to.curare.compose.ui.composable.navigation.routes.SignInRoute import to.curare.compose.ui.composable.widgets.LoadingDataIndicator import to.curare.compose.ui.composable.widgets.dialogs.NewChatBottomSheetDialog import to.curare.compose.ui.composable.widgets.dialogs.StartDirectMessageToNpubOrNip05Dialog @@ -74,6 +77,9 @@ import to.curare.compose.ui.theme.breakpoint import to.curare.compose.ui.theme.listPaneWidthFor import to.curare.compose.ui.theme.readableContent import curare.composeapp.generated.resources.pick_a_conversation_to_read_it_here +import curare.composeapp.generated.resources.messages_need_the_secret_key_this_profile +import curare.composeapp.generated.resources.sign_in_with_the_nsec +import to.curare.compose.ui.composable.widgets.LocalCanSign import to.curare.compose.ui.composable.widgets.ScreenStateTransition import to.curare.compose.ui.theme.ConformancePreviews @@ -120,6 +126,9 @@ fun HomeScreen( } } + // Whether this identity can sign: the one thing the read-only branch below turns on. + val canSign = LocalCanSign.current + val homeScreenViewModel: HomeViewModel = viewModel( factory = HomeViewModel.factory( activeUserPublicKey = activeUserPublicKey, @@ -177,7 +186,11 @@ fun HomeScreen( // the bottom-right of the *window*, which is on top of the // transcript's send button; M3 puts a list-detail layout's primary // action in the list pane, and so does the branch below. - if (listPaneWidth == null) NewChatButton { showBottomSheet = true } + // And only for an identity that can sign: a new chat is a key + // package, a welcome and a gift wrap, none of which a read-only + // identity can produce. Hidden, not disabled -- the empty state + // beside it says why. + if (listPaneWidth == null && canSign) NewChatButton { showBottomSheet = true } } ) { innerPadding -> @Composable @@ -241,7 +254,21 @@ fun HomeScreen( } } - if (listPaneWidth == null) { + if (!canSign) { + // One column at every width. The two-pane layout is a list beside + // a detail, and there is no list: every room is MLS or a gift wrap, + // encrypted to the key this identity does not hold. The empty state + // is the only thing on the screen, which is the one case + // readableContent()'s centring is for -- and its action is where + // the upgrade lives. ChatRoomListViewModel is not composed, so the + // inbox sync and the MLS negentropy it would queue are not queued. + Column( + modifier = Modifier.padding(innerPadding).readableContent().fillMaxSize(), + verticalArrangement = Arrangement.Center, + ) { + ReadOnlyInbox(onSignInWithTheNsec = { onNavigateToRoute(SignInRoute) }) + } + } else if (listPaneWidth == null) { // Compact and medium: the list is the screen, and a room is a route. // Byte for byte the layout this screen has always had. ChatRoomListPane( @@ -310,7 +337,10 @@ fun HomeScreen( } } - if (showBottomSheet) { + // Neither can open without the button above, and the button is hidden for + // an identity that cannot sign; the guard here is so that the two cannot + // drift apart. + if (showBottomSheet && canSign) { NewChatBottomSheetDialog( scope = scope, sheetState = sheetState, @@ -326,7 +356,7 @@ fun HomeScreen( } when { - openNpubDialog.value -> { + openNpubDialog.value && canSign -> { StartDirectMessageToNpubOrNip05Dialog( activeUserPublicKey = activeUserPublicKey, scope = scope, @@ -393,6 +423,28 @@ It has survived not only five centuries, but also the leap into electronic types } } +/** + * What a read-only identity sees where its rooms would be, and the one thing that fills + * it. + * + * `EmptyState`'s message is required for exactly this reason -- an absence has to say + * which absence it is -- and its action slot is where the upgrade lives: the nsec pasted + * on the sign-in screen hits the credentials file's upgrade rule, and startup takes the + * user back here with rooms in it. + */ +@Composable +private fun ReadOnlyInbox(onSignInWithTheNsec: () -> Unit) { + EmptyState( + message = stringResource(Res.string.messages_need_the_secret_key_this_profile), + icon = Icons.Default.Lock, + action = { + TextButton(onClick = onSignInWithTheNsec) { + Text(stringResource(Res.string.sign_in_with_the_nsec)) + } + }, + ) +} + /** * The one action the chat list offers, in whichever slot the layout has for it. * diff --git a/composeApp/src/commonMain/kotlin/to/curare/compose/ui/composable/KeyRecoveryScreen.kt b/composeApp/src/commonMain/kotlin/to/curare/compose/ui/composable/KeyRecoveryScreen.kt index 02198adb..8fc097e6 100644 --- a/composeApp/src/commonMain/kotlin/to/curare/compose/ui/composable/KeyRecoveryScreen.kt +++ b/composeApp/src/commonMain/kotlin/to/curare/compose/ui/composable/KeyRecoveryScreen.kt @@ -129,10 +129,17 @@ fun KeyRecoveryScreen( horizontalAlignment = Alignment.CenterHorizontally ) { Text( - // A bare-key identity has no coins to speak of. + // A bare-key identity has no coins to speak of. Exhaustive rather than + // `else`: the `else` here used to mean "mnemonic", and a kind added later + // would have fallen into it and been promised coins. A read-only identity + // is never offered this screen (docs/npub-sign-in.md, Phase 5); it reads + // as the bare-key kind so that, if it ever is, the sentence is at least + // not about a wallet. text = when (activeIdentity?.kind) { - IdentityKind.NostrSecret -> stringResource(Res.string.these_are_your_keys_keep_them_safe_no_wallet) - else -> stringResource(Res.string.these_are_your_keys_keep_them_safe_so_they) + IdentityKind.NostrSecret, + IdentityKind.NostrPublic -> stringResource(Res.string.these_are_your_keys_keep_them_safe_no_wallet) + IdentityKind.Mnemonic, + null -> stringResource(Res.string.these_are_your_keys_keep_them_safe_so_they) }, style = MaterialTheme.typography.bodyMedium, textAlign = TextAlign.Center @@ -174,7 +181,14 @@ fun KeyRecoveryScreen( } ) - else -> KeyRecoveryOption( + // Nothing to recover: the device holds no secret for this identity. The + // row that leads here is hidden for the kind, so this arm is not reached; + // it exists so that the `when` says so rather than handing a read-only + // identity the phrase option through an `else`. + IdentityKind.NostrPublic -> Unit + + IdentityKind.Mnemonic, + null -> KeyRecoveryOption( icon = Icons.Default.Spellcheck, title = stringResource(Res.string.recovery_phrase), description = stringResource(Res.string.write_down_and_secure_the_12_word_phrase), diff --git a/composeApp/src/commonMain/kotlin/to/curare/compose/ui/composable/LandingScreen.kt b/composeApp/src/commonMain/kotlin/to/curare/compose/ui/composable/LandingScreen.kt index acc93295..0f71ce04 100644 --- a/composeApp/src/commonMain/kotlin/to/curare/compose/ui/composable/LandingScreen.kt +++ b/composeApp/src/commonMain/kotlin/to/curare/compose/ui/composable/LandingScreen.kt @@ -27,7 +27,7 @@ import curare.composeapp.generated.resources.keep_the_feed_alive import curare.composeapp.generated.resources.learn_more import curare.composeapp.generated.resources.curare import curare.composeapp.generated.resources.sign_in -import curare.composeapp.generated.resources.sign_in_with_a_recovery_phrase_or_an_nsec +import curare.composeapp.generated.resources.sign_in_with_a_recovery_phrase_an_nsec_or import androidx.compose.material3.SnackbarHost import to.curare.compose.ui.composable.widgets.LocalSnackbarHostState import to.curare.compose.ui.theme.readableContent @@ -82,7 +82,7 @@ fun LandingScreen( } Text( - text = stringResource(Res.string.sign_in_with_a_recovery_phrase_or_an_nsec), + text = stringResource(Res.string.sign_in_with_a_recovery_phrase_an_nsec_or), modifier = Modifier.padding(MaterialTheme.spacing.space125), style = MaterialTheme.typography.labelSmall, textAlign = TextAlign.Center diff --git a/composeApp/src/commonMain/kotlin/to/curare/compose/ui/composable/NostrSecretScreen.kt b/composeApp/src/commonMain/kotlin/to/curare/compose/ui/composable/NostrSecretScreen.kt index 8362d2a6..761962ed 100644 --- a/composeApp/src/commonMain/kotlin/to/curare/compose/ui/composable/NostrSecretScreen.kt +++ b/composeApp/src/commonMain/kotlin/to/curare/compose/ui/composable/NostrSecretScreen.kt @@ -104,7 +104,7 @@ fun NostrSecretScreen( phoenixGlobal: PhoenixGlobal, activeIdentityStateFlow: StateFlow, nostrRepository: NostrRepository, - forgetNostrKey: suspend (Identity) -> IdentityWriter.ForgetNostrKeyResult, + forgetNostrCredential: suspend (Identity) -> IdentityWriter.ForgetNostrCredentialResult, hideIdentityMetadata: suspend (Identity) -> Unit, onNavigateBack: () -> Unit, onForgotten: () -> Unit, @@ -114,7 +114,7 @@ fun NostrSecretScreen( phoenixGlobal = phoenixGlobal, activeIdentityStateFlow = activeIdentityStateFlow, nostrRepository = nostrRepository, - forgetNostrKey = forgetNostrKey, + forgetNostrCredential = forgetNostrCredential, hideIdentityMetadata = hideIdentityMetadata, ) ) diff --git a/composeApp/src/commonMain/kotlin/to/curare/compose/ui/composable/ShareProfileScreen.kt b/composeApp/src/commonMain/kotlin/to/curare/compose/ui/composable/ShareProfileScreen.kt index 93aa2758..1a09baee 100644 --- a/composeApp/src/commonMain/kotlin/to/curare/compose/ui/composable/ShareProfileScreen.kt +++ b/composeApp/src/commonMain/kotlin/to/curare/compose/ui/composable/ShareProfileScreen.kt @@ -41,6 +41,7 @@ import to.curare.compose.ui.view.model.ShareProfileViewModel import to.curare.compose.ui.view.state.ShareProfileUIState import com.vitorpamplona.quartz.nip01Core.core.HexKey import com.vitorpamplona.quartz.nip01Core.metadata.MetadataEvent +import to.curare.compose.ui.composable.widgets.LocalCanSign import to.curare.compose.ui.theme.spacing import curare.composeapp.generated.resources.Res import org.jetbrains.compose.resources.stringResource @@ -176,7 +177,11 @@ fun ShareProfileScreen( } } - Row( + // Nothing is signed by a re-broadcast, but a copy of the kind 0 is + // queued for the finder relays, and a read-only identity puts nothing + // on a relay -- not even a copy. The broadcast pump is not running for + // it to carry the request anyway. + if (LocalCanSign.current) Row( modifier = Modifier.fillMaxWidth().padding(MaterialTheme.spacing.space250), horizontalArrangement = Arrangement.Center ) { diff --git a/composeApp/src/commonMain/kotlin/to/curare/compose/ui/composable/SignInScreen.kt b/composeApp/src/commonMain/kotlin/to/curare/compose/ui/composable/SignInScreen.kt index d8130c73..4d62fe78 100644 --- a/composeApp/src/commonMain/kotlin/to/curare/compose/ui/composable/SignInScreen.kt +++ b/composeApp/src/commonMain/kotlin/to/curare/compose/ui/composable/SignInScreen.kt @@ -15,6 +15,7 @@ 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.Spellcheck +import androidx.compose.material.icons.filled.Visibility import androidx.compose.material3.Button import androidx.compose.material3.ExperimentalMaterial3Api import androidx.compose.material3.Icon @@ -38,13 +39,13 @@ import androidx.compose.ui.text.input.KeyboardType import androidx.lifecycle.viewmodel.compose.viewModel import curare.composeapp.generated.resources.Res import curare.composeapp.generated.resources.a_password_protected_key_ncryptsec_is_not -import curare.composeapp.generated.resources.an_npub_is_a_public_key_curare_needs_the import curare.composeapp.generated.resources.enter_a_recovery_phrase_or_an_nsec_to_sign_in import curare.composeapp.generated.resources.next import curare.composeapp.generated.resources.paste import curare.composeapp.generated.resources.recognised_as_a_nostr_secret_key_no_wallet +import curare.composeapp.generated.resources.recognised_as_a_public_key_you_will_see import curare.composeapp.generated.resources.recognised_as_a_recovery_phrase_it_also -import curare.composeapp.generated.resources.recovery_phrase_or_nsec +import curare.composeapp.generated.resources.recovery_phrase_nsec_or_npub import curare.composeapp.generated.resources.sign_in import curare.composeapp.generated.resources.signed_in import curare.composeapp.generated.resources.signing_you_in @@ -54,9 +55,10 @@ import curare.composeapp.generated.resources.that_recovery_phrase_is_not_valid_c import curare.composeapp.generated.resources.the_key_could_not_be_saved_on_this_device import curare.composeapp.generated.resources.the_words_or_the_key_never_leave_this_device import curare.composeapp.generated.resources.this_key_is_already_on_this_device -import curare.composeapp.generated.resources.twelve_words_or_nsec1 +import curare.composeapp.generated.resources.twelve_words_nsec1_or_npub1 import curare.composeapp.generated.resources.use_a_different_key import curare.composeapp.generated.resources.you_are_signing_in_as +import com.vitorpamplona.quartz.nip01Core.core.HexKey import fr.acinq.bitcoin.PrivateKey import fr.acinq.phoenix.data.WalletId import org.jetbrains.compose.resources.stringResource @@ -92,7 +94,8 @@ import to.curare.compose.ui.view.state.SignInToProfileUIState @Composable fun SignInToProfileScreen( nostrRepository: NostrRepository, - writeNostrKey: suspend (PrivateKey) -> IdentityWriter.WriteNostrKeyResult, + writeNostrKey: suspend (PrivateKey) -> IdentityWriter.WriteNostrCredentialResult, + writeNostrPublicKey: suspend (HexKey) -> IdentityWriter.WriteNostrCredentialResult, writeRecoveryPhrase: ( words: List, onWritten: (WalletId) -> Unit, @@ -105,6 +108,7 @@ fun SignInToProfileScreen( factory = SignInToProfileViewModel.factory( nostrRepository = nostrRepository, writeNostrKey = writeNostrKey, + writeNostrPublicKey = writeNostrPublicKey, writeRecoveryPhrase = writeRecoveryPhrase, ) ) @@ -191,8 +195,8 @@ private fun InputPrompt(viewModel: SignInToProfileViewModel) { keyboardType = KeyboardType.Ascii, ), textStyle = MaterialTheme.typography.bodyLarge.copy(fontFamily = FontFamily.Monospace), - label = { Text(text = stringResource(Res.string.recovery_phrase_or_nsec), maxLines = 1) }, - placeholder = { Text(text = stringResource(Res.string.twelve_words_or_nsec1), maxLines = 1) }, + label = { Text(text = stringResource(Res.string.recovery_phrase_nsec_or_npub), maxLines = 1) }, + placeholder = { Text(text = stringResource(Res.string.twelve_words_nsec1_or_npub1), maxLines = 1) }, trailingIcon = { IconButton( onClick = { @@ -260,6 +264,15 @@ private fun Confirm( style = MaterialTheme.typography.bodyMedium, ) } + is SignInCredential.NostrPublicKey -> { + // What the user is about to get and not get, said here and nowhere + // else: this is the one step before the choice is made. + Icon(Icons.Default.Visibility, contentDescription = Decorative) + Text( + text = stringResource(Res.string.recognised_as_a_public_key_you_will_see), + style = MaterialTheme.typography.bodyMedium, + ) + } } } @@ -286,7 +299,6 @@ private fun problemMessage(problem: CredentialProblem): String = stringResource( 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.PublicKeyOnly -> Res.string.an_npub_is_a_public_key_curare_needs_the 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 @@ -302,7 +314,8 @@ private fun SignInToProfileScreenPreview() { ) { SignInToProfileScreen( nostrRepository = NostrRepository.NO_OP_NOSTR_REPOSITORY, - writeNostrKey = { IdentityWriter.WriteNostrKeyResult.CannotLoadKeys }, + writeNostrKey = { IdentityWriter.WriteNostrCredentialResult.CannotLoadKeys }, + writeNostrPublicKey = { IdentityWriter.WriteNostrCredentialResult.CannotLoadKeys }, writeRecoveryPhrase = { _, _, onError -> onError(WritingSeedState.Error.CannotLoadSeedMap) }, onNavigateBack = {}, onSignedIn = {}, diff --git a/composeApp/src/commonMain/kotlin/to/curare/compose/ui/composable/SocialPreconditionScreen.kt b/composeApp/src/commonMain/kotlin/to/curare/compose/ui/composable/SocialPreconditionScreen.kt index c4bf10cf..eb779da4 100644 --- a/composeApp/src/commonMain/kotlin/to/curare/compose/ui/composable/SocialPreconditionScreen.kt +++ b/composeApp/src/commonMain/kotlin/to/curare/compose/ui/composable/SocialPreconditionScreen.kt @@ -21,6 +21,7 @@ import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.text.style.TextAlign import androidx.compose.ui.unit.dp +import to.curare.compose.ui.composable.widgets.LocalCanSign import to.curare.compose.ui.theme.spacing import curare.composeapp.generated.resources.Res import org.jetbrains.compose.resources.stringResource @@ -88,36 +89,40 @@ fun SocialPreconditionScreen( modifier = Modifier.weight(1f) ) - Text( - stringResource(Res.string.tell_friends_to_join_you_so_your_feed_stays), - textAlign = TextAlign.Center - ) - - Button( - onClick = { - onNavigateToInviteFriend.invoke() - } - ) { + // Both pending today, and both writes when they exist: an invite is sent, + // an acceptance signed. A read-only identity is offered only the way past. + if (LocalCanSign.current) { Text( - stringResource(Res.string.invite_a_friend) + stringResource(Res.string.tell_friends_to_join_you_so_your_feed_stays), + textAlign = TextAlign.Center ) - } - Spacer( - modifier = Modifier.weight(1f) - ) - - Text( - stringResource(Res.string.view_and_accept_invites_you_may_have), - textAlign = TextAlign.Center - ) - - Button( - onClick = { - onNavigateToViewInvites.invoke() + Button( + onClick = { + onNavigateToInviteFriend.invoke() + } + ) { + Text( + stringResource(Res.string.invite_a_friend) + ) + } + + Spacer( + modifier = Modifier.weight(1f) + ) + + Text( + stringResource(Res.string.view_and_accept_invites_you_may_have), + textAlign = TextAlign.Center + ) + + Button( + onClick = { + onNavigateToViewInvites.invoke() + } + ) { + Text(stringResource(Res.string.view_invites)) } - ) { - Text(stringResource(Res.string.view_invites)) } } } diff --git a/composeApp/src/commonMain/kotlin/to/curare/compose/ui/composable/SovereignWalletStartupScreen.kt b/composeApp/src/commonMain/kotlin/to/curare/compose/ui/composable/SovereignWalletStartupScreen.kt index 2aacad39..1ccb791b 100644 --- a/composeApp/src/commonMain/kotlin/to/curare/compose/ui/composable/SovereignWalletStartupScreen.kt +++ b/composeApp/src/commonMain/kotlin/to/curare/compose/ui/composable/SovereignWalletStartupScreen.kt @@ -189,7 +189,7 @@ fun SovereignWalletStartupScreen( // recomposes into the `activeIdentity != null` branch // above, which is what reports the startup. sovereignWalletViewModel.setActiveIdentity( - Identity( + Identity.signing( id = identity.id, kind = IdentityKind.NostrSecret, nostrPrivateKey = identity.privateKey, @@ -199,6 +199,20 @@ fun SovereignWalletStartupScreen( ) ) } + is StoredIdentity.NostrPublic -> { + // Nothing to start and nothing to decrypt: the + // public key is the whole of what the device + // holds, and the identity is active the moment + // it is read, as the nsec branch above is. + sovereignWalletViewModel.setActiveIdentity( + Identity.readOnly( + id = identity.id, + nostrPublicKey = identity.nostrPublicKey, + userPrefs = dataStoreManager.loadUserPrefsForWallet(identity.id), + internalPrefs = dataStoreManager.loadInternalPrefsForWallet(identity.id), + ) + ) + } } loadingIdentity = null }, diff --git a/composeApp/src/commonMain/kotlin/to/curare/compose/ui/composable/UnsyncedProfileScreen.kt b/composeApp/src/commonMain/kotlin/to/curare/compose/ui/composable/UnsyncedProfileScreen.kt index de6a0293..c4bc67c7 100644 --- a/composeApp/src/commonMain/kotlin/to/curare/compose/ui/composable/UnsyncedProfileScreen.kt +++ b/composeApp/src/commonMain/kotlin/to/curare/compose/ui/composable/UnsyncedProfileScreen.kt @@ -41,6 +41,14 @@ import curare.composeapp.generated.resources.it_may_be_new_or_it_may_live_on_rel import curare.composeapp.generated.resources.name_eg_alan_turing import curare.composeapp.generated.resources.set_up_a_profile import curare.composeapp.generated.resources.try_again +import curare.composeapp.generated.resources.use_a_different_key +import curare.composeapp.generated.resources.use_a_different_key_question +import curare.composeapp.generated.resources.could_not_sign_out_please_try_again +import to.curare.compose.ui.composable.widgets.dialogs.SignOutOfReadOnlyDialog +import to.curare.compose.ui.composable.widgets.rememberNotifier +import to.curare.compose.ui.view.model.SignOutViewModel +import androidx.compose.runtime.LaunchedEffect +import androidx.compose.runtime.rememberCoroutineScope import curare.composeapp.generated.resources.we_are_looking_for_your_profile_on_as_many import curare.composeapp.generated.resources.we_are_searching_the_internet_to_find_your import curare.composeapp.generated.resources.we_could_not_find_a_profile_for_this_key @@ -49,6 +57,7 @@ import org.jetbrains.compose.resources.stringResource import to.curare.compose.repository.NostrRepository import to.curare.compose.ui.composable.widgets.Decorative import to.curare.compose.ui.composable.widgets.EmptyState +import to.curare.compose.ui.composable.widgets.LocalCanSign import to.curare.compose.ui.composable.widgets.LoadingDataIndicator import to.curare.compose.ui.composable.widgets.LocalSnackbarHostState import to.curare.compose.ui.composable.widgets.ScreenStateTransition @@ -69,6 +78,10 @@ import to.curare.compose.ui.view.state.UnsyncedProfileUIState fun UnsyncedProfileScreen( unsyncedProfilePublicKey: String, nostrRepository: NostrRepository, + // The not-found state's exit for an identity that cannot set a profile up: the same + // act as signing out, reached from the other end of the identity's life. Null where + // there is no identity to leave (previews), in which case that kind has no exit here. + signOut: SignOutDependencies? = null, ) { val viewModel: UnsyncedProfileViewModel = viewModel( factory = UnsyncedProfileViewModel.factory( @@ -78,6 +91,31 @@ fun UnsyncedProfileScreen( ) val uiState by viewModel.uiState.collectAsState() + val signOutViewModel: SignOutViewModel? = signOut?.let { + viewModel( + factory = SignOutViewModel.factory( + activeIdentityStateFlow = it.activeIdentityStateFlow, + nostrRepository = nostrRepository, + forgetNostrCredential = it.forgetNostrCredential, + hideIdentityMetadata = it.hideIdentityMetadata, + ), + ) + } + val signOutState = signOutViewModel?.state?.collectAsState()?.value + if (signOutViewModel != null && signOut != null && signOutState is SignOutViewModel.State.Confirming) { + SignOutOfReadOnlyDialog( + title = Res.string.use_a_different_key_question, + nostrPublicKey = signOutViewModel.nostrPublicKey, + onConfirm = { signOutViewModel.signOut(onSignedOut = signOut.onSignedOut) }, + onDismiss = { signOutViewModel.cancel() }, + ) + } + val notify = rememberNotifier(rememberCoroutineScope()) + val couldNotSignOut = stringResource(Res.string.could_not_sign_out_please_try_again) + LaunchedEffect(signOutState) { + if (signOutState is SignOutViewModel.State.Failed) notify(couldNotSignOut) + } + // imePadding for the not-found form's fields. Scaffold( modifier = Modifier.imePadding(), @@ -93,6 +131,7 @@ fun UnsyncedProfileScreen( is UnsyncedProfileUIState.NotFound -> NotFound( viewModel = viewModel, unsignedNostrEventId = state.unsignedNostrEventId, + onUseADifferentKey = signOutViewModel?.let { { it.askToSignOut() } }, ) } } @@ -149,6 +188,8 @@ private fun Searching() { private fun NotFound( viewModel: UnsyncedProfileViewModel, unsignedNostrEventId: Long, + /** Shown only where the set-up form is not; null when there is no identity to leave. */ + onUseADifferentKey: (() -> Unit)?, ) { val nameField = viewModel.formState.nameField.textFieldState val biographyField = viewModel.formState.biographyField.textFieldState @@ -181,6 +222,25 @@ private fun NotFound( style = MaterialTheme.typography.bodyMedium, ) + // Setting a profile up is signing a kind 0, which a read-only identity cannot do. + // The form is not offered to it -- and then this state would have no exit: the + // profile tab is not reachable before ProfileLoaded, so a user whose npub was not + // found on any relay could try again for ever. So, for that kind only, the third + // action: the identity leaves the device, and the way back is the selector or + // Landing. + if (!LocalCanSign.current) { + if (onUseADifferentKey != null) { + TextButton( + modifier = Modifier.align(Alignment.End), + enabled = !isActionPending, + onClick = onUseADifferentKey, + ) { + Text(text = stringResource(Res.string.use_a_different_key)) + } + } + return@Column + } + Text( text = stringResource(Res.string.set_up_a_profile), style = MaterialTheme.typography.titleMedium, diff --git a/composeApp/src/commonMain/kotlin/to/curare/compose/ui/composable/navigation/CurareNavHost.kt b/composeApp/src/commonMain/kotlin/to/curare/compose/ui/composable/navigation/CurareNavHost.kt index 9c4c5e25..d3a12927 100644 --- a/composeApp/src/commonMain/kotlin/to/curare/compose/ui/composable/navigation/CurareNavHost.kt +++ b/composeApp/src/commonMain/kotlin/to/curare/compose/ui/composable/navigation/CurareNavHost.kt @@ -124,6 +124,8 @@ import to.curare.compose.ui.view.state.NavigationUIState import to.curare.compose.ui.view.state.NostrEventDetailUIState import to.curare.compose.ui.view.state.SearchUIState import to.curare.compose.ui.theme.NavigationMotion +import to.curare.compose.ui.composable.SignOutDependencies +import to.curare.compose.ui.composable.widgets.ProvideSigningCapability import to.curare.compose.ui.theme.breakpoint import co.touchlab.kermit.Logger import fr.acinq.phoenix.PhoenixGlobal @@ -430,6 +432,27 @@ fun CurareNavHost( } } + // What signing out of a read-only identity takes, for the two screens that offer it. + // The tail is the nsec forget's: the device no longer holds anything for the + // identity, so re-list -- the selector drops it -- then clear the active identity, + // and the navigation observer sends a null identity to startup, which shows the + // selector or, if this was the last one, Landing. + val signOutOfReadOnlyIdentity = remember(sovereignWalletViewModel) { + SignOutDependencies( + activeIdentityStateFlow = sovereignWalletViewModel.activeIdentity, + forgetNostrCredential = { identity -> sovereignWalletViewModel.forgetNostrCredential(identity) }, + hideIdentityMetadata = { identity -> sovereignWalletViewModel.hideIdentityMetadata(identity) }, + onSignedOut = { + sovereignWalletViewModel.listIdentities { + sovereignWalletViewModel.resetToSelector() + } + }, + ) + } + + // Once, above every screen: what a read-only identity may not be offered is decided + // where the control is drawn, and this is how the control finds out. + ProvideSigningCapability(sovereignWalletViewModel.activeIdentity) { CurareNavigationSuite( navController = navController, breakpoint = MaterialTheme.breakpoint, @@ -704,6 +727,7 @@ fun CurareNavHost( SignInToProfileScreen( nostrRepository = databaseNostrRepository, writeNostrKey = { privateKey -> sovereignWalletViewModel.writeNostrKey(privateKey) }, + writeNostrPublicKey = { publicKey -> sovereignWalletViewModel.writeNostrPublicKey(publicKey) }, writeRecoveryPhrase = { words, onWritten, onError -> sovereignWalletViewModel.writeSeed( words, @@ -742,6 +766,7 @@ fun CurareNavHost( UnsyncedProfileScreen( unsyncedProfilePublicKey = route.publicKey, nostrRepository = databaseNostrRepository, + signOut = signOutOfReadOnlyIdentity, ) } composable { backStackEntry -> @@ -842,7 +867,8 @@ fun CurareNavHost( navController.navigate( route = route ) - } + }, + signOut = signOutOfReadOnlyIdentity, ) } composable { backStackEntry -> @@ -909,7 +935,7 @@ fun CurareNavHost( phoenixGlobal = phoenixGlobal, activeIdentityStateFlow = sovereignWalletViewModel.activeIdentity, nostrRepository = databaseNostrRepository, - forgetNostrKey = { identity -> sovereignWalletViewModel.forgetNostrKey(identity) }, + forgetNostrCredential = { identity -> sovereignWalletViewModel.forgetNostrCredential(identity) }, hideIdentityMetadata = { identity -> sovereignWalletViewModel.hideIdentityMetadata(identity) }, onNavigateBack = { navController.popBackStack() @@ -1654,5 +1680,6 @@ fun CurareNavHost( } } } + } } \ No newline at end of file diff --git a/composeApp/src/commonMain/kotlin/to/curare/compose/ui/composable/widgets/SigningCapability.kt b/composeApp/src/commonMain/kotlin/to/curare/compose/ui/composable/widgets/SigningCapability.kt new file mode 100644 index 00000000..7c4db696 --- /dev/null +++ b/composeApp/src/commonMain/kotlin/to/curare/compose/ui/composable/widgets/SigningCapability.kt @@ -0,0 +1,47 @@ +package to.curare.compose.ui.composable.widgets + +import androidx.compose.runtime.Composable +import androidx.compose.runtime.CompositionLocalProvider +import androidx.compose.runtime.ProvidableCompositionLocal +import androidx.compose.runtime.collectAsState +import androidx.compose.runtime.getValue +import androidx.compose.runtime.staticCompositionLocalOf +import kotlinx.coroutines.flow.StateFlow +import to.curare.compose.identity.Identity + +/** + * Whether the identity the app is running as can sign -- the one question every write + * entrance asks before it is drawn. + * + * A composition local rather than a parameter for the snackbar host's reason: screens + * do not receive the identity, `MetadataEventDetail` -- where *follow* and *send message* + * live -- is several composables below anything that could be handed more, and a + * parameter threaded through twenty-six lists is forgotten in the twenty-seventh. + * [ProvideSigningCapability] sits once, above every screen, in the nav host. + * + * The default is `true` rather than an error, and that is the one way this differs from + * [LocalSnackbarHostState]: the provider cannot be forgotten per screen, so the only + * things composed outside it are previews and tests, and those should render as they + * always have. + * + * A capability, not a kind. A screen asks "can this identity sign?", not "is this an + * npub?", because the answer is what it needs -- and because a remote signer, which can + * sign and holds no local key, would otherwise be a fourth value in every `when`. See + * docs/npub-sign-in.md, Phase 5. + */ +val LocalCanSign: ProvidableCompositionLocal = staticCompositionLocalOf { true } + +/** Provides [LocalCanSign] from the active identity for everything inside [content]. */ +@Composable +fun ProvideSigningCapability( + activeIdentity: StateFlow, + content: @Composable () -> Unit, +) { + val identity by activeIdentity.collectAsState() + // No identity yet -- startup, landing, sign-in -- is not read-only; it is nobody. Those + // screens have no write entrances to hide, and `true` keeps them drawn as they were. + val canSign = identity?.canSign ?: true + CompositionLocalProvider(LocalCanSign provides canSign) { + content() + } +} diff --git a/composeApp/src/commonMain/kotlin/to/curare/compose/ui/composable/widgets/detail/MetadataEventDetail.kt b/composeApp/src/commonMain/kotlin/to/curare/compose/ui/composable/widgets/detail/MetadataEventDetail.kt index 0ee9489e..4359b598 100644 --- a/composeApp/src/commonMain/kotlin/to/curare/compose/ui/composable/widgets/detail/MetadataEventDetail.kt +++ b/composeApp/src/commonMain/kotlin/to/curare/compose/ui/composable/widgets/detail/MetadataEventDetail.kt @@ -54,6 +54,7 @@ import to.curare.compose.ui.view.model.MetadataEventDetailViewModel import to.curare.compose.ui.view.state.MetadataEventDetailUIState import com.vitorpamplona.quartz.nip01Core.core.HexKey import com.vitorpamplona.quartz.nip01Core.metadata.MetadataEvent +import to.curare.compose.ui.composable.widgets.LocalCanSign import to.curare.compose.ui.theme.spacing import curare.composeapp.generated.resources.Res import org.jetbrains.compose.resources.stringResource @@ -83,6 +84,9 @@ fun MetadataEventDetail( ) { val scope = rememberCoroutineScope() + // Whether this identity can sign, which decides which of the controls below exist. + val canSign = LocalCanSign.current + val profile = localNostrEvent.profile val scrollBehavior = TopAppBarDefaults.exitUntilCollapsedScrollBehavior(rememberTopAppBarState()) @@ -178,6 +182,12 @@ fun MetadataEventDetail( if (metadataEventDetailViewModel.isActionPending.value) { LoadingIndicator() + } else if (!canSign) { + // Edit profile is a kind 0, follow and unfollow a + // kind 3: none of them can be signed by a read-only + // identity, so none is offered. The "follows you" + // state below still shows; it is a fact, not an + // action. } else { if (metadataEventDetailUIState.isActiveUser) { Button( @@ -280,7 +290,9 @@ fun MetadataEventDetail( } } - item { + // A message is a gift wrap, sealed with the sender's key. Not for a + // read-only identity. + if (canSign) item { Button( onClick = { onNavigateToChatRoom.invoke( diff --git a/composeApp/src/commonMain/kotlin/to/curare/compose/ui/composable/widgets/dialogs/SignOutOfReadOnlyDialog.kt b/composeApp/src/commonMain/kotlin/to/curare/compose/ui/composable/widgets/dialogs/SignOutOfReadOnlyDialog.kt new file mode 100644 index 00000000..36a70623 --- /dev/null +++ b/composeApp/src/commonMain/kotlin/to/curare/compose/ui/composable/widgets/dialogs/SignOutOfReadOnlyDialog.kt @@ -0,0 +1,43 @@ +package to.curare.compose.ui.composable.widgets.dialogs + +import androidx.compose.material.icons.Icons +import androidx.compose.material.icons.filled.Logout +import androidx.compose.material3.AlertDialog +import androidx.compose.material3.Icon +import androidx.compose.material3.Text +import androidx.compose.material3.TextButton +import androidx.compose.runtime.Composable +import curare.composeapp.generated.resources.Res +import curare.composeapp.generated.resources.cancel +import curare.composeapp.generated.resources.sign_out +import curare.composeapp.generated.resources.this_device_holds_no_key_for_s_so_there +import org.jetbrains.compose.resources.StringResource +import org.jetbrains.compose.resources.stringResource +import to.curare.compose.extensions.hexToNpubHrp +import to.curare.compose.ui.composable.widgets.Decorative + +/** + * The confirmation before a read-only identity leaves the device, naming the npub so + * the user sees which one. Shared by the profile tab's *sign out* and the not-found + * screen's *use a different key*, which differ only in what the title calls it. + */ +@Composable +fun SignOutOfReadOnlyDialog( + title: StringResource, + nostrPublicKey: String?, + onConfirm: () -> Unit, + onDismiss: () -> Unit, +) { + AlertDialog( + onDismissRequest = onDismiss, + icon = { Icon(Icons.Default.Logout, contentDescription = Decorative) }, + title = { Text(stringResource(title)) }, + text = { Text(stringResource(Res.string.this_device_holds_no_key_for_s_so_there, nostrPublicKey?.hexToNpubHrp() ?: "")) }, + confirmButton = { + TextButton(onClick = onConfirm) { Text(stringResource(Res.string.sign_out)) } + }, + dismissButton = { + TextButton(onClick = onDismiss) { Text(stringResource(Res.string.cancel)) } + }, + ) +} diff --git a/composeApp/src/commonMain/kotlin/to/curare/compose/ui/composable/widgets/wallet/WalletsSelector.kt b/composeApp/src/commonMain/kotlin/to/curare/compose/ui/composable/widgets/wallet/WalletsSelector.kt index 92c71449..a6fd1d9c 100644 --- a/composeApp/src/commonMain/kotlin/to/curare/compose/ui/composable/widgets/wallet/WalletsSelector.kt +++ b/composeApp/src/commonMain/kotlin/to/curare/compose/ui/composable/widgets/wallet/WalletsSelector.kt @@ -49,6 +49,9 @@ import fr.acinq.phoenix.utils.preferences.GlobalPrefs import fr.acinq.phoenix.utils.preferences.UserWalletMetadata import fr.acinq.phoenix.utils.preferences.getByWalletIdOrDefault import to.curare.compose.extensions.hexToNpubHrp +import curare.composeapp.generated.resources.Res +import curare.composeapp.generated.resources.read_only +import org.jetbrains.compose.resources.stringResource import to.curare.compose.identity.StoredIdentity import to.curare.compose.ui.theme.spacing @@ -159,6 +162,16 @@ private fun AvailableWalletView( Text(text = metadata.nameOrDefault(), modifier = Modifier, maxLines = 1, overflow = TextOverflow.Ellipsis, style = MaterialTheme.typography.bodyMedium) Spacer(Modifier.height(MaterialTheme.spacing.space25)) Text(text = identity.nostrPublicKey.hexToNpubHrp(), modifier = Modifier, maxLines = 1, overflow = TextOverflow.Ellipsis, style = MaterialTheme.typography.displayMedium.copy(fontFamily = FontFamily.Monospace, fontSize = 12.sp)) + if (identity is StoredIdentity.NostrPublic) { + // Said before the tap, not after: two identities can share an avatar + // and a name, and only one of them will let the user send a message. + Spacer(Modifier.height(MaterialTheme.spacing.space25)) + Text( + text = stringResource(Res.string.read_only), + style = MaterialTheme.typography.labelSmall, + color = MaterialTheme.colorScheme.onSurfaceVariant, + ) + } } } if (isCurrent && canEdit) { diff --git a/composeApp/src/commonMain/kotlin/to/curare/compose/ui/view/model/NostrSecretViewModel.kt b/composeApp/src/commonMain/kotlin/to/curare/compose/ui/view/model/NostrSecretViewModel.kt index 8f0221bc..4ab10928 100644 --- a/composeApp/src/commonMain/kotlin/to/curare/compose/ui/view/model/NostrSecretViewModel.kt +++ b/composeApp/src/commonMain/kotlin/to/curare/compose/ui/view/model/NostrSecretViewModel.kt @@ -7,8 +7,9 @@ import androidx.lifecycle.viewmodel.initializer import androidx.lifecycle.viewmodel.viewModelFactory import co.touchlab.kermit.Logger import fr.acinq.phoenix.PhoenixGlobal -import fr.acinq.phoenix.data.DecryptNostrKeysResult -import fr.acinq.phoenix.managers.NostrKeyManager +import fr.acinq.phoenix.data.DecryptNostrCredentialsResult +import fr.acinq.phoenix.managers.NostrCredentialManager +import fr.acinq.phoenix.security.NostrCredential import kotlinx.coroutines.CoroutineExceptionHandler import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.ExperimentalCoroutinesApi @@ -24,6 +25,7 @@ import kotlinx.coroutines.flow.stateIn import kotlinx.coroutines.launch import kotlinx.coroutines.withContext import to.curare.compose.extensions.hexToNsecHrp +import to.curare.compose.identity.ForgetIdentity import to.curare.compose.identity.Identity import to.curare.compose.identity.IdentityKind import to.curare.compose.identity.IdentityWriter @@ -45,14 +47,15 @@ import to.curare.compose.ui.view.state.NostrSecretUIState * secret it is. * * It also owns the inverse of an import: [forgetKey], which removes the key from the - * device and the account with it. Only for a bare key; a mnemonic identity's key is in - * the seed, and removing a seed is a wallet question this does not answer. + * device and the account with it, through [ForgetIdentity]. Only for a bare key; a + * mnemonic identity's key is in the seed, and removing a seed is a wallet question this + * does not answer. */ class NostrSecretViewModel( val phoenixGlobal: PhoenixGlobal, val activeIdentityStateFlow: StateFlow, private val nostrRepository: NostrRepository, - private val forgetNostrKey: suspend (Identity) -> IdentityWriter.ForgetNostrKeyResult, + private val forgetNostrCredential: suspend (Identity) -> IdentityWriter.ForgetNostrCredentialResult, private val hideIdentityMetadata: suspend (Identity) -> Unit, ) : ViewModel() { @@ -103,25 +106,27 @@ class NostrSecretViewModel( // Keystore-backed, and it reads a file: it blocks, so it cannot run on the main thread. val result = withContext(Dispatchers.IO) { - NostrKeyManager.loadAndDecrypt(phoenixGlobal) + NostrCredentialManager.loadAndDecrypt(phoenixGlobal) } _uiState.value = when (result) { - is DecryptNostrKeysResult.Success -> { - val privateKey = result.keys[identity.nostrPublicKey] - if (privateKey == null) { - logger.e { "key file holds no key for identity=${identity.id}" } + is DecryptNostrCredentialsResult.Success -> { + // A public entry is not a key either: this screen is not offered to a + // read-only identity, and if it were reached there is nothing to show. + val credential = result.credentials[identity.nostrPublicKey] as? NostrCredential.Secret + if (credential == null) { + logger.e { "credentials file holds no secret for identity=${identity.id}" } NostrSecretUIState.Error.NoKeyForThisIdentity } else { - NostrSecretUIState.Revealed(privateKey.value.toHex().hexToNsecHrp()) + NostrSecretUIState.Revealed(credential.privateKey.value.toHex().hexToNsecHrp()) } } - is DecryptNostrKeysResult.Failure.FileNotFound -> { - logger.e { "no key file, so no key for identity=${identity.id}" } + is DecryptNostrCredentialsResult.Failure.FileNotFound -> { + logger.e { "no credentials file, so no key for identity=${identity.id}" } NostrSecretUIState.Error.NoKeyForThisIdentity } - is DecryptNostrKeysResult.Failure -> { - logger.e { "unable to read the nostr keys: $result" } + is DecryptNostrCredentialsResult.Failure -> { + logger.e { "unable to read the nostr credentials: $result" } NostrSecretUIState.Error.KeysUnreadable } } @@ -160,9 +165,9 @@ class NostrSecretViewModel( /** * Key out of the file, preferences deleted, metadata hidden, account rows gone -- in - * that order, so a failure partway leaves the key on disk rather than an identity the - * selector lists but nothing can open. [onForgotten] runs on the main thread once the - * device no longer holds the key; the caller clears the active identity and re-lists. + * that order, for the reason [ForgetIdentity] gives. [onForgotten] runs on the main + * thread once the device no longer holds the key; the caller clears the active + * identity and re-lists. */ fun forgetKey(onForgotten: () -> Unit) { val identity = activeIdentityStateFlow.value ?: return @@ -174,15 +179,15 @@ class NostrSecretViewModel( logger.e("could not forget the key", throwable) _forgetting.value = NostrSecretUIState.Forgetting.Failed }) { - when (forgetNostrKey(identity)) { - is IdentityWriter.ForgetNostrKeyResult.Forgotten -> { - hideIdentityMetadata(identity) - nostrRepository.forgetLocalAccount(identity.nostrPublicKey) + // The sequence is ForgetIdentity's, shared with the two exits a read-only + // identity has; only the state it drives is this screen's. + when (ForgetIdentity.forget(identity, nostrRepository, forgetNostrCredential, hideIdentityMetadata)) { + is ForgetIdentity.Outcome.Forgotten -> { _forgetting.value = NostrSecretUIState.Forgetting.Idle withContext(Dispatchers.Main) { onForgotten() } } - is IdentityWriter.ForgetNostrKeyResult.NotABareKey, - is IdentityWriter.ForgetNostrKeyResult.CannotLoadKeys -> { + is ForgetIdentity.Outcome.NotACredential, + is ForgetIdentity.Outcome.CannotForget -> { _forgetting.value = NostrSecretUIState.Forgetting.Failed } } @@ -196,7 +201,7 @@ class NostrSecretViewModel( phoenixGlobal: PhoenixGlobal, activeIdentityStateFlow: StateFlow, nostrRepository: NostrRepository, - forgetNostrKey: suspend (Identity) -> IdentityWriter.ForgetNostrKeyResult, + forgetNostrCredential: suspend (Identity) -> IdentityWriter.ForgetNostrCredentialResult, hideIdentityMetadata: suspend (Identity) -> Unit, ): ViewModelProvider.Factory = viewModelFactory { initializer { @@ -204,7 +209,7 @@ class NostrSecretViewModel( phoenixGlobal = phoenixGlobal, activeIdentityStateFlow = activeIdentityStateFlow, nostrRepository = nostrRepository, - forgetNostrKey = forgetNostrKey, + forgetNostrCredential = forgetNostrCredential, hideIdentityMetadata = hideIdentityMetadata, ) } diff --git a/composeApp/src/commonMain/kotlin/to/curare/compose/ui/view/model/SignInToProfileViewModel.kt b/composeApp/src/commonMain/kotlin/to/curare/compose/ui/view/model/SignInToProfileViewModel.kt index cbb67bcc..b2dbe433 100644 --- a/composeApp/src/commonMain/kotlin/to/curare/compose/ui/view/model/SignInToProfileViewModel.kt +++ b/composeApp/src/commonMain/kotlin/to/curare/compose/ui/view/model/SignInToProfileViewModel.kt @@ -8,6 +8,7 @@ import androidx.lifecycle.viewModelScope import androidx.lifecycle.viewmodel.initializer import androidx.lifecycle.viewmodel.viewModelFactory import co.touchlab.kermit.Logger +import com.vitorpamplona.quartz.nip01Core.core.HexKey import fr.acinq.bitcoin.PrivateKey import fr.acinq.phoenix.data.WalletId import kotlinx.coroutines.CancellationException @@ -25,14 +26,15 @@ import to.curare.compose.ui.view.state.SignInToProfileUIState import to.curare.compose.ui.view.state.form.SignInToProfileFormState /** - * Signs in with a secret the user already has: a recovery phrase or an nsec. + * Signs in with something the user already has: a recovery phrase, an nsec, or -- to + * look and not sign -- an npub. * - * The two writers are injected as functions rather than reached for, so the commit can - * be driven in a test without a key store, and because the recovery-phrase writer is - * `SovereignWalletViewModel.writeSeed`, which lives in another view model and drives a - * state machine of its own. + * The three writers are injected as functions rather than reached for, so the commit + * can be driven in a test without a key store, and because the recovery-phrase writer + * is `SovereignWalletViewModel.writeSeed`, which lives in another view model and drives + * a state machine of its own. * - * What this does not do is decide where the user goes next. It writes the secret, plants + * What this does not do is decide where the user goes next. It writes the credential, plants * the placeholder account, and hands the new id to [onSignedIn]; the nav host re-lists * identities, selects that one and goes to startup, which is the same tail the create * flow uses. The **order** inside [commit] is load-bearing: the account has to be in the @@ -42,7 +44,8 @@ import to.curare.compose.ui.view.state.form.SignInToProfileFormState */ class SignInToProfileViewModel( private val nostrRepository: NostrRepository, - private val writeNostrKey: suspend (PrivateKey) -> IdentityWriter.WriteNostrKeyResult, + private val writeNostrKey: suspend (PrivateKey) -> IdentityWriter.WriteNostrCredentialResult, + private val writeNostrPublicKey: suspend (HexKey) -> IdentityWriter.WriteNostrCredentialResult, private val writeRecoveryPhrase: ( words: List, onWritten: (WalletId) -> Unit, @@ -56,7 +59,8 @@ class SignInToProfileViewModel( fun factory( nostrRepository: NostrRepository, - writeNostrKey: suspend (PrivateKey) -> IdentityWriter.WriteNostrKeyResult, + writeNostrKey: suspend (PrivateKey) -> IdentityWriter.WriteNostrCredentialResult, + writeNostrPublicKey: suspend (HexKey) -> IdentityWriter.WriteNostrCredentialResult, writeRecoveryPhrase: ( words: List, onWritten: (WalletId) -> Unit, @@ -67,6 +71,7 @@ class SignInToProfileViewModel( SignInToProfileViewModel( nostrRepository = nostrRepository, writeNostrKey = writeNostrKey, + writeNostrPublicKey = writeNostrPublicKey, writeRecoveryPhrase = writeRecoveryPhrase, ) } @@ -102,25 +107,30 @@ class SignInToProfileViewModel( data class Failed(val problem: CredentialProblem) : Outcome } + private suspend fun write(what: String, writer: suspend () -> IdentityWriter.WriteNostrCredentialResult): Outcome = try { + when (val result = writer()) { + is IdentityWriter.WriteNostrCredentialResult.Written -> Outcome.SignedIn(result.id) + is IdentityWriter.WriteNostrCredentialResult.AlreadyExists -> Outcome.Failed(CredentialProblem.AlreadyOnThisDevice) + is IdentityWriter.WriteNostrCredentialResult.CannotLoadKeys -> Outcome.Failed(CredentialProblem.CouldNotWrite) + } + } catch (e: CancellationException) { + throw e + } catch (e: Exception) { + logger.e("could not write the $what", e) + Outcome.Failed(CredentialProblem.CouldNotWrite) + } + /** - * Writes the credential's secret to its store, then plants the placeholder account - * that tells the navigation machine this pubkey has a history to fetch rather than a - * profile to create. Suspends until both are done or one has failed. + * Writes the credential to its store, then plants the placeholder account that tells + * the navigation machine this pubkey has a history to fetch rather than a profile to + * create. Suspends until both are done or one has failed. The plant is idempotent by + * pubkey, which is what lets the nsec of a key held read-only sign in over it. */ suspend fun commit(credential: SignInCredential): Outcome { val written: Outcome = when (credential) { - is SignInCredential.NostrSecret -> try { - when (val result = writeNostrKey(credential.privateKey)) { - is IdentityWriter.WriteNostrKeyResult.Written -> Outcome.SignedIn(result.id) - is IdentityWriter.WriteNostrKeyResult.AlreadyExists -> Outcome.Failed(CredentialProblem.AlreadyOnThisDevice) - is IdentityWriter.WriteNostrKeyResult.CannotLoadKeys -> Outcome.Failed(CredentialProblem.CouldNotWrite) - } - } catch (e: CancellationException) { - throw e - } catch (e: Exception) { - logger.e("could not write the nostr key", e) - Outcome.Failed(CredentialProblem.CouldNotWrite) - } + is SignInCredential.NostrSecret -> write("nostr key") { writeNostrKey(credential.privateKey) } + + is SignInCredential.NostrPublicKey -> write("nostr public key") { writeNostrPublicKey(credential.nostrPublicKey) } is SignInCredential.RecoveryPhrase -> { // Callback-shaped writer, awaited: the seed writer drives WritingSeedState and diff --git a/composeApp/src/commonMain/kotlin/to/curare/compose/ui/view/model/SignOutViewModel.kt b/composeApp/src/commonMain/kotlin/to/curare/compose/ui/view/model/SignOutViewModel.kt new file mode 100644 index 00000000..d0c55dfa --- /dev/null +++ b/composeApp/src/commonMain/kotlin/to/curare/compose/ui/view/model/SignOutViewModel.kt @@ -0,0 +1,106 @@ +package to.curare.compose.ui.view.model + +import androidx.lifecycle.ViewModel +import androidx.lifecycle.ViewModelProvider +import androidx.lifecycle.viewModelScope +import androidx.lifecycle.viewmodel.initializer +import androidx.lifecycle.viewmodel.viewModelFactory +import co.touchlab.kermit.Logger +import kotlinx.coroutines.CoroutineExceptionHandler +import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.IO +import kotlinx.coroutines.flow.MutableStateFlow +import kotlinx.coroutines.flow.StateFlow +import kotlinx.coroutines.flow.asStateFlow +import kotlinx.coroutines.launch +import kotlinx.coroutines.withContext +import to.curare.compose.identity.ForgetIdentity +import to.curare.compose.identity.Identity +import to.curare.compose.identity.IdentityWriter +import to.curare.compose.repository.NostrRepository + +/** + * Signing out of a read-only identity, which is forgetting it: there is nothing on the + * device to lose, so it is the first real sign out in the app. The general case -- a + * seed, with funds behind it -- stays pending, for the reason docs/nsec-sign-in.md gives. + * + * Two screens drive this with the same state: the profile tab's *sign out*, and the + * not-found screen's *use a different key*, which is the same act reached from the other + * end of the identity's life. The sequence is [ForgetIdentity]'s; this owns only the + * confirmation and the in-flight state, the way `NostrSecretViewModel` does for an nsec. + */ +class SignOutViewModel( + private val activeIdentityStateFlow: StateFlow, + private val nostrRepository: NostrRepository, + private val forgetNostrCredential: suspend (Identity) -> IdentityWriter.ForgetNostrCredentialResult, + private val hideIdentityMetadata: suspend (Identity) -> Unit, +) : ViewModel() { + + sealed interface State { + data object Idle : State + data object Confirming : State + data object InProgress : State + data object Failed : State + } + + private val logger = Logger.withTag(TAG) + + private val _state = MutableStateFlow(State.Idle) + val state = _state.asStateFlow() + + /** The npub the confirmation names, so the user sees which identity is leaving. */ + val nostrPublicKey: String? get() = activeIdentityStateFlow.value?.nostrPublicKey + + fun askToSignOut() { + if (_state.value is State.InProgress) return + _state.value = State.Confirming + } + + fun cancel() { + if (_state.value is State.InProgress) return + _state.value = State.Idle + } + + /** [onSignedOut] runs on the main thread once the device holds nothing for the identity. */ + fun signOut(onSignedOut: () -> Unit) { + val identity = activeIdentityStateFlow.value ?: return + if (_state.value is State.InProgress) return + _state.value = State.InProgress + + viewModelScope.launch(Dispatchers.IO + CoroutineExceptionHandler { _, throwable -> + logger.e("could not sign out", throwable) + _state.value = State.Failed + }) { + when (ForgetIdentity.forget(identity, nostrRepository, forgetNostrCredential, hideIdentityMetadata)) { + is ForgetIdentity.Outcome.Forgotten -> { + _state.value = State.Idle + withContext(Dispatchers.Main) { onSignedOut() } + } + is ForgetIdentity.Outcome.NotACredential, + is ForgetIdentity.Outcome.CannotForget -> { + _state.value = State.Failed + } + } + } + } + + companion object { + private const val TAG = "SignOutViewModel" + + fun factory( + activeIdentityStateFlow: StateFlow, + nostrRepository: NostrRepository, + forgetNostrCredential: suspend (Identity) -> IdentityWriter.ForgetNostrCredentialResult, + hideIdentityMetadata: suspend (Identity) -> Unit, + ): ViewModelProvider.Factory = viewModelFactory { + initializer { + SignOutViewModel( + activeIdentityStateFlow = activeIdentityStateFlow, + nostrRepository = nostrRepository, + forgetNostrCredential = forgetNostrCredential, + hideIdentityMetadata = hideIdentityMetadata, + ) + } + } + } +} diff --git a/composeApp/src/commonMain/kotlin/to/curare/compose/ui/view/model/SovereignWalletViewModel.kt b/composeApp/src/commonMain/kotlin/to/curare/compose/ui/view/model/SovereignWalletViewModel.kt index 8d28fbe0..76a2bd7b 100644 --- a/composeApp/src/commonMain/kotlin/to/curare/compose/ui/view/model/SovereignWalletViewModel.kt +++ b/composeApp/src/commonMain/kotlin/to/curare/compose/ui/view/model/SovereignWalletViewModel.kt @@ -14,6 +14,7 @@ import fr.acinq.phoenix.PhoenixBusiness import fr.acinq.phoenix.PhoenixGlobal import com.vitorpamplona.quartz.nip01Core.core.HexKey import fr.acinq.bitcoin.PrivateKey +import fr.acinq.phoenix.data.DecryptNostrCredentialsResult import fr.acinq.phoenix.data.DecryptNostrKeysResult import fr.acinq.phoenix.data.DecryptSeedResult import fr.acinq.phoenix.data.ElectrumConfig @@ -21,7 +22,8 @@ import fr.acinq.phoenix.data.ListWalletState import fr.acinq.phoenix.data.UserWallet import fr.acinq.phoenix.data.WalletId import fr.acinq.phoenix.managers.DataStoreManager -import fr.acinq.phoenix.managers.NostrKeyManager +import fr.acinq.phoenix.managers.NostrCredentialManager +import fr.acinq.phoenix.security.NostrCredential import fr.acinq.phoenix.managers.nostrPrivateKey import fr.acinq.phoenix.utils.preferences.GlobalPrefs import fr.acinq.phoenix.utils.preferences.UserWalletMetadata @@ -158,7 +160,7 @@ class SovereignWalletViewModel( val dataStoreManager = DataStoreManager(business) setActiveIdentity( - Identity( + Identity.signing( id = walletId, kind = IdentityKind.Mnemonic, nostrPrivateKey = keyManager.nostrPrivateKey(), @@ -214,32 +216,53 @@ class SovereignWalletViewModel( is DecryptSeedResult.Success -> result.userWalletsMap } - val nostrKeys: Map = when (val result = NostrKeyManager.loadAndDecrypt(phoenixGlobal)) { - is DecryptNostrKeysResult.Failure.SerializationError -> { - log.e { "cannot deserialize nostr keys file" } + // Before the read, and here rather than in the reader: a listing that writes + // would be a surprise, and this runs from init, before anything else touches + // either file. An old file that cannot be read is left alone and reported the + // way an unreadable credentials file is, so the user sees the error rather + // than silently losing every imported identity. + when (val migration = NostrCredentialManager.migrateFromNostrKeys(phoenixGlobal)) { + is NostrCredentialManager.MigrationResult.Migrated -> log.i { "migrated ${migration.count} nostr key(s) into the credentials file" } + is NostrCredentialManager.MigrationResult.NotNeeded -> Unit + is NostrCredentialManager.MigrationResult.Failed -> { + log.e { "nostr-keys.dat could not be migrated: ${migration.failure}" } + _listWalletState.value = when (val failure = migration.failure) { + is DecryptNostrKeysResult.Failure.SerializationError -> ListWalletState.Error.Serialization + is DecryptNostrKeysResult.Failure.DecryptionError -> ListWalletState.Error.DecryptionError.GeneralException(failure.cause) + is DecryptNostrKeysResult.Failure.KeyStoreFailure -> ListWalletState.Error.DecryptionError.KeystoreFailure(failure.cause) + is DecryptNostrKeysResult.Failure.FileUnreadable, + is DecryptNostrKeysResult.Failure.FileNotFound -> ListWalletState.Error.Generic(null) + } + return@launch + } + } + + val credentials: Map = when (val result = NostrCredentialManager.loadAndDecrypt(phoenixGlobal)) { + is DecryptNostrCredentialsResult.Failure.SerializationError -> { + log.e { "cannot deserialize nostr credentials file" } _listWalletState.value = ListWalletState.Error.Serialization return@launch } - is DecryptNostrKeysResult.Failure.DecryptionError -> { - log.e("cannot decrypt nostr keys file: ", throwable = result.cause) + is DecryptNostrCredentialsResult.Failure.DecryptionError -> { + log.e("cannot decrypt nostr credentials file: ", throwable = result.cause) _listWalletState.value = ListWalletState.Error.DecryptionError.GeneralException(result.cause) return@launch } - is DecryptNostrKeysResult.Failure.KeyStoreFailure -> { + is DecryptNostrCredentialsResult.Failure.KeyStoreFailure -> { log.e("key store failure: ", throwable = result.cause) _listWalletState.value = ListWalletState.Error.DecryptionError.KeystoreFailure(result.cause) return@launch } - is DecryptNostrKeysResult.Failure.FileUnreadable -> { - log.e("aborting, unreadable nostr keys file") + is DecryptNostrCredentialsResult.Failure.FileUnreadable -> { + log.e("aborting, unreadable nostr credentials file") _listWalletState.value = ListWalletState.Error.Generic(null) return@launch } - is DecryptNostrKeysResult.Failure.FileNotFound -> emptyMap() - is DecryptNostrKeysResult.Success -> result.keys + is DecryptNostrCredentialsResult.Failure.FileNotFound -> emptyMap() + is DecryptNostrCredentialsResult.Success -> result.credentials } - val identities = StoredIdentity.merge(wallets, nostrKeys) + val identities = StoredIdentity.merge(wallets, credentials) val metadataMap = getAvailableWalletsMeta(phoenixGlobal).first() identities.keys.forEach { walletId -> @@ -357,7 +380,7 @@ class SovereignWalletViewModel( * Writes a bare nostr key as a new identity, with the same initialisation options * [writeSeed] applies. Suspends; the caller is the sign-in view model's coroutine. */ - suspend fun writeNostrKey(privateKey: PrivateKey): IdentityWriter.WriteNostrKeyResult = + suspend fun writeNostrKey(privateKey: PrivateKey): IdentityWriter.WriteNostrCredentialResult = IdentityWriter.writeNostrKey( log = log, phoenixGlobal = phoenixGlobal, @@ -367,9 +390,20 @@ class SovereignWalletViewModel( customElectrumServer = customElectrumServer.value, ) - /** The inverse of [writeNostrKey]. Only for a bare key; see [IdentityWriter.forgetNostrKey]. */ - suspend fun forgetNostrKey(identity: Identity): IdentityWriter.ForgetNostrKeyResult = - IdentityWriter.forgetNostrKey( + /** Writes a public key as a read-only identity, with the same options. */ + suspend fun writeNostrPublicKey(nostrPublicKey: HexKey): IdentityWriter.WriteNostrCredentialResult = + IdentityWriter.writeNostrPublicKey( + log = log, + phoenixGlobal = phoenixGlobal, + globalPrefs = getGlobalPrefs(), + nostrPublicKey = nostrPublicKey, + isTorEnabled = isTorEnabled.value, + customElectrumServer = customElectrumServer.value, + ) + + /** The inverse of both writers above. Only for a credential; see [IdentityWriter.forgetNostrCredential]. */ + suspend fun forgetNostrCredential(identity: Identity): IdentityWriter.ForgetNostrCredentialResult = + IdentityWriter.forgetNostrCredential( log = log, phoenixGlobal = phoenixGlobal, id = identity.id, diff --git a/composeApp/src/commonMain/kotlin/to/curare/compose/ui/view/model/SynchronizationViewModel.kt b/composeApp/src/commonMain/kotlin/to/curare/compose/ui/view/model/SynchronizationViewModel.kt index c1aa8c78..eb17604d 100644 --- a/composeApp/src/commonMain/kotlin/to/curare/compose/ui/view/model/SynchronizationViewModel.kt +++ b/composeApp/src/commonMain/kotlin/to/curare/compose/ui/view/model/SynchronizationViewModel.kt @@ -30,6 +30,7 @@ import com.vitorpamplona.quartz.nip77Negentropy.NegCloseCmd import com.vitorpamplona.quartz.nip77Negentropy.NegMsgCmd import com.vitorpamplona.quartz.nip77Negentropy.NegOpenCmd import to.curare.compose.identity.Identity +import to.curare.compose.identity.toKeyPair import kotlinx.coroutines.CancellationException import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.Dispatchers @@ -191,10 +192,10 @@ class SynchronizationViewModel( scope.launch { activeIdentityStateFlow.collectLatest { identity -> logger.d("Synchronization identity: $identity") - identity?.nostrPrivateKey?.let { nostrPrivateKey -> - val keyPair = KeyPair( - privKey = nostrPrivateKey.value.toByteArray() - ) + identity?.let { + // Through the helper, never by hand: a read-only identity has no private + // key, and quartz's KeyPair given neither key generates a fresh one. + val keyPair = identity.toKeyPair() // Anything a previous run left mid-flight is ours to retry: it was flipped to // "processing" before the publish and nothing observes that status, so @@ -215,13 +216,23 @@ class SynchronizationViewModel( // throw in one must not take the other two down with it for the rest of the // session. Each pump also guards its own per-request body (see guardPump). supervisorScope { - launch(Dispatchers.IO) { observePendingBroadcastNostrEventRequests(keyPair) } launch(Dispatchers.IO) { observePendingSyncNostrEventRequests(keyPair) } launch(Dispatchers.IO) { observePendingNegentropySynchronizeRequests(keyPair) } - // Runs until cancelled rather than draining a queue, but it belongs - // here for the same reason the pumps do: it needs the active wallet's - // key pair, and a wallet switch must tear it down. - launch(Dispatchers.IO) { liveSubscriptionManager.observe(keyPair) } + // A read-only identity runs the two pumps that read and neither of + // the two that write. The rule Phase 5 of docs/npub-sign-in.md + // leans on: such an identity never sends anything to a relay, not a + // signature and not a copy. The broadcast pump would find nothing -- + // nothing is ever signed -- and the live subscriptions are the + // gift-wrap inbox and the group-membership follow, both fetching + // things this identity cannot open. Not asking is not an + // optimisation; it is the identity not asking for what it cannot use. + if (identity.canSign) { + launch(Dispatchers.IO) { observePendingBroadcastNostrEventRequests(keyPair) } + // Runs until cancelled rather than draining a queue, but it + // belongs here for the same reason the pumps do: it needs the + // active wallet's key pair, and a wallet switch must tear it down. + launch(Dispatchers.IO) { liveSubscriptionManager.observe(keyPair) } + } } } } diff --git a/composeApp/src/jvmTest/kotlin/to/curare/compose/database/dao/ReadOnlyGiftWrapDaoJvmTest.kt b/composeApp/src/jvmTest/kotlin/to/curare/compose/database/dao/ReadOnlyGiftWrapDaoJvmTest.kt new file mode 100644 index 00000000..84045ded --- /dev/null +++ b/composeApp/src/jvmTest/kotlin/to/curare/compose/database/dao/ReadOnlyGiftWrapDaoJvmTest.kt @@ -0,0 +1,106 @@ +package to.curare.compose.database.dao + +import androidx.room3.Room +import com.vitorpamplona.quartz.nip01Core.core.toHexKey +import com.vitorpamplona.quartz.nip01Core.crypto.KeyPair +import com.vitorpamplona.quartz.nip01Core.signers.NostrSignerSync +import com.vitorpamplona.quartz.nip59Giftwrap.seals.SealedRumorEvent +import com.vitorpamplona.quartz.nip59Giftwrap.wraps.GiftWrapEvent +import kotlinx.coroutines.runBlocking +import to.curare.compose.database.CurareDatabase +import to.curare.compose.database.builder.getRoomDatabase +import to.curare.compose.database.model.NostrEvent +import kotlin.test.AfterTest +import kotlin.test.Test +import kotlin.test.assertEquals +import kotlin.test.assertNotNull +import kotlin.time.Instant + +/** + * A gift wrap addressed to a read-only identity is kept and not opened. + * + * `storeNostrEvent` is `@Transaction` and indexes inside it, and a wrap addressed to the + * active key that cannot be unsealed throws -- so before the guard in `indexNostrEvent` + * the throw took the event with it, and looked in the logs like a decryption failure. + * Worse, `decryptGiftWrapSeal` builds `KeyPair(privKey = keyPair.privKey)`, and in + * quartz a `KeyPair` given neither key generates a fresh one: the unseal would have run + * with a key nobody has. A read-only identity holds no key by construction, and the + * wrap is what the branch for someone else's mail already does with it: stored, so the + * key that opens it can be signed in later. + */ +class ReadOnlyGiftWrapDaoJvmTest { + + private val db: CurareDatabase = getRoomDatabase( + Room.inMemoryDatabaseBuilder() + ) + + @AfterTest + fun closeDb() = db.close() + + private val relay = "wss://relay.example" + + /** The user, as the sync pump sees them when the device holds only their public key. */ + private val us = KeyPair() + private val readOnlyUs = KeyPair(pubKey = us.pubKey) + private val peer = KeyPair() + + private fun wrapTo(recipient: KeyPair): NostrEvent { + val signer = NostrSignerSync(peer) + val seal = signer.signNormal( + createdAt = 1_700_000_000, + kind = SealedRumorEvent.KIND, + tags = emptyArray(), + content = signer.nip44Encrypt( + plaintext = """{"kind":14,"content":"dumela"}""", + toPublicKey = recipient.pubKey.toHexKey(), + ), + ) + val giftWrap = GiftWrapEvent.create( + event = seal, + recipientPubKey = recipient.pubKey.toHexKey(), + createdAt = 1_700_000_100, + ) + return NostrEvent( + id = giftWrap.id, + pubKey = giftWrap.pubKey, + kind = giftWrap.kind, + tags = giftWrap.tags, + content = giftWrap.content, + sig = giftWrap.sig, + createdAt = Instant.fromEpochSeconds(giftWrap.createdAt), + ) + } + + @Test + fun `a wrap addressed to a read-only identity is stored, and its seal is not`() = runBlocking { + val wrap = wrapTo(us) + + db.nostrDao().storeNostrEvent( + nostrEvent = wrap, + relayURL = relay, + synchronizationRelayURLs = listOf(relay), + level = 0, + activeKeyPair = readOnlyUs, + ) + + assertNotNull(db.nostrEventDao().getNostrEventById(wrap.id), "the event itself must survive the failed unseal") + assertEquals(listOf(wrap.id), db.giftWrapMessageDao().getAllGiftWrapMessages().map { it.id }) + assertEquals(emptyList(), db.giftWrapSealDao().getAllGiftWrapSeals(), "nothing was opened") + } + + /** The same wrap, once the key is here: the seal comes out. The guard is only about the key's absence. */ + @Test + fun `the same wrap opens once the identity holds its key`() = runBlocking { + val wrap = wrapTo(us) + + db.nostrDao().storeNostrEvent( + nostrEvent = wrap, + relayURL = relay, + synchronizationRelayURLs = listOf(relay), + level = 0, + activeKeyPair = us, + ) + + assertEquals(1, db.giftWrapSealDao().getAllGiftWrapSeals().size) + } +} diff --git a/composeApp/src/jvmTest/kotlin/to/curare/compose/database/repository/SignInToProfileTwiceJvmTest.kt b/composeApp/src/jvmTest/kotlin/to/curare/compose/database/repository/SignInToProfileTwiceJvmTest.kt new file mode 100644 index 00000000..fb6b799f --- /dev/null +++ b/composeApp/src/jvmTest/kotlin/to/curare/compose/database/repository/SignInToProfileTwiceJvmTest.kt @@ -0,0 +1,54 @@ +package to.curare.compose.database.repository + +import androidx.room3.Room +import kotlinx.coroutines.CoroutineScope +import kotlinx.coroutines.Job +import kotlinx.coroutines.cancel +import kotlinx.coroutines.runBlocking +import to.curare.compose.database.CurareDatabase +import to.curare.compose.database.GENESIS_AT +import to.curare.compose.database.builder.getRoomDatabase +import kotlin.test.AfterTest +import kotlin.test.Test +import kotlin.test.assertEquals + +/** + * Signing in twice plants one account. + * + * Until the read-only kind nothing called `signInToProfile` twice for one pubkey: the + * writers refused a second sign-in before it got there. Pasting the nsec of a key held + * read-only is the first path that signs in a pubkey whose account already exists, and + * a second placeholder would be two kind-0 rows for one pubkey -- two accounts + * disagreeing about which is this one. `getLocalAccounts` is every kind-0 row, so the + * count is the assertion. + */ +class SignInToProfileTwiceJvmTest { + + private val db: CurareDatabase = getRoomDatabase( + Room.inMemoryDatabaseBuilder() + ) + private val scope = CoroutineScope(Job()) + private val repository = DatabaseNostrRepository(db, scope) + + private val publicKey = "a".repeat(64) + private val someoneElse = "b".repeat(64) + + @AfterTest + fun closeDb() { + scope.cancel() + db.close() + } + + @Test + fun `a second sign-in for the same key plants nothing, and another key still gets its own account`() = runBlocking { + repository.signInToProfile(publicKey) + repository.signInToProfile(publicKey) + repository.signInToProfile(someoneElse) + + val accounts = repository.getLocalAccounts() + + assertEquals(listOf(publicKey, someoneElse).sorted(), accounts.mapNotNull { it.unsignedNostrEvent?.pubKey }.sorted()) + val placeholder = accounts.first { it.unsignedNostrEvent?.pubKey == publicKey }.unsignedNostrEvent!! + assertEquals(GENESIS_AT, placeholder.signedAt, "the placeholder is what it was: signed at genesis, so the notary skips it") + } +} diff --git a/composeApp/src/jvmTest/kotlin/to/curare/compose/identity/CredentialParserJvmTest.kt b/composeApp/src/jvmTest/kotlin/to/curare/compose/identity/CredentialParserJvmTest.kt index 5645cd2a..602f3aed 100644 --- a/composeApp/src/jvmTest/kotlin/to/curare/compose/identity/CredentialParserJvmTest.kt +++ b/composeApp/src/jvmTest/kotlin/to/curare/compose/identity/CredentialParserJvmTest.kt @@ -1,8 +1,10 @@ package to.curare.compose.identity +import to.curare.compose.extensions.hexToNpubHrp import kotlin.test.Test import kotlin.test.assertEquals import kotlin.test.assertIs +import kotlin.test.assertNotEquals /** * Every row of the sign-in screen's table, in and out. @@ -72,9 +74,33 @@ class CredentialParserJvmTest { } @Test - fun `a public key is named for what it is`() { - assertEquals(CredentialProblem.PublicKeyOnly, refused(npub)) - assertEquals(CredentialProblem.PublicKeyOnly, refused("nostr:$npub")) + fun `an npub, a nostr-prefixed npub and the upper-cased form all name the same public key`() { + for (input in listOf(npub, "nostr:$npub", npub.uppercase())) { + val credential = assertIs(recognised(input), "for '$input'") + assertEquals(publicKey, credential.nostrPublicKey) + } + } + + /** + * Sixty-four hex characters are a secret and stay one: a private key and an x-only + * public key are the same size, and the parser cannot tell them apart -- nor may it + * guess, since an x coordinate is almost always also a valid scalar and the guess + * would never fire. The public key of the vector, pasted as hex, is a *different* + * secret whose npub the confirm step shows. + */ + @Test + fun `sixty-four hex characters are still a secret, even when they are a public key`() { + val credential = assertIs(recognised(publicKey)) + assertNotEquals(publicKey, credential.nostrPublicKey) + } + + @Test + fun `an npub that does not decode, or names no point on the curve, is an invalid key`() { + assertEquals(CredentialProblem.InvalidKey, refused(npub.dropLast(1) + "q")) + // The field prime, bech32-encoded under npub: sixty-four hex characters that are + // not an x coordinate. + val notOnTheCurve = "fffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f".hexToNpubHrp() + assertEquals(CredentialProblem.InvalidKey, refused(notOnTheCurve)) } @Test diff --git a/composeApp/src/jvmTest/kotlin/to/curare/compose/identity/ForgetIdentityJvmTest.kt b/composeApp/src/jvmTest/kotlin/to/curare/compose/identity/ForgetIdentityJvmTest.kt new file mode 100644 index 00000000..5e911e5f --- /dev/null +++ b/composeApp/src/jvmTest/kotlin/to/curare/compose/identity/ForgetIdentityJvmTest.kt @@ -0,0 +1,95 @@ +package to.curare.compose.identity + +import androidx.datastore.preferences.core.PreferenceDataStoreFactory +import com.vitorpamplona.quartz.nip01Core.core.HexKey +import fr.acinq.bitcoin.ByteVector32 +import fr.acinq.bitcoin.PrivateKey +import fr.acinq.phoenix.managers.nostrPublicKeyHex +import fr.acinq.phoenix.utils.preferences.InternalPrefs +import fr.acinq.phoenix.utils.preferences.UserPrefs +import kotlinx.coroutines.runBlocking +import okio.Path.Companion.toPath +import org.junit.Rule +import org.junit.rules.TemporaryFolder +import to.curare.compose.repository.NostrRepository +import kotlin.test.Test +import kotlin.test.assertEquals + +/** + * The sequence, and where it stops. + * + * Forgetting is four effects in an order that matters -- the credential out of the + * file, the metadata hidden, the account rows gone, then the caller's tail -- so that a + * failure partway leaves the credential on disk rather than an identity the selector + * lists but nothing can open. A refusal at the first step must leave the other two + * untouched: an identity that is still on the device must still have its account. + * + * The two writers are recorded rather than run; `IdentityWriterJvmTest` covers what + * they do to the disk. + */ +class ForgetIdentityJvmTest { + + @get:Rule + val temporaryFolder = TemporaryFolder() + + private val privateKey = PrivateKey(ByteVector32("04".repeat(32))) + + private fun prefsStore(name: String) = PreferenceDataStoreFactory.createWithPath { + temporaryFolder.newFolder().resolve("$name.preferences_pb").path.toPath() + } + + private fun readOnlyIdentity() = Identity.readOnly( + id = privateKey.publicKey().xOnly().toWalletId(), + nostrPublicKey = privateKey.nostrPublicKeyHex(), + userPrefs = UserPrefs(prefsStore("user")), + internalPrefs = InternalPrefs(prefsStore("internal")), + ) + + private class Recorder : NostrRepository by NostrRepository.NO_OP_NOSTR_REPOSITORY { + val effects = mutableListOf() + override suspend fun forgetLocalAccount(publicKey: HexKey) { + effects += "forgetLocalAccount:$publicKey" + } + } + + private suspend fun forget(recorder: Recorder, result: IdentityWriter.ForgetNostrCredentialResult) = + ForgetIdentity.forget( + identity = readOnlyIdentity(), + nostrRepository = recorder, + forgetNostrCredential = { recorder.effects += "forgetNostrCredential"; result }, + hideIdentityMetadata = { recorder.effects += "hideIdentityMetadata" }, + ) + + @Test + fun `the credential comes out first, then the metadata, then the account`() = runBlocking { + val recorder = Recorder() + + val outcome = forget(recorder, IdentityWriter.ForgetNostrCredentialResult.Forgotten) + + assertEquals(ForgetIdentity.Outcome.Forgotten, outcome) + assertEquals( + listOf("forgetNostrCredential", "hideIdentityMetadata", "forgetLocalAccount:${privateKey.nostrPublicKeyHex()}"), + recorder.effects, + ) + } + + @Test + fun `a mnemonic identity is refused before anything else is touched`() = runBlocking { + val recorder = Recorder() + + val outcome = forget(recorder, IdentityWriter.ForgetNostrCredentialResult.NotACredential) + + assertEquals(ForgetIdentity.Outcome.NotACredential, outcome) + assertEquals(listOf("forgetNostrCredential"), recorder.effects) + } + + @Test + fun `a store that cannot be read stops the sequence at its first step`() = runBlocking { + val recorder = Recorder() + + val outcome = forget(recorder, IdentityWriter.ForgetNostrCredentialResult.CannotLoadKeys) + + assertEquals(ForgetIdentity.Outcome.CannotForget, outcome) + assertEquals(listOf("forgetNostrCredential"), recorder.effects) + } +} diff --git a/composeApp/src/jvmTest/kotlin/to/curare/compose/identity/IdentityWriterJvmTest.kt b/composeApp/src/jvmTest/kotlin/to/curare/compose/identity/IdentityWriterJvmTest.kt index 19047396..9d04e75c 100644 --- a/composeApp/src/jvmTest/kotlin/to/curare/compose/identity/IdentityWriterJvmTest.kt +++ b/composeApp/src/jvmTest/kotlin/to/curare/compose/identity/IdentityWriterJvmTest.kt @@ -5,9 +5,11 @@ import co.touchlab.kermit.Logger import fr.acinq.bitcoin.PrivateKey import fr.acinq.lightning.Lightning import fr.acinq.phoenix.PhoenixGlobal -import fr.acinq.phoenix.managers.NostrKeyManager +import fr.acinq.phoenix.managers.NostrCredentialManager import fr.acinq.phoenix.managers.computePreferencePath +import fr.acinq.phoenix.managers.nostrPublicKeyHex import fr.acinq.phoenix.security.JvmKeyStore +import fr.acinq.phoenix.security.NostrCredential import fr.acinq.phoenix.utils.PlatformContext import fr.acinq.phoenix.utils.preferences.GlobalPrefs import kotlinx.coroutines.runBlocking @@ -24,12 +26,15 @@ import kotlin.test.assertIs import kotlin.test.assertTrue /** - * The two writers for a bare key, against a real key store and a real directory. + * The writers for a bare key and a bare public key, against a real key store and a + * real directory. * - * What is pinned is the duplicate rule and the inverse. A second import of the same key - * is refused by public key, the same npub imported twice being the one thing the id - * check cannot see; and forgetting takes the key out of the file and the identity's - * preference files off the disk, leaving every other key where it was. + * What is pinned is the duplicate rule, its one exception, and the inverse. A second + * import of the same key is refused by public key, the same npub imported twice being + * the one thing the id check cannot see; a public key already here is *not* a duplicate + * of the secret that signs as it, and the entry becomes a secret one under the id it + * had; and forgetting takes the entry, whichever kind, out of the file and the identity's + * preference files off the disk, leaving every other entry where it was. */ class IdentityWriterJvmTest { @@ -76,36 +81,96 @@ class IdentityWriterJvmTest { customElectrumServer = null, ) - private fun userPrefsFile(stored: StoredIdentity.NostrSecret) = + private suspend fun writePublic(key: PrivateKey) = IdentityWriter.writeNostrPublicKey( + log = log, + phoenixGlobal = phoenixGlobal, + globalPrefs = globalPrefs, + nostrPublicKey = key.nostrPublicKeyHex(), + isTorEnabled = false, + customElectrumServer = null, + ) + + private fun credentials() = NostrCredentialManager.loadAndDecryptOrNull(phoenixGlobal) + + private fun userPrefsFile(stored: StoredIdentity) = computePreferencePath(phoenixGlobal.ctx, "userprefs_${stored.id.nodeIdHash}.preferences_pb") @Test fun `a key is written once and refused the second time, by public key`() = runBlocking { val stored = StoredIdentity.nostrSecret(first) - val written = assertIs(write(first)) + val written = assertIs(write(first)) assertEquals(stored.id, written.id) - assertEquals(mapOf(stored.nostrPublicKey to first), NostrKeyManager.loadAndDecryptOrNull(phoenixGlobal)) + assertEquals(mapOf(stored.nostrPublicKey to NostrCredential.Secret(first)), credentials()) assertTrue(FileSystem.SYSTEM.exists(userPrefsFile(stored)), "the preferences file the recovery screens read") - assertIs(write(first)) + assertIs(write(first)) } @Test - fun `forgetting one key leaves the other, and takes the preferences with it`() = runBlocking { + fun `a public key is written once and refused the second time`() = runBlocking { + val stored = StoredIdentity.nostrPublic(first.nostrPublicKeyHex()) + + val written = assertIs(writePublic(first)) + assertEquals(stored.id, written.id) + assertEquals(mapOf(stored.nostrPublicKey to NostrCredential.Public), credentials()) + assertTrue(FileSystem.SYSTEM.exists(userPrefsFile(stored))) + + assertIs(writePublic(first)) + } + + /** + * The one exception to the duplicate rule, and the reason the two kinds share a + * file: the device does not hold this secret, so refusing it would be false. One + * write, same id, and the preferences the read-only identity had are the ones the + * signing identity keeps. + */ + @Test + fun `the nsec of a key held read-only is accepted, under the same id, and the entry becomes a secret`() = runBlocking { + val readOnly = assertIs(writePublic(first)) + writePublic(second) + + val upgraded = assertIs(write(first)) + + assertEquals(readOnly.id, upgraded.id) + assertEquals( + mapOf( + first.nostrPublicKeyHex() to NostrCredential.Secret(first), + second.nostrPublicKeyHex() to NostrCredential.Public, + ), + credentials(), + ) + assertTrue(FileSystem.SYSTEM.exists(userPrefsFile(StoredIdentity.nostrSecret(first)))) + } + + /** The other direction is a duplicate: the device already holds more than an npub for the key. */ + @Test + fun `the npub of a key held as a secret is refused`() = runBlocking { write(first) - write(second) + + assertIs(writePublic(first)) + assertEquals(mapOf(first.nostrPublicKeyHex() to NostrCredential.Secret(first)), credentials()) + } + + @Test + fun `forgetting one entry leaves the others, whichever kind, and takes the preferences with it`() = runBlocking { + write(first) + writePublic(second) val stored = StoredIdentity.nostrSecret(first) - val result = IdentityWriter.forgetNostrKey(log, phoenixGlobal, stored.id, stored.nostrPublicKey) + val result = IdentityWriter.forgetNostrCredential(log, phoenixGlobal, stored.id, stored.nostrPublicKey) - assertIs(result) - assertEquals( - mapOf(StoredIdentity.nostrSecret(second).nostrPublicKey to second), - NostrKeyManager.loadAndDecryptOrNull(phoenixGlobal), - ) + assertIs(result) + assertEquals(mapOf(second.nostrPublicKeyHex() to NostrCredential.Public), credentials()) assertFalse(FileSystem.SYSTEM.exists(userPrefsFile(stored))) - assertTrue(FileSystem.SYSTEM.exists(userPrefsFile(StoredIdentity.nostrSecret(second)))) + assertTrue(FileSystem.SYSTEM.exists(userPrefsFile(StoredIdentity.nostrPublic(second.nostrPublicKeyHex())))) + + val readOnly = StoredIdentity.nostrPublic(second.nostrPublicKeyHex()) + assertIs( + IdentityWriter.forgetNostrCredential(log, phoenixGlobal, readOnly.id, readOnly.nostrPublicKey) + ) + assertEquals(emptyMap(), credentials()) + assertFalse(FileSystem.SYSTEM.exists(userPrefsFile(readOnly))) } /** A wallet's nostr key is in the seed, not here; removing a seed is a wallet question. */ @@ -114,9 +179,9 @@ class IdentityWriterJvmTest { write(first) val other = StoredIdentity.nostrSecret(second) - assertIs( - IdentityWriter.forgetNostrKey(log, phoenixGlobal, other.id, other.nostrPublicKey) + assertIs( + IdentityWriter.forgetNostrCredential(log, phoenixGlobal, other.id, other.nostrPublicKey) ) - assertEquals(1, NostrKeyManager.loadAndDecryptOrNull(phoenixGlobal)?.size) + assertEquals(1, credentials()?.size) } } diff --git a/composeApp/src/jvmTest/kotlin/to/curare/compose/identity/NpubPreviewRoundTripJvmTest.kt b/composeApp/src/jvmTest/kotlin/to/curare/compose/identity/NpubPreviewRoundTripJvmTest.kt new file mode 100644 index 00000000..5e5ce5a0 --- /dev/null +++ b/composeApp/src/jvmTest/kotlin/to/curare/compose/identity/NpubPreviewRoundTripJvmTest.kt @@ -0,0 +1,262 @@ +package to.curare.compose.identity + +import androidx.datastore.preferences.core.PreferenceDataStoreFactory +import androidx.room3.Room +import co.touchlab.kermit.Logger +import com.vitorpamplona.quartz.nip01Core.metadata.MetadataEvent +import fr.acinq.bitcoin.PrivateKey +import fr.acinq.lightning.Lightning +import fr.acinq.phoenix.PhoenixGlobal +import fr.acinq.phoenix.jvm.BusinessManager +import fr.acinq.phoenix.managers.DataStoreManager +import fr.acinq.phoenix.managers.NodeParamsManager +import fr.acinq.phoenix.managers.NostrCredentialManager +import fr.acinq.phoenix.managers.SeedManager +import fr.acinq.phoenix.managers.computePreferencePath +import fr.acinq.phoenix.managers.nostrPublicKeyHex +import fr.acinq.phoenix.security.JvmKeyStore +import fr.acinq.phoenix.security.NostrCredential +import fr.acinq.phoenix.utils.PlatformContext +import fr.acinq.phoenix.utils.preferences.GlobalPrefs +import kotlinx.coroutines.CoroutineScope +import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.Job +import kotlinx.coroutines.cancel +import kotlinx.coroutines.delay +import kotlinx.coroutines.flow.MutableStateFlow +import kotlinx.coroutines.flow.first +import kotlinx.coroutines.runBlocking +import kotlinx.coroutines.withTimeout +import to.curare.compose.database.CurareDatabase +import to.curare.compose.database.GENESIS_AT +import to.curare.compose.database.builder.getRoomDatabase +import to.curare.compose.database.model.NostrEvent +import to.curare.compose.database.repository.DatabaseChatRepository +import to.curare.compose.database.repository.DatabaseMarmotRepository +import to.curare.compose.database.repository.DatabaseNostrRepository +import to.curare.compose.ui.view.model.NavigationViewModel +import to.curare.compose.ui.view.model.NotaryViewModel +import to.curare.compose.ui.view.model.SignInToProfileViewModel +import to.curare.compose.ui.view.state.NavigationUIState +import java.io.File +import java.nio.file.Files +import kotlin.test.AfterTest +import kotlin.test.BeforeTest +import kotlin.test.Test +import kotlin.test.assertEquals +import kotlin.test.assertFalse +import kotlin.test.assertIs +import kotlin.test.assertNull +import kotlin.test.assertTrue +import kotlin.time.Instant + +/** + * The preview, end to end, and then the upgrade -- Phase 7 of docs/npub-sign-in.md. + * + * Unlike `NsecRestoreRoundTripJvmTest`, the repository here is real: an in-memory + * database under the same DAOs the app runs on, because the assertion this exists for + * is about what is *not* in it. Sign in with an npub the way the sign-in screen does, + * list identities the way startup does, activate the read-only one, hand + * NavigationViewModel the device: it lands on UnqueuedProfileSynchronization. Index the + * kind 0 the relays would have answered with, through the read-only key pair: it lands + * on ProfileLoaded. And with a real NotaryViewModel running against the same database + * for longer than its key package delay: **nothing was signed** -- the only unsigned row + * for the pubkey is the placeholder, still at genesis; no key package bundle; no + * broadcast request; no node. + * + * Then the nsec of the same key is written the way the sign-in screen writes it: the + * same id, one entry that is now a secret, and one account -- the second sign-in + * planted nothing. + */ +class NpubPreviewRoundTripJvmTest { + + private lateinit var storeDir: File + private lateinit var appDir: File + private lateinit var phoenixGlobal: PhoenixGlobal + private lateinit var globalPrefs: GlobalPrefs + + private val db: CurareDatabase = getRoomDatabase( + Room.inMemoryDatabaseBuilder() + ) + private val scope = CoroutineScope(Job() + Dispatchers.IO) + private val nostrRepository = DatabaseNostrRepository(db, scope) + private val chatRepository = DatabaseChatRepository(db, scope) + private val marmotRepository = DatabaseMarmotRepository(db, scope) + + private val log = Logger.withTag("NpubPreviewRoundTripJvmTest") + private val privateKey = PrivateKey(Lightning.randomBytes(32)) + private val publicKey = privateKey.nostrPublicKeyHex() + private val at = Instant.fromEpochSeconds(1_700_000_000) + + @BeforeTest + fun setUp() { + storeDir = Files.createTempDirectory("curare-preview-store").toFile() + appDir = Files.createTempDirectory("curare-preview-app").toFile() + JvmKeyStore.lock() + JvmKeyStore.unlock("correct horse battery staple".toCharArray(), storeDir) + phoenixGlobal = PhoenixGlobal(PlatformContext(applicationDir = appDir)) + globalPrefs = GlobalPrefs( + PreferenceDataStoreFactory.createWithPath { + computePreferencePath(phoenixGlobal.ctx, "globalprefs.preferences_pb") + } + ) + } + + @AfterTest + fun tearDown() { + scope.cancel() + db.close() + JvmKeyStore.lock() + storeDir.deleteRecursively() + appDir.deleteRecursively() + } + + private fun signInViewModel() = SignInToProfileViewModel( + nostrRepository = nostrRepository, + 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(to.curare.compose.ui.view.model.WritingSeedState.Error.CannotLoadSeedMap) }, + ) + + private fun listed() = StoredIdentity.merge( + wallets = SeedManager.loadAndDecryptOrNull(phoenixGlobal) ?: error("seed store unreadable"), + credentials = NostrCredentialManager.loadAndDecryptOrNull(phoenixGlobal) ?: error("credentials unreadable"), + ) + + /** The kind 0 the relays would answer the sign-in sync with. */ + private fun kind0() = NostrEvent( + id = "e".repeat(64), + pubKey = publicKey, + kind = MetadataEvent.KIND, + tags = emptyArray(), + content = """{"name":"Reader"}""", + sig = "0".repeat(128), + createdAt = at, + ) + + @Test + fun `an npub signed in, listed, activated, routed and watched by the notary, with nothing signed`() = runBlocking { + // 1. The sign-in screen's commit, minus the screen: the credential, then the account. + val outcome = signInViewModel().commit(SignInCredential.NostrPublicKey(publicKey)) + val signedIn = assertIs(outcome) + + // 2. What startup lists. + val stored = assertIs(listed()[signedIn.id], "the public key is listed under the id the writer returned") + assertEquals(publicKey, stored.nostrPublicKey) + + // 3. What the startup screen's NostrPublic branch does: an identity with nothing behind it. + val dataStoreManager = DataStoreManager(phoenixGlobal.ctx, chain = NodeParamsManager.chain) + val identity = Identity.readOnly( + id = stored.id, + nostrPublicKey = stored.nostrPublicKey, + userPrefs = dataStoreManager.loadUserPrefsForWallet(stored.id), + internalPrefs = dataStoreManager.loadInternalPrefsForWallet(stored.id), + ) + assertFalse(identity.canSign) + assertNull(identity.nostrPrivateKey) + + val activeIdentity = MutableStateFlow(null) + val navigation = NavigationViewModel( + activeIdentityStateFlow = activeIdentity, + initialNavigationUIState = NavigationUIState.Loading("Introducing... Torch"), + nostrRepository = nostrRepository, + scope = scope, + ) + // The real notary, watching the same rows the app's would. + NotaryViewModel( + activeIdentityStateFlow = activeIdentity, + nostrRepository = nostrRepository, + chatRepository = chatRepository, + marmotRepository = marmotRepository, + scope = scope, + ) + + activeIdentity.value = identity + + // 4. The machine takes it from the placeholder: fetch, do not create. + val first = withTimeout(15_000) { + navigation.navigationUIState.first { it !is NavigationUIState.Loading } + } + assertIs(first) + + // 5. The relays answered; the kind 0 is indexed through the read-only pair: home. + db.nostrDao().storeNostrEvent( + nostrEvent = kind0(), + relayURL = "wss://relay.example", + synchronizationRelayURLs = listOf("wss://relay.example"), + level = 0, + activeKeyPair = identity.toKeyPair(), + ) + val second = withTimeout(15_000) { + navigation.navigationUIState.first { it is NavigationUIState.ProfileLoaded } + } + assertEquals(NavigationUIState.ProfileLoaded(publicKey = publicKey), second) + + // 6. Longer than the notary's key package delay, and then: nothing was signed. + delay(4_500) + val accounts = nostrRepository.getLocalAccounts().filter { it.unsignedNostrEvent?.pubKey == publicKey } + assertEquals(1, accounts.size, "one account for the pubkey") + assertEquals(GENESIS_AT, accounts.single().unsignedNostrEvent!!.signedAt, "the placeholder is still the placeholder") + assertEquals(emptyList(), nostrRepository.observeUnsignedNostrEvents(publicKey).first(), "nothing is queued for a signature") + assertEquals(emptyList(), db.marmotKeyPackageBundleDao().getAllMarmotKeyPackageBundles(publicKey), "no key package bundle was made") + assertNull(db.broadcastNostrEventRequestDao().observeBroadcastNostrEventRequestsByStatus("pending").first(), "nothing is waiting for a relay") + assertNull(identity.business) + assertTrue(BusinessManager.businessFlow.value.isEmpty(), "no PhoenixBusiness was started for a public key") + } + + /** + * The contrast that makes the assertions above worth having: the same harness, as an + * identity that *can* sign, does sign -- the notary makes a key package bundle for it + * within its delay. Without this, "nothing was signed" could be true of a harness in + * which nothing can be signed. + */ + @Test + fun `the same harness as a signing identity does sign`() = runBlocking { + val signedIn = assertIs( + signInViewModel().commit(SignInCredential.NostrSecret(privateKey, publicKey)) + ) + val stored = assertIs(listed()[signedIn.id]) + val dataStoreManager = DataStoreManager(phoenixGlobal.ctx, chain = NodeParamsManager.chain) + val identity = Identity.signing( + id = stored.id, + kind = IdentityKind.NostrSecret, + nostrPrivateKey = stored.privateKey, + userPrefs = dataStoreManager.loadUserPrefsForWallet(stored.id), + internalPrefs = dataStoreManager.loadInternalPrefsForWallet(stored.id), + business = null, + ) + val activeIdentity = MutableStateFlow(identity) + NotaryViewModel( + activeIdentityStateFlow = activeIdentity, + nostrRepository = nostrRepository, + chatRepository = chatRepository, + marmotRepository = marmotRepository, + scope = scope, + ) + + withTimeout(20_000) { + marmotRepository.observeActiveMarmotKeyPackageBundle(publicKey).first { it != null } + } + assertTrue(db.marmotKeyPackageBundleDao().getAllMarmotKeyPackageBundles(publicKey).isNotEmpty()) + } + + @Test + fun `the nsec of a key held read-only signs in over it, under the same id, planting nothing new`() = runBlocking { + val readOnly = assertIs( + signInViewModel().commit(SignInCredential.NostrPublicKey(publicKey)) + ) + assertIs(listed()[readOnly.id]) + + val upgraded = assertIs( + signInViewModel().commit(SignInCredential.NostrSecret(privateKey, publicKey)) + ) + + assertEquals(readOnly.id, upgraded.id, "the identity keeps its id, and with it its preferences and metadata") + val credentials = NostrCredentialManager.loadAndDecryptOrNull(phoenixGlobal) + assertEquals(mapOf(publicKey to NostrCredential.Secret(privateKey)), credentials, "one entry, now a secret") + val identities = listed() + assertEquals(1, identities.size) + assertIs(identities[upgraded.id]) + assertEquals(1, nostrRepository.getLocalAccounts().count { it.unsignedNostrEvent?.pubKey == publicKey }, "the second sign-in planted nothing") + } +} diff --git a/composeApp/src/jvmTest/kotlin/to/curare/compose/identity/NsecRestoreRoundTripJvmTest.kt b/composeApp/src/jvmTest/kotlin/to/curare/compose/identity/NsecRestoreRoundTripJvmTest.kt index 38392235..33525daf 100644 --- a/composeApp/src/jvmTest/kotlin/to/curare/compose/identity/NsecRestoreRoundTripJvmTest.kt +++ b/composeApp/src/jvmTest/kotlin/to/curare/compose/identity/NsecRestoreRoundTripJvmTest.kt @@ -9,7 +9,7 @@ import fr.acinq.phoenix.PhoenixGlobal import fr.acinq.phoenix.jvm.BusinessManager import fr.acinq.phoenix.managers.DataStoreManager import fr.acinq.phoenix.managers.NodeParamsManager -import fr.acinq.phoenix.managers.NostrKeyManager +import fr.acinq.phoenix.managers.NostrCredentialManager import fr.acinq.phoenix.managers.SeedManager import fr.acinq.phoenix.managers.computePreferencePath import fr.acinq.phoenix.security.JvmKeyStore @@ -113,20 +113,20 @@ class NsecRestoreRoundTripJvmTest { @Test fun `an nsec written, listed, activated and routed, with no node started`() = runBlocking { // 1. The sign-in screen's commit, minus the screen. - val written = assertIs( + val written = assertIs( IdentityWriter.writeNostrKey(log, phoenixGlobal, globalPrefs, privateKey, isTorEnabled = false, customElectrumServer = null) ) // 2. What startup lists: both stores, merged. val identities = StoredIdentity.merge( wallets = SeedManager.loadAndDecryptOrNull(phoenixGlobal) ?: error("seed store unreadable"), - nostrKeys = NostrKeyManager.loadAndDecryptOrNull(phoenixGlobal) ?: error("key store unreadable"), + credentials = NostrCredentialManager.loadAndDecryptOrNull(phoenixGlobal) ?: error("key store unreadable"), ) val stored = assertIs(identities[written.id], "the imported key is listed under the id the writer returned") // 3. What the startup screen's NostrSecret branch does: an identity, no node. val dataStoreManager = DataStoreManager(phoenixGlobal.ctx, chain = NodeParamsManager.chain) - val identity = Identity( + val identity = Identity.signing( id = stored.id, kind = IdentityKind.NostrSecret, nostrPrivateKey = stored.privateKey, diff --git a/composeApp/src/jvmTest/kotlin/to/curare/compose/identity/StoredIdentityJvmTest.kt b/composeApp/src/jvmTest/kotlin/to/curare/compose/identity/StoredIdentityJvmTest.kt index e7042b48..bf6bab63 100644 --- a/composeApp/src/jvmTest/kotlin/to/curare/compose/identity/StoredIdentityJvmTest.kt +++ b/composeApp/src/jvmTest/kotlin/to/curare/compose/identity/StoredIdentityJvmTest.kt @@ -4,6 +4,7 @@ import fr.acinq.bitcoin.ByteVector32 import fr.acinq.bitcoin.PrivateKey import fr.acinq.phoenix.data.UserWallet import fr.acinq.phoenix.data.WalletId +import fr.acinq.phoenix.security.NostrCredential import kotlin.test.Test import kotlin.test.assertEquals import kotlin.test.assertIs @@ -29,6 +30,7 @@ class StoredIdentityJvmTest { words = words, ) private val bareKey = PrivateKey(ByteVector32("02".repeat(32))) + private val readOnlyKey = PrivateKey(ByteVector32("03".repeat(32))).publicKey().xOnly().value.toHex() @Test fun `a wallet's nostr key is the NIP-06 derivation of its words`() { @@ -40,10 +42,13 @@ class StoredIdentityJvmTest { fun `both stores land in one map, each under its own id`() { val merged = StoredIdentity.merge( wallets = mapOf(wallet.walletId to wallet), - nostrKeys = mapOf(bareKey.publicKey().xOnly().value.toHex() to bareKey), + credentials = mapOf( + bareKey.publicKey().xOnly().value.toHex() to NostrCredential.Secret(bareKey), + readOnlyKey to NostrCredential.Public, + ), ) - assertEquals(2, merged.size) + assertEquals(3, merged.size) val mnemonic = assertIs(merged[wallet.walletId]) assertEquals(nip06PublicKey, mnemonic.nostrPublicKey) assertEquals(IdentityKind.Mnemonic, mnemonic.kind) @@ -52,6 +57,19 @@ class StoredIdentityJvmTest { assertEquals(IdentityKind.NostrSecret, secret.kind) assertEquals(40, secret.id.nodeIdHash.length, "same shape as a wallet's id") assertNotEquals(wallet.walletId, secret.id) + + val public = assertIs(merged[readOnlyKey.toXonlyPublicKey().toWalletId()]) + assertEquals(IdentityKind.NostrPublic, public.kind) + assertEquals(readOnlyKey, public.nostrPublicKey) + } + + /** The id a read-only identity gets is the one its secret would get, so an upgrade keeps it. */ + @Test + fun `a public key and its secret get the same id`() { + assertEquals( + StoredIdentity.nostrSecret(bareKey).id, + StoredIdentity.nostrPublic(bareKey.publicKey().xOnly().value.toHex()).id, + ) } /** @@ -63,18 +81,36 @@ class StoredIdentityJvmTest { fun `a wallet and its own nostr key as a bare secret do not collide by id`() { val merged = StoredIdentity.merge( wallets = mapOf(wallet.walletId to wallet), - nostrKeys = mapOf(nip06PublicKey to nip06PrivateKey), + credentials = mapOf(nip06PublicKey to NostrCredential.Secret(nip06PrivateKey)), ) assertEquals(2, merged.size) assertEquals(1, merged.values.map { it.nostrPublicKey }.toSet().size, "one npub, twice") } + /** + * The one precedence the merge decides. A recovery phrase pasted over a public + * credential is written across two files -- the credential removed first, then the + * seed -- and a crash between the two would leave neither, never both; this is the + * rule for the "both" that is not supposed to happen, so that it lists the wallet + * rather than one npub twice. + */ + @Test + fun `a public key a seed already derives is listed as the wallet only`() { + val merged = StoredIdentity.merge( + wallets = mapOf(wallet.walletId to wallet), + credentials = mapOf(nip06PublicKey to NostrCredential.Public), + ) + + assertEquals(1, merged.size) + assertIs(merged[wallet.walletId]) + } + @Test fun `a key filed under a public key it does not derive is dropped`() { val merged = StoredIdentity.merge( wallets = emptyMap(), - nostrKeys = mapOf(nip06PublicKey to bareKey), + credentials = mapOf(nip06PublicKey to NostrCredential.Secret(bareKey)), ) assertEquals(emptyMap(), merged) diff --git a/composeApp/src/jvmTest/kotlin/to/curare/compose/ui/composable/ReadOnlyEntrancesJvmTest.kt b/composeApp/src/jvmTest/kotlin/to/curare/compose/ui/composable/ReadOnlyEntrancesJvmTest.kt new file mode 100644 index 00000000..a3d24148 --- /dev/null +++ b/composeApp/src/jvmTest/kotlin/to/curare/compose/ui/composable/ReadOnlyEntrancesJvmTest.kt @@ -0,0 +1,290 @@ +package to.curare.compose.ui.composable + +import androidx.compose.runtime.Composable +import androidx.compose.runtime.CompositionLocalProvider +import androidx.compose.ui.test.ExperimentalTestApi +import androidx.compose.ui.test.assertCountEquals +import androidx.compose.ui.test.assertIsDisplayed +import androidx.compose.ui.test.onAllNodesWithText +import androidx.compose.ui.test.onFirst +import androidx.compose.ui.test.onNodeWithText +import androidx.compose.ui.test.performClick +import androidx.compose.ui.test.runDesktopComposeUiTest +import androidx.datastore.preferences.core.PreferenceDataStoreFactory +import fr.acinq.phoenix.data.WalletId +import fr.acinq.phoenix.utils.preferences.InternalPrefs +import fr.acinq.phoenix.utils.preferences.UserPrefs +import kotlinx.coroutines.flow.MutableStateFlow +import okio.Path.Companion.toPath +import to.curare.compose.database.GENESIS_AT +import to.curare.compose.database.model.SynchronizeNostrEventRequest +import to.curare.compose.database.model.UnsignedNostrEvent +import to.curare.compose.database.model.intermdiate.LocalAccount +import to.curare.compose.database.model.types.SynchronizationFilter +import to.curare.compose.extensions.hexToNpubHrp +import to.curare.compose.identity.Identity +import to.curare.compose.nostr.SignInSync +import java.nio.file.Files +import kotlin.time.Instant +import com.vitorpamplona.quartz.nip01Core.metadata.MetadataEvent +import com.vitorpamplona.quartz.nip10Notes.TextNoteEvent +import kotlinx.coroutines.flow.Flow +import kotlinx.coroutines.flow.flowOf +import to.curare.compose.database.model.NostrEvent +import to.curare.compose.database.model.Profile +import to.curare.compose.database.model.intermdiate.LocalChatRoom +import to.curare.compose.database.model.intermdiate.LocalNostrEvent +import to.curare.compose.database.model.intermdiate.LocalProfileWithFollowing +import to.curare.compose.repository.ChatRepository +import to.curare.compose.repository.DkgRepository +import to.curare.compose.repository.FrostSigningRepository +import to.curare.compose.repository.NostrRepository +import to.curare.compose.ui.composable.widgets.LocalCanSign +import to.curare.compose.ui.composable.widgets.ProvideSnackbarHost +import to.curare.compose.ui.theme.CurareTheme +import to.curare.compose.ui.view.state.ActiveProfileUIState +import to.curare.compose.ui.view.state.HomeScreenUIState +import kotlin.test.Test + +/** + * The inventory in Phase 5 of docs/npub-sign-in.md, as assertions. + * + * Every write entrance one tap from the three tabs has a row there, and a row without an + * assertion is a row that will regress: the compiler cannot say whether the inventory is + * complete, since `LocalCanSign` is read where a control is drawn and nothing forces a + * control to read it. So each screen is composed twice, once as an identity that can + * sign and once as one that cannot, and the controls are looked for by their text. + * + * The repositories are the no-op ones with the reads each screen makes delegated to a + * fixed answer, as `ChatPaneLayoutJvmTest` does. + */ +@OptIn(ExperimentalTestApi::class) +class ReadOnlyEntrancesJvmTest { + + private val publicKey = "de1a1e64d1c4e0d6bd97b0e73d4dfd0e1ec1cdd1e6d8d0e2b9a7f3c5d0e1a2b3" + private val eventId = "aa11bb22cc33dd44ee55ff6600778899aabbccddeeff00112233445566778899" + + // --- Home: the room list, or the empty state with the upgrade --- + + @Test + fun `an identity that can sign is offered a new chat, and no upgrade`() = runDesktopComposeUiTest(400, 900) { + setContent { AsIdentity(canSign = true) { Home() } } + + onNodeWithText("New chat", useUnmergedTree = true).assertIsDisplayed() + onNodeWithText("Sign in with the nsec", useUnmergedTree = true).assertDoesNotExist() + } + + @Test + fun `a read-only identity is offered the upgrade, and no new chat`() = runDesktopComposeUiTest(400, 900) { + setContent { AsIdentity(canSign = false) { Home() } } + + onNodeWithText("Sign in with the nsec", useUnmergedTree = true).assertIsDisplayed() + onNodeWithText("New chat", useUnmergedTree = true).assertDoesNotExist() + } + + /** One column at every width: there is no list to put a detail beside. */ + @Test + fun `a read-only identity in a large window still has one column`() = runDesktopComposeUiTest(1400, 900) { + setContent { AsIdentity(canSign = false) { Home() } } + + onNodeWithText("Sign in with the nsec", useUnmergedTree = true).assertIsDisplayed() + onNodeWithText("New chat", useUnmergedTree = true).assertDoesNotExist() + onNodeWithText("Pick a conversation to read it here.", useUnmergedTree = true).assertDoesNotExist() + } + + // --- Profile: key packages and key recovery, or neither --- + + @Test + fun `an identity that can sign is offered key recovery and key packages`() = runDesktopComposeUiTest(400, 1200) { + setContent { AsIdentity(canSign = true) { ActiveProfile() } } + + onNodeWithText("Key recovery", useUnmergedTree = true).assertIsDisplayed() + onNodeWithText("Key package management", useUnmergedTree = true).assertIsDisplayed() + onNodeWithText("Sign out", useUnmergedTree = true).assertIsDisplayed() + } + + @Test + fun `a read-only identity is offered neither, and can still sign out`() = runDesktopComposeUiTest(400, 1200) { + setContent { AsIdentity(canSign = false) { ActiveProfile() } } + + onNodeWithText("Key recovery", useUnmergedTree = true).assertDoesNotExist() + onNodeWithText("Key package management", useUnmergedTree = true).assertDoesNotExist() + onNodeWithText("Sign out", useUnmergedTree = true).assertIsDisplayed() + } + + // --- Profile: sign out is real for a read-only identity, and confirms first --- + + @Test + fun `a read-only identity's sign out asks before it acts, naming the npub`() = runDesktopComposeUiTest(400, 1200) { + setContent { AsIdentity(canSign = false) { ActiveProfile(signOut = signOutDependencies) } } + + onNodeWithText("Sign out", useUnmergedTree = true).performClick() + + onNodeWithText("Sign out of this profile?", useUnmergedTree = true).assertIsDisplayed() + // The screen shows the npub once already; the dialog names it a second time. + onAllNodesWithText(publicKey.hexToNpubHrp(), substring = true, useUnmergedTree = true).assertCountEquals(2) + onNodeWithText("nothing to lose", substring = true, useUnmergedTree = true).assertIsDisplayed() + } + + // --- Not found: set one up, or use a different key --- + + @Test + fun `an identity that can sign is offered the set-up form when its profile is not found`() = runDesktopComposeUiTest(400, 1200) { + setContent { AsIdentity(canSign = true) { NotFound() } } + + onNodeWithText("Try again", useUnmergedTree = true).assertIsDisplayed() + // Heading and button both say it; either is the form. + onAllNodesWithText("Set up a profile", useUnmergedTree = true).onFirst().assertIsDisplayed() + onNodeWithText("Use a different key", useUnmergedTree = true).assertDoesNotExist() + } + + @Test + fun `a read-only identity is offered a different key instead, and it confirms first`() = runDesktopComposeUiTest(400, 1200) { + setContent { AsIdentity(canSign = false) { NotFound() } } + + onNodeWithText("Try again", useUnmergedTree = true).assertIsDisplayed() + onNodeWithText("Set up a profile", useUnmergedTree = true).assertDoesNotExist() + onNodeWithText("Use a different key", useUnmergedTree = true).assertIsDisplayed() + + onNodeWithText("Use a different key", useUnmergedTree = true).performClick() + + onNodeWithText("Use a different key?", useUnmergedTree = true).assertIsDisplayed() + } + + // --- harness --- + + private val readOnlyIdentity = MutableStateFlow( + Identity.readOnly( + id = WalletId("ab".repeat(20)), + nostrPublicKey = publicKey, + userPrefs = UserPrefs(PreferenceDataStoreFactory.createWithPath { Files.createTempFile("user", ".preferences_pb").also { it.toFile().delete() }.toString().toPath() }), + internalPrefs = InternalPrefs(PreferenceDataStoreFactory.createWithPath { Files.createTempFile("internal", ".preferences_pb").also { it.toFile().delete() }.toString().toPath() }), + ) + ) + + /** Never run in these tests: the dialogs are looked at, not confirmed. */ + private val signOutDependencies = SignOutDependencies( + activeIdentityStateFlow = readOnlyIdentity, + forgetNostrCredential = { error("not reached") }, + hideIdentityMetadata = { error("not reached") }, + onSignedOut = { error("not reached") }, + ) + + @Composable + private fun NotFound() { + UnsyncedProfileScreen( + unsyncedProfilePublicKey = publicKey, + nostrRepository = NotFoundAccount, + signOut = signOutDependencies, + ) + } + + private val at = Instant.fromEpochSeconds(1_700_000_000) + + /** An account whose one sign-in request has finished with nothing: the not-found state. */ + private val NotFoundAccount = object : NostrRepository by NostrRepository.NO_OP_NOSTR_REPOSITORY { + override suspend fun observeLocalAccount(publicKey: String): Flow = flowOf( + LocalAccount( + unsignedNostrEvent = UnsignedNostrEvent( + id = 1, pubKey = publicKey, kind = 0, tags = emptyArray(), content = "{}", + signedAt = GENESIS_AT, createdAt = at, updatedAt = at, savedAt = at, + ), + nostrEvent = null, + profile = null, + broadcastNostrEventRequest = null, + broadcastNostrEventReceipt = null, + synchronizeNostrEventRequests = listOf( + SynchronizeNostrEventRequest( + id = "req", purpose = SignInSync.PURPOSE, status = SignInSync.STATUS_COMPLETE, + relayURL = "wss://relay.example", level = 0, + synchronizationFilters = arrayOf(SynchronizationFilter(authors = arrayOf(publicKey), kinds = SignInSync.KINDS)), + unsignedNostrEventId = 1, createdAt = at, updatedAt = at, + ) + ), + ) + ) + } + + @Composable + private fun AsIdentity(canSign: Boolean, content: @Composable () -> Unit) { + CurareTheme { + ProvideSnackbarHost { + CompositionLocalProvider(LocalCanSign provides canSign) { + content() + } + } + } + } + + @Composable + private fun Home() { + HomeScreen( + activeUserPublicKey = publicKey, + initialHomeScreenUIState = HomeScreenUIState.Loaded(profileWithFollowing = profile), + onNavigateToRoute = {}, + onNavigateToDirectMessageDetail = {}, + onNavigateToChatRoomCreation = {}, + nostrRepository = FixedProfile, + chatRepository = NoRooms, + frostSigningRepository = FrostSigningRepository.NO_OP_FROST_SIGNING_REPOSITORY, + dkgRepository = DkgRepository.NO_OP_DKG_REPOSITORY, + ) + } + + @Composable + private fun ActiveProfile(signOut: SignOutDependencies? = null) { + ActiveProfileScreen( + initialActiveProfileUIState = ActiveProfileUIState.Loaded( + localNostrEvent = LocalNostrEvent(nostrEvent = metadataEvent, profile = profile.profile), + ), + activeUserPublicKey = publicKey, + nostrEventId = eventId, + onNavigateBack = {}, + onNavigateToRoute = {}, + nostrRepository = FixedProfile, + signOut = signOut, + ) + } + + private val metadataEvent = NostrEvent( + id = eventId, + pubKey = publicKey, + content = """{"name":"Reader"}""", + tags = emptyArray(), + sig = "", + kind = MetadataEvent.KIND, + ) + + private val profile = LocalProfileWithFollowing( + nostrEvent = NostrEvent( + id = eventId, + pubKey = publicKey, + content = "", + tags = emptyArray(), + sig = "", + kind = TextNoteEvent.KIND, + ), + profile = Profile( + publicKey = publicKey, + displayName = "Reader", + nostrEventId = eventId, + ), + following = emptyList(), + ) + + private val FixedProfile = object : NostrRepository by NostrRepository.NO_OP_NOSTR_REPOSITORY { + override suspend fun observeProfileWithFollowing( + publicKey: String, + ): Flow = flowOf(profile) + + override suspend fun observeLocalNostrEventById( + nostrEventId: String, + ): Flow = flowOf(LocalNostrEvent(nostrEvent = metadataEvent, profile = profile.profile)) + } + + private val NoRooms = object : ChatRepository by ChatRepository.NO_OP_CHAT_REPOSITORY { + override suspend fun observeChatRoomListByPublicKey( + publicKey: String, + ): Flow> = flowOf(emptyList()) + } +} diff --git a/composeApp/src/jvmTest/kotlin/to/curare/compose/ui/view/model/NavigationIdentityRoutingJvmTest.kt b/composeApp/src/jvmTest/kotlin/to/curare/compose/ui/view/model/NavigationIdentityRoutingJvmTest.kt index c2160410..55a246e1 100644 --- a/composeApp/src/jvmTest/kotlin/to/curare/compose/ui/view/model/NavigationIdentityRoutingJvmTest.kt +++ b/composeApp/src/jvmTest/kotlin/to/curare/compose/ui/view/model/NavigationIdentityRoutingJvmTest.kt @@ -6,6 +6,7 @@ import com.vitorpamplona.quartz.nip01Core.core.toHexKey import com.vitorpamplona.quartz.nip01Core.crypto.KeyPair import fr.acinq.bitcoin.ByteVector32 import fr.acinq.bitcoin.PrivateKey +import fr.acinq.phoenix.managers.nostrPublicKeyHex import fr.acinq.phoenix.utils.preferences.InternalPrefs import fr.acinq.phoenix.utils.preferences.UserPrefs import kotlinx.coroutines.CoroutineScope @@ -31,6 +32,10 @@ import to.curare.compose.ui.composable.navigation.routes.SovereignWalletStartupR import to.curare.compose.ui.view.state.NavigationUIState import kotlin.test.Test import kotlin.test.assertEquals +import kotlin.test.assertFailsWith +import kotlin.test.assertFalse +import kotlin.test.assertNull +import kotlin.test.assertTrue import kotlin.time.Instant /** @@ -65,7 +70,7 @@ class NavigationIdentityRoutingJvmTest { temporaryFolder.newFolder().resolve("$name.preferences_pb").path.toPath() } - private fun nostrSecretIdentity() = Identity( + private fun nostrSecretIdentity() = Identity.signing( id = privateKey.publicKey().xOnly().toWalletId(), kind = IdentityKind.NostrSecret, nostrPrivateKey = privateKey, @@ -74,6 +79,14 @@ class NavigationIdentityRoutingJvmTest { business = null, ) + /** The same key, held as a public key only: same id, no secret, no node. */ + private fun readOnlyIdentity() = Identity.readOnly( + id = privateKey.publicKey().xOnly().toWalletId(), + nostrPublicKey = privateKey.nostrPublicKeyHex(), + userPrefs = UserPrefs(prefsStore("user")), + internalPrefs = InternalPrefs(prefsStore("internal")), + ) + /** Everything `observeProfile` reads, and nothing else; every other member throws. */ private class Device( private val accounts: List @@ -176,4 +189,107 @@ class NavigationIdentityRoutingJvmTest { viewModel.navigationUIState.value, ) } + + /** + * A read-only identity is the same identity minus the secret: same public key, same + * id, and the machine routes it by its account exactly as it routes the nsec. + */ + @Test + fun `a read-only identity has the id and public key its secret would, and cannot sign`() { + val readOnly = readOnlyIdentity() + val signing = nostrSecretIdentity() + + assertEquals(signing.nostrPublicKey, readOnly.nostrPublicKey) + assertEquals(signing.id, readOnly.id) + assertNull(readOnly.nostrPrivateKey) + assertNull(readOnly.business) + assertFalse(readOnly.canSign) + assertTrue(signing.canSign) + assertEquals(IdentityKind.NostrPublic, readOnly.kind) + } + + @Test + fun `a read-only identity is routed by its account, like any other`() { + val identity = readOnlyIdentity() + val scope = CoroutineScope(Job()) + val viewModel = NavigationViewModel( + activeIdentityStateFlow = MutableStateFlow(identity), + initialNavigationUIState = stranded, + nostrRepository = Device(listOf(syncedAccount(identity.nostrPublicKey))), + scope = scope, + ) + + try { + val destination = runBlocking { + withTimeout(15_000) { viewModel.navigationUIState.first { it != stranded } } + } + + assertEquals( + NavigationUIState.ProfileLoaded(publicKey = identity.nostrPublicKey), + destination, + "a read-only identity was not routed by its account", + ) + } finally { + scope.cancel() + } + } + + /** + * The two checks that make [Identity.nostrPublicKey] safe to be a field. Without + * them a data class would accept a key filed under someone else's public key, or a + * "read-only" identity that could in fact sign. + */ + @Test + fun `an identity whose kind and key disagree is refused, and so is one whose key does not derive its public key`() { + val prefs = UserPrefs(prefsStore("user")) + val internal = InternalPrefs(prefsStore("internal")) + + // A secret filed under a public key it does not derive. + assertFailsWith { + Identity( + id = privateKey.publicKey().xOnly().toWalletId(), + kind = IdentityKind.NostrSecret, + nostrPublicKey = "a".repeat(64), + nostrPrivateKey = privateKey, + userPrefs = prefs, + internalPrefs = internal, + business = null, + ) + } + // A read-only kind that nonetheless carries a key. + assertFailsWith { + Identity( + id = privateKey.publicKey().xOnly().toWalletId(), + kind = IdentityKind.NostrPublic, + nostrPublicKey = privateKey.nostrPublicKeyHex(), + nostrPrivateKey = privateKey, + userPrefs = prefs, + internalPrefs = internal, + business = null, + ) + } + // A signing kind with no key to sign with. + assertFailsWith { + Identity( + id = privateKey.publicKey().xOnly().toWalletId(), + kind = IdentityKind.NostrSecret, + nostrPublicKey = privateKey.nostrPublicKeyHex(), + nostrPrivateKey = null, + userPrefs = prefs, + internalPrefs = internal, + business = null, + ) + } + // And the factory refuses to build a "signing" read-only identity at all. + assertFailsWith { + Identity.signing( + id = privateKey.publicKey().xOnly().toWalletId(), + kind = IdentityKind.NostrPublic, + nostrPrivateKey = privateKey, + userPrefs = prefs, + internalPrefs = internal, + business = null, + ) + } + } } diff --git a/composeApp/src/jvmTest/kotlin/to/curare/compose/ui/view/model/NostrSecretViewModelJvmTest.kt b/composeApp/src/jvmTest/kotlin/to/curare/compose/ui/view/model/NostrSecretViewModelJvmTest.kt index b13bd49b..2f4d7e8c 100644 --- a/composeApp/src/jvmTest/kotlin/to/curare/compose/ui/view/model/NostrSecretViewModelJvmTest.kt +++ b/composeApp/src/jvmTest/kotlin/to/curare/compose/ui/view/model/NostrSecretViewModelJvmTest.kt @@ -68,7 +68,7 @@ class NostrSecretViewModelJvmTest { temporaryFolder.newFolder().resolve("$name.preferences_pb").path.toPath() } - private fun identity() = Identity( + private fun identity() = Identity.signing( id = privateKey.publicKey().xOnly().toWalletId(), kind = IdentityKind.NostrSecret, nostrPrivateKey = privateKey, @@ -79,26 +79,26 @@ class NostrSecretViewModelJvmTest { private fun viewModel( recorder: Recorder, - forgetOutcome: IdentityWriter.ForgetNostrKeyResult, + forgetOutcome: IdentityWriter.ForgetNostrCredentialResult, ) = NostrSecretViewModel( phoenixGlobal = PhoenixGlobal(PlatformContext(applicationDir = temporaryFolder.newFolder())), activeIdentityStateFlow = MutableStateFlow(identity()), nostrRepository = recorder, - forgetNostrKey = { recorder.effects += "forgetNostrKey"; forgetOutcome }, + forgetNostrCredential = { recorder.effects += "forgetNostrCredential"; forgetOutcome }, hideIdentityMetadata = { recorder.effects += "hideIdentityMetadata" }, ) @Test fun `the key comes out first, then the metadata, the account, and the caller is told`() { val recorder = Recorder() - val viewModel = viewModel(recorder, IdentityWriter.ForgetNostrKeyResult.Forgotten) + val viewModel = viewModel(recorder, IdentityWriter.ForgetNostrCredentialResult.Forgotten) val told = CompletableDeferred() viewModel.forgetKey { told.complete(Unit) } runBlocking { withTimeout(10_000) { told.await() } } assertEquals( - listOf("forgetNostrKey", "hideIdentityMetadata", "forgetLocalAccount"), + listOf("forgetNostrCredential", "hideIdentityMetadata", "forgetLocalAccount"), recorder.effects, ) assertEquals(NostrSecretUIState.Forgetting.Idle, viewModel.forgetting.value) @@ -107,7 +107,7 @@ class NostrSecretViewModelJvmTest { @Test fun `a key that could not be removed leaves everything else alone`() { val recorder = Recorder() - val viewModel = viewModel(recorder, IdentityWriter.ForgetNostrKeyResult.CannotLoadKeys) + val viewModel = viewModel(recorder, IdentityWriter.ForgetNostrCredentialResult.CannotLoadKeys) viewModel.forgetKey { error("must not be told") } val state = runBlocking { @@ -115,6 +115,6 @@ class NostrSecretViewModelJvmTest { } assertEquals(NostrSecretUIState.Forgetting.Failed, state) - assertEquals(listOf("forgetNostrKey"), recorder.effects) + assertEquals(listOf("forgetNostrCredential"), recorder.effects) } } diff --git a/composeApp/src/jvmTest/kotlin/to/curare/compose/ui/view/model/SignInToProfileViewModelJvmTest.kt b/composeApp/src/jvmTest/kotlin/to/curare/compose/ui/view/model/SignInToProfileViewModelJvmTest.kt index 64cc86fc..b79152cc 100644 --- a/composeApp/src/jvmTest/kotlin/to/curare/compose/ui/view/model/SignInToProfileViewModelJvmTest.kt +++ b/composeApp/src/jvmTest/kotlin/to/curare/compose/ui/view/model/SignInToProfileViewModelJvmTest.kt @@ -31,6 +31,7 @@ class SignInToProfileViewModelJvmTest { private val nostrSecret = SignInCredential.NostrSecret(privateKey, publicKey) private val recoveryPhrase = SignInCredential.RecoveryPhrase(words, publicKey) + private val nostrPublicKey = SignInCredential.NostrPublicKey(publicKey) /** Records the order of effects; throws on anything the sign-in should not touch. */ private class Recorder : NostrRepository by NostrRepository.NO_OP_NOSTR_REPOSITORY { @@ -42,14 +43,36 @@ class SignInToProfileViewModelJvmTest { private fun viewModel( recorder: Recorder, - nostrKeyOutcome: () -> IdentityWriter.WriteNostrKeyResult = { IdentityWriter.WriteNostrKeyResult.Written(id) }, + nostrKeyOutcome: () -> IdentityWriter.WriteNostrCredentialResult = { IdentityWriter.WriteNostrCredentialResult.Written(id) }, + publicKeyOutcome: () -> IdentityWriter.WriteNostrCredentialResult = { IdentityWriter.WriteNostrCredentialResult.Written(id) }, seedOutcome: ((WalletId) -> Unit, (WritingSeedState.Error) -> Unit) -> Unit = { onWritten, _ -> onWritten(id) }, ) = SignInToProfileViewModel( nostrRepository = recorder, writeNostrKey = { recorder.effects += "writeNostrKey"; nostrKeyOutcome() }, + writeNostrPublicKey = { recorder.effects += "writeNostrPublicKey"; publicKeyOutcome() }, writeRecoveryPhrase = { _, onWritten, onError -> recorder.effects += "writeRecoveryPhrase"; seedOutcome(onWritten, onError) }, ) + @Test + fun `a public key is written, then its account is planted, then the id comes back`() = runBlocking { + val recorder = Recorder() + + val outcome = viewModel(recorder).commit(nostrPublicKey) + + assertEquals(SignInToProfileViewModel.Outcome.SignedIn(id), outcome) + assertEquals(listOf("writeNostrPublicKey", "signInToProfile:$publicKey"), recorder.effects) + } + + @Test + fun `the npub of a key already here is refused, and no account is planted`() = runBlocking { + val recorder = Recorder() + + val outcome = viewModel(recorder, publicKeyOutcome = { IdentityWriter.WriteNostrCredentialResult.AlreadyExists }).commit(nostrPublicKey) + + assertEquals(SignInToProfileViewModel.Outcome.Failed(CredentialProblem.AlreadyOnThisDevice), outcome) + assertEquals(listOf("writeNostrPublicKey"), recorder.effects) + } + @Test fun `an nsec is written, then its account is planted, then the id comes back`() = runBlocking { val recorder = Recorder() @@ -74,7 +97,7 @@ class SignInToProfileViewModelJvmTest { fun `a key already on the device is refused, and no account is planted`() = runBlocking { val recorder = Recorder() - val outcome = viewModel(recorder, nostrKeyOutcome = { IdentityWriter.WriteNostrKeyResult.AlreadyExists }).commit(nostrSecret) + val outcome = viewModel(recorder, nostrKeyOutcome = { IdentityWriter.WriteNostrCredentialResult.AlreadyExists }).commit(nostrSecret) assertEquals(SignInToProfileViewModel.Outcome.Failed(CredentialProblem.AlreadyOnThisDevice), outcome) assertEquals(listOf("writeNostrKey"), recorder.effects) @@ -97,7 +120,7 @@ class SignInToProfileViewModelJvmTest { assertEquals( SignInToProfileViewModel.Outcome.Failed(CredentialProblem.CouldNotWrite), - viewModel(recorder, nostrKeyOutcome = { IdentityWriter.WriteNostrKeyResult.CannotLoadKeys }).commit(nostrSecret), + viewModel(recorder, nostrKeyOutcome = { IdentityWriter.WriteNostrCredentialResult.CannotLoadKeys }).commit(nostrSecret), ) assertEquals( SignInToProfileViewModel.Outcome.Failed(CredentialProblem.CouldNotWrite), diff --git a/composeApp/src/jvmTest/kotlin/to/curare/compose/ui/view/model/SignOutViewModelJvmTest.kt b/composeApp/src/jvmTest/kotlin/to/curare/compose/ui/view/model/SignOutViewModelJvmTest.kt new file mode 100644 index 00000000..a2017e10 --- /dev/null +++ b/composeApp/src/jvmTest/kotlin/to/curare/compose/ui/view/model/SignOutViewModelJvmTest.kt @@ -0,0 +1,106 @@ +package to.curare.compose.ui.view.model + +import androidx.datastore.preferences.core.PreferenceDataStoreFactory +import com.vitorpamplona.quartz.nip01Core.core.HexKey +import fr.acinq.bitcoin.ByteVector32 +import fr.acinq.bitcoin.PrivateKey +import fr.acinq.phoenix.managers.nostrPublicKeyHex +import fr.acinq.phoenix.utils.preferences.InternalPrefs +import fr.acinq.phoenix.utils.preferences.UserPrefs +import kotlinx.coroutines.CompletableDeferred +import kotlinx.coroutines.flow.MutableStateFlow +import kotlinx.coroutines.flow.first +import kotlinx.coroutines.runBlocking +import kotlinx.coroutines.withTimeout +import okio.Path.Companion.toPath +import org.junit.Rule +import org.junit.rules.TemporaryFolder +import to.curare.compose.identity.Identity +import to.curare.compose.identity.IdentityWriter +import to.curare.compose.identity.toWalletId +import to.curare.compose.repository.NostrRepository +import kotlin.test.Test +import kotlin.test.assertEquals + +/** + * Sign out for a read-only identity: the confirmation, the in-flight state, and the + * caller being told only once the device holds nothing for the identity. The sequence + * itself is `ForgetIdentity`'s and is pinned there; this is the state around it, the + * way `NostrSecretViewModelJvmTest` pins the nsec screen's. + */ +class SignOutViewModelJvmTest { + + @get:Rule + val temporaryFolder = TemporaryFolder() + + private val privateKey = PrivateKey(ByteVector32("05".repeat(32))) + + private fun prefsStore(name: String) = PreferenceDataStoreFactory.createWithPath { + temporaryFolder.newFolder().resolve("$name.preferences_pb").path.toPath() + } + + private fun identity() = Identity.readOnly( + id = privateKey.publicKey().xOnly().toWalletId(), + nostrPublicKey = privateKey.nostrPublicKeyHex(), + userPrefs = UserPrefs(prefsStore("user")), + internalPrefs = InternalPrefs(prefsStore("internal")), + ) + + private class Recorder : NostrRepository by NostrRepository.NO_OP_NOSTR_REPOSITORY { + val effects = mutableListOf() + override suspend fun forgetLocalAccount(publicKey: HexKey) { + effects += "forgetLocalAccount" + } + } + + private fun viewModel(recorder: Recorder, outcome: IdentityWriter.ForgetNostrCredentialResult) = SignOutViewModel( + activeIdentityStateFlow = MutableStateFlow(identity()), + nostrRepository = recorder, + forgetNostrCredential = { recorder.effects += "forgetNostrCredential"; outcome }, + hideIdentityMetadata = { recorder.effects += "hideIdentityMetadata" }, + ) + + @Test + fun `asking, then confirming, forgets and tells the caller, and the state is idle again`() = runBlocking { + val recorder = Recorder() + val viewModel = viewModel(recorder, IdentityWriter.ForgetNostrCredentialResult.Forgotten) + val told = CompletableDeferred() + + assertEquals(SignOutViewModel.State.Idle, viewModel.state.value) + viewModel.askToSignOut() + assertEquals(SignOutViewModel.State.Confirming, viewModel.state.value) + assertEquals(privateKey.nostrPublicKeyHex(), viewModel.nostrPublicKey, "the confirmation names the identity") + + viewModel.signOut { told.complete(Unit) } + withTimeout(10_000) { told.await() } + + assertEquals(listOf("forgetNostrCredential", "hideIdentityMetadata", "forgetLocalAccount"), recorder.effects) + withTimeout(10_000) { viewModel.state.first { it == SignOutViewModel.State.Idle } } + } + + @Test + fun `cancelling from the confirmation touches nothing`() { + val recorder = Recorder() + val viewModel = viewModel(recorder, IdentityWriter.ForgetNostrCredentialResult.Forgotten) + + viewModel.askToSignOut() + viewModel.cancel() + + assertEquals(SignOutViewModel.State.Idle, viewModel.state.value) + assertEquals(emptyList(), recorder.effects) + } + + @Test + fun `a failure is a state, the caller is not told, and nothing after the first step ran`() = runBlocking { + val recorder = Recorder() + val viewModel = viewModel(recorder, IdentityWriter.ForgetNostrCredentialResult.CannotLoadKeys) + var told = false + + viewModel.askToSignOut() + viewModel.signOut { told = true } + withTimeout(10_000) { viewModel.state.first { it == SignOutViewModel.State.Failed } } + + assertEquals(false, told) + assertEquals(listOf("forgetNostrCredential"), recorder.effects) + } +} diff --git a/docs/README.md b/docs/README.md index b336f076..a4596850 100644 --- a/docs/README.md +++ b/docs/README.md @@ -17,6 +17,7 @@ silent, or a decision that looked arbitrary and was not. | [long-running-sync.md](./long-running-sync.md) | the chat subscriptions that stay open instead of pulling once per screen — why the request queue could not simply hold one, and how the group filter follows the room list | | [dead-code.md](./dead-code.md) | code in the sync and relay stack that nothing calls, why each piece is still there, and which of it is a bug rather than a leftover | | [nsec-sign-in.md](./nsec-sign-in.md) | signing in with an existing nostr key — why an nsec can never have a wallet behind it, the ten call sites that make it small, and the sign-in machine that was already built and unreachable | +| [npub-sign-in.md](./npub-sign-in.md) | signing in with only a public key — what a key that cannot sign can still see here, why that is a preview rather than a browser, and the four decisions the word settles | | [jvm-target.md](./jvm-target.md) | what desktop support cost, phased — why the native chain was already done, why an empty source set in our phoenix fork was the real blocker, and why DAO tests need none of it | | [material-design-conformance.md](./material-design-conformance.md) | what the M3 foundations actually require, measured against all 43 screens — the colour pairing that renders the app's own proposals invisible, and eight phases that put the decisions back in the theme | @@ -40,3 +41,7 @@ The nsec sign-in note is a phased plan that has been built; it inherits the key-storage decision from the jvm-target note and drives the navigation state machine `NavigationViewModel.processLocalAccount` implements, so read it with the code open, and read its table of where the build chose differently first. +The npub sign-in note is a phased plan that has been built, and reads as that +plan's out-of-scope note answered: it takes the `Identity` type and the sign-in +machine as given and asks what an identity with no secret is for, before it asks +how to build one; read its table of where the build chose differently first. diff --git a/docs/npub-sign-in.md b/docs/npub-sign-in.md new file mode 100644 index 00000000..cd031b45 --- /dev/null +++ b/docs/npub-sign-in.md @@ -0,0 +1,976 @@ +# Signing in with an npub + +How a user looks at this app as a profile they hold no secret for, what such an +identity can and cannot do here, and why the answer to "what is it for" decides +every screen it touches. + +Read this after [nsec-sign-in.md](./nsec-sign-in.md). It inherits the `Identity` +type, the two key stores, the sign-in screen and the not-found exit from there, and +most of what follows is that plan's out-of-scope note taken at its word — "a +read-only mode is a product, not a branch" — and asked what the product would be. + +**Built**, phases 1–7, one commit each, in the order given; Phase 8 is the rollout +and is process rather than code. The phases are kept as written because they are +the reasoning, and the code reads better against the argument it came from than +against a summary of itself. Where the implementation chose differently the table +below says so: + +| what the plan said | what it turned out to be | +|---|---| +| the startup screen's third branch in Phase 3 | in Phase 2: `StoredIdentity` is sealed, and the compiler asked for the branch the moment `NostrPublic` existed. The right code either way, one phase early | +| `KeyRecoveryScreen`'s `NostrPublic` arm "unreachable, and says so" | for the option, `Unit` with the comment; for the sentence above it, grouped with `NostrSecret` — so that if the screen is ever reached it does not promise coins | +| "the old reader kept as `LegacyNostrKeysFile` for exactly one caller" | `LegacyNostrKeysFile` is the read half of what was `NostrKeyManager`, and `EncryptedNostrKeys` stays beside it, because the migration's test has to *produce* a v1 file and nothing else can | +| the migration, unspecified in its outcomes | `MigrationResult` — `Migrated(count)`, `NotNeeded`, `Failed(failure)` — and `listIdentities` maps a failure onto the same `ListWalletState.Error` an unreadable credentials file gets, per kind | +| the wire shape as "a `@Serializable sealed class`" | two types: `NostrCredential`, whose `Secret` carries a `PrivateKey` and cannot be built with a key that is not one, and a private serializable mirror inside the encrypted file whose `Secret` carries hex | +| the DAO guard as "belt and braces" | load-bearing between Phase 3 and Phase 5, when the room list's inbox sync still ran for a read-only identity; and verified both ways — the test fails with the guard removed | +| `ProvideSigningCapability` from the active identity | a null identity — startup, landing, sign-in — answers *true*: it is nobody, not read-only, and those screens have nothing to hide | +| `ForgetIdentity` "dispatches the first step on its kind" | no dispatch: since the credentials file the first step is one call for both credential kinds, and `forgetNostrCredential` itself answers `NotACredential` for a mnemonic | +| sign out and the not-found exit, shape unspecified | one `SignOutViewModel` owning the confirmation and the in-flight state, one `SignOutOfReadOnlyDialog` differing only in its title, and a `SignOutDependencies` bundle so each screen takes one nullable parameter rather than four lambdas that throw | +| `signInToProfile` "made idempotent by pubkey" | done, and tested by signing in twice and counting one; the sign-in view model's three writers now go through one shared write-and-map | +| the round trip "with the network faked at the repository" | with the *database* real: an in-memory Room under the app's own DAOs and a real `NotaryViewModel`, because "nothing was signed" is about what is not in the tables — plus a contrast case the plan did not ask for, the same harness as a signing identity producing a key package, so the assertions are known to bite | +| `use_a_different_key` as a new string | it existed: the sign-in screen's own "use a different key" button. One string, two screens, one meaning | + +One thing found on the way that is in no phase: a compose test that looks for a +floating action button's label by text has to search the unmerged tree, because +`ExtendedFloatingActionButton` merges its label into the button's semantics — and +on the merged tree an `assertDoesNotExist` for a hidden control is vacuously true. +`ReadOnlyEntrancesJvmTest` uses the unmerged tree for every lookup for that reason. + +The library commit is on `claude/nostr-credentials` in the submodule, at `84cc44c`, +one commit ahead of the library's `master` and bumped into the app by the Phase 2 +commit; it has to be pushed with this branch and tagged for JitPack consumers +before any of this leaves the machine. The nsec plan's `59c11ed` reached `master` +through the library's PR #1 but was never tagged; Phase 8 below says why the two go +out on one tag. + +## The constraint + +A nostr public key can be addressed and can verify. It cannot do anything else, +and in this app "anything else" is most of the app: + +| what needs the secret | where | +|---|---| +| signing every queued event — the kind 0, the follow list, key packages, group posts, proposals | `NotaryViewModel.observeUnsignedNostrEvents` | +| opening a NIP-17 gift wrap addressed to the user | [GiftWrapMessage.kt:126](../composeApp/src/commonMain/kotlin/to/curare/compose/database/model/GiftWrapMessage.kt) — NIP-44 with the recipient's key | +| joining a Marmot group — a key package has to be signed and published before any welcome can be addressed to it, and the welcome itself arrives as a gift wrap | `MarmotRepository.publishMarmotKeyPackageBundle`, `MarmotInboundManager` | +| the ChillDKG host key, `sha256(tag ‖ nostrPrivateKey)` | [ChillDkgRitualManager.kt:117](../composeApp/src/commonMain/kotlin/to/curare/compose/managers/ChillDkgRitualManager.kt) | + +What a public key *gets* is the events it has published — the kind 0, the kind 3, +the relay lists — and the profiles of the people it follows, because indexing a +kind 3 plants a placeholder for each and queues its sync +([NostrDao.kt:1128](../composeApp/src/commonMain/kotlin/to/curare/compose/database/dao/NostrDao.kt)). +In a client with a public feed, that is the client: read-only in Damus or Amethyst +means "browse as this person". + +**This app has no public feed.** The home tab is a list of chat rooms, and every +room is MLS or a gift wrap, both encrypted to the key the user did not paste. The +curated lists, proposals, ceremonies and translations are reached only through a +room (`ChatRoomDetailScreen`). Search is over profiles, and trending notes is a +string that says "coming soon". So a read-only identity here sees its own profile +card, the people it follows — as search results, by name, once the sync has +fetched them; nothing renders the list itself — any profile's detail, and share +profile. That is the honest inventory, and it is thin — thin +enough that the first thing to decide is not how to build it but what it is +[for](#the-one-decision-to-make-first). + +## What is already built + +More than the nsec plan's out-of-scope note suggests, because that plan built most +of it on the way. + +| piece | where | state | +|---|---|---| +| the parser recognises `npub1…` and `nostr:npub1…` — and refuses it, as `PublicKeyOnly` | [CredentialParser.kt:94](../composeApp/src/commonMain/kotlin/to/curare/compose/identity/CredentialParser.kt) | one branch from accepting it | +| `signInToProfile(pubkey)` plants the `GENESIS_AT` placeholder from a pubkey alone | [DatabaseNostrRepository.kt:258](../composeApp/src/commonMain/kotlin/to/curare/compose/database/repository/DatabaseNostrRepository.kt) | built; needs one property, see [Phase 4](#a-sign-in-that-can-be-repeated) | +| the state machine from there — `UnqueuedProfileSynchronization → UnsyncedProfile → UnindexedProfile → ProfileLoaded` — reads `identity.nostrPublicKey` and never a key | [NavigationViewModel.kt](../composeApp/src/commonMain/kotlin/to/curare/compose/ui/view/model/NavigationViewModel.kt) | built | +| the sign-in sync, the indexer relays, the one hop, and the not-found exit | `SignInSync`, `UnsyncedProfileViewModel` | built; the exit needs a third action, see [Phase 6](#phase-6--leaving) | +| `RelaysSocketManager` follows the identity's relay list by pubkey | [RelaysSocketManager.kt:70](../composeApp/src/commonMain/kotlin/to/curare/compose/network/relays/RelaysSocketManager.kt) | works unchanged | +| the notary returns before doing anything when there is no key | [NotaryViewModel.kt:72](../composeApp/src/commonMain/kotlin/to/curare/compose/ui/view/model/NotaryViewModel.kt) | works unchanged — and so the key package bundle it would publish is never attempted | +| quartz's `KeyPair(pubKey = …)` with no private key, commented in its own source as "this is a read-only account" | `com.vitorpamplona.quartz.nip01Core.crypto.KeyPair` | usable; it is why the DAO carries `privKey!!` at all | +| `Identity.business` is nullable; a read-only identity is `NostrSecret` minus the secret | [Identity.kt](../composeApp/src/commonMain/kotlin/to/curare/compose/identity/Identity.kt) | one field from it | +| the forget flow — key out, prefs deleted, metadata hidden, account rows gone, re-list, selector | `NostrSecretViewModel.forgetKey`, `IdentityWriter.forgetNostrKey` | built for an nsec; the sequence transfers whole | +| `WalletsSelector` shows the npub for every kind | [WalletsSelector.kt:161](../composeApp/src/commonMain/kotlin/to/curare/compose/ui/composable/widgets/wallet/WalletsSelector.kt) | needs a "read only" label | +| `nostr-keys.dat`, with a version byte and a doc that says "a new shape would be a new version" | `EncryptedNostrKeys`, `NostrKeyManager`, `AtomicFileWrite` | the envelope, the atomic write and the manager shape all carry over; only the entries change | +| a string, `this_will_give_you_read_only_access_to_the` | `strings.xml` | present, unused, and says too little | + +## What actually blocks it + +Five things, in dependency order. + +**The identity's key is not optional.** `Identity.nostrPrivateKey` is a +`PrivateKey` and `nostrPublicKey` is computed from it +([Identity.kt:50](../composeApp/src/commonMain/kotlin/to/curare/compose/identity/Identity.kt), +62). Every reader of the identity compiles against that. + +**There is nowhere to keep a public key.** Both stores hold secrets. `nostr-keys.dat` +is a map from public key to private key, and `EncryptedNostrKeys` refuses a file +whose entry does not derive the key it is filed under — the right rule for that +shape, which is why the answer is a new shape rather than a value smuggled into +this one ([Phase 2](#phase-2--one-credentials-file)). + +**The pumps are gated on the private key.** `SynchronizationViewModel` runs its +four collectors inside `identity?.nostrPrivateKey?.let { … }` +([SynchronizationViewModel.kt:194](../composeApp/src/commonMain/kotlin/to/curare/compose/ui/view/model/SynchronizationViewModel.kt)). +A read-only identity's sign-in sync would be queued and never dispatched, and the +machine would park on `UnsyncedProfile` for good — the nsec plan's Phase 5 failure +again, from a different cause. + +**The DAO opens what is addressed to it, or rolls back.** `storeNostrEvent` is +`@Transaction` and indexes inside it; a gift wrap addressed to the active key that +cannot be unsealed throws +([NostrDao.kt:448–459](../composeApp/src/commonMain/kotlin/to/curare/compose/database/dao/NostrDao.kt)), +and the throw takes the event with it. Worse, and not obvious: `decryptGiftWrapSeal` +builds `KeyPair(privKey = keyPair.privKey)` +([GiftWrapMessage.kt:126](../composeApp/src/commonMain/kotlin/to/curare/compose/database/model/GiftWrapMessage.kt)), +and in quartz a `KeyPair` given neither key *generates a fresh random one*. A +read-only pair forwarded there would try to open the wrap with a key nobody has, +fail, and roll back — silently correct-looking in the logs. + +**Every write entrance is unconditional.** Some twenty-five view models write +something the notary has to sign or a key has to seal. Most are behind a chat +room and unreachable without one; but the "New chat" button, +follow, send message, key package management, key recovery and the not-found +screen's "set one up" are each one tap from the three tabs. A pasted npub that +lands on a screen offering "New chat" is not a preview, it is a broken app. + +## The one decision to make first + +What is a read-only identity *for?* Three answers were considered. + +**Browsing.** Needs a public feed. This app does not have one, and a mode whose +whole content is "coming soon" should not ship ahead of it. + +**Auditing a group from outside.** The curated lists a group publishes are public +events (kinds 31889, 31888, 31890), and a member's device is not the only place they +could be read. But nothing today reaches them except through a room, and building +a public list browser is a feature with its own screens — the feed problem in a +smaller shape. + +**A preview.** Look at the app as your own profile — the name it has for you, the +people it knows you follow, what it found on the relays — before you paste a secret +into it. And, having looked, paste it. + +**This plan takes the third.** It is what the thin inventory is actually good for, +and it settles four questions that would otherwise each be an argument of their own: + +- The Messages tab shows an empty state that says why it is empty and offers the + one thing that fills it: signing in with the nsec. +- Pasting the nsec of a key already here read-only is an **upgrade in place**, not + `AlreadyOnThisDevice`. The device does not have that key; refusing it would be + false. +- Sign out is real for this kind, and only this kind: there is nothing on the + device to lose. It is the first sign out in the app, and the general case stays + pending for the reason the nsec plan gave. +- Not-found offers *try again* or *a different key*, never *set one up* — a profile + cannot be set up for a key that cannot sign its kind 0. + +Everything below is downstream of that one word, preview, and if it is ever +revisited — a public feed lands, say — the places to change are the four above. + +--- + +## Phase 1 — a key the identity may not have + +**App only. No behaviour change.** A type change that ships alone, so its diff is +boring. + +### The type + +```kotlin +enum class IdentityKind { + Mnemonic, + NostrSecret, + /** A bare nostr public key. Nothing can be signed, opened or derived from it. */ + NostrPublic, +} + +data class Identity( + val id: WalletId, + val kind: IdentityKind, + val nostrPublicKey: HexKey, + /** Null only for [IdentityKind.NostrPublic]. */ + val nostrPrivateKey: PrivateKey?, + val userPrefs: UserPrefs, + val internalPrefs: InternalPrefs, + val business: PhoenixBusiness?, +) { + /** What the notary, the pumps and every write entrance ask. */ + val canSign: Boolean get() = nostrPrivateKey != null + + init { + require((nostrPrivateKey == null) == (kind == IdentityKind.NostrPublic)) { "kind and key disagree" } + require(nostrPrivateKey == null || nostrPrivateKey.nostrPublicKeyHex() == nostrPublicKey) { "key does not derive its public key" } + } + + override fun toString(): String = "Identity(id=$id, kind=$kind, key=)" + + companion object { + fun signing(id: WalletId, kind: IdentityKind, privateKey: PrivateKey, userPrefs: UserPrefs, internalPrefs: InternalPrefs, business: PhoenixBusiness?): Identity + fun readOnly(id: WalletId, nostrPublicKey: HexKey, userPrefs: UserPrefs, internalPrefs: InternalPrefs): Identity + } +} +``` + +`nostrPublicKey` moves from a derived property to a constructor field, because for +one kind there is nothing to derive it from; the two `require`s in `init` keep the +field and the key from disagreeing, which a data class would otherwise happily +allow. The factories exist so that the two places that build a signing identity +today — `SovereignWalletViewModel.setActiveWallet` and the nsec branch of +`SovereignWalletStartupScreen` — keep deriving the pubkey in one place, and so that +nobody constructs a read-only identity with a key by accident. + +`id` for a read-only identity is `toWalletId()` of the x-only key — the **same id** +its nsec would have. That is deliberate and it is what makes the upgrade in +[Phase 2](#the-upgrade-rule) free: preferences and metadata are keyed by id, and a +read-only identity that becomes a signing one keeps both. + +### The readers + +Every reader of `nostrPrivateKey` already reaches it through `?.` on a nullable +identity — `activeIdentityStateFlow.value?.nostrPrivateKey` in the DKG, chat-room +and subgroup view models, `.map { it?.nostrPrivateKey }` in the notary, +`identity?.nostrPrivateKey?.let` in the pumps. Making the field nullable changes +the type of none of those expressions, and **the compiler will be silent**. That +is worth saying plainly, because it is the opposite of Phase 1 of the nsec plan, +where twenty-five parameter types forced every site to be looked at: here nothing +forces anything, and the sites that need a decision are found by reading, in +[Phase 5](#phase-5--what-a-read-only-screen-shows), not by compiling. + +One site does change. `KeyRecoveryScreen` branches on `activeIdentity?.kind` with +`NostrSecret` in one arm and `else` in the other +([KeyRecoveryScreen.kt:177](../composeApp/src/commonMain/kotlin/to/curare/compose/ui/composable/KeyRecoveryScreen.kt)), +and the `else` meant *mnemonic*. A read-only identity would fall into it and be +offered a recovery phrase it does not have. Make both `when`s in that file +exhaustive; the `NostrPublic` arm is unreachable after Phase 5 hides the row, and +an unreachable arm that says so is better than an `else` that will mean something +different next time a kind is added. + +### Tests + +`NavigationIdentityRoutingJvmTest` has a `nostrSecretIdentity()` fixture and the +case that a nodeless identity is routed by its account rather than to startup. It +gains a `readOnlyIdentity()` fixture and the same case: with the placeholder +account, `UnqueuedProfileSynchronization`; with a kind 0 indexed, `ProfileLoaded`. +And the two `require`s each get a one-line negative test, because they are the +whole reason the field is a constructor parameter. + +--- + +## Phase 2 — one credentials file + +**Library, then app. The library half needs nothing above it; the app half needs +Phase 1.** The only phase that touches the library, and the one place this plan +changes one of the nsec plan's stores rather than adding to them. + +### The file that was written expecting this + +`EncryptedNostrKeys`'s own doc says it: "this file has one shape, and a new shape +would be a new version." A read-only credential is the new shape. Rather than a +second file beside `nostr-keys.dat` holding public keys in the clear — the design +this plan first had, and rejected for the reason in the +[appendix](#a-plaintext-sibling-file-for-public-keys) — the file becomes what its +name should have been: **`nostr-credentials.dat`**, one entry per nostr public key, +each entry saying what the device holds for it. + +```json +{ + "": { "type": "secret", "privateKey": "" }, + "": { "type": "public" } +} +``` + +Same envelope — version byte, sixteen-byte iv, ciphertext of UTF-8 JSON under +`KeyStoreNames.KEY_NO_AUTH` — same atomic write through `AtomicFileWrite`, same +manager shape. The JSON is a `Map` with `NostrCredential` +a `@Serializable sealed class` and `type` its class discriminator — kotlinx's +standard sealed polymorphism, `Json { classDiscriminator = "type" }`, which the +library does not use elsewhere (its cloud payloads pick a variant by a version +field) and which is chosen here because the two variants have different fields and +the map then decodes in one call with no hand-written dispatch. + +```kotlin +package fr.acinq.phoenix.security + +@Serializable +sealed class NostrCredential { + @Serializable @SerialName("secret") data class Secret(val privateKey: PrivateKey) : NostrCredential() + @Serializable @SerialName("public") data object Public : NostrCredential() +} + +class EncryptedNostrCredentials(val iv: ByteArray, val ciphertext: ByteArray) { + fun decryptAndGetCredentials(): Map + fun serialize(): ByteArray + companion object { + const val VERSION: Byte = 1 + fun deserialize(bytes: ByteArray): EncryptedNostrCredentials + fun encrypt(credentials: Map): EncryptedNostrCredentials + } +} +``` + +The read keeps the check that makes the file trustworthy and adds its counterpart: +a `secret` entry must derive the public key it is filed under, as today, and a +`public` entry's map key must be sixty-four hex characters naming a point on the +curve. Either failure is `SerializationError`, because either can only be +corruption. + +Encrypting a public key protects nothing and costs nothing. What it buys is one +read path with one failure classification, and — a small thing, but real — the +list of profiles a user has looked at is a browsing record, and it is at rest +under the same key as everything else about them. + +### Why the file is renamed rather than versioned in place + +A version byte of 2 in `nostr-keys.dat` would be the natural move and it is the +wrong one. An older build's reader throws on an unknown version, `NostrKeyManager` +classifies that as `SerializationError`, and `listIdentities` **returns** on that +result before it publishes anything +([SovereignWalletViewModel.kt:218](../composeApp/src/commonMain/kotlin/to/curare/compose/ui/view/model/SovereignWalletViewModel.kt)): +the old build would list no identities at all, seed wallets included. That is the +`seed.dat` failure the nsec plan's appendix rejected a version-4 payload for. A +file the old build does not look for cannot do that to it. + +So: `nostr-credentials.dat`, version 1 of a new file, and the old reader kept as +`LegacyNostrKeysFile` for exactly one caller. + +### Migration + +`NostrCredentialManager.migrateFromNostrKeys(phoenixGlobal)`: if +`nostr-credentials.dat` is absent and `nostr-keys.dat` exists, read the old file, +convert every entry to `Secret`, write the new file through the verified atomic +write, and **delete the old one**. Called once from `listIdentities`, which runs +from `SovereignWalletViewModel.init` before anything else touches either file, so +a read stays a read and the migration is a named step with a test of its own. + +Delete, rather than leave a frozen copy for an older build to find. A copy goes +stale in the one direction that matters: a key the user asks the new build to +*forget* would survive in a file only the old build reads, and come back on a +downgrade. Losing sight of every nsec identity on a downgrade until the next +upgrade is the lesser failure, and [Phase 8](#phase-8--rollout) says so out loud. + +As far as the repository can show, the migration will run for nobody: the library +commit that introduced `nostr-keys.dat` carries no tag and the app has none. It +exists because the repository cannot prove a negative, and because it is thirty +lines. + +### Listing + +```kotlin +sealed interface StoredIdentity { + … + data class NostrPublic( + override val id: WalletId, + override val nostrPublicKey: HexKey, + ) : StoredIdentity { + override val kind: IdentityKind get() = IdentityKind.NostrPublic + } +} +``` + +`StoredIdentity.merge(wallets, credentials)` keeps its two inputs; a `Secret` is a +`NostrSecret` and a `Public` a `NostrPublic`. One entry per pubkey is the file's +own invariant, so there is no precedence between credentials to decide. There is +one between a seed and a credential, and it exists for the one upgrade that has to +span two files (below): a `Public` whose pubkey a seed derives is dropped, with a +log line, and the next write repairs the file. + +### The writers + +```kotlin +object IdentityWriter { + … + suspend fun writeNostrPublicKey(log, phoenixGlobal, globalPrefs, publicKey: HexKey, isTorEnabled, customElectrumServer): WriteNostrCredentialResult + suspend fun forgetNostrCredential(log, phoenixGlobal, id: WalletId, publicKey: HexKey): ForgetNostrCredentialResult +} +``` + +`writeNostrKey` stays and writes a `Secret`; `writeNostrPublicKey` writes a +`Public`; both refuse a duplicate by public key against the seeds *and* the +credentials, and both `prepareIdentity` — the Tor and Electrum preferences mean +even less to a read-only identity than to an nsec one, and are saved for the +reason the nsec plan gave. `forgetNostrKey` becomes `forgetNostrCredential` and +removes an entry of either kind; its `NotABareKey` becomes `NotACredential`, which +still means a mnemonic. + +### The upgrade rule + +`writeNostrKey`'s duplicate check learns one distinction: + +| the pubkey is already here as | pasting its nsec | pasting its npub | +|---|---|---| +| a wallet (seed) | `AlreadyExists` | `AlreadyExists` | +| a `secret` credential | `AlreadyExists` | `AlreadyExists` | +| a `public` credential | **upgrade**: the entry becomes `secret`, in one write; `Written(id)` with the id unchanged | `AlreadyExists` | + +One write, because it is one file. There is no window in which the device holds +both or neither, and nothing to reconcile afterwards — which is the whole reason +this phase is a library change and not a second file. + +The one upgrade that still spans two files is a *recovery phrase* pasted over a +public credential: the seed goes to `seed.dat`, and that file cannot hold anything +else. `writeMnemonic` removes the `public` entry **first**, then writes the seed. +A crash between the two loses the read-only identity — recoverable by pasting the +npub again — rather than leaving one pubkey listed twice under two ids, which is +what the reverse order would do and what the merge rule above is there to catch +if it somehow happens anyway. The wallet's id is `hash160(nodeId)` and its +preferences are fresh, as a new wallet's are today. + +### Tests + +In the library, after the two that exist: `EncryptedNostrCredentialsTest` in +`commonTest`, the layout as literal bytes with one entry of each kind, because the +format is a compatibility contract from the moment it exists; and, in `jvmTest`, a +round trip through the key store, plus the migration — a v1 `nostr-keys.dat` +written by `LegacyNostrKeysFile`'s test fixture, read back as `Secret` entries in +`nostr-credentials.dat`, the old file gone. + +In the app: `StoredIdentityJvmTest` gains a `Public` credential listed as +`NostrPublic`, and a `Public` whose pubkey a seed derives dropped. +`IdentityWriterJvmTest` gains: a public key is written once and refused the second +time; its nsec is then accepted, under the same id, and the entry is now `secret`; +the npub of an nsec already here is refused; forgetting a credential of either kind +leaves the others and takes its preferences. + +--- + +## Phase 3 — listing, starting, and reading without a key + +**App. Needs Phase 2.** + +### Listing and starting + +`SovereignWalletViewModel.listIdentities` runs the migration, then reads +`nostr-credentials.dat` where it read `nostr-keys.dat`, with the same five results +handled the same way; the change is the type of the map it hands to `merge` +([SovereignWalletViewModel.kt:242](../composeApp/src/commonMain/kotlin/to/curare/compose/ui/view/model/SovereignWalletViewModel.kt)). + +`SovereignWalletStartupScreen` gains its third branch, beside the nsec one +([SovereignWalletStartupScreen.kt:185](../composeApp/src/commonMain/kotlin/to/curare/compose/ui/composable/SovereignWalletStartupScreen.kt)): + +```kotlin +is StoredIdentity.NostrPublic -> sovereignWalletViewModel.setActiveIdentity( + Identity.readOnly( + id = identity.id, + nostrPublicKey = identity.nostrPublicKey, + userPrefs = dataStoreManager.loadUserPrefsForWallet(identity.id), + internalPrefs = dataStoreManager.loadInternalPrefsForWallet(identity.id), + ) +) +``` + +No node, no `platformStartupLogic`, active the moment it is read — exactly the nsec +branch. The screen-lock gate wraps all three, as it was built to. + +`WalletsSelector` shows the npub for every kind already; a read-only row adds the +words *read only* under it, in `labelSmall`, so the user can tell which of two +identities with the same avatar will let them send a message before they tap. + +### The pumps + +`SynchronizationViewModel`'s collector becomes + +```kotlin +activeIdentityStateFlow.collectLatest { identity -> + identity?.let { + val keyPair = identity.toKeyPair() + … + supervisorScope { + launch(Dispatchers.IO) { observePendingSyncNostrEventRequests(keyPair) } + launch(Dispatchers.IO) { observePendingNegentropySynchronizeRequests(keyPair) } + if (identity.canSign) { + launch(Dispatchers.IO) { observePendingBroadcastNostrEventRequests(keyPair) } + launch(Dispatchers.IO) { liveSubscriptionManager.observe(keyPair) } + } + } + } +} +``` + +**A read-only identity runs the two pumps that read and neither of the two that +write.** Stated as a rule, because Phase 5 leans on it: *a read-only identity never +sends anything to a relay*, not a signature and not a copy. The broadcast pump +would find nothing — nothing is ever signed, and the one control that queues an +already-signed event is hidden — and the +live subscriptions are the gift-wrap inbox and the group-membership follow, both of +which fetch things this identity cannot open, and the catch-up negentropy for the +same. Not running them is not an optimisation; it is the identity not asking for +what it cannot use. The sync pump and the negentropy pump are what the sign-in +sync, the one hop and *try again* are queued on, and they are all a preview needs. + +`Identity.toKeyPair()` is the one place a quartz `KeyPair` is built from an +identity: + +```kotlin +fun Identity.toKeyPair(): KeyPair = KeyPair( + privKey = nostrPrivateKey?.value?.toByteArray(), + pubKey = nostrPublicKey.hexToByteArray(), +) +``` + +With a private key, quartz recomputes the public key from it and the second +argument is a cross-check. Without one, it is the read-only constructor. What it +must never be is `KeyPair(privKey = null)` with nothing else — that is quartz's +"make me a new key", and it is what `decryptGiftWrapSeal` does today +([GiftWrapMessage.kt:126](../composeApp/src/commonMain/kotlin/to/curare/compose/database/model/GiftWrapMessage.kt)). +The helper exists so that the trap has one place to be avoided; leave a comment on +it that says what the trap is. + +### The one DAO guard + +After the `isAddressedTo` check in `indexNostrEvent` +([NostrDao.kt:439](../composeApp/src/commonMain/kotlin/to/curare/compose/database/dao/NostrDao.kt)): + +```kotlin +if (activeKeyPair.privKey == null) { + // Addressed to us, and we cannot open it. Keep the event and the wrap we just + // stored, as the branch above does for wraps addressed to someone else; the + // key that opens this one may be signed in later. + logger.d("GiftWrap ${nostrEvent.id} is addressed to us, but this identity holds no key") + return@let +} +``` + +The two `privKey!!` sites further down (lines 898 and 1376) are downstream of a +successful unseal and a Marmot room this device is in; a read-only identity reaches +neither, and they stay as they are. With the live subscriptions off, and once +Phase 5 leaves the room list uncomposed, a gift wrap addressed to a read-only +identity arrives only if something else asks for kind 1059 — nothing else does — +so this guard is belt and braces. It stays because the alternative, when something +does ask, is a rolled-back transaction that logs as a decryption failure and is +not one; and between this phase and Phase 5 it is not belt and braces at all, it +is what keeps the room list's inbox sync from rolling back every wrap it fetches. + +### Tests + +`NostrDaoJvmTest` gains one case: a gift wrap addressed to a read-only `KeyPair` +is stored, its `GiftWrapMessage` row is stored, no seal is stored, and nothing +throws — `NostrNip17DaoJvmTest` has the fixtures for building the wrap. The +listing itself is covered where the nsec plan ended up covering it: `merge`, in +`StoredIdentityJvmTest` (Phase 2), and the round trip in Phase 7, which lists +through the view model against a real directory and a real key store. The nsec plan asked for a +`SovereignWalletViewModel` listing test of its own and the build did not write +one; this plan does not pretend to. + +--- + +## Phase 4 — the sign-in screen + +**App. Needs Phase 3.** The field accepts a third thing. + +### Shape + +| pasted | recognised as | validation | +|---|---|---| +| words | recovery phrase | unchanged | +| `nsec1…`, `nostr:nsec1…` | nostr secret | unchanged | +| 64 hex characters | **nostr secret, still** | see below | +| `npub1…`, `nostr:npub1…` | nostr public key, read only | bech32 decodes with hrp `npub` to 32 bytes that are an x coordinate on the curve — `XonlyPublicKey(bytes).publicKey.isValid()`, the counterpart of the `isValid()` a secret is checked with | +| `ncryptsec1…` | rejected, with the reason | unchanged | + +**Hex stays a secret.** A private key and an x-only public key are both thirty-two +bytes, and sixty-four hex characters cannot say which it is. The parser has always +read hex as a secret and shown the derived npub on the confirm step so a wrong +paste is visible; a user who pastes a public key as hex will see an npub they do +not recognise and go back. Guessing — "it is not a valid secret, so try it as a +public key" — would never fire when it mattered: a public key's x coordinate is, +with overwhelming probability, also a valid scalar, so the parser would accept it +as a secret, derive an unrelated npub, and never reach the guess. An npub has to +arrive as an npub. + +`CredentialProblem.PublicKeyOnly` goes, and with it the string +`an_npub_is_a_public_key_curare_needs_the`. An npub that does not decode, or +decodes to a point that is not on the curve, is `InvalidKey`, which already says +"that nostr key is not valid". + +### The confirm step + +`SignInCredential` gains + +```kotlin +data class NostrPublicKey(override val nostrPublicKey: HexKey) : SignInCredential +``` + +and `Confirm` a third arm, `Icons.Default.Visibility` beside a sentence that says +what the user is about to get and not get. `this_will_give_you_read_only_access_to_the` +says "This will give you read only access to the profile", which is true and not +enough: it does not say that messages stay closed, and it does not say what to do +about it. Replace it: + +> 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. + +Sentence case, one string, read on the confirm step and nowhere else. The button +still says *Sign in*. + +### Committing + +```kotlin +is SignInCredential.NostrPublicKey -> when (val result = writeNostrPublicKey(credential.nostrPublicKey)) { + is Written -> Outcome.SignedIn(result.id) + is AlreadyExists -> Outcome.Failed(CredentialProblem.AlreadyOnThisDevice) + is CannotLoadKeys -> Outcome.Failed(CredentialProblem.CouldNotWrite) +} +``` + +then `signInToProfile`, then the same tail as the other two: re-list, select, go to +startup. Startup finds a `StoredIdentity.NostrPublic`, activates it, and the machine +runs from the placeholder exactly as it does for an nsec — the sync pump is running +because Phase 3 made it run. + +### A sign-in that can be repeated + +`signInToProfile` inserts a new kind-0 `UnsignedNostrEvent` every time it is called +([DatabaseNostrRepository.kt:258](../composeApp/src/commonMain/kotlin/to/curare/compose/database/repository/DatabaseNostrRepository.kt)). +Until now nothing called it twice for one pubkey: the writers refused the second +sign-in before it got there. The upgrade is the first path that signs in a pubkey +whose account already exists, and a second placeholder would be "two kind-0 rows +for one pubkey, two accounts disagreeing about which is this one" — the failure +`setUpProfileForExistingKey`'s own comment describes. + +Make it idempotent by pubkey: if a kind-0 `UnsignedNostrEvent` exists for the key, +do nothing. That is the right property regardless of the upgrade, and the existing +test `both credentials of one key plant the same account` becomes `…plant one +account, however many times they sign in`. + +### Landing + +The caption under *Sign in* names what the screen accepts, and the label and +placeholder on the field do too. Three strings change to say "a recovery phrase, +an nsec, or an npub to look around" — the last clause because a user who does not +know the word *read-only* should still be told the difference before they paste. + +### Tests + +`CredentialParserJvmTest`: an npub, a `nostr:`-prefixed npub and the upper-cased +form all name the same public key; an npub that does not decode is an invalid key; +sixty-four hex characters are still a secret. `SignInToProfileViewModelJvmTest`: a +public key is written, then its account is planted, then the id comes back; the +npub of a key already here is refused and plants nothing; the nsec of a key here +read-only is written under the same id and plants nothing new. + +--- + +## Phase 5 — what a read-only screen shows + +**App. Compiles on Phase 1; visible after Phase 3.** The half the nsec plan called +a product. + +### One question, asked in one way + +Screens do not receive the identity. `HomeScreen`, `ActiveProfileScreen` and the +detail widgets take an `activeUserPublicKey`, and `MetadataEventDetail` — where +*follow* and *send message* live — is several composables below anything that +could be handed more. Threading `canSign` down would be the snackbar host's +problem again: the same parameter in twenty-six lists and forgotten in the +twenty-seventh. + +```kotlin +// ui/composable/widgets/SigningCapability.kt +val LocalCanSign: ProvidableCompositionLocal = staticCompositionLocalOf { true } + +@Composable +fun ProvideSigningCapability(activeIdentity: StateFlow, content: @Composable () -> Unit) +``` + +Provided once, in `CurareNavHost` around the `NavHost`, from +`sovereignWalletViewModel.activeIdentity`. The default is `true` rather than an +error, and that is the one way this differs from `LocalSnackbarHostState`: the +provider sits above every screen and cannot be forgotten per screen, so the only +things composed outside it are previews and the existing compose tests, and those +should render as they always have. + +It is a capability, not a kind. A screen asks "can this identity sign?", not "is +this an npub?", because the answer is what it needs and because a remote signer — +which can sign and holds no local key — would otherwise be a fourth value in every +`when` (see [Out of scope](#out-of-scope)). + +### The inventory + +Every write entrance reachable from the three tabs without a chat room, and what +a read-only identity gets instead. A row that says *hidden* is hidden, not +disabled: a disabled "New chat" invites the question "why", and the answer is on +the empty state beside it. + +| screen | control | it writes | read only | +|---|---|---|---| +| `HomeScreen` | *New chat* (both layouts), the sheet, the npub dialog | key packages, welcomes, gift wraps | hidden; the tab shows the [empty state below](#the-messages-tab) | +| `HomeScreen` | `ChatRoomListViewModel.initiate` | queues the inbox sync and the MLS negentropy | not composed, so not queued | +| `MetadataEventDetail` | *follow*, *unfollow*, *follow back* ([:215](../composeApp/src/commonMain/kotlin/to/curare/compose/ui/composable/widgets/detail/MetadataEventDetail.kt)) | a kind 3 | hidden; the "follows you" state still shows | +| `MetadataEventDetail` | *send message* ([:303](../composeApp/src/commonMain/kotlin/to/curare/compose/ui/composable/widgets/detail/MetadataEventDetail.kt)) | a gift wrap | hidden | +| `MetadataEventDetail` | *edit profile* | a kind 0 | hidden (it is `ImplementationPendingRoute` today, and stays so for the other kinds) | +| `ActiveProfileScreen` | *key package management* ([:233](../composeApp/src/commonMain/kotlin/to/curare/compose/ui/composable/ActiveProfileScreen.kt)) | key packages | hidden | +| `ActiveProfileScreen` | *key recovery* ([:286](../composeApp/src/commonMain/kotlin/to/curare/compose/ui/composable/ActiveProfileScreen.kt)) | nothing, but there is nothing to recover | hidden | +| `ActiveProfileScreen` | *sign out* ([:341](../composeApp/src/commonMain/kotlin/to/curare/compose/ui/composable/ActiveProfileScreen.kt)) | — | **real**, see [Phase 6](#phase-6--leaving) | +| `ShareProfileScreen` | *re-broadcast* ([:191](../composeApp/src/commonMain/kotlin/to/curare/compose/ui/composable/ShareProfileScreen.kt)) | nothing is signed, but a copy of the kind 0 is queued for the finder relays | hidden; a preview puts nothing on a relay, not even a copy, and the broadcast pump is not running to carry it | +| `UnsyncedProfileScreen` | *set one up* ([:217](../composeApp/src/commonMain/kotlin/to/curare/compose/ui/composable/UnsyncedProfileScreen.kt)) | the six-event bootstrap | hidden; replaced, see Phase 6 | +| `SocialPreconditionScreen` | *invite a friend*, *view invites* | pending, and writes when they exist | hidden; only *skip for now* | +| `WriteNewNoteScreen` and the rest | — | — | unreachable: every route to them starts in a room or behind a control above | + +Two things are *not* on the list because they are already handled. The notary's +key package bundle is behind its key check, so a read-only identity never publishes +one. And the DKG, chat-room and subgroup view models each answer a missing key with +an error state — they are unreachable, and if they were reached they would say so +rather than crash. + +### The Messages tab + +Where the room list would be, for a read-only identity: + +```kotlin +EmptyState( + message = stringResource(Res.string.messages_need_the_secret_key_this_profile), + icon = Icons.Default.Lock, + action = { + TextButton(onClick = { onNavigateToRoute(SignInRoute) }) { + Text(stringResource(Res.string.sign_in_with_the_nsec)) + } + }, +) +``` + +> Messages need the secret key. This profile is read only: you can see it and the +> people it follows, but nothing here can be opened or sent. + +`EmptyState`'s message is required for exactly this reason — an absence has to say +which absence it is — and its `action` slot is where the upgrade lives. The +`SignInRoute` it opens is the same screen as landing's; the nsec pasted there hits +the upgrade rule, and the tail takes the user through startup to a Messages tab +with rooms in it. + +One column at every width. The two-pane layout is a list beside a detail, and +there is no list; an empty state that is the only thing on the screen is the one +case `readableContent()`'s centring is for. + +The tab stays. Hiding it would leave a navigation bar with two items — the +conformance work promoted search and profile to peers precisely so the bar would +not be "strictly worse than the app bar it replaced", and two items is halfway +back to that — and the bar is where the upgrade is found. + +### Tests + +`ReadOnlyEntrancesJvmTest`, with `runDesktopComposeUiTest` as `ChatPaneLayoutJvmTest` +does: `HomeScreen` in its loaded state under `LocalCanSign provides false` has no +node with the text *New chat* and one with *Sign in with the nsec*; under `true`, +the reverse. `ActiveProfileScreen` under `false` has no *Key recovery* and has +*Sign out*. The inventory above is the list of assertions; a row without one is a +row that will regress. + +And `./gradlew :composeApp:m3Audit` — an empty state with an action and a new +`when` arm is where a `16.dp` and a "Read Only" arrive. + +--- + +## Phase 6 — leaving + +**App. Needs Phases 2 and 5.** Two exits, one sequence. + +### Sign out, for the kind that can + +`NostrSecretViewModel.forgetKey` does five things in an order that matters — key +out of the file, preferences deleted, metadata hidden, account rows gone, then the +caller re-lists and clears the active identity — and the order is documented on the +function: a failure partway leaves the key on disk rather than an identity the +selector lists but nothing can open. The sequence is the same for a read-only +identity, and since Phase 2 the first step is the same call — `forgetNostrCredential` +removes an entry of either kind. Lift the sequence into a `ForgetIdentity` helper +that takes the identity, returns `NotACredential` for a mnemonic one, and is +called by `NostrSecretViewModel` and the two exits below alike. + +`ActiveProfileScreen`'s *sign out* then does, for a read-only identity only, what +its colour has been promising: a confirmation dialog naming the npub — + +> Sign out of this profile? This device holds no key for it, so there is nothing +> to lose. The profile stays on the relays, and you can sign in again any time. + +— and `ForgetIdentity`, then the nav host's existing tail +(`listIdentities { resetToSelector() }`, which shows the selector or, if this was +the last identity, Landing). For the other two kinds the button keeps routing to +`ImplementationPendingRoute("Sign out")`, and the nsec plan's reason stands: +removing a seed is a wallet question. + +### The not-found exit + +`UnsyncedProfileScreen`'s not-found state offers *try again* and *set one up*. For +a read-only identity the second is hidden by Phase 5 — and then the state has +**no exit**: the profile tab is not reachable before `ProfileLoaded`, so a user +whose npub was not found on any relay could try again for ever. That is the nsec +plan's "parks on a spinner" with the spinner replaced by a button. + +A third action, shown only where the second is not: *use a different key*, which +is `ForgetIdentity` behind the same confirmation and the same tail, landing on the +selector or Landing. The screen learns the two callbacks the way `NostrSecretScreen` +did — passed from the nav host — and reads `LocalCanSign` to decide which of the +two it shows. + +### Tests + +`ForgetIdentity` gets the `IdentityWriterJvmTest` treatment: a read-only identity +is forgotten and its list entry, preferences and account rows are gone; the other +entries remain. `UnsyncedProfileViewModel`'s existing decision test is unchanged — +not-found is still not-found — and the screen test asserts which action each kind +gets. + +--- + +## Phase 7 — the tests that actually prove it + +Two, beside `NsecRestoreRoundTripJvmTest`, whose fixture they reuse. + +**The preview, end to end.** Write an npub through Phase 2's writer, list +identities, activate the `NostrPublic` one, hand `NavigationViewModel` a repository +holding the placeholder: `UnqueuedProfileSynchronization`. The same account with a +kind 0 indexed: `ProfileLoaded`. Then the assertion the nsec round trip makes about +the node, made about the key: **nothing was signed**. The only `UnsignedNostrEvent` +for the pubkey is the placeholder, still at `GENESIS_AT`; no key package bundle +row; no broadcast request; `identity.business == null`; `identity.canSign` false. + +**The upgrade.** From the state above, write the nsec of the same pubkey through +`writeNostrKey`: `Written` with the same id; the credentials file holds one entry +for the pubkey and it is `secret`; `signInToProfile` planted nothing new, and the +account routes to `ProfileLoaded` as before. Re-list: one identity, `NostrSecret`, +same id, same metadata. + +--- + +## Phase 8 — rollout + +**Library first, and on the tag the nsec work still owes.** Phase 2 is a commit +on the submodule, reaching the app as a pointer bump in the Phase 2 commit. The +library commit that introduced `nostr-keys.dat` is on the library's `master` — it +arrived through PR #1 — but is untagged, and the library has no tags at all; the +nsec plan says it has to be tagged before any of that work leaves the machine, and +Phase 2 goes out on the same tag, so that no JitPack consumer ever sees the v1 file +without the reader that migrates it. + +**Phase 1 ships alone.** A type change with two `require`s and one exhaustive +`when`; if the release after it behaves differently, the cause is in one diff. + +**Phases 3 through 5 ship together.** A build with the file but not the screen is +harmless; a build with the screen but not the file strands the user at +"Initializing…"; and a build with both but not Phase 5 is the thing this plan is +for — an identity that looks signed in and offers "New chat". Phase 6 can follow +by a release: without it a read-only identity has no sign out and no not-found +exit, which is a dead end but not a lie. + +**Old builds and the new file.** A build before Phase 3 does not read +`nostr-credentials.dat` and does not know it exists. If it also predates the nsec +work it is unaffected in every way. If it is a build *with* `nostr-keys.dat` and +the migration has run on this device, that file is gone and the build lists no +nsec identities until the next upgrade — the failure Phase 2 chose over a +forgotten key coming back, and the one line of this rollout worth a release note. +`seed.dat` is untouched throughout. + +## Estimate + +| phase | work | days | blocked by | +|---|---|---|---| +| 1 | a key the identity may not have | 0.5–1 | — | +| 2 | the credentials file, migration, the writers, the upgrade rule (library + app) | 1.5 | 1 | +| 3 | listing, starting, the pumps, the DAO guard | 1 | 2 | +| 4 | the sign-in screen; an idempotent sign-in | 0.5–1 | 3 | +| 5 | the capability, the inventory, the Messages tab | 1 | 1 to compile, 3 to see | +| 6 | sign out, and the not-found exit | 0.5 | 2, 5 | +| 7 | the two round trips | 0.5 | 4, 5, 6 | +| 8 | rollout | — | all | + +**Roughly one focused week.** Phase 5 is where the estimate is least reliable: +the inventory was made by reading, and the compiler will not say whether it is +complete. The compose tests are how it is checked, and a row found late is a row +added to both. + +## Out of scope + +- **A public feed.** The thing that would make read-only *browsing* rather than + *previewing*. Its own plan, and when it lands the four decisions under + [the one decision](#the-one-decision-to-make-first) are the places to revisit. +- **NIP-46 remote signer, NIP-55 Android signer.** This plan builds half of what + they need — an identity whose secret is not on `Identity` — and none of the + other half, a signing interface the notary calls instead of a `NostrSignerSync`. + `LocalCanSign` is a Boolean on purpose: a remote signer answers it *true* — + which is why `canSign` is a property of the identity and not `nostrPrivateKey != null` + repeated at each site — and the question it adds is "can it derive?": the + ChillDKG host key needs the raw bytes, and no signer protocol gives them. A + second capability, not a third value of this one. +- **NIP-05 sign-in.** `alice@example.com` resolves to a pubkey with one HTTPS + request, and the app already accepts a NIP-05 for starting a message. It is a + natural fourth row in Phase 4's table, and it is a network round trip on a form + field, which is why `EditGroupCuratedSchemaViewModel.pubkeyOrNull` declined it. + A cheap follow-on once the npub path is proven. +- **NIP-49 `ncryptsec`.** Unchanged from the nsec plan. +- **Setting up a profile for a public key.** Impossible: the kind 0 has to be + signed. Said here so that nobody looks for the branch Phase 5 hid. +- **Reading a group's curated lists from outside it.** Public events, but every + path to them goes through a room today. The feed problem in a smaller shape. +- **Tightening secrets in memory.** Unchanged, and this plan adds no secret to + tighten. + +## Appendix — what was considered and rejected + +### A plaintext sibling file for public keys + +This plan's first design: `nostr-public-keys.json` beside the two `.dat` files, +unencrypted because a public key is public, written through the same atomic +helper, and app-side — no library change, no tag. It was rejected in review, and +rightly. The upgrade became two writes across two files with a crash window +between them and a "secret wins" rule in `merge` to repair the window; forget +became two paths; and the advantage that paid for all of that was worth less than +it looked, because the library commit that introduced `nostr-keys.dat` is itself +untagged, so a credentials format rides the tag that work already owes. One file, +one entry per pubkey, one write. + +### A sentinel entry in the version-1 format + +An empty-string value, or a zero key, under the pubkey, in `nostr-keys.dat` as it +is. Rejected because the file's contract is the reason it is trustworthy: +`EncryptedNostrKeys` refuses an entry whose key does not derive its pubkey, and a +sentinel is exactly such an entry. A typed credential is what a sentinel is trying +to be, and the file's doc had already reserved a version for it. + +### Bumping the version in place + +Version byte 2 in `nostr-keys.dat`, with the typed entries. Rejected in +[Phase 2](#why-the-file-is-renamed-rather-than-versioned-in-place): an older +build's `listIdentities` returns on `SerializationError` before it publishes +anything, so the old build would list no identities at all, seed wallets included. +A new file name is invisible to a build that does not know it. + +### A fake private key + +Give a read-only identity a random `PrivateKey` so that nothing has to become +nullable. The notary would sign as a key nobody follows, the DAO would try to +unseal wraps with it, the key package bundle would be published under it, and +every one of those would look, in the logs, like success. The nsec plan rejected +the fake `LocalKeyManager` for the same reason: a real object in a state its +authors never intended. Nullable is honest. + +### Gating on the kind at each site + +`if (identity.kind == IdentityKind.NostrPublic) hide()`. Works today, and is the +wrong question: the site wants to know whether it can sign. When a remote signer +arrives — the nsec plan already names it — every such `if` is a bug, and the +compiler will point at none of them. + +### Hiding the Messages tab + +A read-only identity lands on its profile and the bar has two items. Rejected: the +bar is the navigation, M3 gives a navigation bar three to five destinations and the +conformance work made an IA decision to reach three, and the empty state is where +the upgrade is offered. An identity that cannot find the way to become a signing +one is a preview of nothing. + +### Running all four pumps regardless + +Let the broadcast pump idle and the live subscriptions fetch what they fetch; the +DAO guard keeps the wraps. Rejected for what it costs the user for nothing: +`GiftWrapMessage` rows that will never be opened, placeholder profiles for their +senders, profile syncs for each, and a socket held open for an inbox that cannot +be read. The pumps that run are the ones with something to do. + +### A Room table for the list + +`ReadOnlyIdentity(publicKey)`, listed by the repository. Rejected because the +startup listing is built from the key stores by a view model that has no +repository, and because the nsec plan's listing test exists to catch two stores +disagreeing about what an id is; a store in a different layer, read at a different +time, is a second opinion where the credentials file is meant to be the only one. diff --git a/docs/nsec-sign-in.md b/docs/nsec-sign-in.md index 88eacdd6..dae20b76 100644 --- a/docs/nsec-sign-in.md +++ b/docs/nsec-sign-in.md @@ -947,7 +947,8 @@ found. would accept it. But every write path in the app assumes a key: the notary would have nothing to sign with and the state machine would park on `UnsignedProfile` the first time anything was queued. A read-only mode is a - product, not a branch. + product, not a branch — and [npub-sign-in.md](./npub-sign-in.md) is the plan + for that product, starting from what it is for. - **NIP-49 `ncryptsec`.** A passphrase-encrypted nsec. quartz 1.14.0 ships `nip49PrivKeyEnc.Nip49.decrypt`, so it is one call and a passphrase field; it belongs in Phase 4's table once the plain nsec path is proven, and is a cheap diff --git a/lightning-kmp-app b/lightning-kmp-app index 59c11ed9..84cc44c8 160000 --- a/lightning-kmp-app +++ b/lightning-kmp-app @@ -1 +1 @@ -Subproject commit 59c11ed926ac05c820b98afb4cc961a5a3506310 +Subproject commit 84cc44c855e3d173e26016b807c449153a3af597