Add NIP-07 quick login and redesign login dialog

This commit is contained in:
Alex Gleason committed 2026-06-23 22:06:10 +03:00
1 parent 9a9616be29
commit b50dbdb2dc
3 files changed
+330 -298

No files matched your search

+152 -297
View File
@@ -5,9 +5,8 @@ import {
Eye, Eye,
EyeOff, EyeOff,
Key, Key,
ChevronDown,
ChevronUp,
Loader2, Loader2,
FileUp,
ExternalLink, ExternalLink,
} from 'lucide-react'; } from 'lucide-react';
import { Button } from '@/components/ui/button'; import { Button } from '@/components/ui/button';
@@ -15,12 +14,11 @@ import { Input } from '@/components/ui/input';
import { Textarea } from '@/components/ui/textarea'; import { Textarea } from '@/components/ui/textarea';
import { Dialog, DialogContent, DialogHeader, DialogTitle } from '@/components/ui/dialog'; import { Dialog, DialogContent, DialogHeader, DialogTitle } from '@/components/ui/dialog';
import { import {
Collapsible, DropdownMenu,
CollapsibleContent, DropdownMenuContent,
CollapsibleTrigger, DropdownMenuItem,
} from '@/components/ui/collapsible'; DropdownMenuTrigger,
import { Alert, AlertDescription } from '@/components/ui/alert'; } from '@/components/ui/dropdown-menu';
import { QRCodeCanvas } from '@/components/ui/qrcode';
import { toast } from '@/hooks/useToast'; import { toast } from '@/hooks/useToast';
import { import {
useLoginActions, useLoginActions,
@@ -31,7 +29,6 @@ import {
} from '@/hooks/useLoginActions'; } from '@/hooks/useLoginActions';
import { useNostrPublish } from '@/hooks/useNostrPublish'; import { useNostrPublish } from '@/hooks/useNostrPublish';
import { useUploadFile } from '@/hooks/useUploadFile'; import { useUploadFile } from '@/hooks/useUploadFile';
import { useIsMobile } from '@/hooks/useIsMobile';
import { useCurrentUser } from '@/hooks/useCurrentUser'; import { useCurrentUser } from '@/hooks/useCurrentUser';
import { generateSecretKey, getPublicKey, nip19 } from 'nostr-tools'; import { generateSecretKey, getPublicKey, nip19 } from 'nostr-tools';
@@ -40,7 +37,7 @@ interface AuthDialogProps {
onClose: () => void; 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 validateNsec = (nsec: string) => /^nsec1[a-zA-Z0-9]{58}$/.test(nsec);
const validateBunkerUri = (uri: string) => uri.startsWith('bunker://'); const validateBunkerUri = (uri: string) => uri.startsWith('bunker://');
@@ -91,30 +88,22 @@ const AuthDialog: React.FC<AuthDialogProps> = ({ isOpen, onClose }) => {
const [isGenerating, setIsGenerating] = useState(false); const [isGenerating, setIsGenerating] = useState(false);
const [profileData, setProfileData] = useState({ name: '', about: '', picture: '' }); const [profileData, setProfileData] = useState({ name: '', about: '', picture: '' });
// Login state // Login state — single input accepting either an nsec or a bunker URI.
const [loginNsec, setLoginNsec] = useState(''); const [loginInput, setLoginInput] = useState('');
const [isLoggingIn, setIsLoggingIn] = useState(false); const [isLoggingIn, setIsLoggingIn] = useState(false);
const [loginError, setLoginError] = useState(''); 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<NostrConnectParams | null>(null); const [nostrConnectParams, setNostrConnectParams] = useState<NostrConnectParams | null>(null);
const [nostrConnectUri, setNostrConnectUri] = useState(''); const [nostrConnectUri, setNostrConnectUri] = useState('');
const [connectError, setConnectError] = useState<string | null>(null); const [connectError, setConnectError] = useState<string | null>(null);
// Progress status for the nostrconnect handshake. `null` means the user // Progress status for the nostrconnect handshake. `null` means the user
// hasn't kicked off the handshake yet (or they canceled) — we show the QR // hasn't launched the signer yet (or they canceled).
// / "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.
const [connectStatus, setConnectStatus] = useState<NostrConnectStatus | null>(null); const [connectStatus, setConnectStatus] = useState<NostrConnectStatus | null>(null);
// Tracks whether the user has explicitly initiated the handshake from the // Whether the user has launched the signer app. Until then we show the
// mobile UI. The listen subscription itself starts the moment params are // login form; once launched we swap in the progress view.
// 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`.
const [hasOpenedSigner, setHasOpenedSigner] = useState(false); const [hasOpenedSigner, setHasOpenedSigner] = useState(false);
const [showBunkerInput, setShowBunkerInput] = useState(false);
const [bunkerUri, setBunkerUri] = useState('');
const login = useLoginActions(); const login = useLoginActions();
// Stable refs so the nostrconnect listening effect below doesn't restart on // Stable refs so the nostrconnect listening effect below doesn't restart on
@@ -137,9 +126,6 @@ const AuthDialog: React.FC<AuthDialogProps> = ({ isOpen, onClose }) => {
const avatarFileInputRef = useRef<HTMLInputElement>(null); const avatarFileInputRef = useRef<HTMLInputElement>(null);
const fileInputRef = useRef<HTMLInputElement>(null); const fileInputRef = useRef<HTMLInputElement>(null);
const abortControllerRef = useRef<AbortController | null>(null); const abortControllerRef = useRef<AbortController | null>(null);
const isMobile = useIsMobile();
const hasExtension = typeof window !== 'undefined' && 'nostr' in window;
// Reset state when the dialog closes. // Reset state when the dialog closes.
// This is the "reset state when a prop changes" pattern; the usual // This is the "reset state when a prop changes" pattern; the usual
@@ -151,28 +137,26 @@ const AuthDialog: React.FC<AuthDialogProps> = ({ isOpen, onClose }) => {
/* eslint-disable react-hooks/set-state-in-effect */ /* eslint-disable react-hooks/set-state-in-effect */
setStep('welcome'); setStep('welcome');
setNsec(''); setNsec('');
setLoginNsec(''); setLoginInput('');
setShowKey(false); setShowKey(false);
setIsGenerating(false); setIsGenerating(false);
setIsLoggingIn(false); setIsLoggingIn(false);
setLoginError(''); setLoginError('');
setShowMoreOptions(false);
setProfileData({ name: '', about: '', picture: '' }); setProfileData({ name: '', about: '', picture: '' });
setNostrConnectParams(null); setNostrConnectParams(null);
setNostrConnectUri(''); setNostrConnectUri('');
setConnectError(null); setConnectError(null);
setConnectStatus(null); setConnectStatus(null);
setHasOpenedSigner(false); setHasOpenedSigner(false);
setShowBunkerInput(false);
setBunkerUri('');
/* eslint-enable react-hooks/set-state-in-effect */ /* eslint-enable react-hooks/set-state-in-effect */
abortControllerRef.current?.abort(); abortControllerRef.current?.abort();
abortControllerRef.current = null; abortControllerRef.current = null;
} }
}, [isOpen]); }, [isOpen]);
// Generate a nostrconnect session (QR code data). // Generate a nostrconnect session and return its URI. The listening effect
const generateConnectSession = useCallback(() => { // (keyed on the params) handles the handshake once params are set.
const generateConnectSession = useCallback((): string => {
const relayUrls = login.getRelayUrls(); const relayUrls = login.getRelayUrls();
const params = generateNostrConnectParams(relayUrls); const params = generateNostrConnectParams(relayUrls);
const uri = generateNostrConnectURI(params, { const uri = generateNostrConnectURI(params, {
@@ -181,6 +165,7 @@ const AuthDialog: React.FC<AuthDialogProps> = ({ isOpen, onClose }) => {
setNostrConnectParams(params); setNostrConnectParams(params);
setNostrConnectUri(uri); setNostrConnectUri(uri);
setConnectError(null); setConnectError(null);
return uri;
}, [login]); }, [login]);
// Start listening for a nostrconnect response once params are set. // Start listening for a nostrconnect response once params are set.
@@ -240,36 +225,17 @@ const AuthDialog: React.FC<AuthDialogProps> = ({ isOpen, onClose }) => {
setConnectError(null); setConnectError(null);
setConnectStatus(null); setConnectStatus(null);
setHasOpenedSigner(false); 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 = () => { const handleOpenSignerApp = () => {
if (!nostrConnectUri) return; setLoginError('');
// 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.
setHasOpenedSigner(true); setHasOpenedSigner(true);
window.location.href = nostrConnectUri; const uri = nostrConnectUri || generateConnectSession();
}; if (uri) {
window.location.href = uri;
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();
} }
}; };
@@ -299,14 +265,29 @@ const AuthDialog: React.FC<AuthDialogProps> = ({ isOpen, onClose }) => {
} }
}; };
// Login: submit the entered nsec. // Login: submit the entered value — either an nsec or a bunker:// URI.
const handleLogin = () => { const handleLogin = () => {
if (!loginNsec.trim()) { const value = loginInput.trim();
setLoginError('Enter your secret key.'); if (!value) {
setLoginError('Enter your secret key or bunker URI.');
return; 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; return;
} }
@@ -315,7 +296,7 @@ const AuthDialog: React.FC<AuthDialogProps> = ({ isOpen, onClose }) => {
// Timeout gives the UI a chance to repaint before the synchronous login. // Timeout gives the UI a chance to repaint before the synchronous login.
setTimeout(() => { setTimeout(() => {
try { try {
login.nsec(loginNsec); login.nsec(value);
onClose(); onClose();
} catch { } catch {
setLoginError("Couldn't log in with this key."); setLoginError("Couldn't log in with this key.");
@@ -327,12 +308,14 @@ const AuthDialog: React.FC<AuthDialogProps> = ({ isOpen, onClose }) => {
const handleFileUpload = (e: React.ChangeEvent<HTMLInputElement>) => { const handleFileUpload = (e: React.ChangeEvent<HTMLInputElement>) => {
const file = e.target.files?.[0]; const file = e.target.files?.[0];
if (!file) return; if (!file) return;
e.target.value = '';
const reader = new FileReader(); const reader = new FileReader();
reader.onload = (event) => { reader.onload = (event) => {
const content = event.target?.result as string; const content = event.target?.result as string;
if (content && validateNsec(content.trim())) { if (content && validateNsec(content.trim())) {
setLoginNsec(content.trim()); setLoginInput(content.trim());
setLoginError('');
} else { } else {
setLoginError('File does not contain a valid secret key.'); setLoginError('File does not contain a valid secret key.');
} }
@@ -341,18 +324,6 @@ const AuthDialog: React.FC<AuthDialogProps> = ({ isOpen, onClose }) => {
reader.readAsText(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<HTMLInputElement>) => { const handleAvatarUpload = async (e: React.ChangeEvent<HTMLInputElement>) => {
const file = e.target.files?.[0]; const file = e.target.files?.[0];
if (!file) return; if (!file) return;
@@ -434,22 +405,12 @@ const AuthDialog: React.FC<AuthDialogProps> = ({ isOpen, onClose }) => {
return 'Your profile'; return 'Your profile';
case 'login': case 'login':
return 'Log in'; return 'Log in';
case 'connect':
return 'Connect signer';
} }
}; };
// Decide whether to render the progress view in place of the QR/button. // Once the user launches the signer app we replace the login form with a
// Mobile: flip in as soon as the user taps "Open signer app" (tracked by // progress view so they see feedback while the handshake completes.
// `hasOpenedSigner`) so they see feedback the moment they return from the const showProgressView = hasOpenedSigner;
// 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)
);
return ( return (
<Dialog open={isOpen} onOpenChange={onClose}> <Dialog open={isOpen} onOpenChange={onClose}>
@@ -468,18 +429,14 @@ const AuthDialog: React.FC<AuthDialogProps> = ({ isOpen, onClose }) => {
🔑 🔑
</div> </div>
<p className="text-sm text-muted-foreground">
Join with a new Nostr account, or log in with one you already have.
</p>
<div className="space-y-2"> <div className="space-y-2">
<Button onClick={() => setStep('generate')} className="w-full h-12"> <Button onClick={() => setStep('generate')} className="w-full h-12 rounded-full">
Create a new Nostr account Create a new Nostr account
</Button> </Button>
<Button <Button
variant="outline" variant="link"
onClick={() => setStep('login')} onClick={() => setStep('login')}
className="w-full h-12" className="w-full text-muted-foreground"
> >
Log in to an existing account Log in to an existing account
</Button> </Button>
@@ -514,7 +471,7 @@ const AuthDialog: React.FC<AuthDialogProps> = ({ isOpen, onClose }) => {
</div> </div>
{!isGenerating && ( {!isGenerating && (
<Button onClick={generateKey} className="w-full h-12"> <Button onClick={generateKey} className="w-full h-12 rounded-full">
Generate key Generate key
</Button> </Button>
)} )}
@@ -567,7 +524,7 @@ const AuthDialog: React.FC<AuthDialogProps> = ({ isOpen, onClose }) => {
</p> </p>
</div> </div>
<Button onClick={downloadAndProceed} className="w-full h-12"> <Button onClick={downloadAndProceed} className="w-full h-12 rounded-full">
<Download className="w-4 h-4 mr-2" /> <Download className="w-4 h-4 mr-2" />
Download &amp; continue Download &amp; continue
</Button> </Button>
@@ -655,7 +612,7 @@ const AuthDialog: React.FC<AuthDialogProps> = ({ isOpen, onClose }) => {
<Button <Button
onClick={() => finishSignup(false)} onClick={() => finishSignup(false)}
disabled={isPublishing} disabled={isPublishing}
className="w-full h-12" className="w-full h-12 rounded-full"
> >
{isPublishing ? 'Saving…' : 'Finish'} {isPublishing ? 'Saving…' : 'Finish'}
</Button> </Button>
@@ -663,7 +620,7 @@ const AuthDialog: React.FC<AuthDialogProps> = ({ isOpen, onClose }) => {
variant="ghost" variant="ghost"
onClick={() => finishSignup(true)} onClick={() => finishSignup(true)}
disabled={isPublishing} disabled={isPublishing}
className="w-full" className="w-full rounded-full"
> >
Skip for now Skip for now
</Button> </Button>
@@ -674,170 +631,49 @@ const AuthDialog: React.FC<AuthDialogProps> = ({ isOpen, onClose }) => {
{/* Login step. */} {/* Login step. */}
{step === 'login' && ( {step === 'login' && (
<div className="space-y-4"> <div className="space-y-4">
{hasExtension ? ( {connectError ? (
<> <div className="flex flex-col items-center space-y-3 py-4">
<Button <p className="text-sm text-destructive text-center">{connectError}</p>
onClick={handleExtensionLogin} <Button variant="outline" onClick={handleConnectRetry} className="rounded-full">
disabled={isLoggingIn} Try again
className="w-full h-12"
>
{isLoggingIn ? 'Logging in…' : 'Log in with extension'}
</Button> </Button>
</div>
<Button ) : showProgressView ? (
variant="outline" <div className="flex flex-col items-center space-y-4 py-6 w-full">
onClick={goToConnect} <Loader2 className="w-8 h-8 animate-spin text-primary" />
className="w-full h-12" <p className="text-sm text-muted-foreground text-center min-h-[1.25rem]">
{connectStatusLabel(connectStatus) || 'Waiting for your signer…'}
</p>
<button
type="button"
onClick={handleConnectRetry}
className="text-sm text-primary hover:underline underline-offset-4 font-medium"
> >
Use remote signer Cancel
</Button> </button>
</div>
<Collapsible open={showMoreOptions} onOpenChange={setShowMoreOptions}>
<CollapsibleTrigger className="w-full flex items-center justify-center gap-1 text-sm text-muted-foreground hover:text-foreground py-2">
<span>Use secret key</span>
<ChevronDown
className={`w-4 h-4 transition-transform ${
showMoreOptions ? 'rotate-180' : ''
}`}
/>
</CollapsibleTrigger>
<CollapsibleContent className="space-y-3 pt-1">
<NsecLoginForm
loginNsec={loginNsec}
setLoginNsec={setLoginNsec}
loginError={loginError}
setLoginError={setLoginError}
isLoggingIn={isLoggingIn}
onSubmit={handleLogin}
onFileChange={handleFileUpload}
fileInputRef={fileInputRef}
/>
</CollapsibleContent>
</Collapsible>
</>
) : ( ) : (
<> <NsecLoginForm
<NsecLoginForm loginInput={loginInput}
loginNsec={loginNsec} setLoginInput={setLoginInput}
setLoginNsec={setLoginNsec} loginError={loginError}
loginError={loginError} setLoginError={setLoginError}
setLoginError={setLoginError} isLoggingIn={isLoggingIn}
isLoggingIn={isLoggingIn} onSubmit={handleLogin}
onSubmit={handleLogin} onFileChange={handleFileUpload}
onFileChange={handleFileUpload} onOpenSignerApp={handleOpenSignerApp}
fileInputRef={fileInputRef} fileInputRef={fileInputRef}
/> />
<Button
variant="outline"
onClick={goToConnect}
className="w-full"
>
Use remote signer
</Button>
</>
)} )}
<button {!connectError && !showProgressView && (
onClick={() => setStep('welcome')} <button
className="w-full text-sm text-muted-foreground hover:text-foreground" onClick={() => setStep('welcome')}
> className="w-full text-sm text-muted-foreground hover:text-foreground"
Back >
</button> Back
</div> </button>
)} )}
{/* Connect step — nostrconnect QR + bunker URI fallback. */}
{step === 'connect' && (
<div className="space-y-4">
<div className="flex flex-col items-center space-y-4">
{connectError ? (
<div className="flex flex-col items-center space-y-3 py-4">
<p className="text-sm text-destructive text-center">{connectError}</p>
<Button variant="outline" onClick={handleConnectRetry}>
Try again
</Button>
</div>
) : 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.
<div className="flex flex-col items-center space-y-4 py-6 w-full">
<Loader2 className="w-8 h-8 animate-spin text-primary" />
<p className="text-sm text-muted-foreground text-center min-h-[1.25rem]">
{connectStatusLabel(connectStatus)}
</p>
<button
type="button"
onClick={handleConnectRetry}
className="text-sm text-primary hover:underline underline-offset-4 font-medium"
>
Cancel
</button>
</div>
) : nostrConnectUri ? (
<>
{!isMobile && (
<div className="p-4 bg-white rounded-xl">
<QRCodeCanvas value={nostrConnectUri} size={180} level="M" />
</div>
)}
{isMobile && (
<Button onClick={handleOpenSignerApp} className="w-full h-12">
<ExternalLink className="w-5 h-5 mr-2" />
Open signer app
</Button>
)}
</>
) : (
<div className="flex items-center justify-center h-[100px]">
<Loader2 className="w-8 h-8 animate-spin text-muted-foreground" />
</div>
)}
</div>
{/* Manual bunker URI fallback. */}
<Collapsible open={showBunkerInput} onOpenChange={setShowBunkerInput}>
<CollapsibleTrigger className="w-full flex items-center justify-center gap-1 text-sm text-muted-foreground hover:text-foreground py-2">
<span>Enter bunker URI manually</span>
{showBunkerInput ? (
<ChevronUp className="w-4 h-4" />
) : (
<ChevronDown className="w-4 h-4" />
)}
</CollapsibleTrigger>
<CollapsibleContent className="space-y-3 pt-2">
<Input
value={bunkerUri}
onChange={(e) => setBunkerUri(e.target.value)}
placeholder="bunker://…"
className="text-base md:text-sm"
/>
{bunkerUri && !validateBunkerUri(bunkerUri) && (
<Alert variant="destructive">
<AlertDescription>Invalid bunker URI format.</AlertDescription>
</Alert>
)}
<Button
variant="outline"
onClick={handleBunkerLogin}
disabled={
isLoggingIn || !bunkerUri.trim() || !validateBunkerUri(bunkerUri)
}
className="w-full"
>
{isLoggingIn ? 'Connecting…' : 'Connect'}
</Button>
</CollapsibleContent>
</Collapsible>
<button
onClick={() => setStep('login')}
className="w-full text-sm text-muted-foreground hover:text-foreground"
>
Back
</button>
</div> </div>
)} )}
</div> </div>
@@ -846,26 +682,28 @@ const AuthDialog: React.FC<AuthDialogProps> = ({ 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 { interface NsecLoginFormProps {
loginNsec: string; loginInput: string;
setLoginNsec: (v: string) => void; setLoginInput: (v: string) => void;
loginError: string; loginError: string;
setLoginError: (v: string) => void; setLoginError: (v: string) => void;
isLoggingIn: boolean; isLoggingIn: boolean;
onSubmit: () => void; onSubmit: () => void;
onFileChange: (e: React.ChangeEvent<HTMLInputElement>) => void; onFileChange: (e: React.ChangeEvent<HTMLInputElement>) => void;
onOpenSignerApp: () => void;
fileInputRef: React.RefObject<HTMLInputElement | null>; fileInputRef: React.RefObject<HTMLInputElement | null>;
} }
const NsecLoginForm: React.FC<NsecLoginFormProps> = ({ const NsecLoginForm: React.FC<NsecLoginFormProps> = ({
loginNsec, loginInput,
setLoginNsec, setLoginInput,
loginError, loginError,
setLoginError, setLoginError,
isLoggingIn, isLoggingIn,
onSubmit, onSubmit,
onFileChange, onFileChange,
onOpenSignerApp,
fileInputRef, fileInputRef,
}) => ( }) => (
<form <form
@@ -875,27 +713,20 @@ const NsecLoginForm: React.FC<NsecLoginFormProps> = ({
}} }}
className="space-y-3" className="space-y-3"
> >
<Input <div className="relative">
type="password" <Input
value={loginNsec} type="password"
onChange={(e) => { value={loginInput}
setLoginNsec(e.target.value); onChange={(e) => {
if (loginError) setLoginError(''); setLoginInput(e.target.value);
}} if (loginError) setLoginError('');
placeholder="nsec1…" }}
autoComplete="off" placeholder="nsec1… or bunker://…"
className={loginError ? 'border-destructive focus-visible:ring-destructive' : ''} autoComplete="off"
/> className={`pr-10 ${
{loginError && <p className="text-sm text-destructive">{loginError}</p>} loginError ? 'border-destructive focus-visible:ring-destructive' : ''
}`}
<div className="flex gap-2"> />
<Button
type="submit"
disabled={isLoggingIn || !loginNsec.trim()}
className="flex-1"
>
{isLoggingIn ? 'Logging in…' : 'Log in'}
</Button>
<input <input
type="file" type="file"
accept=".txt" accept=".txt"
@@ -903,15 +734,39 @@ const NsecLoginForm: React.FC<NsecLoginFormProps> = ({
ref={fileInputRef} ref={fileInputRef}
onChange={onFileChange} onChange={onFileChange}
/> />
<Button <DropdownMenu>
type="button" <DropdownMenuTrigger asChild>
variant="outline" <Button
size="icon" type="button"
onClick={() => fileInputRef.current?.click()} variant="ghost"
> size="icon"
<Upload className="w-4 h-4" /> className="absolute right-0 top-0 h-full px-3 hover:bg-transparent"
</Button> title="More login options"
>
<Upload className="h-4 w-4 text-muted-foreground" />
</Button>
</DropdownMenuTrigger>
<DropdownMenuContent align="end">
<DropdownMenuItem onSelect={() => fileInputRef.current?.click()}>
<FileUp className="h-4 w-4" />
Select key file
</DropdownMenuItem>
<DropdownMenuItem onSelect={onOpenSignerApp}>
<ExternalLink className="h-4 w-4" />
Open signer app
</DropdownMenuItem>
</DropdownMenuContent>
</DropdownMenu>
</div> </div>
{loginError && <p className="text-sm text-destructive">{loginError}</p>}
<Button
type="submit"
disabled={isLoggingIn || !loginInput.trim()}
className="w-full rounded-full"
>
{isLoggingIn ? 'Logging in…' : 'Log in'}
</Button>
</form> </form>
); );
+48 -1
View File
@@ -1,10 +1,28 @@
import { useState } from 'react'; import { useState } from 'react';
import { Button } from '@/components/ui/button.tsx'; import { Button } from '@/components/ui/button.tsx';
import AuthDialog from './AuthDialog'; import AuthDialog from './AuthDialog';
import { QuickLoginDialog } from './QuickLoginDialog';
import { useLoggedInAccounts } from '@/hooks/useLoggedInAccounts'; import { useLoggedInAccounts } from '@/hooks/useLoggedInAccounts';
import { AccountSwitcher } from './AccountSwitcher'; import { AccountSwitcher } from './AccountSwitcher';
import { cn } from '@/lib/utils'; import { cn } from '@/lib/utils';
/** Minimal shape of the NIP-07 provider injected at `window.nostr`. */
interface Nip07Provider {
getPublicKey(): Promise<string>;
}
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 { export interface LoginAreaProps {
className?: string; className?: string;
} }
@@ -12,6 +30,23 @@ export interface LoginAreaProps {
export function LoginArea({ className }: LoginAreaProps) { export function LoginArea({ className }: LoginAreaProps) {
const { currentUser } = useLoggedInAccounts(); const { currentUser } = useLoggedInAccounts();
const [authDialogOpen, setAuthDialogOpen] = useState(false); const [authDialogOpen, setAuthDialogOpen] = useState(false);
const [quickLoginPubkey, setQuickLoginPubkey] = useState<string | null>(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 ( return (
<div className={cn('inline-flex items-center justify-center', className)}> <div className={cn('inline-flex items-center justify-center', className)}>
@@ -19,13 +54,25 @@ export function LoginArea({ className }: LoginAreaProps) {
<AccountSwitcher onAddAccountClick={() => setAuthDialogOpen(true)} /> <AccountSwitcher onAddAccountClick={() => setAuthDialogOpen(true)} />
) : ( ) : (
<Button <Button
onClick={() => setAuthDialogOpen(true)} onClick={handleJoin}
className="flex items-center gap-2 px-5 py-2 rounded-full bg-primary text-primary-foreground font-medium transition-all hover:bg-primary/90 animate-scale-in" className="flex items-center gap-2 px-5 py-2 rounded-full bg-primary text-primary-foreground font-medium transition-all hover:bg-primary/90 animate-scale-in"
> >
<span className="truncate">Join</span> <span className="truncate">Join</span>
</Button> </Button>
)} )}
{quickLoginPubkey && (
<QuickLoginDialog
isOpen={quickLoginPubkey !== null}
pubkey={quickLoginPubkey}
onClose={() => setQuickLoginPubkey(null)}
onOtherLogin={() => {
setQuickLoginPubkey(null);
setAuthDialogOpen(true);
}}
/>
)}
<AuthDialog <AuthDialog
isOpen={authDialogOpen} isOpen={authDialogOpen}
onClose={() => setAuthDialogOpen(false)} onClose={() => setAuthDialogOpen(false)}
+130
View File
@@ -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 (
<Dialog open={isOpen} onOpenChange={(open) => !open && onClose()}>
<DialogContent className="sm:max-w-sm">
<DialogHeader>
<DialogTitle className="text-center">Welcome back</DialogTitle>
</DialogHeader>
<div className="flex flex-col items-center gap-3 py-4">
{author.isLoading ? (
<>
<Skeleton className="size-20 rounded-full" />
<Skeleton className="h-5 w-32" />
</>
) : (
<>
<Avatar className="size-20">
<AvatarImage src={picture} alt={displayName} />
<AvatarFallback className="text-xl">
{displayName.slice(0, 2).toUpperCase()}
</AvatarFallback>
</Avatar>
<p className="text-lg font-semibold leading-none">{displayName}</p>
</>
)}
</div>
{error && (
<p className="text-sm text-destructive text-center" role="alert">
{error}
</p>
)}
<div className="flex flex-col items-center gap-2">
<Button
className="w-full rounded-full"
onClick={handleLogin}
disabled={isLoggingIn}
>
{isLoggingIn ? (
<>
<Loader2 className="size-4 animate-spin" />
Logging in…
</>
) : (
'Log in'
)}
</Button>
<Button
variant="link"
size="sm"
className="text-muted-foreground"
onClick={onOtherLogin}
disabled={isLoggingIn}
>
Other ways to log in
</Button>
</div>
</DialogContent>
</Dialog>
);
}
/** 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';
}
}