From 4878f9414c76f91a8c7cca63388ab1d4d9b83231 Mon Sep 17 00:00:00 2001 From: Alex Gleason Date: Sun, 24 May 2026 17:50:59 -0500 Subject: [PATCH] Switch to the newly added account when logging in MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit addLogin appends to the end of the logins array, but the current user is logins[0]. So when an already-logged-in user opened "Add another account" and chose any login method, the new account silently landed at the back of the queue while the prior account remained current. Most damaging on the signup path: login.nsec(nsec) was called before the profile step, then publishEvent({ kind: 0, ... }) signed kind 0 metadata with the *previous* user's signer — overwriting their profile. - useLoginActions: wrap each addLogin in addAndActivate, which also calls setLogin(login.id) to promote the new login to logins[0]. - AuthDialog.finishSignup: defensive guard that verifies the active signer matches the just-generated nsec before publishing kind 0; refuse and toast otherwise. Belt and suspenders against any future regression in the switch logic. - Add a targeted regression test for the auto-switch behavior. --- src/components/auth/AuthDialog.tsx | 28 +++++++++++++++++ src/hooks/useLoginActions.test.tsx | 50 ++++++++++++++++++++++++++++++ src/hooks/useLoginActions.ts | 21 ++++++++++--- 3 files changed, 94 insertions(+), 5 deletions(-) create mode 100644 src/hooks/useLoginActions.test.tsx diff --git a/src/components/auth/AuthDialog.tsx b/src/components/auth/AuthDialog.tsx index 497f27b..4d1c4ed 100644 --- a/src/components/auth/AuthDialog.tsx +++ b/src/components/auth/AuthDialog.tsx @@ -32,6 +32,7 @@ import { import { useNostrPublish } from '@/hooks/useNostrPublish'; import { useUploadFile } from '@/hooks/useUploadFile'; import { useIsMobile } from '@/hooks/useIsMobile'; +import { useCurrentUser } from '@/hooks/useCurrentUser'; import { generateSecretKey, getPublicKey, nip19 } from 'nostr-tools'; interface AuthDialogProps { @@ -132,6 +133,7 @@ const AuthDialog: React.FC = ({ isOpen, onClose }) => { const { mutateAsync: publishEvent, isPending: isPublishing } = useNostrPublish(); const { mutateAsync: uploadFile, isPending: isUploading } = useUploadFile(); + const { user: currentUser } = useCurrentUser(); const avatarFileInputRef = useRef(null); const fileInputRef = useRef(null); const abortControllerRef = useRef(null); @@ -377,6 +379,32 @@ const AuthDialog: React.FC = ({ isOpen, onClose }) => { const finishSignup = async (skipProfile = false) => { try { if (!skipProfile && (profileData.name || profileData.about || profileData.picture)) { + // Defensive guard: only publish kind 0 if the current signer is + // the freshly generated key. If the auto-switch ever fails (e.g. + // a regression in useLoginActions), publishing here would sign + // with the *previous* user's signer and overwrite their kind 0 + // metadata — destroying their profile. Refuse rather than risk + // it. + let expectedPubkey: string | null = null; + try { + const decoded = nip19.decode(nsec); + if (decoded.type === 'nsec') { + expectedPubkey = getPublicKey(decoded.data); + } + } catch { + // fall through to the mismatch branch below + } + + if (!expectedPubkey || currentUser?.pubkey !== expectedPubkey) { + toast({ + title: 'Profile not saved', + description: + 'The new account is not active yet, so your profile was not published (this prevents overwriting another account). Try again from your profile settings.', + variant: 'destructive', + }); + return; + } + const metadata: Record = {}; if (profileData.name) metadata.name = profileData.name; if (profileData.about) metadata.about = profileData.about; diff --git a/src/hooks/useLoginActions.test.tsx b/src/hooks/useLoginActions.test.tsx new file mode 100644 index 0000000..9893230 --- /dev/null +++ b/src/hooks/useLoginActions.test.tsx @@ -0,0 +1,50 @@ +import { describe, it, expect } from 'vitest'; +import { act, renderHook, waitFor } from '@testing-library/react'; +import { generateSecretKey, nip19, getPublicKey } from 'nostr-tools'; +import { useNostrLogin } from '@nostrify/react/login'; + +import { TestApp } from '@/test/TestApp'; +import { useLoginActions } from './useLoginActions'; + +/** + * Regression test: adding a second login while one is already logged in + * must switch the current user to the new login (logins[0]). Without the + * fix, addLogin appends the new login to the end of the array and + * logins[0] remains the previously-logged-in user — leading to the + * destructive bug where the signup profile step signs kind 0 metadata + * with the *original* user's signer, overwriting their profile. + */ +describe('useLoginActions auto-switch', () => { + it('promotes the newly added nsec login to logins[0]', async () => { + const nsec1 = nip19.nsecEncode(generateSecretKey()); + const sk2 = generateSecretKey(); + const nsec2 = nip19.nsecEncode(sk2); + const pubkey2 = getPublicKey(sk2); + + const { result } = renderHook( + () => ({ + actions: useLoginActions(), + login: useNostrLogin(), + }), + { wrapper: TestApp }, + ); + + // NostrLoginProvider renders null while it reads logins from storage, + // so wait for the provider to mount. + await waitFor(() => expect(result.current).not.toBeNull()); + + act(() => { + result.current.actions.nsec(nsec1); + }); + + expect(result.current.login.logins).toHaveLength(1); + + act(() => { + result.current.actions.nsec(nsec2); + }); + + expect(result.current.login.logins).toHaveLength(2); + // The newly added login MUST be at index 0 (current user). + expect(result.current.login.logins[0].pubkey).toBe(pubkey2); + }); +}); diff --git a/src/hooks/useLoginActions.ts b/src/hooks/useLoginActions.ts index f4ebcab..ec1660f 100644 --- a/src/hooks/useLoginActions.ts +++ b/src/hooks/useLoginActions.ts @@ -1,6 +1,7 @@ import { useNostr } from '@nostrify/react'; import { NLogin, + type NLoginType, type NostrConnectParams, type NostrConnectStatus, useNostrLogin, @@ -15,24 +16,34 @@ export { generateNostrConnectParams, generateNostrConnectURI } from '@nostrify/r export function useLoginActions() { const { nostr } = useNostr(); - const { logins, addLogin, removeLogin } = useNostrLogin(); + const { logins, addLogin, setLogin, removeLogin } = useNostrLogin(); const { config } = useAppContext(); + // Add a login and promote it to be the current user. Without the + // setLogin call the new login is appended to the end of the array, + // leaving the prior account as logins[0] — which is what + // useCurrentUser / useLoggedInAccounts treat as the active user. + // Promoting here makes "Add another account" actually switch. + const addAndActivate = (login: NLoginType) => { + addLogin(login); + setLogin(login.id); + }; + return { // Login with a Nostr secret key nsec(nsec: string): void { const login = NLogin.fromNsec(nsec); - addLogin(login); + addAndActivate(login); }, // Login with a NIP-46 "bunker://" URI async bunker(uri: string): Promise { const login = await NLogin.fromBunker(uri, nostr); - addLogin(login); + addAndActivate(login); }, // Login with a NIP-07 browser extension async extension(): Promise { const login = await NLogin.fromExtension(); - addLogin(login); + addAndActivate(login); }, // Login via nostrconnect:// (client-initiated NIP-46) // The client displays a QR code and waits for the remote signer to connect. @@ -45,7 +56,7 @@ export function useLoginActions() { onStatus?: (status: NostrConnectStatus) => void, ): Promise { const login = await NLogin.fromNostrConnect(params, nostr, { signal, onStatus }); - addLogin(login); + addAndActivate(login); }, // Get the relay URLs for NIP-46 nostrconnect communication getRelayUrls(): string[] {