From fc34ae02d45ec532460115549a5872a8ae8360cf Mon Sep 17 00:00:00 2001 From: Alex Gleason Date: Sun, 26 Apr 2026 20:16:14 -0500 Subject: [PATCH] Unify login/signup into single AuthDialog with 'Join' button LoginArea now shows a single 'Join' button instead of separate 'Log in' and 'Sign Up' buttons. The button opens a unified AuthDialog ported from espy with steps: welcome \u2192 generate \u2192 secure \u2192 profile \u2192 login \u2192 connect. The welcome step lets the user choose 'Create new account' or 'I already have an account', so no functionality is lost \u2014 extension login, nostrconnect QR flow, bunker URI, and secret-key file upload are all preserved. Styling uses the template's neutral shadcn look rather than espy's gradients, and copy is generic (no product branding). Deletes LoginDialog.tsx and SignupDialog.tsx; updates AGENTS.md to describe the new single-button behavior. --- AGENTS.md | 6 +- src/components/auth/AuthDialog.tsx | 832 +++++++++++++++++++++++++++ src/components/auth/LoginArea.tsx | 52 +- src/components/auth/LoginDialog.tsx | 511 ---------------- src/components/auth/SignupDialog.tsx | 361 ------------ 5 files changed, 849 insertions(+), 913 deletions(-) create mode 100644 src/components/auth/AuthDialog.tsx delete mode 100644 src/components/auth/LoginDialog.tsx delete mode 100644 src/components/auth/SignupDialog.tsx diff --git a/AGENTS.md b/AGENTS.md index 20c625f..4453735 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -17,7 +17,7 @@ This project is a Nostr client application built with React 19.x, TailwindCSS 3. - `/src/components/`: UI components including NostrProvider for Nostr integration - `/src/components/ui/`: shadcn/ui components (48+ components available) - - `/src/components/auth/`: Authentication-related components (LoginArea, LoginDialog, etc.) + - `/src/components/auth/`: Authentication-related components (LoginArea, AuthDialog, AccountSwitcher) - `/src/hooks/`: Custom hooks including: - `useNostr`: Core Nostr protocol integration - `useAuthor`: Fetch user profile data by pubkey @@ -663,9 +663,9 @@ function MyComponent() { } ``` -The `LoginArea` component handles all the login-related UI and interactions, including displaying login dialogs, sign up functionality, and switching between accounts. It should not be wrapped in any conditional logic. +The `LoginArea` component handles all the login-related UI and interactions, including displaying the unified auth dialog (signup, login with extension/nsec/remote signer) and switching between accounts. It should not be wrapped in any conditional logic. -`LoginArea` displays both "Log in" and "Sign Up" buttons when the user is logged out, and changes to an account switcher once the user is logged in. It is an inline-flex element by default. To make it expand to the width of its container, you can pass a className like `flex` (to make it a block element) or `w-full`. If it is left as inline-flex, it's recommended to set a max width. +`LoginArea` displays a single "Join" button when the user is logged out, and changes to an account switcher once the user is logged in. The "Join" button opens an `AuthDialog` that lets the user either create a new account or log in with an existing one. It is an inline-flex element by default. To make it expand to the width of its container, you can pass a className like `flex` (to make it a block element) or `w-full`. If it is left as inline-flex, it's recommended to set a max width. **Important**: Social applications should include a profile menu button in the main interface (typically in headers/navigation) to provide access to account settings, profile editing, and logout functionality. Don't only show `LoginArea` in logged-out states. diff --git a/src/components/auth/AuthDialog.tsx b/src/components/auth/AuthDialog.tsx new file mode 100644 index 0000000..c337296 --- /dev/null +++ b/src/components/auth/AuthDialog.tsx @@ -0,0 +1,832 @@ +import React, { useState, useEffect, useRef, useCallback } from 'react'; +import { + Download, + Upload, + Eye, + EyeOff, + Key, + Copy, + Check, + ChevronDown, + ChevronUp, + Loader2, + ExternalLink, +} from 'lucide-react'; +import { Button } from '@/components/ui/button'; +import { Input } from '@/components/ui/input'; +import { Textarea } from '@/components/ui/textarea'; +import { Dialog, DialogContent, DialogHeader, DialogTitle } from '@/components/ui/dialog'; +import { + Collapsible, + CollapsibleContent, + CollapsibleTrigger, +} from '@/components/ui/collapsible'; +import { Alert, AlertDescription } from '@/components/ui/alert'; +import { QRCodeCanvas } from '@/components/ui/qrcode'; +import { toast } from '@/hooks/useToast'; +import { + useLoginActions, + generateNostrConnectParams, + generateNostrConnectURI, + type NostrConnectParams, +} from '@/hooks/useLoginActions'; +import { useNostrPublish } from '@/hooks/useNostrPublish'; +import { useUploadFile } from '@/hooks/useUploadFile'; +import { useIsMobile } from '@/hooks/useIsMobile'; +import { generateSecretKey, getPublicKey, nip19 } from 'nostr-tools'; + +interface AuthDialogProps { + isOpen: boolean; + onClose: () => void; +} + +type Step = 'welcome' | 'generate' | 'secure' | 'profile' | 'login' | 'connect'; + +const validateNsec = (nsec: string) => /^nsec1[a-zA-Z0-9]{58}$/.test(nsec); +const validateBunkerUri = (uri: string) => uri.startsWith('bunker://'); + +/** Check if running on an actual mobile device (not just a small screen). */ +function isMobileDevice(): boolean { + if (typeof navigator === 'undefined') return false; + return /Android|iPhone|iPad|iPod/i.test(navigator.userAgent); +} + +/** Download an nsec to a text file — same behavior as the previous SignupDialog. */ +function downloadNsecFile(nsec: string) { + const decoded = nip19.decode(nsec); + if (decoded.type !== 'nsec') throw new Error('Invalid nsec key'); + const pubkey = getPublicKey(decoded.data); + const npub = nip19.npubEncode(pubkey); + const filename = `nostr-${location.hostname.replaceAll(/\./g, '-')}-${npub.slice(5, 9)}.nsec.txt`; + + const blob = new Blob([nsec], { type: 'text/plain; charset=utf-8' }); + const url = globalThis.URL.createObjectURL(blob); + const a = document.createElement('a'); + a.href = url; + a.download = filename; + a.style.display = 'none'; + document.body.appendChild(a); + a.click(); + globalThis.URL.revokeObjectURL(url); + document.body.removeChild(a); +} + +const AuthDialog: React.FC = ({ isOpen, onClose }) => { + const [step, setStep] = useState('welcome'); + + // Signup state + const [nsec, setNsec] = useState(''); + const [showKey, setShowKey] = useState(false); + const [isGenerating, setIsGenerating] = useState(false); + const [profileData, setProfileData] = useState({ name: '', about: '', picture: '' }); + + // Login state + const [loginNsec, setLoginNsec] = useState(''); + const [isLoggingIn, setIsLoggingIn] = useState(false); + const [loginError, setLoginError] = useState(''); + const [showMoreOptions, setShowMoreOptions] = useState(false); + + // Nostrconnect / bunker state + const [nostrConnectParams, setNostrConnectParams] = useState(null); + const [nostrConnectUri, setNostrConnectUri] = useState(''); + const [isWaitingForConnect, setIsWaitingForConnect] = useState(false); + const [connectError, setConnectError] = useState(null); + const [uriCopied, setUriCopied] = useState(false); + const [showBunkerInput, setShowBunkerInput] = useState(false); + const [bunkerUri, setBunkerUri] = useState(''); + + const login = useLoginActions(); + // Stable ref so the nostrconnect effect doesn't restart on every render. + const loginRef = useRef(login); + loginRef.current = login; + + const { mutateAsync: publishEvent, isPending: isPublishing } = useNostrPublish(); + const { mutateAsync: uploadFile, isPending: isUploading } = useUploadFile(); + const avatarFileInputRef = useRef(null); + const fileInputRef = useRef(null); + const abortControllerRef = useRef(null); + const isMobile = useIsMobile(); + + const hasExtension = typeof window !== 'undefined' && 'nostr' in window; + + // Reset state when the dialog closes. + useEffect(() => { + if (!isOpen) { + setStep('welcome'); + setNsec(''); + setLoginNsec(''); + setShowKey(false); + setIsGenerating(false); + setIsLoggingIn(false); + setLoginError(''); + setShowMoreOptions(false); + setProfileData({ name: '', about: '', picture: '' }); + setNostrConnectParams(null); + setNostrConnectUri(''); + setIsWaitingForConnect(false); + setConnectError(null); + setUriCopied(false); + setShowBunkerInput(false); + setBunkerUri(''); + abortControllerRef.current?.abort(); + abortControllerRef.current = null; + } + }, [isOpen]); + + // Generate a nostrconnect session (QR code data). + const generateConnectSession = useCallback(() => { + const relayUrls = login.getRelayUrls(); + const params = generateNostrConnectParams(relayUrls); + const uri = generateNostrConnectURI(params, { + callback: isMobileDevice() ? `${window.location.origin}/remoteloginsuccess` : undefined, + }); + setNostrConnectParams(params); + setNostrConnectUri(uri); + setConnectError(null); + }, [login]); + + // Start listening for a nostrconnect response once params are set. + useEffect(() => { + if (!nostrConnectParams || isWaitingForConnect) return; + + let cancelled = false; + + const startListening = async () => { + setIsWaitingForConnect(true); + abortControllerRef.current = new AbortController(); + + try { + await loginRef.current.nostrconnect( + nostrConnectParams, + abortControllerRef.current.signal, + ); + if (!cancelled) onClose(); + } catch (error) { + if (cancelled) return; + if (error instanceof Error && error.name === 'AbortError') return; + console.error('Nostrconnect failed:', error); + setConnectError(error instanceof Error ? error.message : String(error)); + setIsWaitingForConnect(false); + } + }; + + startListening(); + + return () => { + cancelled = true; + }; + // NOTE: isWaitingForConnect is intentionally excluded from deps. Including + // it would cancel the first run the moment it sets the flag to true and + // spawn a duplicate listener. + // eslint-disable-next-line react-hooks/exhaustive-deps + }, [nostrConnectParams, onClose]); + + const handleConnectRetry = useCallback(() => { + setNostrConnectParams(null); + setNostrConnectUri(''); + setIsWaitingForConnect(false); + setConnectError(null); + setTimeout(() => generateConnectSession(), 0); + }, [generateConnectSession]); + + const handleCopyUri = async () => { + await navigator.clipboard.writeText(nostrConnectUri); + setUriCopied(true); + setTimeout(() => setUriCopied(false), 2000); + }; + + const handleOpenSignerApp = () => { + if (!nostrConnectUri) return; + window.location.href = nostrConnectUri; + }; + + const handleBunkerLogin = async () => { + if (!bunkerUri.trim() || !validateBunkerUri(bunkerUri)) return; + + setIsLoggingIn(true); + try { + await login.bunker(bunkerUri); + onClose(); + } catch { + setConnectError('Failed to connect. Check the bunker URI.'); + setIsLoggingIn(false); + } + }; + + const goToConnect = () => { + setStep('connect'); + if (!nostrConnectParams && !connectError) { + generateConnectSession(); + } + }; + + // Signup: generate a key with a brief spinner for feedback. + const generateKey = () => { + setIsGenerating(true); + setTimeout(() => { + const sk = generateSecretKey(); + setNsec(nip19.nsecEncode(sk)); + setStep('secure'); + setIsGenerating(false); + }, 750); + }; + + // Signup: download the nsec to a file and move on to the profile step. + const downloadAndProceed = () => { + try { + downloadNsecFile(nsec); + login.nsec(nsec); + setStep('profile'); + } catch { + toast({ + title: 'Download failed', + description: 'Could not download the key file. Please copy it manually.', + variant: 'destructive', + }); + } + }; + + // Login: submit the entered nsec. + const handleLogin = () => { + if (!loginNsec.trim()) { + setLoginError('Enter your secret key.'); + return; + } + if (!validateNsec(loginNsec)) { + setLoginError('Invalid secret key. Must start with nsec1.'); + return; + } + + setIsLoggingIn(true); + setLoginError(''); + // Timeout gives the UI a chance to repaint before the synchronous login. + setTimeout(() => { + try { + login.nsec(loginNsec); + onClose(); + } catch { + setLoginError("Couldn't log in with this key."); + setIsLoggingIn(false); + } + }, 50); + }; + + const handleFileUpload = (e: React.ChangeEvent) => { + const file = e.target.files?.[0]; + if (!file) return; + + const reader = new FileReader(); + reader.onload = (event) => { + const content = event.target?.result as string; + if (content && validateNsec(content.trim())) { + setLoginNsec(content.trim()); + } else { + setLoginError('File does not contain a valid secret key.'); + } + }; + reader.onerror = () => setLoginError('Failed to read file.'); + reader.readAsText(file); + }; + + const handleExtensionLogin = async () => { + if (!hasExtension) return; + setIsLoggingIn(true); + try { + await login.extension(); + onClose(); + } catch (e) { + setLoginError(e instanceof Error ? e.message : 'Extension login failed.'); + setIsLoggingIn(false); + } + }; + + const handleAvatarUpload = async (e: React.ChangeEvent) => { + const file = e.target.files?.[0]; + if (!file) return; + e.target.value = ''; + + if (!file.type.startsWith('image/')) { + toast({ title: 'Please select an image.', variant: 'destructive' }); + return; + } + if (file.size > 5 * 1024 * 1024) { + toast({ title: 'Image too large (max 5MB).', variant: 'destructive' }); + return; + } + + try { + const tags = await uploadFile(file); + const url = tags[0]?.[1]; + if (url) setProfileData((prev) => ({ ...prev, picture: url })); + } catch { + toast({ title: 'Upload failed.', variant: 'destructive' }); + } + }; + + const finishSignup = async (skipProfile = false) => { + try { + if (!skipProfile && (profileData.name || profileData.about || profileData.picture)) { + const metadata: Record = {}; + if (profileData.name) metadata.name = profileData.name; + if (profileData.about) metadata.about = profileData.about; + if (profileData.picture) metadata.picture = profileData.picture; + await publishEvent({ kind: 0, content: JSON.stringify(metadata) }); + } + } catch { + toast({ + title: 'Profile setup failed', + description: 'Your account was created but the profile could not be saved. You can update it later.', + variant: 'destructive', + }); + } finally { + onClose(); + } + }; + + const getTitle = () => { + switch (step) { + case 'welcome': + return 'Welcome'; + case 'generate': + return 'Create account'; + case 'secure': + return 'Save your key'; + case 'profile': + return 'Your profile'; + case 'login': + return 'Log in'; + case 'connect': + return 'Connect signer'; + } + }; + + return ( + + + + + {getTitle()} + + + +
+ {/* Welcome step — the unified entry point. */} + {step === 'welcome' && ( +
+
+ 🔑 +
+ +

+ Join with a new Nostr account, or log in with one you already have. +

+ +
+ + +
+
+ )} + + {/* Generate step. */} + {step === 'generate' && ( +
+
+ {isGenerating ? ( +
+ +
+ ) : ( +
+ +
+ )} +
+ +
+

+ {isGenerating ? 'Creating your key…' : 'Your key is your identity'} +

+

+ {isGenerating + ? 'This only takes a moment.' + : "We'll generate a secret key just for you. Keep it safe — it's the only way to log in."} +

+
+ + {!isGenerating && ( + + )} + + +
+ )} + + {/* Secure step — show + download nsec. */} + {step === 'secure' && ( +
+
+ +
+ +

+ Store your key somewhere safe. You'll need it to log in again. +

+ +
+ + +
+ +
+

+ This key is your only way to access your account. If you lose it, you lose the account. +

+
+ + +
+ )} + + {/* Profile step — optional metadata. */} + {step === 'profile' && ( +
+

+ Tell others a bit about yourself (optional). +

+ +
+
+ + + setProfileData((prev) => ({ ...prev, name: e.target.value })) + } + placeholder="Your name" + /> +
+ +
+ +