From ca1b0cd303e5653bb31f0d93d29518717da9c412 Mon Sep 17 00:00:00 2001 From: Derek Ross Date: Mon, 29 Dec 2025 14:56:46 -0500 Subject: [PATCH] feat: add NIP-46 nostrconnect with QR code for web login --- package-lock.json | 10 ++ package.json | 1 + src/components/auth/LoginDialog.tsx | 246 ++++++++++++++++++++++------ src/hooks/useLoginActions.ts | 112 +++++++++++++ 4 files changed, 321 insertions(+), 48 deletions(-) diff --git a/package-lock.json b/package-lock.json index 4ae585c..c026696 100644 --- a/package-lock.json +++ b/package-lock.json @@ -54,6 +54,7 @@ "lucide-react": "^0.462.0", "nostr-tools": "^2.13.0", "qrcode": "^1.5.4", + "qrcode.react": "^4.2.0", "react": "^18.3.1", "react-day-picker": "^8.10.1", "react-dom": "^18.3.1", @@ -6680,6 +6681,15 @@ "node": ">=10.13.0" } }, + "node_modules/qrcode.react": { + "version": "4.2.0", + "resolved": "https://registry.npmjs.org/qrcode.react/-/qrcode.react-4.2.0.tgz", + "integrity": "sha512-QpgqWi8rD9DsS9EP3z7BT+5lY5SFhsqGjpgW5DY/i3mK4M9DTBNz3ErMi8BWYEfI3L0d8GIbGmcdFAS1uIRGjA==", + "license": "ISC", + "peerDependencies": { + "react": "^16.8.0 || ^17.0.0 || ^18.0.0 || ^19.0.0" + } + }, "node_modules/queue-microtask": { "version": "1.2.3", "resolved": "https://registry.npmjs.org/queue-microtask/-/queue-microtask-1.2.3.tgz", diff --git a/package.json b/package.json index 981616a..1ca8a97 100644 --- a/package.json +++ b/package.json @@ -56,6 +56,7 @@ "lucide-react": "^0.462.0", "nostr-tools": "^2.13.0", "qrcode": "^1.5.4", + "qrcode.react": "^4.2.0", "react": "^18.3.1", "react-day-picker": "^8.10.1", "react-dom": "^18.3.1", diff --git a/src/components/auth/LoginDialog.tsx b/src/components/auth/LoginDialog.tsx index ff40ec0..3f3398f 100644 --- a/src/components/auth/LoginDialog.tsx +++ b/src/components/auth/LoginDialog.tsx @@ -1,14 +1,20 @@ // 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, { useCallback, useEffect, useRef, useState } from 'react'; +import { QRCodeSVG } from 'qrcode.react'; +import { Shield, Upload, AlertTriangle, UserPlus, KeyRound, Sparkles, Loader2, Copy, Check, ChevronDown, ChevronUp, Link } 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 { + useLoginActions, + generateNostrConnectParams, + generateNostrConnectURI, + type NostrConnectParams, +} from '@/hooks/useLoginActions'; import { cn } from '@/lib/utils'; interface LoginDialogProps { @@ -23,7 +29,7 @@ const validateNsec = (nsec: string) => { }; const validateBunkerUri = (uri: string) => { - return uri.startsWith('bunker://'); + return uri.startsWith('bunker://') || uri.startsWith('nostrconnect://'); }; const LoginDialog: React.FC = ({ isOpen, onClose, onLogin, onSignup }) => { @@ -31,6 +37,12 @@ const LoginDialog: React.FC = ({ isOpen, onClose, onLogin, onS const [isFileLoading, setIsFileLoading] = useState(false); const [nsec, setNsec] = useState(''); const [bunkerUri, setBunkerUri] = useState(''); + const [nostrConnectParams, setNostrConnectParams] = useState(null); + const [nostrConnectUri, setNostrConnectUri] = useState(''); + const [isWaitingForConnect, setIsWaitingForConnect] = useState(false); + const [connectError, setConnectError] = useState(null); + const [copied, setCopied] = useState(false); + const [showBunkerInput, setShowBunkerInput] = useState(false); const [errors, setErrors] = useState<{ nsec?: string; bunker?: string; @@ -38,17 +50,61 @@ const LoginDialog: React.FC = ({ isOpen, onClose, onLogin, onS extension?: string; }>({}); const fileInputRef = useRef(null); + const abortControllerRef = useRef(null); const login = useLoginActions(); + // Check if extension is available + const hasExtension = 'nostr' in window; + + // Generate nostrconnect params (sync) - just creates the QR code data + const generateConnectSession = useCallback(() => { + const relayUrl = login.getRelayUrl(); + const params = generateNostrConnectParams([relayUrl]); + const uri = generateNostrConnectURI(params, 'MKStack'); + setNostrConnectParams(params); + setNostrConnectUri(uri); + setConnectError(null); + }, [login]); + + // Start listening for connection (async) - runs after params are set + useEffect(() => { + if (!nostrConnectParams || isWaitingForConnect) return; + + const startListening = async () => { + setIsWaitingForConnect(true); + abortControllerRef.current = new AbortController(); + + try { + await login.nostrconnect(nostrConnectParams); + onLogin(); + onClose(); + } catch (error) { + console.error('Nostrconnect failed:', error); + setConnectError(error instanceof Error ? error.message : 'Connection failed'); + setIsWaitingForConnect(false); + } + }; + + startListening(); + }, [nostrConnectParams, login, onLogin, onClose, isWaitingForConnect]); + // Reset all state when dialog opens/closes useEffect(() => { - if (isOpen) { - // Reset state when dialog opens + if (!isOpen) { + // Reset state when dialog closes setIsLoading(false); setIsFileLoading(false); setNsec(''); setBunkerUri(''); + setNostrConnectParams(null); + setNostrConnectUri(''); + setIsWaitingForConnect(false); + setConnectError(null); + setShowBunkerInput(false); setErrors({}); + if (abortControllerRef.current) { + abortControllerRef.current.abort(); + } // Reset file input if (fileInputRef.current) { fileInputRef.current.value = ''; @@ -56,6 +112,22 @@ const LoginDialog: React.FC = ({ isOpen, onClose, onLogin, onS } }, [isOpen]); + // Retry connection with new params + const handleRetry = useCallback(() => { + setNostrConnectParams(null); + setNostrConnectUri(''); + setIsWaitingForConnect(false); + setConnectError(null); + // Generate new session after state clears + setTimeout(() => generateConnectSession(), 0); + }, [generateConnectSession]); + + const handleCopyUri = async () => { + await navigator.clipboard.writeText(nostrConnectUri); + setCopied(true); + setTimeout(() => setCopied(false), 2000); + }; + const handleExtensionLogin = async () => { setIsLoading(true); setErrors(prev => ({ ...prev, extension: undefined })); @@ -69,8 +141,6 @@ 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, @@ -118,7 +188,7 @@ const LoginDialog: React.FC = ({ isOpen, onClose, onLogin, onS } if (!validateBunkerUri(bunkerUri)) { - setErrors(prev => ({ ...prev, bunker: 'Invalid bunker URI format. Must start with bunker://' })); + setErrors(prev => ({ ...prev, bunker: 'Invalid URI format. Must start with bunker:// or nostrconnect://' })); return; } @@ -177,7 +247,7 @@ const LoginDialog: React.FC = ({ isOpen, onClose, onLogin, onS } }; - const defaultTab = 'nostr' in window ? 'extension' : 'key'; + const defaultTab = hasExtension ? 'extension' : 'connect'; return ( @@ -226,21 +296,30 @@ const LoginDialog: React.FC = ({ isOpen, onClose, onLogin, onS {/* Login Methods */} - + { + if (value === 'connect' && !nostrConnectParams && !connectError) { + generateConnectSession(); + } + }} + > Extension + + + Connect + Key - - - Bunker - + {errors.extension && ( @@ -265,6 +344,110 @@ const LoginDialog: React.FC = ({ isOpen, onClose, onLogin, onS + + {/* Nostrconnect Section */} +
+ {connectError ? ( +
+

{connectError}

+ +
+ ) : nostrConnectUri ? ( + <> + {/* QR Code */} +
+ +
+ + {/* Status message */} +
+ {isWaitingForConnect ? ( + <> + + Waiting for connection... + + ) : ( + Scan with your signer app + )} +
+ + {/* Copy button */} + + + ) : ( +
+ +
+ )} +
+ + {/* Manual URI input section - collapsible */} +
+ + + {showBunkerInput && ( +
+
+ setBunkerUri(e.target.value)} + className='rounded-lg border-gray-300 dark:border-gray-700 focus-visible:ring-primary text-sm' + placeholder='bunker://' + /> + {bunkerUri && !validateBunkerUri(bunkerUri) && ( +

URI must start with bunker:// or nostrconnect://

+ )} +
+ + +
+ )} +
+
+
@@ -333,39 +516,6 @@ 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}

