diff --git a/package-lock.json b/package-lock.json index 4c38838..e7095cd 100644 --- a/package-lock.json +++ b/package-lock.json @@ -9,7 +9,7 @@ "version": "0.0.0", "dependencies": { "@nostrify/nostrify": "^0.52.0", - "@nostrify/react": "^0.5.2", + "@nostrify/react": "^0.6.0", "@radix-ui/react-toast": "^1.2.1", "@tanstack/react-query": "^5.100.5", "@unhead/react": "^3.1.0", @@ -1034,9 +1034,9 @@ } }, "node_modules/@nostrify/react": { - "version": "0.5.2", - "resolved": "https://registry.npmjs.org/@nostrify/react/-/react-0.5.2.tgz", - "integrity": "sha512-9Djb+lHM+ius/Eu8eaC6B2VCRwtfd/qxP0bq8VE+Y+4/wuXMTw2PQ+/c4blQh6szuKwB822mkqsQhv5adT5Ofg==", + "version": "0.6.0", + "resolved": "https://registry.npmjs.org/@nostrify/react/-/react-0.6.0.tgz", + "integrity": "sha512-6vjF5UagAW5QRpxAu/of9lyI7837wwoyX/NLGQbEs6fcMQXjTo/m7wUBPipoj0E460QvyNXff5O8Byn72enWbQ==", "dependencies": { "@nostrify/nostrify": "0.52.0", "@nostrify/types": "0.37.0" diff --git a/package.json b/package.json index 3c2b118..f55381a 100644 --- a/package.json +++ b/package.json @@ -10,7 +10,7 @@ }, "dependencies": { "@nostrify/nostrify": "^0.52.0", - "@nostrify/react": "^0.5.2", + "@nostrify/react": "^0.6.0", "@radix-ui/react-toast": "^1.2.1", "@tanstack/react-query": "^5.100.5", "@unhead/react": "^3.1.0", diff --git a/src/components/auth/AuthDialog.tsx b/src/components/auth/AuthDialog.tsx index 0e200f8..497f27b 100644 --- a/src/components/auth/AuthDialog.tsx +++ b/src/components/auth/AuthDialog.tsx @@ -5,8 +5,6 @@ import { Eye, EyeOff, Key, - Copy, - Check, ChevronDown, ChevronUp, Loader2, @@ -29,6 +27,7 @@ import { generateNostrConnectParams, generateNostrConnectURI, type NostrConnectParams, + type NostrConnectStatus, } from '@/hooks/useLoginActions'; import { useNostrPublish } from '@/hooks/useNostrPublish'; import { useUploadFile } from '@/hooks/useUploadFile'; @@ -45,6 +44,17 @@ type Step = 'welcome' | 'generate' | 'secure' | 'profile' | 'login' | 'connect'; const validateNsec = (nsec: string) => /^nsec1[a-zA-Z0-9]{58}$/.test(nsec); const validateBunkerUri = (uri: string) => uri.startsWith('bunker://'); +const connectStatusLabel = (status: NostrConnectStatus | null): string => { + switch (status) { + case 'awaiting-connect': + return 'Waiting for signer connection…'; + case 'getting-public-key': + return 'Getting public key…'; + default: + return ''; + } +}; + /** Check if running on an actual mobile device (not just a small screen). */ function isMobileDevice(): boolean { if (typeof navigator === 'undefined') return false; @@ -89,18 +99,36 @@ const AuthDialog: React.FC = ({ isOpen, onClose }) => { // Nostrconnect / bunker state const [nostrConnectParams, setNostrConnectParams] = useState(null); const [nostrConnectUri, setNostrConnectUri] = useState(''); - const [isWaitingForConnect, setIsWaitingForConnect] = useState(false); const [connectError, setConnectError] = useState(null); - const [uriCopied, setUriCopied] = useState(false); + // 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. + 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`. + const [hasOpenedSigner, setHasOpenedSigner] = useState(false); const [showBunkerInput, setShowBunkerInput] = useState(false); const [bunkerUri, setBunkerUri] = useState(''); const login = useLoginActions(); - // Stable ref so the nostrconnect effect doesn't restart on every render. + // Stable refs so the nostrconnect listening effect below doesn't restart on + // every parent render. Parents typically pass inline arrow functions for + // onClose, and useLoginActions returns a fresh object each render — without + // stable refs, an effect depending on them would tear down the in-flight + // subscription on every render and cause approved logins to be swallowed. const loginRef = useRef(login); + const onCloseRef = useRef(onClose); useEffect(() => { loginRef.current = login; }, [login]); + useEffect(() => { + onCloseRef.current = onClose; + }, [onClose]); const { mutateAsync: publishEvent, isPending: isPublishing } = useNostrPublish(); const { mutateAsync: uploadFile, isPending: isUploading } = useUploadFile(); @@ -130,9 +158,9 @@ const AuthDialog: React.FC = ({ isOpen, onClose }) => { setProfileData({ name: '', about: '', picture: '' }); setNostrConnectParams(null); setNostrConnectUri(''); - setIsWaitingForConnect(false); setConnectError(null); - setUriCopied(false); + setConnectStatus(null); + setHasOpenedSigner(false); setShowBunkerInput(false); setBunkerUri(''); /* eslint-enable react-hooks/set-state-in-effect */ @@ -154,57 +182,72 @@ const AuthDialog: React.FC = ({ isOpen, onClose }) => { }, [login]); // Start listening for a nostrconnect response once params are set. + // + // Deps are intentionally limited to `nostrConnectParams` so that parent + // re-renders (which produce fresh onClose closures and a fresh `login` + // object from useLoginActions) do NOT tear down an in-flight + // subscription. An earlier version used a `cancelled` flag flipped by + // the effect's cleanup, which caused a successful nostrconnect response + // to be silently swallowed after the signer approved — the subscription + // was re-created mid-handshake and the first instance's success branch + // saw `cancelled === true`. + // + // Cancellation is handled explicitly by the `isOpen` effect (on dialog + // close) and by handleConnectRetry() (on user cancel/retry). useEffect(() => { - if (!nostrConnectParams || isWaitingForConnect) return; - - let cancelled = false; + if (!nostrConnectParams) return; const startListening = async () => { - setIsWaitingForConnect(true); - abortControllerRef.current = new AbortController(); + const controller = new AbortController(); + abortControllerRef.current = controller; try { await loginRef.current.nostrconnect( nostrConnectParams, - abortControllerRef.current.signal, + controller.signal, + (status) => { + if (controller.signal.aborted) return; + setConnectStatus(status); + }, ); - if (!cancelled) onClose(); + // If the dialog was explicitly closed (handled by the isOpen + // effect, which aborts the controller), don't try to re-close it. + // Otherwise the user is logged in — close the dialog. + if (controller.signal.aborted) return; + onCloseRef.current(); } catch (error) { - if (cancelled) return; + // AbortError means we intentionally aborted (dialog closed or retry) if (error instanceof Error && error.name === 'AbortError') return; + if (controller.signal.aborted) return; console.error('Nostrconnect failed:', error); + setConnectStatus(null); setConnectError(error instanceof Error ? error.message : String(error)); - setIsWaitingForConnect(false); } }; startListening(); - return () => { - cancelled = true; - }; - // NOTE: isWaitingForConnect is intentionally excluded from deps. Including - // it would cancel the first run the moment it sets the flag to true and - // spawn a duplicate listener. - // eslint-disable-next-line react-hooks/exhaustive-deps - }, [nostrConnectParams, onClose]); + // No cleanup here: we do NOT want a re-render-triggered effect teardown + // to cancel the in-flight subscription. + }, [nostrConnectParams]); const handleConnectRetry = useCallback(() => { + abortControllerRef.current?.abort(); setNostrConnectParams(null); setNostrConnectUri(''); - setIsWaitingForConnect(false); setConnectError(null); + setConnectStatus(null); + setHasOpenedSigner(false); setTimeout(() => generateConnectSession(), 0); }, [generateConnectSession]); - const handleCopyUri = async () => { - await navigator.clipboard.writeText(nostrConnectUri); - setUriCopied(true); - setTimeout(() => setUriCopied(false), 2000); - }; - 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. + setHasOpenedSigner(true); window.location.href = nostrConnectUri; }; @@ -368,6 +411,18 @@ const AuthDialog: React.FC = ({ isOpen, onClose }) => { } }; + // 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) + ); + return ( @@ -666,10 +721,6 @@ const AuthDialog: React.FC = ({ isOpen, onClose }) => { {/* Connect step — nostrconnect QR + bunker URI fallback. */} {step === 'connect' && (
-

- {isMobile ? 'Open your signer app to connect.' : 'Scan with your signer app.'} -

-
{connectError ? (
@@ -678,6 +729,24 @@ const AuthDialog: React.FC = ({ isOpen, onClose }) => { Try again
+ ) : 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 && ( @@ -692,25 +761,6 @@ const AuthDialog: React.FC = ({ isOpen, onClose }) => { Open signer app )} - - ) : (
diff --git a/src/hooks/useLoginActions.ts b/src/hooks/useLoginActions.ts index 56f673a..c087580 100644 --- a/src/hooks/useLoginActions.ts +++ b/src/hooks/useLoginActions.ts @@ -1,10 +1,15 @@ import { useNostr } from '@nostrify/react'; -import { NLogin, type NostrConnectParams, useNostrLogin } from '@nostrify/react/login'; +import { + NLogin, + type NostrConnectParams, + type NostrConnectStatus, + useNostrLogin, +} from '@nostrify/react/login'; import { useAppContext } from '@/hooks/useAppContext'; // NOTE: This file should not be edited except for adding new login methods. -export type { NostrConnectParams }; +export type { NostrConnectParams, NostrConnectStatus }; export { generateNostrConnectParams, generateNostrConnectURI } from '@nostrify/react/login'; export function useLoginActions() { @@ -29,9 +34,16 @@ export function useLoginActions() { addLogin(login); }, // Login via nostrconnect:// (client-initiated NIP-46) - // The client displays a QR code and waits for the remote signer to connect - async nostrconnect(params: NostrConnectParams, signal?: AbortSignal): Promise { - const login = await NLogin.fromNostrConnect(params, nostr, { signal }); + // The client displays a QR code and waits for the remote signer to connect. + // + // `onStatus` is forwarded from @nostrify/react so the UI can render + // live progress through the handshake phases — see NostrConnectStatus. + async nostrconnect( + params: NostrConnectParams, + signal?: AbortSignal, + onStatus?: (status: NostrConnectStatus) => void, + ): Promise { + const login = await NLogin.fromNostrConnect(params, nostr, { signal, onStatus }); addLogin(login); }, // Get the relay URLs for NIP-46 nostrconnect communication @@ -39,7 +51,7 @@ export function useLoginActions() { const relays = config.relayMetadata.relays .filter((r) => r.write) .map((r) => r.url); - return relays.length > 0 ? relays : ['wss://relay.damus.io']; + return relays.length > 0 ? relays : ['wss://relay.ditto.pub']; }, // Log out the current user async logout(): Promise {