diff --git a/src/components/auth/AuthDialog.tsx b/src/components/auth/AuthDialog.tsx index 81f1abd..54eb5d0 100644 --- a/src/components/auth/AuthDialog.tsx +++ b/src/components/auth/AuthDialog.tsx @@ -5,9 +5,8 @@ import { Eye, EyeOff, Key, - ChevronDown, - ChevronUp, Loader2, + FileUp, ExternalLink, } from 'lucide-react'; import { Button } from '@/components/ui/button'; @@ -15,12 +14,11 @@ 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'; + DropdownMenu, + DropdownMenuContent, + DropdownMenuItem, + DropdownMenuTrigger, +} from '@/components/ui/dropdown-menu'; import { toast } from '@/hooks/useToast'; import { useLoginActions, @@ -31,7 +29,6 @@ import { } from '@/hooks/useLoginActions'; 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'; @@ -40,7 +37,7 @@ interface AuthDialogProps { onClose: () => void; } -type Step = 'welcome' | 'generate' | 'secure' | 'profile' | 'login' | 'connect'; +type Step = 'welcome' | 'generate' | 'secure' | 'profile' | 'login'; const validateNsec = (nsec: string) => /^nsec1[a-zA-Z0-9]{58}$/.test(nsec); const validateBunkerUri = (uri: string) => uri.startsWith('bunker://'); @@ -91,30 +88,22 @@ const AuthDialog: React.FC = ({ isOpen, onClose }) => { const [isGenerating, setIsGenerating] = useState(false); const [profileData, setProfileData] = useState({ name: '', about: '', picture: '' }); - // Login state - const [loginNsec, setLoginNsec] = useState(''); + // Login state — single input accepting either an nsec or a bunker URI. + const [loginInput, setLoginInput] = useState(''); const [isLoggingIn, setIsLoggingIn] = useState(false); const [loginError, setLoginError] = useState(''); - const [showMoreOptions, setShowMoreOptions] = useState(false); - // Nostrconnect / bunker state + // Nostrconnect ("Open signer app") state. No QR code is shown — the URI is + // launched directly on the device and the app listens for the handshake. const [nostrConnectParams, setNostrConnectParams] = useState(null); const [nostrConnectUri, setNostrConnectUri] = useState(''); const [connectError, setConnectError] = useState(null); // Progress status for the nostrconnect handshake. `null` means the user - // hasn't kicked off the handshake yet (or they canceled) — we show the QR - // / "Open signer app" button. Once the handshake advances we swap in a - // spinner with a live status line so the user knows something is working. + // hasn't launched the signer yet (or they canceled). const [connectStatus, setConnectStatus] = useState(null); - // Tracks whether the user has explicitly initiated the handshake from the - // mobile UI. The listen subscription itself starts the moment params are - // generated — without this flag we'd flip into the progress view as soon - // as the user enters the Remote Signer step, before they've done anything. - // Desktop doesn't need this: it stays on the QR until the handshake - // advances past `awaiting-connect`. + // Whether the user has launched the signer app. Until then we show the + // login form; once launched we swap in the progress view. const [hasOpenedSigner, setHasOpenedSigner] = useState(false); - const [showBunkerInput, setShowBunkerInput] = useState(false); - const [bunkerUri, setBunkerUri] = useState(''); const login = useLoginActions(); // Stable refs so the nostrconnect listening effect below doesn't restart on @@ -137,9 +126,6 @@ const AuthDialog: React.FC = ({ isOpen, onClose }) => { 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. // This is the "reset state when a prop changes" pattern; the usual @@ -151,28 +137,26 @@ const AuthDialog: React.FC = ({ isOpen, onClose }) => { /* eslint-disable react-hooks/set-state-in-effect */ setStep('welcome'); setNsec(''); - setLoginNsec(''); + setLoginInput(''); setShowKey(false); setIsGenerating(false); setIsLoggingIn(false); setLoginError(''); - setShowMoreOptions(false); setProfileData({ name: '', about: '', picture: '' }); setNostrConnectParams(null); setNostrConnectUri(''); setConnectError(null); setConnectStatus(null); setHasOpenedSigner(false); - setShowBunkerInput(false); - setBunkerUri(''); /* eslint-enable react-hooks/set-state-in-effect */ abortControllerRef.current?.abort(); abortControllerRef.current = null; } }, [isOpen]); - // Generate a nostrconnect session (QR code data). - const generateConnectSession = useCallback(() => { + // Generate a nostrconnect session and return its URI. The listening effect + // (keyed on the params) handles the handshake once params are set. + const generateConnectSession = useCallback((): string => { const relayUrls = login.getRelayUrls(); const params = generateNostrConnectParams(relayUrls); const uri = generateNostrConnectURI(params, { @@ -181,6 +165,7 @@ const AuthDialog: React.FC = ({ isOpen, onClose }) => { setNostrConnectParams(params); setNostrConnectUri(uri); setConnectError(null); + return uri; }, [login]); // Start listening for a nostrconnect response once params are set. @@ -240,36 +225,17 @@ const AuthDialog: React.FC = ({ isOpen, onClose }) => { setConnectError(null); setConnectStatus(null); setHasOpenedSigner(false); - setTimeout(() => generateConnectSession(), 0); - }, [generateConnectSession]); + }, []); + // Launch a remote signer app via nostrconnect. Generates the session (if + // needed) and navigates to the URI; the listening effect handles the + // handshake. No QR code is shown. const handleOpenSignerApp = () => { - if (!nostrConnectUri) return; - // Flip into the progress view *synchronously* before navigating so that - // when the user returns from the signer app, the dialog is already - // showing "Waiting for signer connection…" — not the original button - // they're worried they need to re-tap. + setLoginError(''); setHasOpenedSigner(true); - 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(); + const uri = nostrConnectUri || generateConnectSession(); + if (uri) { + window.location.href = uri; } }; @@ -299,14 +265,29 @@ const AuthDialog: React.FC = ({ isOpen, onClose }) => { } }; - // Login: submit the entered nsec. + // Login: submit the entered value — either an nsec or a bunker:// URI. const handleLogin = () => { - if (!loginNsec.trim()) { - setLoginError('Enter your secret key.'); + const value = loginInput.trim(); + if (!value) { + setLoginError('Enter your secret key or bunker URI.'); return; } - if (!validateNsec(loginNsec)) { - setLoginError('Invalid secret key. Must start with nsec1.'); + + if (validateBunkerUri(value)) { + setIsLoggingIn(true); + setLoginError(''); + login + .bunker(value) + .then(() => onClose()) + .catch(() => { + setLoginError('Failed to connect. Check the bunker URI.'); + setIsLoggingIn(false); + }); + return; + } + + if (!validateNsec(value)) { + setLoginError('Enter a valid nsec1… key or bunker://… URI.'); return; } @@ -315,7 +296,7 @@ const AuthDialog: React.FC = ({ isOpen, onClose }) => { // Timeout gives the UI a chance to repaint before the synchronous login. setTimeout(() => { try { - login.nsec(loginNsec); + login.nsec(value); onClose(); } catch { setLoginError("Couldn't log in with this key."); @@ -327,12 +308,14 @@ const AuthDialog: React.FC = ({ isOpen, onClose }) => { const handleFileUpload = (e: React.ChangeEvent) => { const file = e.target.files?.[0]; if (!file) return; + e.target.value = ''; const reader = new FileReader(); reader.onload = (event) => { const content = event.target?.result as string; if (content && validateNsec(content.trim())) { - setLoginNsec(content.trim()); + setLoginInput(content.trim()); + setLoginError(''); } else { setLoginError('File does not contain a valid secret key.'); } @@ -341,18 +324,6 @@ const AuthDialog: React.FC = ({ isOpen, onClose }) => { 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; @@ -434,22 +405,12 @@ const AuthDialog: React.FC = ({ isOpen, onClose }) => { return 'Your profile'; case 'login': return 'Log in'; - case 'connect': - return 'Connect signer'; } }; - // Decide whether to render the progress view in place of the QR/button. - // Mobile: flip in as soon as the user taps "Open signer app" (tracked by - // `hasOpenedSigner`) so they see feedback the moment they return from the - // signer. Desktop: keep the QR visible through the `awaiting-connect` - // phase (it's still actionable — they might scan with another device) and - // only swap in once the signer has acknowledged and we're fetching the - // pubkey. - const showProgressView = connectStatus !== null && ( - connectStatus === 'getting-public-key' || - (isMobile && hasOpenedSigner) - ); + // Once the user launches the signer app we replace the login form with a + // progress view so they see feedback while the handshake completes. + const showProgressView = hasOpenedSigner; return ( @@ -468,18 +429,14 @@ const AuthDialog: React.FC = ({ isOpen, onClose }) => { 🔑 -

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

-
- @@ -514,7 +471,7 @@ const AuthDialog: React.FC = ({ isOpen, onClose }) => {
{!isGenerating && ( - )} @@ -567,7 +524,7 @@ const AuthDialog: React.FC = ({ isOpen, onClose }) => {

- @@ -655,7 +612,7 @@ const AuthDialog: React.FC = ({ isOpen, onClose }) => { @@ -663,7 +620,7 @@ const AuthDialog: React.FC = ({ isOpen, onClose }) => { variant="ghost" onClick={() => finishSignup(true)} disabled={isPublishing} - className="w-full" + className="w-full rounded-full" > Skip for now @@ -674,170 +631,49 @@ const AuthDialog: React.FC = ({ isOpen, onClose }) => { {/* Login step. */} {step === 'login' && (
- {hasExtension ? ( - <> - - - - - - - Use secret key - - - - - - - + Cancel + +
) : ( - <> - - - + )} - - - )} - - {/* Connect step — nostrconnect QR + bunker URI fallback. */} - {step === 'connect' && ( -
-
- {connectError ? ( -
-

{connectError}

- -
- ) : showProgressView ? ( - // Progress view — replaces the QR/button once the handshake - // is under way. Gives the user live feedback through each - // phase so a stuck signer is visibly stuck, not silently - // stuck. -
- -

- {connectStatusLabel(connectStatus)} -

- -
- ) : nostrConnectUri ? ( - <> - {!isMobile && ( -
- -
- )} - - {isMobile && ( - - )} - - ) : ( -
- -
- )} -
- - {/* Manual bunker URI fallback. */} - - - Enter bunker URI manually - {showBunkerInput ? ( - - ) : ( - - )} - - - setBunkerUri(e.target.value)} - placeholder="bunker://…" - className="text-base md:text-sm" - /> - {bunkerUri && !validateBunkerUri(bunkerUri) && ( - - Invalid bunker URI format. - - )} - - - - - + {!connectError && !showProgressView && ( + + )}
)} @@ -846,26 +682,28 @@ const AuthDialog: React.FC = ({ isOpen, onClose }) => { ); }; -/** Shared nsec input + submit + file-upload block used in the login step. */ +/** Shared login input (nsec or bunker URI) + submit + actions dropdown. */ interface NsecLoginFormProps { - loginNsec: string; - setLoginNsec: (v: string) => void; + loginInput: string; + setLoginInput: (v: string) => void; loginError: string; setLoginError: (v: string) => void; isLoggingIn: boolean; onSubmit: () => void; onFileChange: (e: React.ChangeEvent) => void; + onOpenSignerApp: () => void; fileInputRef: React.RefObject; } const NsecLoginForm: React.FC = ({ - loginNsec, - setLoginNsec, + loginInput, + setLoginInput, loginError, setLoginError, isLoggingIn, onSubmit, onFileChange, + onOpenSignerApp, fileInputRef, }) => (
= ({ }} className="space-y-3" > - { - setLoginNsec(e.target.value); - if (loginError) setLoginError(''); - }} - placeholder="nsec1…" - autoComplete="off" - className={loginError ? 'border-destructive focus-visible:ring-destructive' : ''} - /> - {loginError &&

{loginError}

} - -
- +
+ { + setLoginInput(e.target.value); + if (loginError) setLoginError(''); + }} + placeholder="nsec1… or bunker://…" + autoComplete="off" + className={`pr-10 ${ + loginError ? 'border-destructive focus-visible:ring-destructive' : '' + }`} + /> = ({ ref={fileInputRef} onChange={onFileChange} /> - + + + + + + fileInputRef.current?.click()}> + + Select key file + + + + Open signer app + + +
+ {loginError &&

{loginError}

} + + ); diff --git a/src/components/auth/LoginArea.tsx b/src/components/auth/LoginArea.tsx index cb401a9..00f0bd8 100644 --- a/src/components/auth/LoginArea.tsx +++ b/src/components/auth/LoginArea.tsx @@ -1,10 +1,28 @@ import { useState } from 'react'; import { Button } from '@/components/ui/button.tsx'; import AuthDialog from './AuthDialog'; +import { QuickLoginDialog } from './QuickLoginDialog'; import { useLoggedInAccounts } from '@/hooks/useLoggedInAccounts'; import { AccountSwitcher } from './AccountSwitcher'; import { cn } from '@/lib/utils'; +/** Minimal shape of the NIP-07 provider injected at `window.nostr`. */ +interface Nip07Provider { + getPublicKey(): Promise; +} + +function getNip07Provider(): Nip07Provider | undefined { + if (typeof window === 'undefined' || !('nostr' in window)) return undefined; + const provider = (window as { nostr?: unknown }).nostr; + if ( + provider && + typeof (provider as Nip07Provider).getPublicKey === 'function' + ) { + return provider as Nip07Provider; + } + return undefined; +} + export interface LoginAreaProps { className?: string; } @@ -12,6 +30,23 @@ export interface LoginAreaProps { export function LoginArea({ className }: LoginAreaProps) { const { currentUser } = useLoggedInAccounts(); const [authDialogOpen, setAuthDialogOpen] = useState(false); + const [quickLoginPubkey, setQuickLoginPubkey] = useState(null); + + const handleJoin = async () => { + const provider = getNip07Provider(); + if (provider) { + try { + const pubkey = await provider.getPublicKey(); + if (pubkey) { + setQuickLoginPubkey(pubkey); + return; + } + } catch { + // Extension declined or errored — fall through to the full dialog. + } + } + setAuthDialogOpen(true); + }; return (
@@ -19,13 +54,25 @@ export function LoginArea({ className }: LoginAreaProps) { setAuthDialogOpen(true)} /> ) : ( )} + {quickLoginPubkey && ( + setQuickLoginPubkey(null)} + onOtherLogin={() => { + setQuickLoginPubkey(null); + setAuthDialogOpen(true); + }} + /> + )} + setAuthDialogOpen(false)} diff --git a/src/components/auth/QuickLoginDialog.tsx b/src/components/auth/QuickLoginDialog.tsx new file mode 100644 index 0000000..4b8bb0b --- /dev/null +++ b/src/components/auth/QuickLoginDialog.tsx @@ -0,0 +1,130 @@ +import { useState } from 'react'; +import { Loader2 } from 'lucide-react'; +import { nip19 } from 'nostr-tools'; +import { Button } from '@/components/ui/button'; +import { + Dialog, + DialogContent, + DialogHeader, + DialogTitle, +} from '@/components/ui/dialog'; +import { Avatar, AvatarFallback, AvatarImage } from '@/components/ui/avatar'; +import { Skeleton } from '@/components/ui/skeleton'; +import { useAuthor } from '@/hooks/useAuthor'; +import { useLoginActions } from '@/hooks/useLoginActions'; + +interface QuickLoginDialogProps { + /** Whether the dialog is open. */ + isOpen: boolean; + /** The pubkey (hex) detected from the NIP-07 extension. */ + pubkey: string; + /** Close the dialog. */ + onClose: () => void; + /** Continue to the full login dialog ("Other login"). */ + onOtherLogin: () => void; +} + +/** + * Confirmation dialog shown when a NIP-07 extension is present and exposes a + * public key. Displays the detected account's profile and a one-tap "Log in" + * button, with a smaller "Other login" escape hatch to the full AuthDialog. + */ +export function QuickLoginDialog({ + isOpen, + pubkey, + onClose, + onOtherLogin, +}: QuickLoginDialogProps) { + const author = useAuthor(pubkey); + const login = useLoginActions(); + const [isLoggingIn, setIsLoggingIn] = useState(false); + const [error, setError] = useState(''); + + const metadata = author.data?.metadata; + const displayName = + metadata?.display_name || metadata?.name || genericName(pubkey); + const picture = metadata?.picture; + + const handleLogin = async () => { + setIsLoggingIn(true); + setError(''); + try { + await login.extension(); + onClose(); + } catch (e) { + setError(e instanceof Error ? e.message : 'Login failed.'); + setIsLoggingIn(false); + } + }; + + return ( + !open && onClose()}> + + + Welcome back + + +
+ {author.isLoading ? ( + <> + + + + ) : ( + <> + + + + {displayName.slice(0, 2).toUpperCase()} + + +

{displayName}

+ + )} +
+ + {error && ( +

+ {error} +

+ )} + +
+ + +
+
+
+ ); +} + +/** Fallback display name derived from the npub when no metadata is available. */ +function genericName(pubkey: string): string { + try { + const npub = nip19.npubEncode(pubkey); + return `${npub.slice(0, 10)}…${npub.slice(-4)}`; + } catch { + return 'Nostr user'; + } +}