- )} -
- -
- -
-
diff --git a/src/hooks/useLoginActions.ts b/src/hooks/useLoginActions.ts index f0d98a9..a75fe1d 100644 --- a/src/hooks/useLoginActions.ts +++ b/src/hooks/useLoginActions.ts @@ -1,11 +1,55 @@ +import { NConnectSigner, NSecSigner } from '@nostrify/nostrify'; import { useNostr } from '@nostrify/react'; import { NLogin, useNostrLogin } from '@nostrify/react/login'; +import { generateSecretKey, getPublicKey } from 'nostr-tools'; +import { nip19 } from 'nostr-tools'; + +import { useAppContext } from '@/hooks/useAppContext'; // NOTE: This file should not be edited except for adding new login methods. +/** Parameters for initiating a nostrconnect:// session */ +export interface NostrConnectParams { + clientSecretKey: Uint8Array; + clientPubkey: string; + secret: string; + relays: string[]; +} + +/** Generates a nostrconnect:// URI for QR code display */ +export function generateNostrConnectURI(params: NostrConnectParams, appName?: string): string { + const searchParams = new URLSearchParams(); + + for (const relay of params.relays) { + searchParams.append('relay', relay); + } + searchParams.set('secret', params.secret); + + if (appName) { + searchParams.set('name', appName); + } + + return `nostrconnect://${params.clientPubkey}?${searchParams.toString()}`; +} + +/** Generates random parameters for a nostrconnect session */ +export function generateNostrConnectParams(relays: string[]): NostrConnectParams { + const clientSecretKey = generateSecretKey(); + const clientPubkey = getPublicKey(clientSecretKey); + const secret = crypto.randomUUID().slice(0, 8); + + return { + clientSecretKey, + clientPubkey, + secret, + relays, + }; +} + export function useLoginActions() { const { nostr } = useNostr(); const { logins, addLogin, removeLogin } = useNostrLogin(); + const { config } = useAppContext(); return { // Login with a Nostr secret key @@ -23,6 +67,74 @@ export function useLoginActions() { const login = await NLogin.fromExtension(); 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): Promise { + const clientSigner = new NSecSigner(params.clientSecretKey); + const clientPubkey = getPublicKey(params.clientSecretKey); + + // Create a relay group for the connection + const relayGroup = nostr.group(params.relays); + + // Wait for the connect response from the remote signer + // We subscribe to kind 24133 events p-tagged to our client pubkey + const signal = AbortSignal.timeout(120_000); // 2 minute timeout + + const sub = relayGroup.req( + [{ kinds: [24133], '#p': [clientPubkey], limit: 1 }], + { signal } + ); + + for await (const msg of sub) { + if (msg[0] === 'CLOSED') { + throw new Error('Connection closed before remote signer responded'); + } + if (msg[0] === 'EVENT') { + const event = msg[2]; + + // Decrypt the response + const decrypted = await clientSigner.nip44!.decrypt(event.pubkey, event.content); + const response = JSON.parse(decrypted); + + // Validate the secret matches + if (response.result !== params.secret && response.result !== 'ack') { + continue; // Not our response, keep waiting + } + + // Success! The remote signer has connected + // Now create the NConnectSigner for ongoing use + const bunkerPubkey = event.pubkey; + + const signer = new NConnectSigner({ + relay: relayGroup, + pubkey: bunkerPubkey, + signer: clientSigner, + timeout: 60_000, + }); + + // Get the actual user pubkey + const userPubkey = await signer.getPublicKey(); + + // Create and add the login + const login = new NLogin('bunker', userPubkey, { + bunkerPubkey, + clientNsec: nip19.nsecEncode(params.clientSecretKey), + relays: params.relays, + }); + + addLogin(login); + return; + } + } + + throw new Error('Timeout waiting for remote signer'); + }, + // Get the current relay URL for nostrconnect + getRelayUrl(): string { + // Get the first write-enabled relay, or fallback to a default + const writeRelay = config.relayMetadata?.relays?.find(r => r.write); + return writeRelay?.url ?? 'wss://relay.nostr.band'; + }, // Log out the current user async logout(): Promise { const login = logins[0];