From 0013ece0132cf2556c9e3d91b836e37e8a3d8239 Mon Sep 17 00:00:00 2001 From: hzrd149 Date: Tue, 12 May 2026 16:08:38 -0500 Subject: [PATCH 1/2] Add nostrconnect:// QR code login for NIP-46 remote signers Adds the client-initiated NIP-46 flow alongside the existing bunker:// paste input. Desktop users scan a generated QR code with their signer app (Amber, nsec.app, etc.); mobile users get an "Open signer app" deep-link plus a /remoteloginsuccess callback page. The pasted bunker:// URI moves into a collapsible fallback below the QR. A shared BunkerLoginPanel component owns the session lifecycle and is embedded in both LoginDialog and SimpleLoginDialog. The listener effect depends only on a sessionToken and reads login/onLoggedIn/config through refs so parent re-renders don't tear down an in-flight handshake. Co-Authored-By: Claude Opus 4.7 (1M context) --- package-lock.json | 29 ++- src/AppRouter.tsx | 2 + src/components/auth/BunkerLoginPanel.tsx | 291 ++++++++++++++++++++++ src/components/auth/LoginDialog.tsx | 77 +----- src/components/auth/SimpleLoginDialog.tsx | 71 +----- src/hooks/useLoginActions.ts | 9 + src/pages/RemoteLoginSuccess.tsx | 43 ++++ 7 files changed, 388 insertions(+), 134 deletions(-) create mode 100644 src/components/auth/BunkerLoginPanel.tsx create mode 100644 src/pages/RemoteLoginSuccess.tsx diff --git a/package-lock.json b/package-lock.json index 304336c7..1a1228e6 100644 --- a/package-lock.json +++ b/package-lock.json @@ -1,12 +1,12 @@ { "name": "shakespeare.diy", - "version": "9.13.1", + "version": "9.13.2", "lockfileVersion": 3, "requires": true, "packages": { "": { "name": "shakespeare.diy", - "version": "9.13.1", + "version": "9.13.2", "license": "AGPL-3.0-or-later", "dependencies": { "@capacitor/app": "^8.1.0", @@ -5003,6 +5003,7 @@ "cpu": [ "arm" ], + "dev": true, "license": "MIT", "optional": true, "os": [ @@ -5016,6 +5017,7 @@ "cpu": [ "arm64" ], + "dev": true, "license": "MIT", "optional": true, "os": [ @@ -5029,6 +5031,7 @@ "cpu": [ "arm64" ], + "dev": true, "license": "MIT", "optional": true, "os": [ @@ -5042,6 +5045,7 @@ "cpu": [ "x64" ], + "dev": true, "license": "MIT", "optional": true, "os": [ @@ -5055,6 +5059,7 @@ "cpu": [ "arm64" ], + "dev": true, "license": "MIT", "optional": true, "os": [ @@ -5068,6 +5073,7 @@ "cpu": [ "x64" ], + "dev": true, "license": "MIT", "optional": true, "os": [ @@ -5081,6 +5087,7 @@ "cpu": [ "arm" ], + "dev": true, "license": "MIT", "optional": true, "os": [ @@ -5094,6 +5101,7 @@ "cpu": [ "arm" ], + "dev": true, "license": "MIT", "optional": true, "os": [ @@ -5107,6 +5115,7 @@ "cpu": [ "arm64" ], + "dev": true, "license": "MIT", "optional": true, "os": [ @@ -5120,6 +5129,7 @@ "cpu": [ "arm64" ], + "dev": true, "license": "MIT", "optional": true, "os": [ @@ -5133,6 +5143,7 @@ "cpu": [ "loong64" ], + "dev": true, "license": "MIT", "optional": true, "os": [ @@ -5146,6 +5157,7 @@ "cpu": [ "loong64" ], + "dev": true, "license": "MIT", "optional": true, "os": [ @@ -5159,6 +5171,7 @@ "cpu": [ "ppc64" ], + "dev": true, "license": "MIT", "optional": true, "os": [ @@ -5172,6 +5185,7 @@ "cpu": [ "ppc64" ], + "dev": true, "license": "MIT", "optional": true, "os": [ @@ -5185,6 +5199,7 @@ "cpu": [ "riscv64" ], + "dev": true, "license": "MIT", "optional": true, "os": [ @@ -5198,6 +5213,7 @@ "cpu": [ "riscv64" ], + "dev": true, "license": "MIT", "optional": true, "os": [ @@ -5211,6 +5227,7 @@ "cpu": [ "s390x" ], + "dev": true, "license": "MIT", "optional": true, "os": [ @@ -5224,6 +5241,7 @@ "cpu": [ "x64" ], + "dev": true, "license": "MIT", "optional": true, "os": [ @@ -5237,6 +5255,7 @@ "cpu": [ "x64" ], + "dev": true, "license": "MIT", "optional": true, "os": [ @@ -5250,6 +5269,7 @@ "cpu": [ "x64" ], + "dev": true, "license": "MIT", "optional": true, "os": [ @@ -5263,6 +5283,7 @@ "cpu": [ "arm64" ], + "dev": true, "license": "MIT", "optional": true, "os": [ @@ -5276,6 +5297,7 @@ "cpu": [ "arm64" ], + "dev": true, "license": "MIT", "optional": true, "os": [ @@ -5289,6 +5311,7 @@ "cpu": [ "ia32" ], + "dev": true, "license": "MIT", "optional": true, "os": [ @@ -5302,6 +5325,7 @@ "cpu": [ "x64" ], + "dev": true, "license": "MIT", "optional": true, "os": [ @@ -5315,6 +5339,7 @@ "cpu": [ "x64" ], + "dev": true, "license": "MIT", "optional": true, "os": [ diff --git a/src/AppRouter.tsx b/src/AppRouter.tsx index 5b263dbf..6ad874c0 100644 --- a/src/AppRouter.tsx +++ b/src/AppRouter.tsx @@ -21,6 +21,7 @@ import GitHubOAuth from "./pages/GitHubOAuth"; import NetlifyOAuth from "./pages/NetlifyOAuth"; import VercelOAuth from "./pages/VercelOAuth"; import OpenRouterOAuth from "./pages/OpenRouterOAuth"; +import RemoteLoginSuccess from "./pages/RemoteLoginSuccess"; import { NIP19Page } from "./pages/NIP19Page"; import NotFound from "./pages/NotFound"; import { ProjectView } from "./pages/ProjectView"; @@ -43,6 +44,7 @@ export function AppRouter() { } /> } /> } /> + } /> }> } /> } /> diff --git a/src/components/auth/BunkerLoginPanel.tsx b/src/components/auth/BunkerLoginPanel.tsx new file mode 100644 index 00000000..4e234894 --- /dev/null +++ b/src/components/auth/BunkerLoginPanel.tsx @@ -0,0 +1,291 @@ +import React, { useCallback, useEffect, useRef, useState } from 'react'; +import QRCode from 'qrcode'; +import { ChevronDown, ChevronUp, ExternalLink, Loader2 } from 'lucide-react'; +import { + generateNostrConnectParams, + generateNostrConnectURI, + type NostrConnectParams, +} from '@nostrify/react/login'; + +import { Button } from '@/components/ui/button'; +import { Input } from '@/components/ui/input'; +import { Alert, AlertDescription } from '@/components/ui/alert'; +import { + Collapsible, + CollapsibleContent, + CollapsibleTrigger, +} from '@/components/ui/collapsible'; +import { useLoginActions } from '@/hooks/useLoginActions'; +import { useAppContext } from '@/hooks/useAppContext'; + +interface BunkerLoginPanelProps { + /** Called after a successful login (either nostrconnect or pasted bunker URI). */ + onLoggedIn: () => void; +} + +const validateBunkerUri = (uri: string) => uri.startsWith('bunker://'); + +// UA-based mobile check. Distinct from the viewport-based `useIsMobile` — +// here we care whether the platform can deep-link into a signer app, not +// whether the window is narrow. +const isMobileDevice = (): boolean => { + if (typeof navigator === 'undefined') return false; + return /Android|iPhone|iPad|iPod/i.test(navigator.userAgent); +}; + +/** + * Shared NIP-46 login panel: presents a `nostrconnect://` QR code (desktop) + * or an "Open signer app" deep-link (mobile) as the primary path, with the + * legacy `bunker://` paste input as a collapsible fallback. + * + * Mount/unmount drives the session lifecycle — when the parent's tab is + * inactive the panel is unmounted, which aborts the listener and clears + * state. Switching back generates a fresh session. + */ +export const BunkerLoginPanel: React.FC = ({ onLoggedIn }) => { + const login = useLoginActions(); + const { config } = useAppContext(); + + const [sessionToken, setSessionToken] = useState(0); + const [nostrConnectUri, setNostrConnectUri] = useState(''); + const [qrDataUrl, setQrDataUrl] = useState(''); + const [connectError, setConnectError] = useState(null); + const [hasOpenedSigner, setHasOpenedSigner] = useState(false); + const [showBunkerInput, setShowBunkerInput] = useState(false); + const [bunkerUri, setBunkerUri] = useState(''); + const [bunkerError, setBunkerError] = useState(null); + const [isBunkerLoggingIn, setIsBunkerLoggingIn] = useState(false); + + const abortControllerRef = useRef(null); + // Refs so the listener effect can read the latest values without + // re-running on every parent re-render. gm-protocol documents the trap: + // a stale closure mid-handshake silently drops the signer's response. + // `config` is rebuilt every render by AppProvider, so we must NOT + // depend on it in the effect's dep array — otherwise the in-flight + // subscription is torn down on each parent render. + const loginRef = useRef(login); + const onLoggedInRef = useRef(onLoggedIn); + const configRef = useRef(config); + + useEffect(() => { + loginRef.current = login; + onLoggedInRef.current = onLoggedIn; + configRef.current = config; + }); + + const isMobile = isMobileDevice(); + + // Generate a session and start listening for the signer. Driven by + // `sessionToken` so a "Try again" can force a fresh session deterministically. + // Intentionally has only `sessionToken` in its deps — see comment on the + // refs above for why. + useEffect(() => { + let cancelled = false; + const controller = new AbortController(); + abortControllerRef.current?.abort(); + abortControllerRef.current = controller; + + const run = async () => { + const relayUrls = (configRef.current.relayMetadata?.relays ?? []) + .filter((r) => r.write !== false) + .map((r) => r.url); + + if (relayUrls.length === 0) { + if (!cancelled) { + setConnectError( + 'No relays configured. Add a relay in settings to use this login method.', + ); + } + return; + } + + const params: NostrConnectParams = generateNostrConnectParams(relayUrls); + const uri = generateNostrConnectURI(params, { + name: 'Shakespeare', + callback: isMobileDevice() + ? `${window.location.origin}/remoteloginsuccess` + : undefined, + }); + + try { + const dataUrl = await QRCode.toDataURL(uri, { + width: 400, + margin: 2, + color: { dark: '#000000', light: '#FFFFFF' }, + }); + if (cancelled) return; + setQrDataUrl(dataUrl); + } catch (e) { + console.error('Failed to render nostrconnect QR:', e); + } + + if (cancelled) return; + setNostrConnectUri(uri); + setConnectError(null); + + try { + await loginRef.current.nostrconnect(params, controller.signal); + if (cancelled || controller.signal.aborted) return; + onLoggedInRef.current(); + } catch (error) { + if (cancelled || controller.signal.aborted) return; + if (error instanceof Error && error.name === 'AbortError') return; + console.error('nostrconnect failed:', error); + setConnectError( + error instanceof Error ? error.message : 'Failed to connect to signer.', + ); + } + }; + + void run(); + + return () => { + cancelled = true; + controller.abort(); + }; + // Intentional: deps limited to `sessionToken` so parent re-renders + // don't tear down the in-flight subscription. Config + login are read + // via refs that are updated each render. + // eslint-disable-next-line react-hooks/exhaustive-deps + }, [sessionToken]); + + const handleConnectRetry = useCallback(() => { + setNostrConnectUri(''); + setQrDataUrl(''); + setConnectError(null); + setHasOpenedSigner(false); + setSessionToken((t) => t + 1); + }, []); + + const handleOpenSignerApp = () => { + if (!nostrConnectUri) return; + // Flip into the waiting view *before* navigating so the user sees + // feedback the moment they return from the signer app. + setHasOpenedSigner(true); + window.location.href = nostrConnectUri; + }; + + const handleBunkerLogin = async () => { + if (!bunkerUri.trim()) { + setBunkerError('Please enter a bunker URI'); + return; + } + if (!validateBunkerUri(bunkerUri)) { + setBunkerError('Invalid bunker URI format. Must start with bunker://'); + return; + } + + setIsBunkerLoggingIn(true); + setBunkerError(null); + try { + await login.bunker(bunkerUri); + onLoggedIn(); + } catch { + setBunkerError('Failed to connect to bunker. Please check the URI.'); + } finally { + setIsBunkerLoggingIn(false); + } + }; + + // Mobile: flip to waiting view once the user taps "Open signer app" so + // the return trip shows progress, not the original button. Desktop: + // keep the QR scannable (no per-phase progress in @nostrify/react v0.4.1). + const showWaitingView = isMobile && hasOpenedSigner && !connectError; + + return ( +
+
+ {connectError ? ( +
+ + {connectError} + + +
+ ) : showWaitingView ? ( +
+ +

+ Waiting for signer… +

+ +
+ ) : nostrConnectUri && qrDataUrl ? ( + <> + {!isMobile && ( + <> +
+ nostrconnect QR code +
+

+ Scan this QR code with your Nostr signer app to log in. +

+ + )} + + {isMobile && ( + + )} + + ) : ( +
+ +
+ )} +
+ + + + Enter bunker URI manually + {showBunkerInput ? ( + + ) : ( + + )} + + + { + setBunkerUri(e.target.value); + if (bunkerError) setBunkerError(null); + }} + placeholder="bunker://" + className={bunkerError ? 'border-red-500' : ''} + autoComplete="off" + /> + {bunkerError && ( +

{bunkerError}

+ )} + +
+
+
+ ); +}; + +export default BunkerLoginPanel; diff --git a/src/components/auth/LoginDialog.tsx b/src/components/auth/LoginDialog.tsx index 100b085c..502dadc8 100644 --- a/src/components/auth/LoginDialog.tsx +++ b/src/components/auth/LoginDialog.tsx @@ -10,6 +10,7 @@ import { Tabs, TabsContent, TabsList, TabsTrigger } from '@/components/ui/tabs'; import { Alert, AlertDescription } from '@/components/ui/alert'; import { useLoginActions } from '@/hooks/useLoginActions'; import { cn } from '@/lib/utils'; +import BunkerLoginPanel from '@/components/auth/BunkerLoginPanel'; interface LoginDialogProps { isOpen: boolean; @@ -22,18 +23,12 @@ const validateNsec = (nsec: string) => { return /^nsec1[a-zA-Z0-9]{58}$/.test(nsec); }; -const validateBunkerUri = (uri: string) => { - return uri.startsWith('bunker://'); -}; - const LoginDialog: React.FC = ({ isOpen, onClose, onLogin, onSignup }) => { const [isLoading, setIsLoading] = useState(false); const [isFileLoading, setIsFileLoading] = useState(false); const [nsec, setNsec] = useState(''); - const [bunkerUri, setBunkerUri] = useState(''); const [errors, setErrors] = useState<{ nsec?: string; - bunker?: string; file?: string; extension?: string; }>({}); @@ -47,7 +42,6 @@ const LoginDialog: React.FC = ({ isOpen, onClose, onLogin, onS setIsLoading(false); setIsFileLoading(false); setNsec(''); - setBunkerUri(''); setErrors({}); // Reset file input if (fileInputRef.current) { @@ -111,36 +105,6 @@ const LoginDialog: React.FC = ({ isOpen, onClose, onLogin, onS executeLogin(nsec); }; - const handleBunkerLogin = async () => { - if (!bunkerUri.trim()) { - setErrors(prev => ({ ...prev, bunker: 'Please enter a bunker URI' })); - return; - } - - if (!validateBunkerUri(bunkerUri)) { - setErrors(prev => ({ ...prev, bunker: 'Invalid bunker URI format. Must start with bunker://' })); - return; - } - - setIsLoading(true); - setErrors(prev => ({ ...prev, bunker: undefined })); - - try { - await login.bunker(bunkerUri); - onLogin(); - onClose(); - // Clear the URI from memory - setBunkerUri(''); - } catch { - setErrors(prev => ({ - ...prev, - bunker: 'Failed to connect to bunker. Please check the URI.' - })); - } finally { - setIsLoading(false); - } - }; - const handleFileUpload = (e: React.ChangeEvent) => { const file = e.target.files?.[0]; if (!file) return; @@ -333,38 +297,13 @@ const LoginDialog: React.FC = ({ isOpen, onClose, onLogin, onS - -
- - { - setBunkerUri(e.target.value); - if (errors.bunker) setErrors(prev => ({ ...prev, bunker: undefined })); - }} - className={`rounded-lg border-gray-300 dark:border-gray-700 focus-visible:ring-primary ${ - errors.bunker ? 'border-red-500' : '' - }`} - placeholder='bunker://' - autoComplete="off" - /> - {errors.bunker && ( -

{errors.bunker}

- )} -
- -
- -
+ + { + onLogin(); + onClose(); + }} + /> diff --git a/src/components/auth/SimpleLoginDialog.tsx b/src/components/auth/SimpleLoginDialog.tsx index 15092e94..e2987af4 100644 --- a/src/components/auth/SimpleLoginDialog.tsx +++ b/src/components/auth/SimpleLoginDialog.tsx @@ -1,11 +1,12 @@ import React, { useState, useEffect, useRef } from 'react'; -import { Cloud, Upload } from 'lucide-react'; +import { Upload } from 'lucide-react'; import { Button } from '@/components/ui/button'; import { Input } from '@/components/ui/input'; import { Dialog, DialogContent, DialogHeader, DialogTitle } from "@/components/ui/dialog"; // Alert components removed as they're not used in the simplified design import { useLoginActions } from '@/hooks/useLoginActions'; import { cn } from '@/lib/utils'; +import BunkerLoginPanel from '@/components/auth/BunkerLoginPanel'; // Only using key-add step now @@ -20,10 +21,6 @@ const validateNsec = (nsec: string) => { return /^nsec1[a-zA-Z0-9]{58}$/.test(nsec); }; -const validateBunkerUri = (uri: string) => { - return uri.startsWith('bunker://'); -}; - const SimpleLoginDialog: React.FC = ({ isOpen, onClose, @@ -34,11 +31,9 @@ const SimpleLoginDialog: React.FC = ({ const [isLoading, setIsLoading] = useState(false); const [isFileLoading, setIsFileLoading] = useState(false); const [nsec, setNsec] = useState(''); - const [bunkerUri, setBunkerUri] = useState(''); const [activeTab, setActiveTab] = useState<'nsec' | 'bunker'>('nsec'); const [errors, setErrors] = useState<{ nsec?: string; - bunker?: string; extension?: string; file?: string; }>({}); @@ -52,7 +47,6 @@ const SimpleLoginDialog: React.FC = ({ setIsLoading(false); setIsFileLoading(false); setNsec(''); - setBunkerUri(''); setActiveTab('nsec'); setErrors({}); // Reset file input @@ -97,35 +91,6 @@ const SimpleLoginDialog: React.FC = ({ executeLogin(nsec); }; - const handleBunkerLogin = async () => { - if (!bunkerUri.trim()) { - setErrors(prev => ({ ...prev, bunker: 'Please enter a bunker URI' })); - return; - } - - if (!validateBunkerUri(bunkerUri)) { - setErrors(prev => ({ ...prev, bunker: 'Invalid bunker URI format. Must start with bunker://' })); - return; - } - - setIsLoading(true); - setErrors(prev => ({ ...prev, bunker: undefined })); - - try { - await login.bunker(bunkerUri); - onLogin(); - onClose(); - setBunkerUri(''); - } catch { - setErrors(prev => ({ - ...prev, - bunker: 'Failed to connect to bunker. Please check the URI.' - })); - } finally { - setIsLoading(false); - } - }; - const executeLogin = (key: string) => { setIsLoading(true); setErrors({}); @@ -278,32 +243,12 @@ const SimpleLoginDialog: React.FC = ({ )} {activeTab === 'bunker' && ( -
-
- { - setBunkerUri(e.target.value); - if (errors.bunker) setErrors(prev => ({ ...prev, bunker: undefined })); - }} - placeholder="bunker://" - className={errors.bunker ? 'border-red-500' : ''} - /> - {errors.bunker && ( -

{errors.bunker}

- )} -
- - -
+ { + onLogin(); + onClose(); + }} + /> )}
diff --git a/src/hooks/useLoginActions.ts b/src/hooks/useLoginActions.ts index f0d98a97..1fdac3d5 100644 --- a/src/hooks/useLoginActions.ts +++ b/src/hooks/useLoginActions.ts @@ -1,5 +1,6 @@ import { useNostr } from '@nostrify/react'; import { NLogin, useNostrLogin } from '@nostrify/react/login'; +import type { NostrConnectParams } from '@nostrify/react/login'; // NOTE: This file should not be edited except for adding new login methods. @@ -18,6 +19,14 @@ export function useLoginActions() { const login = await NLogin.fromBunker(uri, nostr); addLogin(login); }, + // Login via client-initiated NIP-46 ("nostrconnect://" QR code). + // Caller generates params with `generateNostrConnectParams`, renders the + // URI as a QR/deep-link, and awaits this promise — it resolves when the + // remote signer connects back over the relay. + async nostrconnect(params: NostrConnectParams, signal?: AbortSignal): Promise { + const login = await NLogin.fromNostrConnect(params, nostr, { signal }); + addLogin(login); + }, // Login with a NIP-07 browser extension async extension(): Promise { const login = await NLogin.fromExtension(); diff --git a/src/pages/RemoteLoginSuccess.tsx b/src/pages/RemoteLoginSuccess.tsx new file mode 100644 index 00000000..f22675de --- /dev/null +++ b/src/pages/RemoteLoginSuccess.tsx @@ -0,0 +1,43 @@ +import { useSeoMeta } from "@unhead/react"; +import { useEffect } from "react"; +import { CheckCircle2 } from "lucide-react"; + +// Callback target for mobile NIP-46 signer apps after they approve a +// `nostrconnect://` request. The actual login completes via the relay +// subscription in the original tab — this page just provides a friendly +// landing if the signer opened it in a new tab/window. +const RemoteLoginSuccess = () => { + useSeoMeta({ + title: "Signer connected", + description: "You can return to Shakespeare.", + }); + + useEffect(() => { + // Best-effort: most signers open this in a new tab. Try to close it; + // the manual link below is the fallback when the browser refuses. + window.setTimeout(() => { + try { + window.close(); + } catch { + // ignored + } + }, 500); + }, []); + + return ( +
+
+ +

