mirror of
https://gitlab.com/soapbox-pub/mkstack.git
synced 2026-12-03 08:07:21 +00:00
feat: add NIP-46 nostrconnect with QR code for web login
This commit is contained in:
1 parent
413aa93e4f
commit
ca1b0cd303
4 files changed
+321
-48
No files matched your search
Generated
+10
@@ -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",
|
||||
|
||||
@@ -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",
|
||||
|
||||
@@ -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<LoginDialogProps> = ({ isOpen, onClose, onLogin, onSignup }) => {
|
||||
@@ -31,6 +37,12 @@ const LoginDialog: React.FC<LoginDialogProps> = ({ isOpen, onClose, onLogin, onS
|
||||
const [isFileLoading, setIsFileLoading] = useState(false);
|
||||
const [nsec, setNsec] = useState('');
|
||||
const [bunkerUri, setBunkerUri] = useState('');
|
||||
const [nostrConnectParams, setNostrConnectParams] = useState<NostrConnectParams | null>(null);
|
||||
const [nostrConnectUri, setNostrConnectUri] = useState<string>('');
|
||||
const [isWaitingForConnect, setIsWaitingForConnect] = useState(false);
|
||||
const [connectError, setConnectError] = useState<string | null>(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<LoginDialogProps> = ({ isOpen, onClose, onLogin, onS
|
||||
extension?: string;
|
||||
}>({});
|
||||
const fileInputRef = useRef<HTMLInputElement>(null);
|
||||
const abortControllerRef = useRef<AbortController | null>(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<LoginDialogProps> = ({ 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<LoginDialogProps> = ({ 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<LoginDialogProps> = ({ 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<LoginDialogProps> = ({ isOpen, onClose, onLogin, onS
|
||||
}
|
||||
};
|
||||
|
||||
const defaultTab = 'nostr' in window ? 'extension' : 'key';
|
||||
const defaultTab = hasExtension ? 'extension' : 'connect';
|
||||
|
||||
return (
|
||||
<Dialog open={isOpen} onOpenChange={onClose}>
|
||||
@@ -226,21 +296,30 @@ const LoginDialog: React.FC<LoginDialogProps> = ({ isOpen, onClose, onLogin, onS
|
||||
</div>
|
||||
|
||||
{/* Login Methods */}
|
||||
<Tabs defaultValue={defaultTab} className="w-full">
|
||||
<Tabs
|
||||
defaultValue={defaultTab}
|
||||
className="w-full"
|
||||
onValueChange={(value) => {
|
||||
if (value === 'connect' && !nostrConnectParams && !connectError) {
|
||||
generateConnectSession();
|
||||
}
|
||||
}}
|
||||
>
|
||||
<TabsList className="grid w-full grid-cols-3 bg-muted/80 rounded-lg mb-4">
|
||||
<TabsTrigger value="extension" className="flex items-center gap-2">
|
||||
<Shield className="w-4 h-4" />
|
||||
<span>Extension</span>
|
||||
</TabsTrigger>
|
||||
<TabsTrigger value="connect" className="flex items-center gap-2">
|
||||
<Link className="w-4 h-4" />
|
||||
<span>Connect</span>
|
||||
</TabsTrigger>
|
||||
<TabsTrigger value="key" className="flex items-center gap-2">
|
||||
<KeyRound className="w-4 h-4" />
|
||||
<span>Key</span>
|
||||
</TabsTrigger>
|
||||
<TabsTrigger value="bunker" className="flex items-center gap-2">
|
||||
<Cloud className="w-4 h-4" />
|
||||
<span>Bunker</span>
|
||||
</TabsTrigger>
|
||||
</TabsList>
|
||||
|
||||
<TabsContent value='extension' className='space-y-3 bg-muted'>
|
||||
{errors.extension && (
|
||||
<Alert variant="destructive">
|
||||
@@ -265,6 +344,110 @@ const LoginDialog: React.FC<LoginDialogProps> = ({ isOpen, onClose, onLogin, onS
|
||||
</div>
|
||||
</TabsContent>
|
||||
|
||||
<TabsContent value='connect' className='space-y-4'>
|
||||
{/* Nostrconnect Section */}
|
||||
<div className='flex flex-col items-center space-y-4'>
|
||||
{connectError ? (
|
||||
<div className='flex flex-col items-center space-y-4 py-4'>
|
||||
<p className='text-sm text-red-500 text-center'>{connectError}</p>
|
||||
<Button variant='outline' onClick={handleRetry}>
|
||||
Try Again
|
||||
</Button>
|
||||
</div>
|
||||
) : nostrConnectUri ? (
|
||||
<>
|
||||
{/* QR Code */}
|
||||
<div className='p-4 bg-white rounded-xl'>
|
||||
<QRCodeSVG
|
||||
value={nostrConnectUri}
|
||||
size={180}
|
||||
level='M'
|
||||
includeMargin={false}
|
||||
/>
|
||||
</div>
|
||||
|
||||
{/* Status message */}
|
||||
<div className='flex items-center gap-2 text-sm text-muted-foreground'>
|
||||
{isWaitingForConnect ? (
|
||||
<>
|
||||
<Loader2 className='w-4 h-4 animate-spin' />
|
||||
<span>Waiting for connection...</span>
|
||||
</>
|
||||
) : (
|
||||
<span>Scan with your signer app</span>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{/* Copy button */}
|
||||
<Button
|
||||
variant='outline'
|
||||
size='sm'
|
||||
className='gap-2'
|
||||
onClick={handleCopyUri}
|
||||
>
|
||||
{copied ? (
|
||||
<>
|
||||
<Check className='w-4 h-4' />
|
||||
Copied!
|
||||
</>
|
||||
) : (
|
||||
<>
|
||||
<Copy className='w-4 h-4' />
|
||||
Copy Connection String
|
||||
</>
|
||||
)}
|
||||
</Button>
|
||||
</>
|
||||
) : (
|
||||
<div className='flex items-center justify-center h-[100px]'>
|
||||
<Loader2 className='w-8 h-8 animate-spin text-muted-foreground' />
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{/* Manual URI input section - collapsible */}
|
||||
<div className='pt-4 border-t border-gray-200 dark:border-gray-700'>
|
||||
<button
|
||||
type='button'
|
||||
onClick={() => setShowBunkerInput(!showBunkerInput)}
|
||||
className='flex items-center justify-center gap-2 w-full text-sm text-muted-foreground hover:text-foreground transition-colors py-2'
|
||||
>
|
||||
<span>Manual bunker connection</span>
|
||||
{showBunkerInput ? (
|
||||
<ChevronUp className='w-4 h-4' />
|
||||
) : (
|
||||
<ChevronDown className='w-4 h-4' />
|
||||
)}
|
||||
</button>
|
||||
|
||||
{showBunkerInput && (
|
||||
<div className='space-y-3 mt-3'>
|
||||
<div className='space-y-2'>
|
||||
<Input
|
||||
id='connectBunkerUri'
|
||||
value={bunkerUri}
|
||||
onChange={(e) => 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) && (
|
||||
<p className='text-red-500 text-xs'>URI must start with bunker:// or nostrconnect://</p>
|
||||
)}
|
||||
</div>
|
||||
|
||||
<Button
|
||||
className='w-full rounded-full py-4'
|
||||
variant='outline'
|
||||
onClick={handleBunkerLogin}
|
||||
disabled={isLoading || !bunkerUri.trim() || !validateBunkerUri(bunkerUri)}
|
||||
>
|
||||
{isLoading ? 'Connecting...' : 'Connect with Bunker'}
|
||||
</Button>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</TabsContent>
|
||||
|
||||
<TabsContent value='key' className='space-y-4'>
|
||||
<div className='space-y-4'>
|
||||
<div className='space-y-2'>
|
||||
@@ -333,39 +516,6 @@ const LoginDialog: React.FC<LoginDialogProps> = ({ isOpen, onClose, onLogin, onS
|
||||
</div>
|
||||
</TabsContent>
|
||||
|
||||
<TabsContent value='bunker' className='space-y-3 bg-muted'>
|
||||
<div className='space-y-2'>
|
||||
<label htmlFor='bunkerUri' className='text-sm font-medium text-gray-700 dark:text-gray-400'>
|
||||
Bunker URI
|
||||
</label>
|
||||
<Input
|
||||
id='bunkerUri'
|
||||
value={bunkerUri}
|
||||
onChange={(e) => {
|
||||
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 && (
|
||||
<p className="text-sm text-red-500">{errors.bunker}</p>
|
||||
)}
|
||||
</div>
|
||||
|
||||
<div className="flex justify-center">
|
||||
<Button
|
||||
className='w-full rounded-full py-4'
|
||||
onClick={handleBunkerLogin}
|
||||
disabled={isLoading || !bunkerUri.trim()}
|
||||
>
|
||||
{isLoading ? 'Connecting...' : 'Login with Bunker'}
|
||||
</Button>
|
||||
</div>
|
||||
</TabsContent>
|
||||
</Tabs>
|
||||
</div>
|
||||
</DialogContent>
|
||||
|
||||
@@ -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<void> {
|
||||
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<void> {
|
||||
const login = logins[0];
|
||||
|
||||
Reference in new issue
Block a user