Signer connected

+

+ You can return to Shakespeare. Your login should complete automatically. +

+ + Open Shakespeare + +
+
+ ); +}; + +export default RemoteLoginSuccess; From 9313d2e0ee1b958c62a6e8d83e7a4e3ffded1245 Mon Sep 17 00:00:00 2001 From: hzrd149 Date: Fri, 15 May 2026 10:43:57 -0500 Subject: [PATCH 2/2] Unify login dialog inputs and gate QR code behind a button MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Collapses the separate "Secret Key" and "Bunker" tabs into a single input that auto-detects nsec vs bunker:// from the pasted string. File upload runs the same detection on file contents. The nostrconnect QR flow is now opt-in on both platforms — no relay subscription opens until the user clicks "Login with remote signer" (desktop) or "Open signer app" (mobile). Mobile skips QR rendering and deep-links to the signer once the URI is generated. BunkerLoginPanel is renamed to LoginPanel and owns all string-based methods plus the QR session lifecycle. LoginDialog drops its Extension/Key/Bunker Tabs structure; SimpleLoginDialog drops the nsec/bunker tab switcher. Both now mount LoginPanel directly with extension login below. Co-Authored-By: Claude Opus 4.7 (1M context) --- src/components/auth/BunkerLoginPanel.tsx | 291 --------------- src/components/auth/LoginDialog.tsx | 248 ++----------- src/components/auth/LoginPanel.tsx | 427 ++++++++++++++++++++++ src/components/auth/SimpleLoginDialog.tsx | 267 +++----------- 4 files changed, 507 insertions(+), 726 deletions(-) delete mode 100644 src/components/auth/BunkerLoginPanel.tsx create mode 100644 src/components/auth/LoginPanel.tsx diff --git a/src/components/auth/BunkerLoginPanel.tsx b/src/components/auth/BunkerLoginPanel.tsx deleted file mode 100644 index 4e234894..00000000 --- a/src/components/auth/BunkerLoginPanel.tsx +++ /dev/null @@ -1,291 +0,0 @@ -import React, { useCallback, useEffect, useRef, useState } from 'react'; -import QRCode from 'qrcode'; -import { ChevronDown, ChevronUp, ExternalLink, Loader2 } from 'lucide-react'; -import { - generateNostrConnectParams, - generateNostrConnectURI, - type NostrConnectParams, -} from '@nostrify/react/login'; - -import { Button } from '@/components/ui/button'; -import { Input } from '@/components/ui/input'; -import { Alert, AlertDescription } from '@/components/ui/alert'; -import { - Collapsible, - CollapsibleContent, - CollapsibleTrigger, -} from '@/components/ui/collapsible'; -import { useLoginActions } from '@/hooks/useLoginActions'; -import { useAppContext } from '@/hooks/useAppContext'; - -interface BunkerLoginPanelProps { - /** Called after a successful login (either nostrconnect or pasted bunker URI). */ - onLoggedIn: () => void; -} - -const validateBunkerUri = (uri: string) => uri.startsWith('bunker://'); - -// UA-based mobile check. Distinct from the viewport-based `useIsMobile` — -// here we care whether the platform can deep-link into a signer app, not -// whether the window is narrow. -const isMobileDevice = (): boolean => { - if (typeof navigator === 'undefined') return false; - return /Android|iPhone|iPad|iPod/i.test(navigator.userAgent); -}; - -/** - * Shared NIP-46 login panel: presents a `nostrconnect://` QR code (desktop) - * or an "Open signer app" deep-link (mobile) as the primary path, with the - * legacy `bunker://` paste input as a collapsible fallback. - * - * Mount/unmount drives the session lifecycle — when the parent's tab is - * inactive the panel is unmounted, which aborts the listener and clears - * state. Switching back generates a fresh session. - */ -export const BunkerLoginPanel: React.FC = ({ onLoggedIn }) => { - const login = useLoginActions(); - const { config } = useAppContext(); - - const [sessionToken, setSessionToken] = useState(0); - const [nostrConnectUri, setNostrConnectUri] = useState(''); - const [qrDataUrl, setQrDataUrl] = useState(''); - const [connectError, setConnectError] = useState(null); - const [hasOpenedSigner, setHasOpenedSigner] = useState(false); - const [showBunkerInput, setShowBunkerInput] = useState(false); - const [bunkerUri, setBunkerUri] = useState(''); - const [bunkerError, setBunkerError] = useState(null); - const [isBunkerLoggingIn, setIsBunkerLoggingIn] = useState(false); - - const abortControllerRef = useRef(null); - // Refs so the listener effect can read the latest values without - // re-running on every parent re-render. gm-protocol documents the trap: - // a stale closure mid-handshake silently drops the signer's response. - // `config` is rebuilt every render by AppProvider, so we must NOT - // depend on it in the effect's dep array — otherwise the in-flight - // subscription is torn down on each parent render. - const loginRef = useRef(login); - const onLoggedInRef = useRef(onLoggedIn); - const configRef = useRef(config); - - useEffect(() => { - loginRef.current = login; - onLoggedInRef.current = onLoggedIn; - configRef.current = config; - }); - - const isMobile = isMobileDevice(); - - // Generate a session and start listening for the signer. Driven by - // `sessionToken` so a "Try again" can force a fresh session deterministically. - // Intentionally has only `sessionToken` in its deps — see comment on the - // refs above for why. - useEffect(() => { - let cancelled = false; - const controller = new AbortController(); - abortControllerRef.current?.abort(); - abortControllerRef.current = controller; - - const run = async () => { - const relayUrls = (configRef.current.relayMetadata?.relays ?? []) - .filter((r) => r.write !== false) - .map((r) => r.url); - - if (relayUrls.length === 0) { - if (!cancelled) { - setConnectError( - 'No relays configured. Add a relay in settings to use this login method.', - ); - } - return; - } - - const params: NostrConnectParams = generateNostrConnectParams(relayUrls); - const uri = generateNostrConnectURI(params, { - name: 'Shakespeare', - callback: isMobileDevice() - ? `${window.location.origin}/remoteloginsuccess` - : undefined, - }); - - try { - const dataUrl = await QRCode.toDataURL(uri, { - width: 400, - margin: 2, - color: { dark: '#000000', light: '#FFFFFF' }, - }); - if (cancelled) return; - setQrDataUrl(dataUrl); - } catch (e) { - console.error('Failed to render nostrconnect QR:', e); - } - - if (cancelled) return; - setNostrConnectUri(uri); - setConnectError(null); - - try { - await loginRef.current.nostrconnect(params, controller.signal); - if (cancelled || controller.signal.aborted) return; - onLoggedInRef.current(); - } catch (error) { - if (cancelled || controller.signal.aborted) return; - if (error instanceof Error && error.name === 'AbortError') return; - console.error('nostrconnect failed:', error); - setConnectError( - error instanceof Error ? error.message : 'Failed to connect to signer.', - ); - } - }; - - void run(); - - return () => { - cancelled = true; - controller.abort(); - }; - // Intentional: deps limited to `sessionToken` so parent re-renders - // don't tear down the in-flight subscription. Config + login are read - // via refs that are updated each render. - // eslint-disable-next-line react-hooks/exhaustive-deps - }, [sessionToken]); - - const handleConnectRetry = useCallback(() => { - setNostrConnectUri(''); - setQrDataUrl(''); - setConnectError(null); - setHasOpenedSigner(false); - setSessionToken((t) => t + 1); - }, []); - - const handleOpenSignerApp = () => { - if (!nostrConnectUri) return; - // Flip into the waiting view *before* navigating so the user sees - // feedback the moment they return from the signer app. - setHasOpenedSigner(true); - window.location.href = nostrConnectUri; - }; - - const handleBunkerLogin = async () => { - if (!bunkerUri.trim()) { - setBunkerError('Please enter a bunker URI'); - return; - } - if (!validateBunkerUri(bunkerUri)) { - setBunkerError('Invalid bunker URI format. Must start with bunker://'); - return; - } - - setIsBunkerLoggingIn(true); - setBunkerError(null); - try { - await login.bunker(bunkerUri); - onLoggedIn(); - } catch { - setBunkerError('Failed to connect to bunker. Please check the URI.'); - } finally { - setIsBunkerLoggingIn(false); - } - }; - - // Mobile: flip to waiting view once the user taps "Open signer app" so - // the return trip shows progress, not the original button. Desktop: - // keep the QR scannable (no per-phase progress in @nostrify/react v0.4.1). - const showWaitingView = isMobile && hasOpenedSigner && !connectError; - - return ( -
-
- {connectError ? ( -
- - {connectError} - - -
- ) : showWaitingView ? ( -
- -

- Waiting for signer… -

- -
- ) : nostrConnectUri && qrDataUrl ? ( - <> - {!isMobile && ( - <> -
- nostrconnect QR code -
-

- Scan this QR code with your Nostr signer app to log in. -

- - )} - - {isMobile && ( - - )} - - ) : ( -
- -
- )} -
- - - - Enter bunker URI manually - {showBunkerInput ? ( - - ) : ( - - )} - - - { - setBunkerUri(e.target.value); - if (bunkerError) setBunkerError(null); - }} - placeholder="bunker://" - className={bunkerError ? 'border-red-500' : ''} - autoComplete="off" - /> - {bunkerError && ( -

{bunkerError}

- )} - -
-
-
- ); -}; - -export default BunkerLoginPanel; diff --git a/src/components/auth/LoginDialog.tsx b/src/components/auth/LoginDialog.tsx index 502dadc8..8ccfda33 100644 --- a/src/components/auth/LoginDialog.tsx +++ b/src/components/auth/LoginDialog.tsx @@ -1,16 +1,14 @@ // NOTE: This file is stable and usually should not be modified. // It is important that all functionality in this file is preserved, and should only be modified if explicitly requested. -import React, { useRef, useState, useEffect } from 'react'; -import { Shield, Upload, AlertTriangle, UserPlus, KeyRound, Sparkles, Cloud } from 'lucide-react'; +import React, { useState, useEffect } from 'react'; +import { Shield, AlertTriangle, UserPlus, Sparkles } from 'lucide-react'; import { Button } from '@/components/ui/button'; -import { Input } from '@/components/ui/input'; import { Dialog, DialogContent, DialogHeader, DialogDescription } from "@/components/ui/dialog"; -import { Tabs, TabsContent, TabsList, TabsTrigger } from '@/components/ui/tabs'; import { Alert, AlertDescription } from '@/components/ui/alert'; import { useLoginActions } from '@/hooks/useLoginActions'; import { cn } from '@/lib/utils'; -import BunkerLoginPanel from '@/components/auth/BunkerLoginPanel'; +import LoginPanel from '@/components/auth/LoginPanel'; interface LoginDialogProps { isOpen: boolean; @@ -19,40 +17,21 @@ interface LoginDialogProps { onSignup?: () => void; } -const validateNsec = (nsec: string) => { - return /^nsec1[a-zA-Z0-9]{58}$/.test(nsec); -}; - const LoginDialog: React.FC = ({ isOpen, onClose, onLogin, onSignup }) => { - const [isLoading, setIsLoading] = useState(false); - const [isFileLoading, setIsFileLoading] = useState(false); - const [nsec, setNsec] = useState(''); - const [errors, setErrors] = useState<{ - nsec?: string; - file?: string; - extension?: string; - }>({}); - const fileInputRef = useRef(null); + const [isExtensionLoading, setIsExtensionLoading] = useState(false); + const [extensionError, setExtensionError] = useState(null); const login = useLoginActions(); - // Reset all state when dialog opens/closes useEffect(() => { if (isOpen) { - // Reset state when dialog opens - setIsLoading(false); - setIsFileLoading(false); - setNsec(''); - setErrors({}); - // Reset file input - if (fileInputRef.current) { - fileInputRef.current.value = ''; - } + setIsExtensionLoading(false); + setExtensionError(null); } }, [isOpen]); const handleExtensionLogin = async () => { - setIsLoading(true); - setErrors(prev => ({ ...prev, extension: undefined })); + setIsExtensionLoading(true); + setExtensionError(null); try { if (!('nostr' in window)) { @@ -63,77 +42,15 @@ const LoginDialog: React.FC = ({ isOpen, onClose, onLogin, onS onClose(); } catch (e: unknown) { const error = e as Error; - console.error('Bunker login failed:', error); - console.error('Nsec login failed:', error); console.error('Extension login failed:', error); - setErrors(prev => ({ - ...prev, - extension: error instanceof Error ? error.message : 'Extension login failed' - })); + setExtensionError( + error instanceof Error ? error.message : 'Extension login failed', + ); } finally { - setIsLoading(false); + setIsExtensionLoading(false); } }; - const executeLogin = (key: string) => { - setIsLoading(true); - setErrors({}); - - // Use a timeout to allow the UI to update before the synchronous login call - setTimeout(() => { - try { - login.nsec(key); - onLogin(); - onClose(); - } catch { - setErrors({ nsec: "Failed to login with this key. Please check that it's correct." }); - setIsLoading(false); - } - }, 50); - }; - - const handleKeyLogin = () => { - if (!nsec.trim()) { - setErrors(prev => ({ ...prev, nsec: 'Please enter your secret key' })); - return; - } - - if (!validateNsec(nsec)) { - setErrors(prev => ({ ...prev, nsec: 'Invalid secret key format. Must be a valid nsec starting with nsec1.' })); - return; - } - executeLogin(nsec); - }; - - const handleFileUpload = (e: React.ChangeEvent) => { - const file = e.target.files?.[0]; - if (!file) return; - - setIsFileLoading(true); - setErrors({}); - - const reader = new FileReader(); - reader.onload = (event) => { - setIsFileLoading(false); - const content = event.target?.result as string; - if (content) { - const trimmedContent = content.trim(); - if (validateNsec(trimmedContent)) { - executeLogin(trimmedContent); - } else { - setErrors({ file: 'File does not contain a valid secret key.' }); - } - } else { - setErrors({ file: 'Could not read file content.' }); - } - }; - reader.onerror = () => { - setIsFileLoading(false); - setErrors({ file: 'Failed to read file.' }); - }; - reader.readAsText(file); - }; - const handleSignupClick = () => { onClose(); if (onSignup) { @@ -141,7 +58,12 @@ const LoginDialog: React.FC = ({ isOpen, onClose, onLogin, onS } }; - const defaultTab = 'nostr' in window ? 'extension' : 'key'; + const handleLoggedIn = () => { + onLogin(); + onClose(); + }; + + const hasExtension = typeof window !== 'undefined' && 'nostr' in window; return ( @@ -189,123 +111,29 @@ const LoginDialog: React.FC = ({ isOpen, onClose, onLogin, onS
- {/* Login Methods */} - - - - - Extension - - - - Key - - - - Bunker - - - - {errors.extension && ( + {/* Unified login panel — QR + nsec/bunker input + file upload */} + + + {/* Extension login (only shown when a NIP-07 extension is present) */} + {hasExtension && ( +
+ {extensionError && ( - {errors.extension} + {extensionError} )} -
- -

- Login with one click using the browser extension -

-
- -
-
- - - -
-
- - { - setNsec(e.target.value); - if (errors.nsec) setErrors(prev => ({ ...prev, nsec: undefined })); - }} - className={`rounded-lg ${ - errors.nsec ? 'border-red-500 focus-visible:ring-red-500' : '' - }`} - placeholder='nsec1...' - autoComplete="off" - /> - {errors.nsec && ( -

{errors.nsec}

- )} -
- - - -
-
-
-
-
- - or - -
-
- -
- - - {errors.file && ( -

{errors.file}

- )} -
-
-
- - - { - onLogin(); - onClose(); - }} - /> - - + +
+ )} diff --git a/src/components/auth/LoginPanel.tsx b/src/components/auth/LoginPanel.tsx new file mode 100644 index 00000000..1c3dbe8c --- /dev/null +++ b/src/components/auth/LoginPanel.tsx @@ -0,0 +1,427 @@ +import React, { useCallback, useEffect, useRef, useState } from 'react'; +import QRCode from 'qrcode'; +import { ExternalLink, Loader2, Upload } from 'lucide-react'; +import { + generateNostrConnectParams, + generateNostrConnectURI, + type NostrConnectParams, +} from '@nostrify/react/login'; + +import { Button } from '@/components/ui/button'; +import { Input } from '@/components/ui/input'; +import { Alert, AlertDescription } from '@/components/ui/alert'; +import { useLoginActions } from '@/hooks/useLoginActions'; +import { useAppContext } from '@/hooks/useAppContext'; + +interface LoginPanelProps { + /** Called after a successful login (nostrconnect QR, nsec, bunker URI, or key file). */ + onLoggedIn: () => void; +} + +const NSEC_REGEX = /^nsec1[a-zA-Z0-9]{58}$/; + +type InputKind = 'nsec' | 'bunker' | 'unknown'; + +const detectInputKind = (value: string): InputKind => { + const trimmed = value.trim(); + if (NSEC_REGEX.test(trimmed)) return 'nsec'; + if (trimmed.startsWith('bunker://')) return 'bunker'; + return 'unknown'; +}; + +// UA-based mobile check. Distinct from the viewport-based `useIsMobile` — +// here we care whether the platform can deep-link into a signer app, not +// whether the window is narrow. +const isMobileDevice = (): boolean => { + if (typeof navigator === 'undefined') return false; + return /Android|iPhone|iPad|iPod/i.test(navigator.userAgent); +}; + +/** + * Unified login panel for all string-based methods: + * - `nostrconnect://` flow gated behind a button. Desktop reveals a QR code; + * mobile redirects to a signer-app deep-link. + * - A single paste input that accepts either an `nsec1…` secret key OR a + * `bunker://` URI — the type is detected from the string on submit. + * - File upload for plain-text nsec / bunker URI files. + * + * The nostrconnect session is only opened when the user clicks the button + * (so the dialog doesn't open a relay subscription for users who just want + * to paste a key). Panel unmount aborts any in-flight listener. + */ +export const LoginPanel: React.FC = ({ onLoggedIn }) => { + const login = useLoginActions(); + const { config } = useAppContext(); + + // Session is gated: stays idle until the user clicks the remote-signer + // button. Bumping `sessionToken` while started restarts the session + // (used by "Try again"). + const [sessionStarted, setSessionStarted] = useState(false); + const [sessionToken, setSessionToken] = useState(0); + const [nostrConnectUri, setNostrConnectUri] = useState(''); + const [qrDataUrl, setQrDataUrl] = useState(''); + const [connectError, setConnectError] = useState(null); + const [hasOpenedSigner, setHasOpenedSigner] = useState(false); + // Mobile-only: tracks "user pressed Open signer app but the URI isn't + // generated yet — navigate as soon as it is." + const [pendingNavigate, setPendingNavigate] = useState(false); + + // Unified text input — accepts nsec or bunker URI, type detected on submit. + const [input, setInput] = useState(''); + const [inputError, setInputError] = useState(null); + const [isInputLoggingIn, setIsInputLoggingIn] = useState(false); + const [isFileLoading, setIsFileLoading] = useState(false); + const fileInputRef = useRef(null); + + const abortControllerRef = useRef(null); + // Refs so the listener effect can read the latest values without + // re-running on every parent re-render. `config` is rebuilt every render + // by AppProvider, so we must NOT depend on it in the effect's dep array — + // otherwise the in-flight subscription is torn down on each parent render. + const loginRef = useRef(login); + const onLoggedInRef = useRef(onLoggedIn); + const configRef = useRef(config); + + useEffect(() => { + loginRef.current = login; + onLoggedInRef.current = onLoggedIn; + configRef.current = config; + }); + + const isMobile = isMobileDevice(); + + // Open a nostrconnect session and start listening for the signer. Runs + // only after the user clicks the start button (`sessionStarted=true`), + // and re-runs when `sessionToken` is bumped by "Try again". + useEffect(() => { + if (!sessionStarted) return; + + let cancelled = false; + const controller = new AbortController(); + abortControllerRef.current?.abort(); + abortControllerRef.current = controller; + + const run = async () => { + const relayUrls = (configRef.current.relayMetadata?.relays ?? []) + .filter((r) => r.write !== false) + .map((r) => r.url); + + if (relayUrls.length === 0) { + if (!cancelled) { + setConnectError( + 'No relays configured. Add a relay in settings to use this login method.', + ); + } + return; + } + + const params: NostrConnectParams = generateNostrConnectParams(relayUrls); + const uri = generateNostrConnectURI(params, { + name: 'Shakespeare', + callback: isMobileDevice() + ? `${window.location.origin}/remoteloginsuccess` + : undefined, + }); + + // Publish the URI ASAP so a pending mobile navigate can fire while + // the QR renders in the background. + if (cancelled) return; + setNostrConnectUri(uri); + setConnectError(null); + + // Desktop renders a QR; mobile redirects, so skip the work there. + if (!isMobileDevice()) { + try { + const dataUrl = await QRCode.toDataURL(uri, { + width: 400, + margin: 2, + color: { dark: '#000000', light: '#FFFFFF' }, + }); + if (cancelled) return; + setQrDataUrl(dataUrl); + } catch (e) { + console.error('Failed to render nostrconnect QR:', e); + } + } + + try { + await loginRef.current.nostrconnect(params, controller.signal); + if (cancelled || controller.signal.aborted) return; + onLoggedInRef.current(); + } catch (error) { + if (cancelled || controller.signal.aborted) return; + if (error instanceof Error && error.name === 'AbortError') return; + console.error('nostrconnect failed:', error); + setConnectError( + error instanceof Error ? error.message : 'Failed to connect to signer.', + ); + } + }; + + void run(); + + return () => { + cancelled = true; + controller.abort(); + }; + // Intentional: deps limited to `sessionStarted` + `sessionToken` so + // parent re-renders don't tear down the in-flight subscription. Config + // + login are read via refs that are updated each render. + }, [sessionStarted, sessionToken]); + + // Mobile: once the URI is ready and the user already tapped "Open signer + // app", navigate to the deep-link. Runs once per click; the flag is + // consumed here. + useEffect(() => { + if (!pendingNavigate || !nostrConnectUri || connectError) return; + setPendingNavigate(false); + setHasOpenedSigner(true); + window.location.href = nostrConnectUri; + }, [pendingNavigate, nostrConnectUri, connectError]); + + const handleStartDesktopSession = () => { + setSessionStarted(true); + }; + + const handleOpenSignerApp = () => { + // Mobile: arm the navigate-when-ready effect and start the session. + // If the session is already running (e.g. retry after error), this + // just navigates with the existing URI. + setPendingNavigate(true); + setSessionStarted(true); + }; + + const handleConnectRetry = useCallback(() => { + setNostrConnectUri(''); + setQrDataUrl(''); + setConnectError(null); + setHasOpenedSigner(false); + setPendingNavigate(false); + setSessionToken((t) => t + 1); + }, []); + + const submitInput = async (rawValue: string) => { + const trimmed = rawValue.trim(); + if (!trimmed) { + setInputError('Enter a secret key or bunker URI'); + return; + } + + const kind = detectInputKind(trimmed); + if (kind === 'unknown') { + setInputError('Unrecognized format. Expected nsec1… or bunker://…'); + return; + } + + setIsInputLoggingIn(true); + setInputError(null); + + try { + if (kind === 'nsec') { + // login.nsec is synchronous but throws on bad keys. + login.nsec(trimmed); + } else { + await login.bunker(trimmed); + } + onLoggedIn(); + } catch { + setInputError( + kind === 'nsec' + ? "Failed to log in with this key. Please check that it's correct." + : 'Failed to connect to bunker. Please check the URI.', + ); + } finally { + setIsInputLoggingIn(false); + } + }; + + const handleSubmit = () => { + void submitInput(input); + }; + + const handleFileUpload = (e: React.ChangeEvent) => { + const file = e.target.files?.[0]; + if (!file) return; + + setIsFileLoading(true); + setInputError(null); + + const reader = new FileReader(); + reader.onload = (event) => { + setIsFileLoading(false); + const content = event.target?.result as string; + if (!content) { + setInputError('Could not read file content.'); + return; + } + const trimmed = content.trim(); + if (detectInputKind(trimmed) === 'unknown') { + setInputError('File does not contain a valid nsec or bunker URI.'); + return; + } + setInput(trimmed); + void submitInput(trimmed); + }; + reader.onerror = () => { + setIsFileLoading(false); + setInputError('Failed to read file.'); + }; + reader.readAsText(file); + // Reset so the same file can be selected again after a failure. + if (fileInputRef.current) fileInputRef.current.value = ''; + }; + + const renderRemoteSignerSection = () => { + // Idle: just a button. Clicking it generates the session and either + // reveals the QR (desktop) or deep-links to a signer app (mobile). + if (!sessionStarted) { + return ( + + ); + } + + if (connectError) { + return ( +
+ + {connectError} + + +
+ ); + } + + if (isMobile && hasOpenedSigner) { + return ( +
+ +

+ Waiting for signer… +

+ +
+ ); + } + + if (!isMobile && qrDataUrl) { + return ( +
+
+ nostrconnect QR code +
+

+ Scan this QR code with your Nostr signer app to log in. +

+ +
+ ); + } + + // Mobile pre-navigate or desktop pre-QR — short transient state. + return ( +
+ +
+ ); + }; + + return ( +
+ {renderRemoteSignerSection()} + +
+
+
+
+
+ + or paste a key or URI + +
+
+ +
+ { + setInput(e.target.value); + if (inputError) setInputError(null); + }} + onKeyDown={(e) => { + if (e.key === 'Enter' && input.trim() && !isInputLoggingIn) { + e.preventDefault(); + handleSubmit(); + } + }} + placeholder="nsec1… or bunker://…" + className={inputError ? 'border-red-500' : ''} + autoComplete="off" + /> + {inputError && ( +

{inputError}

+ )} +
+ +
+ + + + +
+
+ ); +}; + +export default LoginPanel; diff --git a/src/components/auth/SimpleLoginDialog.tsx b/src/components/auth/SimpleLoginDialog.tsx index e2987af4..de6f9373 100644 --- a/src/components/auth/SimpleLoginDialog.tsx +++ b/src/components/auth/SimpleLoginDialog.tsx @@ -1,14 +1,7 @@ -import React, { useState, useEffect, useRef } from 'react'; -import { Upload } from 'lucide-react'; -import { Button } from '@/components/ui/button'; -import { Input } from '@/components/ui/input'; +import React, { useState, useEffect } from 'react'; import { Dialog, DialogContent, DialogHeader, DialogTitle } from "@/components/ui/dialog"; -// Alert components removed as they're not used in the simplified design import { useLoginActions } from '@/hooks/useLoginActions'; -import { cn } from '@/lib/utils'; -import BunkerLoginPanel from '@/components/auth/BunkerLoginPanel'; - -// Only using key-add step now +import LoginPanel from '@/components/auth/LoginPanel'; interface SimpleLoginDialogProps { isOpen: boolean; @@ -17,48 +10,27 @@ interface SimpleLoginDialogProps { onSignup?: () => void; } -const validateNsec = (nsec: string) => { - return /^nsec1[a-zA-Z0-9]{58}$/.test(nsec); -}; - const SimpleLoginDialog: React.FC = ({ isOpen, onClose, onLogin, onSignup }) => { - // Removed step state - we only have one step now - const [isLoading, setIsLoading] = useState(false); - const [isFileLoading, setIsFileLoading] = useState(false); - const [nsec, setNsec] = useState(''); - const [activeTab, setActiveTab] = useState<'nsec' | 'bunker'>('nsec'); - const [errors, setErrors] = useState<{ - nsec?: string; - extension?: string; - file?: string; - }>({}); - const fileInputRef = useRef(null); + const [isExtensionLoading, setIsExtensionLoading] = useState(false); + const [extensionError, setExtensionError] = useState(null); const login = useLoginActions(); - // Reset state when dialog opens/closes useEffect(() => { if (isOpen) { - setIsLoading(false); - setIsFileLoading(false); - setNsec(''); - setActiveTab('nsec'); - setErrors({}); - // Reset file input - if (fileInputRef.current) { - fileInputRef.current.value = ''; - } + setIsExtensionLoading(false); + setExtensionError(null); } }, [isOpen]); const handleExtensionLogin = async () => { - setIsLoading(true); - setErrors(prev => ({ ...prev, extension: undefined })); + setIsExtensionLoading(true); + setExtensionError(null); try { if (!('nostr' in window)) { @@ -69,74 +41,12 @@ const SimpleLoginDialog: React.FC = ({ onClose(); } catch (e: unknown) { const error = e as Error; - setErrors(prev => ({ - ...prev, - extension: error instanceof Error ? error.message : 'Extension login failed' - })); + setExtensionError(error instanceof Error ? error.message : 'Extension login failed'); } finally { - setIsLoading(false); + setIsExtensionLoading(false); } }; - const handleKeyLogin = () => { - if (!nsec.trim()) { - setErrors(prev => ({ ...prev, nsec: 'Please enter your secret key' })); - return; - } - - if (!validateNsec(nsec)) { - setErrors(prev => ({ ...prev, nsec: 'Invalid secret key format. Must be a valid nsec starting with nsec1.' })); - return; - } - executeLogin(nsec); - }; - - const executeLogin = (key: string) => { - setIsLoading(true); - setErrors({}); - - // Use a timeout to allow the UI to update before the synchronous login call - setTimeout(() => { - try { - login.nsec(key); - onLogin(); - onClose(); - } catch { - setErrors({ nsec: "Failed to login with this key. Please check that it's correct." }); - setIsLoading(false); - } - }, 50); - }; - - const handleFileUpload = (e: React.ChangeEvent) => { - const file = e.target.files?.[0]; - if (!file) return; - - setIsFileLoading(true); - setErrors({}); - - const reader = new FileReader(); - reader.onload = (event) => { - setIsFileLoading(false); - const content = event.target?.result as string; - if (content) { - const trimmedContent = content.trim(); - if (validateNsec(trimmedContent)) { - executeLogin(trimmedContent); - } else { - setErrors({ file: 'File does not contain a valid secret key.' }); - } - } else { - setErrors({ file: 'Could not read file content.' }); - } - }; - reader.onerror = () => { - setIsFileLoading(false); - setErrors({ file: 'Failed to read file.' }); - }; - reader.readAsText(file); - }; - const handleSignupClick = () => { onClose(); if (onSignup) { @@ -144,6 +54,11 @@ const SimpleLoginDialog: React.FC = ({ } }; + const handleLoggedIn = () => { + onLogin(); + onClose(); + }; + return ( @@ -151,139 +66,41 @@ const SimpleLoginDialog: React.FC = ({ Log in -
+

Welcome back to Shakespeare

Sign in to your existing account

-
-
- 🔑 -
+
+
-
- {/* Tab selector */} -
- - + {window.nostr && ( +
+

+ +

+ {extensionError && ( +

{extensionError}

+ )}
+ )} - {activeTab === 'nsec' && ( -
-
- { - setNsec(e.target.value); - if (errors.nsec) setErrors(prev => ({ ...prev, nsec: undefined })); - }} - placeholder="nsec1..." - className={errors.nsec ? 'border-red-500' : ''} - /> - {errors.nsec && ( -

{errors.nsec}

- )} -
- -
- - - - -
- - {errors.file && ( -

{errors.file}

- )} -
- )} - - {activeTab === 'bunker' && ( - { - onLogin(); - onClose(); - }} - /> - )} - -
-
-
-
-
- or -
-
- - {/* Extension indicator - only show if extension is detected */} - {window.nostr && ( -
-

- -

-
- )} - -
- New to Shakespeare? - -
+
+ New to Shakespeare? +
@@ -291,4 +108,4 @@ const SimpleLoginDialog: React.FC = ({ ); }; -export default SimpleLoginDialog; \ No newline at end of file +export default SimpleLoginDialog;