4 Commits

Author SHA1 Message Date
woikos
d9343a76bb v0.5.1: Remove CAT token support from NRC and NIP-46 bunker
- Delete cashu-token.service.ts and TokenDisplay component
- Simplify NRC to use only secret-based authentication
- Remove CAT token handling from bunker signer
- Clean up related types and UI elements

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2026-01-19 06:03:17 +01:00
woikos
28b8720dbf v0.5.0: CAT token service improvements
- Improved Cashu Access Token handling
- Version bump to v0.5.0

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2026-01-15 21:54:18 +01:00
woikos
5b23ea04d0 Add QR scanner to bunker login and enhance NRC functionality
- Add QR scanner button to bunker URL paste input for easier mobile login
- Enhance NRC (Nostr Relay Connect) with improved connection handling
- Update NRC settings UI with better status display
- Improve bunker signer reliability

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2026-01-15 10:41:00 +01:00
woikos
ecd7c36400 Add NRC (Nostr Relay Connect) for cross-device sync
Implements NRC listener that allows other user clients to connect
and sync events through a rendezvous relay. Features:
- REQ-only (read) sync for security
- Secret-based and CAT token authentication
- NIP-44 encrypted tunneling
- Device-specific event filtering via d-tag prefix
- Session management with timeouts
- Settings UI with QR code connection flow

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2026-01-11 09:16:03 +01:00
24 changed files with 3708 additions and 987 deletions

11
package-lock.json generated
View File

@@ -1,12 +1,12 @@
{
"name": "smesh",
"version": "0.3.0",
"version": "0.4.1",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "smesh",
"version": "0.3.0",
"version": "0.4.1",
"license": "MIT",
"dependencies": {
"@dnd-kit/core": "^6.3.1",
@@ -56,6 +56,7 @@
"emoji-picker-react": "^4.12.2",
"flexsearch": "^0.7.43",
"franc-min": "^6.2.0",
"html5-qrcode": "^2.3.8",
"i18next": "^24.2.0",
"i18next-browser-languagedetector": "^8.0.4",
"jotai": "^2.15.0",
@@ -8932,6 +8933,12 @@
"url": "https://opencollective.com/unified"
}
},
"node_modules/html5-qrcode": {
"version": "2.3.8",
"resolved": "https://registry.npmjs.org/html5-qrcode/-/html5-qrcode-2.3.8.tgz",
"integrity": "sha512-jsr4vafJhwoLVEDW3n1KvPnCCXWaQfRng0/EEYk1vNcQGcG/htAdhJX0be8YyqMoSz7+hZvOZSTAepsabiuhiQ==",
"license": "Apache-2.0"
},
"node_modules/i18next": {
"version": "24.2.0",
"resolved": "https://registry.npmjs.org/i18next/-/i18next-24.2.0.tgz",

View File

@@ -1,6 +1,6 @@
{
"name": "smesh",
"version": "0.4.1",
"version": "0.5.1",
"description": "A user-friendly Nostr client for exploring relay feeds",
"private": true,
"type": "module",
@@ -70,6 +70,7 @@
"emoji-picker-react": "^4.12.2",
"flexsearch": "^0.7.43",
"franc-min": "^6.2.0",
"html5-qrcode": "^2.3.8",
"i18next": "^24.2.0",
"i18next-browser-languagedetector": "^8.0.4",
"jotai": "^2.15.0",

File diff suppressed because one or more lines are too long

After

Width:  |  Height:  |  Size: 10 KiB

View File

@@ -16,6 +16,7 @@ import { SocialGraphFilterProvider } from '@/providers/SocialGraphFilterProvider
import { MediaUploadServiceProvider } from '@/providers/MediaUploadServiceProvider'
import { MuteListProvider } from '@/providers/MuteListProvider'
import { NostrProvider } from '@/providers/NostrProvider'
import { NRCProvider } from '@/providers/NRCProvider'
import { PasswordPromptProvider } from '@/providers/PasswordPromptProvider'
import { PinListProvider } from '@/providers/PinListProvider'
import { PinnedUsersProvider } from '@/providers/PinnedUsersProvider'
@@ -38,6 +39,7 @@ export default function App(): JSX.Element {
<DeletedEventProvider>
<PasswordPromptProvider>
<NostrProvider>
<NRCProvider>
<RepositoryProvider>
<SettingsSyncProvider>
<ZapProvider>
@@ -72,6 +74,7 @@ export default function App(): JSX.Element {
</ZapProvider>
</SettingsSyncProvider>
</RepositoryProvider>
</NRCProvider>
</NostrProvider>
</PasswordPromptProvider>
</DeletedEventProvider>

View File

@@ -1,9 +1,10 @@
import QrScannerModal from '@/components/QrScannerModal'
import { Button } from '@/components/ui/button'
import { Input } from '@/components/ui/input'
import { Label } from '@/components/ui/label'
import { useNostr } from '@/providers/NostrProvider'
import { BunkerSigner } from '@/providers/NostrProvider/bunker.signer'
import { ArrowLeft, Loader2, QrCode, Server, Copy, Check } from 'lucide-react'
import { ArrowLeft, Loader2, QrCode, Server, Copy, Check, ScanLine } from 'lucide-react'
import { useState, useEffect } from 'react'
import { useTranslation } from 'react-i18next'
import QRCode from 'qrcode'
@@ -28,6 +29,7 @@ export default function BunkerLogin({
const [connectUrl, setConnectUrl] = useState<string | null>(null)
const [qrDataUrl, setQrDataUrl] = useState<string | null>(null)
const [copied, setCopied] = useState(false)
const [showScanner, setShowScanner] = useState(false)
// Generate QR code when in scan mode
useEffect(() => {
@@ -88,6 +90,11 @@ export default function BunkerLogin({
}
}, [mode, relayUrl, bunkerLoginWithSigner, onLoginSuccess])
const handleScan = (result: string) => {
setBunkerUrl(result)
setError(null)
}
const handlePasteSubmit = async (e: React.FormEvent) => {
e.preventDefault()
if (!bunkerUrl.trim()) {
@@ -263,49 +270,66 @@ export default function BunkerLogin({
// Paste mode
return (
<div className="flex flex-col gap-4" onClick={(e) => e.stopPropagation()}>
<div className="flex items-center gap-2">
<Button size="icon" variant="ghost" className="rounded-full" onClick={() => setMode('choose')}>
<ArrowLeft className="size-4" />
</Button>
<>
{showScanner && (
<QrScannerModal onScan={handleScan} onClose={() => setShowScanner(false)} />
)}
<div className="flex flex-col gap-4" onClick={(e) => e.stopPropagation()}>
<div className="flex items-center gap-2">
<Server className="size-5" />
<span className="font-semibold">{t('Paste Bunker URL')}</span>
<Button size="icon" variant="ghost" className="rounded-full" onClick={() => setMode('choose')}>
<ArrowLeft className="size-4" />
</Button>
<div className="flex items-center gap-2">
<Server className="size-5" />
<span className="font-semibold">{t('Paste Bunker URL')}</span>
</div>
</div>
</div>
<form onSubmit={handlePasteSubmit} className="space-y-4">
<div className="space-y-2">
<Label htmlFor="bunkerUrl">{t('Bunker URL')}</Label>
<Input
id="bunkerUrl"
type="text"
placeholder="bunker://pubkey?relay=wss://..."
value={bunkerUrl}
onChange={(e) => setBunkerUrl(e.target.value)}
disabled={loading}
className="font-mono text-sm"
/>
<p className="text-xs text-muted-foreground">
{t(
'Enter the bunker connection URL. This is typically provided by your signing device or service.'
<form onSubmit={handlePasteSubmit} className="space-y-4">
<div className="space-y-2">
<Label htmlFor="bunkerUrl">{t('Bunker URL')}</Label>
<div className="flex gap-2">
<Input
id="bunkerUrl"
type="text"
placeholder="bunker://pubkey?relay=wss://..."
value={bunkerUrl}
onChange={(e) => setBunkerUrl(e.target.value)}
disabled={loading}
className="font-mono text-sm"
/>
<Button
type="button"
variant="outline"
size="icon"
onClick={() => setShowScanner(true)}
disabled={loading}
title={t('Scan QR code')}
>
<ScanLine className="h-4 w-4" />
</Button>
</div>
<p className="text-xs text-muted-foreground">
{t(
'Enter the bunker connection URL. This is typically provided by your signing device or service.'
)}
</p>
</div>
{error && <div className="text-sm text-destructive">{error}</div>}
<Button type="submit" className="w-full" disabled={loading || !bunkerUrl.trim()}>
{loading ? (
<>
<Loader2 className="mr-2 h-4 w-4 animate-spin" />
{t('Connecting...')}
</>
) : (
t('Connect to Bunker')
)}
</p>
</div>
{error && <div className="text-sm text-destructive">{error}</div>}
<Button type="submit" className="w-full" disabled={loading || !bunkerUrl.trim()}>
{loading ? (
<>
<Loader2 className="mr-2 h-4 w-4 animate-spin" />
{t('Connecting...')}
</>
) : (
t('Connect to Bunker')
)}
</Button>
</form>
</div>
</Button>
</form>
</div>
</>
)
}

View File

@@ -0,0 +1,823 @@
/**
* NRC Settings Component
*
* UI for managing Nostr Relay Connect (NRC) connections and listener settings.
* Includes both:
* - Listener mode: Allow other devices to connect to this one
* - Client mode: Connect to and sync from other devices
*/
import { useState, useCallback, useRef } from 'react'
import { useTranslation } from 'react-i18next'
import { useNRC } from '@/providers/NRCProvider'
import { useNostr } from '@/providers/NostrProvider'
import storage, { dispatchSettingsChanged } from '@/services/local-storage.service'
import { Button } from '@/components/ui/button'
import { Input } from '@/components/ui/input'
import { Label } from '@/components/ui/label'
import { Switch } from '@/components/ui/switch'
import { Tabs, TabsContent, TabsList, TabsTrigger } from '@/components/ui/tabs'
import {
Dialog,
DialogContent,
DialogDescription,
DialogFooter,
DialogHeader,
DialogTitle
} from '@/components/ui/dialog'
import {
AlertDialog,
AlertDialogAction,
AlertDialogCancel,
AlertDialogContent,
AlertDialogDescription,
AlertDialogFooter,
AlertDialogHeader,
AlertDialogTitle,
AlertDialogTrigger
} from '@/components/ui/alert-dialog'
import {
Link2,
Plus,
Trash2,
Copy,
Check,
QrCode,
Wifi,
WifiOff,
Users,
Server,
RefreshCw,
Smartphone,
Download,
Camera,
Zap
} from 'lucide-react'
import { NRCConnection, RemoteConnection } from '@/services/nrc'
import QRCode from 'qrcode'
import { Html5Qrcode } from 'html5-qrcode'
export default function NRCSettings() {
const { t } = useTranslation()
const { pubkey } = useNostr()
const {
// Listener state
isEnabled,
isConnected,
connections,
activeSessions,
rendezvousUrl,
enable,
disable,
addConnection,
removeConnection,
getConnectionURI,
setRendezvousUrl,
// Client state
remoteConnections,
isSyncing,
syncProgress,
addRemoteConnection,
removeRemoteConnection,
testRemoteConnection,
syncFromDevice,
syncAllRemotes
} = useNRC()
// Listener state
const [newConnectionLabel, setNewConnectionLabel] = useState('')
const [isAddDialogOpen, setIsAddDialogOpen] = useState(false)
const [isQRDialogOpen, setIsQRDialogOpen] = useState(false)
const [currentQRConnection, setCurrentQRConnection] = useState<NRCConnection | null>(null)
const [currentQRUri, setCurrentQRUri] = useState('')
const [qrDataUrl, setQrDataUrl] = useState('')
const [copiedUri, setCopiedUri] = useState(false)
const [isLoading, setIsLoading] = useState(false)
// Client state
const [connectionUri, setConnectionUri] = useState('')
const [newRemoteLabel, setNewRemoteLabel] = useState('')
const [isConnectDialogOpen, setIsConnectDialogOpen] = useState(false)
const [isScannerOpen, setIsScannerOpen] = useState(false)
const [scannerError, setScannerError] = useState('')
const scannerRef = useRef<Html5Qrcode | null>(null)
const scannerContainerRef = useRef<HTMLDivElement>(null)
// Private config sync setting
const [nrcOnlyConfigSync, setNrcOnlyConfigSync] = useState(storage.getNrcOnlyConfigSync())
const handleToggleNrcOnlyConfig = useCallback((checked: boolean) => {
storage.setNrcOnlyConfigSync(checked)
setNrcOnlyConfigSync(checked)
dispatchSettingsChanged()
}, [])
// Generate QR code when URI changes
const generateQRCode = useCallback(async (uri: string) => {
try {
const dataUrl = await QRCode.toDataURL(uri, {
width: 256,
margin: 2,
color: { dark: '#000000', light: '#ffffff' }
})
setQrDataUrl(dataUrl)
} catch (error) {
console.error('Failed to generate QR code:', error)
}
}, [])
const handleToggleEnabled = useCallback(async () => {
if (isEnabled) {
disable()
} else {
setIsLoading(true)
try {
await enable()
} catch (error) {
console.error('Failed to enable NRC:', error)
} finally {
setIsLoading(false)
}
}
}, [isEnabled, enable, disable])
const handleAddConnection = useCallback(async () => {
if (!newConnectionLabel.trim()) return
setIsLoading(true)
try {
const { uri, connection } = await addConnection(newConnectionLabel.trim())
setIsAddDialogOpen(false)
setNewConnectionLabel('')
// Show QR code
setCurrentQRConnection(connection)
setCurrentQRUri(uri)
await generateQRCode(uri)
setIsQRDialogOpen(true)
} catch (error) {
console.error('Failed to add connection:', error)
} finally {
setIsLoading(false)
}
}, [newConnectionLabel, addConnection])
const handleShowQR = useCallback(
async (connection: NRCConnection) => {
try {
const uri = getConnectionURI(connection)
setCurrentQRConnection(connection)
setCurrentQRUri(uri)
await generateQRCode(uri)
setIsQRDialogOpen(true)
} catch (error) {
console.error('Failed to get connection URI:', error)
}
},
[getConnectionURI, generateQRCode]
)
const handleCopyUri = useCallback(async () => {
try {
await navigator.clipboard.writeText(currentQRUri)
setCopiedUri(true)
setTimeout(() => setCopiedUri(false), 2000)
} catch (error) {
console.error('Failed to copy URI:', error)
}
}, [currentQRUri])
const handleRemoveConnection = useCallback(
async (id: string) => {
try {
await removeConnection(id)
} catch (error) {
console.error('Failed to remove connection:', error)
}
},
[removeConnection]
)
// ===== Client Handlers =====
const handleAddRemoteConnection = useCallback(async () => {
if (!connectionUri.trim() || !newRemoteLabel.trim()) return
setIsLoading(true)
try {
await addRemoteConnection(connectionUri.trim(), newRemoteLabel.trim())
setIsConnectDialogOpen(false)
setConnectionUri('')
setNewRemoteLabel('')
} catch (error) {
console.error('Failed to add remote connection:', error)
} finally {
setIsLoading(false)
}
}, [connectionUri, newRemoteLabel, addRemoteConnection])
const handleRemoveRemoteConnection = useCallback(
async (id: string) => {
try {
await removeRemoteConnection(id)
} catch (error) {
console.error('Failed to remove remote connection:', error)
}
},
[removeRemoteConnection]
)
const handleSyncDevice = useCallback(
async (id: string) => {
try {
await syncFromDevice(id)
} catch (error) {
console.error('Failed to sync from device:', error)
}
},
[syncFromDevice]
)
const handleTestConnection = useCallback(
async (id: string) => {
try {
await testRemoteConnection(id)
} catch (error) {
console.error('Failed to test connection:', error)
}
},
[testRemoteConnection]
)
const handleSyncAll = useCallback(async () => {
try {
await syncAllRemotes()
} catch (error) {
console.error('Failed to sync all remotes:', error)
}
}, [syncAllRemotes])
const startScanner = useCallback(async () => {
if (!scannerContainerRef.current) return
setScannerError('')
try {
const scanner = new Html5Qrcode('qr-scanner-container')
scannerRef.current = scanner
await scanner.start(
{ facingMode: 'environment' },
{
fps: 10,
qrbox: { width: 250, height: 250 }
},
(decodedText) => {
// Found a QR code
if (decodedText.startsWith('nostr+relayconnect://')) {
setConnectionUri(decodedText)
stopScanner()
setIsScannerOpen(false)
setIsConnectDialogOpen(true)
}
},
() => {
// Ignore errors while scanning
}
)
} catch (error) {
console.error('Failed to start scanner:', error)
setScannerError(error instanceof Error ? error.message : 'Failed to start camera')
}
}, [])
const stopScanner = useCallback(() => {
if (scannerRef.current) {
scannerRef.current.stop().catch(() => {
// Ignore errors when stopping
})
scannerRef.current = null
}
}, [])
const handleOpenScanner = useCallback(() => {
setIsScannerOpen(true)
// Start scanner after dialog renders
setTimeout(startScanner, 100)
}, [startScanner])
const handleCloseScanner = useCallback(() => {
stopScanner()
setIsScannerOpen(false)
setScannerError('')
}, [stopScanner])
if (!pubkey) {
return (
<div className="text-muted-foreground text-sm">
{t('Login required to use NRC')}
</div>
)
}
return (
<div className="space-y-6">
{/* Private Configuration Sync Toggle */}
<div className="flex items-center justify-between p-3 bg-muted/30 rounded-lg">
<div className="space-y-1">
<Label htmlFor="nrc-only-config" className="text-base font-medium">
{t('Private Configuration Sync')}
</Label>
<p className="text-sm text-muted-foreground">
{t('Only sync configurations between paired devices, not to public relays')}
</p>
</div>
<Switch
id="nrc-only-config"
checked={nrcOnlyConfigSync}
onCheckedChange={handleToggleNrcOnlyConfig}
/>
</div>
<Tabs defaultValue="listener" className="w-full">
<TabsList className="grid w-full grid-cols-2">
<TabsTrigger value="listener" className="gap-2">
<Server className="w-4 h-4" />
{t('Share')}
</TabsTrigger>
<TabsTrigger value="client" className="gap-2">
<Smartphone className="w-4 h-4" />
{t('Connect')}
</TabsTrigger>
</TabsList>
{/* ===== LISTENER TAB ===== */}
<TabsContent value="listener" className="space-y-6 mt-4">
{/* Enable/Disable Toggle */}
<div className="flex items-center justify-between">
<div className="space-y-1">
<Label htmlFor="nrc-enabled" className="text-base font-medium">
{t('Enable Relay Connect')}
</Label>
<p className="text-sm text-muted-foreground">
{t('Allow other devices to sync with this client')}
</p>
</div>
<Switch
id="nrc-enabled"
checked={isEnabled}
onCheckedChange={handleToggleEnabled}
disabled={isLoading}
/>
</div>
{/* Status Indicator */}
{isEnabled && (
<div className="flex items-center gap-4 p-3 bg-muted/50 rounded-lg">
<div className="flex items-center gap-2">
{isConnected ? (
<Wifi className="w-4 h-4 text-green-500" />
) : (
<WifiOff className="w-4 h-4 text-yellow-500" />
)}
<span className="text-sm">
{isConnected ? t('Connected') : t('Connecting...')}
</span>
</div>
{activeSessions > 0 && (
<div className="flex items-center gap-2">
<Users className="w-4 h-4" />
<span className="text-sm">
{activeSessions} {t('active session(s)')}
</span>
</div>
)}
</div>
)}
{/* Rendezvous Relay */}
<div className="space-y-2">
<Label htmlFor="rendezvous-url" className="flex items-center gap-2">
<Server className="w-4 h-4" />
{t('Rendezvous Relay')}
</Label>
<Input
id="rendezvous-url"
value={rendezvousUrl}
onChange={(e) => setRendezvousUrl(e.target.value)}
placeholder="wss://relay.example.com"
disabled={isEnabled}
/>
{isEnabled && (
<p className="text-xs text-muted-foreground">
{t('Disable NRC to change the relay')}
</p>
)}
</div>
{/* Connections List */}
<div className="space-y-3">
<div className="flex items-center justify-between">
<Label className="flex items-center gap-2">
<Link2 className="w-4 h-4" />
{t('Authorized Devices')}
</Label>
<Button
variant="outline"
size="sm"
onClick={() => setIsAddDialogOpen(true)}
className="gap-1"
>
<Plus className="w-4 h-4" />
{t('Add')}
</Button>
</div>
{connections.length === 0 ? (
<div className="text-sm text-muted-foreground p-4 text-center border border-dashed rounded-lg">
{t('No devices connected yet')}
</div>
) : (
<div className="space-y-2">
{connections.map((connection) => (
<div
key={connection.id}
className="flex items-center justify-between p-3 bg-muted/30 rounded-lg"
>
<div className="flex-1 min-w-0">
<div className="font-medium truncate">{connection.label}</div>
<div className="text-xs text-muted-foreground">
{new Date(connection.createdAt).toLocaleDateString()}
</div>
</div>
<div className="flex items-center gap-1">
<Button
variant="ghost"
size="icon"
onClick={() => handleShowQR(connection)}
title={t('Show QR Code')}
>
<QrCode className="w-4 h-4" />
</Button>
<AlertDialog>
<AlertDialogTrigger asChild>
<Button
variant="ghost"
size="icon"
className="text-destructive hover:text-destructive"
title={t('Remove')}
>
<Trash2 className="w-4 h-4" />
</Button>
</AlertDialogTrigger>
<AlertDialogContent>
<AlertDialogHeader>
<AlertDialogTitle>{t('Remove Device?')}</AlertDialogTitle>
<AlertDialogDescription>
{t('This will revoke access for "{{label}}". The device will no longer be able to sync.', {
label: connection.label
})}
</AlertDialogDescription>
</AlertDialogHeader>
<AlertDialogFooter>
<AlertDialogCancel>{t('Cancel')}</AlertDialogCancel>
<AlertDialogAction
onClick={() => handleRemoveConnection(connection.id)}
className="bg-destructive text-destructive-foreground hover:bg-destructive/90"
>
{t('Remove')}
</AlertDialogAction>
</AlertDialogFooter>
</AlertDialogContent>
</AlertDialog>
</div>
</div>
))}
</div>
)}
</div>
</TabsContent>
{/* ===== CLIENT TAB ===== */}
<TabsContent value="client" className="space-y-6 mt-4">
{/* Sync Progress */}
{isSyncing && syncProgress && (
<div className="p-3 bg-muted/50 rounded-lg space-y-2">
<div className="flex items-center gap-2">
<RefreshCw className="w-4 h-4 animate-spin" />
<span className="text-sm font-medium">
{syncProgress.phase === 'connecting' && t('Connecting...')}
{syncProgress.phase === 'requesting' && t('Requesting events...')}
{syncProgress.phase === 'receiving' && t('Receiving events...')}
{syncProgress.phase === 'complete' && t('Sync complete')}
{syncProgress.phase === 'error' && t('Error')}
</span>
</div>
{syncProgress.eventsReceived > 0 && (
<div className="text-xs text-muted-foreground">
{t('{{count}} events received', { count: syncProgress.eventsReceived })}
</div>
)}
{syncProgress.message && syncProgress.phase === 'error' && (
<div className="text-xs text-destructive">{syncProgress.message}</div>
)}
</div>
)}
{/* Connect to Device */}
<div className="space-y-3">
<div className="flex items-center justify-between">
<Label className="flex items-center gap-2">
<Download className="w-4 h-4" />
{t('Remote Devices')}
</Label>
<div className="flex gap-2">
<Button
variant="outline"
size="sm"
onClick={handleOpenScanner}
className="gap-1"
>
<Camera className="w-4 h-4" />
{t('Scan')}
</Button>
<Button
variant="outline"
size="sm"
onClick={() => setIsConnectDialogOpen(true)}
className="gap-1"
>
<Plus className="w-4 h-4" />
{t('Add')}
</Button>
</div>
</div>
{remoteConnections.length === 0 ? (
<div className="text-sm text-muted-foreground p-4 text-center border border-dashed rounded-lg">
{t('No remote devices configured')}
</div>
) : (
<div className="space-y-2">
{/* Sync All Button */}
{remoteConnections.length > 1 && (
<Button
variant="secondary"
size="sm"
onClick={handleSyncAll}
disabled={isSyncing}
className="w-full gap-2"
>
<RefreshCw className={`w-4 h-4 ${isSyncing ? 'animate-spin' : ''}`} />
{t('Sync All Devices')}
</Button>
)}
{remoteConnections.map((remote: RemoteConnection) => (
<div
key={remote.id}
className="flex items-center justify-between p-3 bg-muted/30 rounded-lg"
>
<div className="flex-1 min-w-0">
<div className="font-medium truncate">{remote.label}</div>
<div className="text-xs text-muted-foreground">
{remote.lastSync ? (
<>
{t('Last sync')}: {new Date(remote.lastSync).toLocaleString()}
{remote.eventCount !== undefined && (
<span className="ml-2">({remote.eventCount} {t('events')})</span>
)}
</>
) : (
t('Never synced')
)}
</div>
</div>
<div className="flex items-center gap-1">
{/* Show Test button if never synced, Sync button otherwise */}
{!remote.lastSync ? (
<Button
variant="ghost"
size="icon"
onClick={() => handleTestConnection(remote.id)}
disabled={isSyncing}
title={t('Test Connection')}
>
<Zap className={`w-4 h-4 ${isSyncing ? 'animate-pulse' : ''}`} />
</Button>
) : null}
<Button
variant="ghost"
size="icon"
onClick={() => handleSyncDevice(remote.id)}
disabled={isSyncing}
title={t('Sync')}
>
<RefreshCw className={`w-4 h-4 ${isSyncing ? 'animate-spin' : ''}`} />
</Button>
<AlertDialog>
<AlertDialogTrigger asChild>
<Button
variant="ghost"
size="icon"
className="text-destructive hover:text-destructive"
title={t('Remove')}
>
<Trash2 className="w-4 h-4" />
</Button>
</AlertDialogTrigger>
<AlertDialogContent>
<AlertDialogHeader>
<AlertDialogTitle>{t('Remove Remote Device?')}</AlertDialogTitle>
<AlertDialogDescription>
{t('This will remove "{{label}}" from your remote devices list.', {
label: remote.label
})}
</AlertDialogDescription>
</AlertDialogHeader>
<AlertDialogFooter>
<AlertDialogCancel>{t('Cancel')}</AlertDialogCancel>
<AlertDialogAction
onClick={() => handleRemoveRemoteConnection(remote.id)}
className="bg-destructive text-destructive-foreground hover:bg-destructive/90"
>
{t('Remove')}
</AlertDialogAction>
</AlertDialogFooter>
</AlertDialogContent>
</AlertDialog>
</div>
</div>
))}
</div>
)}
</div>
</TabsContent>
</Tabs>
{/* ===== DIALOGS ===== */}
{/* Add Connection Dialog (Listener) */}
<Dialog open={isAddDialogOpen} onOpenChange={setIsAddDialogOpen}>
<DialogContent>
<DialogHeader>
<DialogTitle>{t('Add Device')}</DialogTitle>
<DialogDescription>
{t('Create a connection URI to link another device')}
</DialogDescription>
</DialogHeader>
<div className="space-y-4 py-4">
<div className="space-y-2">
<Label htmlFor="device-label">{t('Device Name')}</Label>
<Input
id="device-label"
value={newConnectionLabel}
onChange={(e) => setNewConnectionLabel(e.target.value)}
placeholder={t('e.g., Phone, Laptop')}
onKeyDown={(e) => {
if (e.key === 'Enter') {
handleAddConnection()
}
}}
/>
</div>
</div>
<DialogFooter>
<Button variant="outline" onClick={() => setIsAddDialogOpen(false)}>
{t('Cancel')}
</Button>
<Button
onClick={handleAddConnection}
disabled={!newConnectionLabel.trim() || isLoading}
>
{t('Create')}
</Button>
</DialogFooter>
</DialogContent>
</Dialog>
{/* QR Code Dialog */}
<Dialog open={isQRDialogOpen} onOpenChange={setIsQRDialogOpen}>
<DialogContent className="sm:max-w-md">
<DialogHeader>
<DialogTitle>{t('Connection QR Code')}</DialogTitle>
<DialogDescription>
{currentQRConnection && (
<>
{t('Scan this code with "{{label}}" to connect', {
label: currentQRConnection.label
})}
</>
)}
</DialogDescription>
</DialogHeader>
<div className="flex flex-col items-center gap-4 py-4">
{qrDataUrl && (
<div className="p-4 bg-white rounded-lg">
<img src={qrDataUrl} alt="Connection QR Code" className="w-64 h-64" />
</div>
)}
<div className="w-full">
<div className="flex items-center gap-2">
<Input
value={currentQRUri}
readOnly
className="font-mono text-xs"
/>
<Button
variant="outline"
size="icon"
onClick={handleCopyUri}
title={t('Copy')}
>
{copiedUri ? (
<Check className="w-4 h-4 text-green-500" />
) : (
<Copy className="w-4 h-4" />
)}
</Button>
</div>
</div>
</div>
<DialogFooter>
<Button onClick={() => setIsQRDialogOpen(false)}>{t('Done')}</Button>
</DialogFooter>
</DialogContent>
</Dialog>
{/* Connect to Remote Dialog (Client) */}
<Dialog open={isConnectDialogOpen} onOpenChange={setIsConnectDialogOpen}>
<DialogContent>
<DialogHeader>
<DialogTitle>{t('Connect to Device')}</DialogTitle>
<DialogDescription>
{t('Enter a connection URI from another device to sync with it')}
</DialogDescription>
</DialogHeader>
<div className="space-y-4 py-4">
<div className="space-y-2">
<Label htmlFor="connection-uri">{t('Connection URI')}</Label>
<Input
id="connection-uri"
value={connectionUri}
onChange={(e) => setConnectionUri(e.target.value)}
placeholder="nostr+relayconnect://..."
className="font-mono text-xs"
/>
</div>
<div className="space-y-2">
<Label htmlFor="remote-label">{t('Device Name')}</Label>
<Input
id="remote-label"
value={newRemoteLabel}
onChange={(e) => setNewRemoteLabel(e.target.value)}
placeholder={t('e.g., Desktop, Main Phone')}
onKeyDown={(e) => {
if (e.key === 'Enter') {
handleAddRemoteConnection()
}
}}
/>
</div>
</div>
<DialogFooter>
<Button variant="outline" onClick={() => setIsConnectDialogOpen(false)}>
{t('Cancel')}
</Button>
<Button
onClick={handleAddRemoteConnection}
disabled={!connectionUri.trim() || !newRemoteLabel.trim() || isLoading}
>
{t('Connect')}
</Button>
</DialogFooter>
</DialogContent>
</Dialog>
{/* QR Scanner Dialog */}
<Dialog open={isScannerOpen} onOpenChange={handleCloseScanner}>
<DialogContent className="sm:max-w-md">
<DialogHeader>
<DialogTitle>{t('Scan QR Code')}</DialogTitle>
<DialogDescription>
{t('Point your camera at a connection QR code')}
</DialogDescription>
</DialogHeader>
<div className="py-4">
<div
id="qr-scanner-container"
ref={scannerContainerRef}
className="w-full aspect-square bg-muted rounded-lg overflow-hidden"
/>
{scannerError && (
<div className="mt-2 text-sm text-destructive">{scannerError}</div>
)}
</div>
<DialogFooter>
<Button variant="outline" onClick={handleCloseScanner}>
{t('Cancel')}
</Button>
</DialogFooter>
</DialogContent>
</Dialog>
</div>
)
}

View File

@@ -6,6 +6,7 @@ import EmojiPackList from '@/components/EmojiPackList'
import EmojiPickerDialog from '@/components/EmojiPickerDialog'
import FavoriteRelaysSetting from '@/components/FavoriteRelaysSetting'
import MailboxSetting from '@/components/MailboxSetting'
import NRCSettings from '@/components/NRCSettings'
import NoteList from '@/components/NoteList'
import Tabs from '@/components/Tabs'
import {
@@ -73,6 +74,7 @@ import {
PencilLine,
RotateCcw,
ScanLine,
RefreshCw,
Server,
Settings2,
Smile,
@@ -105,7 +107,7 @@ const NOTIFICATION_STYLES = [
] as const
// Accordion item values for keyboard navigation
const ACCORDION_ITEMS = ['general', 'appearance', 'relays', 'wallet', 'posts', 'emoji-packs', 'messaging', 'system']
const ACCORDION_ITEMS = ['general', 'appearance', 'relays', 'sync', 'wallet', 'posts', 'emoji-packs', 'messaging', 'system']
export default function Settings() {
const { t, i18n } = useTranslation()
@@ -123,7 +125,7 @@ export default function Settings() {
// Get the visible accordion items based on pubkey availability
const visibleAccordionItems = pubkey
? ACCORDION_ITEMS
: ACCORDION_ITEMS.filter((item) => !['wallet', 'posts', 'emoji-packs', 'messaging'].includes(item))
: ACCORDION_ITEMS.filter((item) => !['sync', 'wallet', 'posts', 'emoji-packs', 'messaging'].includes(item))
// Register as a navigation region - Settings decides what "up/down" means
const handleSettingsIntent = useCallback(
@@ -548,6 +550,23 @@ export default function Settings() {
</AccordionItem>
</NavigableAccordionItem>
{/* Sync (NRC) */}
{!!pubkey && (
<NavigableAccordionItem ref={setAccordionRef('sync')} isSelected={isAccordionSelected('sync')}>
<AccordionItem value="sync">
<AccordionTrigger className="px-4 hover:no-underline">
<div className="flex items-center gap-4">
<RefreshCw className="size-4" />
<span>{t('Device Sync')}</span>
</div>
</AccordionTrigger>
<AccordionContent className="px-4">
<NRCSettings />
</AccordionContent>
</AccordionItem>
</NavigableAccordionItem>
)}
{/* Wallet */}
{!!pubkey && (
<NavigableAccordionItem ref={setAccordionRef('wallet')} isSelected={isAccordionSelected('wallet')}>

View File

@@ -1,280 +0,0 @@
import { Button } from '@/components/ui/button'
import {
Card,
CardContent,
CardDescription,
CardFooter,
CardHeader,
CardTitle
} from '@/components/ui/card'
import { Tabs, TabsContent, TabsList, TabsTrigger } from '@/components/ui/tabs'
import cashuTokenService, { TCashuToken, TokenScope } from '@/services/cashu-token.service'
import { useNostr } from '@/providers/NostrProvider'
import { Clock, Copy, Key, RefreshCw, Shield } from 'lucide-react'
import { useCallback, useEffect, useState } from 'react'
import { useTranslation } from 'react-i18next'
import { toast } from 'sonner'
import QrCode from '../QrCode'
import dayjs from 'dayjs'
import relativeTime from 'dayjs/plugin/relativeTime'
import * as utils from '@noble/curves/abstract/utils'
dayjs.extend(relativeTime)
interface TokenDisplayProps {
bunkerPubkey: string
mintUrl: string
}
export default function TokenDisplay({ bunkerPubkey, mintUrl }: TokenDisplayProps) {
const { t } = useTranslation()
const { signHttpAuth, pubkey } = useNostr()
const [currentToken, setCurrentToken] = useState<TCashuToken | null>(null)
const [nextToken, setNextToken] = useState<TCashuToken | null>(null)
const [loading, setLoading] = useState(false)
const [refreshing, setRefreshing] = useState(false)
// Load tokens on mount
useEffect(() => {
const stored = cashuTokenService.loadTokens(bunkerPubkey)
if (stored) {
setCurrentToken(stored.current || null)
setNextToken(stored.next || null)
}
}, [bunkerPubkey])
// Request a new token
const requestToken = useCallback(async () => {
if (!pubkey) {
toast.error(t('You must be logged in to request a token'))
return
}
setLoading(true)
try {
cashuTokenService.setMint(mintUrl)
await cashuTokenService.fetchMintInfo()
const userPubkey = utils.hexToBytes(pubkey)
const token = await cashuTokenService.requestToken(
TokenScope.NIP46,
userPubkey,
signHttpAuth,
[24133] // NIP-46 kind
)
// Store the token
if (currentToken && cashuTokenService.verifyToken(currentToken)) {
// Current still valid, store new as next
cashuTokenService.storeTokens(bunkerPubkey, currentToken, token)
setNextToken(token)
} else {
// Current expired or missing, use new as current
cashuTokenService.storeTokens(bunkerPubkey, token)
setCurrentToken(token)
setNextToken(null)
}
toast.success(t('Token obtained successfully'))
} catch (err) {
toast.error(t('Failed to get token') + ': ' + (err as Error).message)
} finally {
setLoading(false)
}
}, [bunkerPubkey, mintUrl, pubkey, signHttpAuth, currentToken, t])
// Refresh tokens (promote next to current if needed)
const refreshTokens = useCallback(async () => {
if (!pubkey) return
setRefreshing(true)
try {
// Check if current needs refresh
if (currentToken && cashuTokenService.needsRefresh(currentToken)) {
// Request a new token as next
if (!nextToken) {
await requestToken()
}
}
// Promote next to current if current expired
const now = Date.now() / 1000
if (currentToken && currentToken.expiry <= now && nextToken) {
cashuTokenService.storeTokens(bunkerPubkey, nextToken)
setCurrentToken(nextToken)
setNextToken(null)
toast.info(t('Token rotated'))
}
} finally {
setRefreshing(false)
}
}, [bunkerPubkey, currentToken, nextToken, pubkey, requestToken, t])
// Copy token to clipboard
const copyToken = useCallback(
(token: TCashuToken) => {
const encoded = cashuTokenService.encodeToken(token)
navigator.clipboard.writeText(encoded)
toast.success(t('Token copied to clipboard'))
},
[t]
)
// Format expiry time
const formatExpiry = (expiry: number) => {
const date = dayjs.unix(expiry)
const now = dayjs()
if (date.isBefore(now)) {
return t('Expired')
}
return date.fromNow()
}
// Check if token is expired
const isExpired = (token: TCashuToken) => {
return token.expiry < Date.now() / 1000
}
return (
<Card>
<CardHeader>
<CardTitle className="flex items-center gap-2">
<Shield className="h-5 w-5" />
{t('Access Tokens')}
</CardTitle>
<CardDescription>
{t('Cashu tokens for authenticated bunker access')}
</CardDescription>
</CardHeader>
<CardContent>
{!currentToken && !nextToken ? (
<div className="text-center py-8">
<Key className="h-12 w-12 mx-auto text-muted-foreground mb-4" />
<p className="text-muted-foreground mb-4">
{t('No tokens available. Request one to enable bunker access.')}
</p>
<Button onClick={requestToken} disabled={loading}>
{loading ? t('Requesting...') : t('Request Token')}
</Button>
</div>
) : (
<Tabs defaultValue="current" className="w-full">
<TabsList className="grid w-full grid-cols-2">
<TabsTrigger value="current" className="relative">
{t('Current')}
{currentToken && isExpired(currentToken) && (
<span className="absolute top-1 right-1 h-2 w-2 rounded-full bg-destructive" />
)}
</TabsTrigger>
<TabsTrigger value="next">
{t('Next')}
{nextToken && (
<span className="absolute top-1 right-1 h-2 w-2 rounded-full bg-green-500" />
)}
</TabsTrigger>
</TabsList>
<TabsContent value="current" className="space-y-4">
{currentToken ? (
<TokenCard
token={currentToken}
formatExpiry={formatExpiry}
isExpired={isExpired(currentToken)}
onCopy={() => copyToken(currentToken)}
/>
) : (
<div className="text-center py-4 text-muted-foreground">
{t('No current token')}
</div>
)}
</TabsContent>
<TabsContent value="next" className="space-y-4">
{nextToken ? (
<TokenCard
token={nextToken}
formatExpiry={formatExpiry}
isExpired={isExpired(nextToken)}
onCopy={() => copyToken(nextToken)}
/>
) : (
<div className="text-center py-4 text-muted-foreground">
{t('No pending token. One will be requested before current expires.')}
</div>
)}
</TabsContent>
</Tabs>
)}
</CardContent>
<CardFooter className="flex gap-2">
<Button variant="outline" onClick={refreshTokens} disabled={refreshing} className="flex-1">
<RefreshCw className={`h-4 w-4 mr-2 ${refreshing ? 'animate-spin' : ''}`} />
{t('Refresh')}
</Button>
<Button onClick={requestToken} disabled={loading} className="flex-1">
{loading ? t('Requesting...') : t('Request New Token')}
</Button>
</CardFooter>
</Card>
)
}
// Individual token display card
function TokenCard({
token,
formatExpiry,
isExpired,
onCopy
}: {
token: TCashuToken
formatExpiry: (expiry: number) => string
isExpired: boolean
onCopy: () => void
}) {
const { t } = useTranslation()
const encoded = cashuTokenService.encodeToken(token)
return (
<div className="space-y-4">
<div className="flex justify-center">
<QrCode value={encoded} size={200} />
</div>
<div className="space-y-2 text-sm">
<div className="flex items-center justify-between">
<span className="text-muted-foreground">{t('Scope')}</span>
<span className="font-mono">{token.scope}</span>
</div>
<div className="flex items-center justify-between">
<span className="text-muted-foreground">{t('Keyset')}</span>
<span className="font-mono text-xs">{token.keysetId}</span>
</div>
<div className="flex items-center justify-between">
<span className="text-muted-foreground flex items-center gap-1">
<Clock className="h-3 w-3" />
{t('Expires')}
</span>
<span className={isExpired ? 'text-destructive' : 'text-green-600'}>
{formatExpiry(token.expiry)}
</span>
</div>
{token.kinds && token.kinds.length > 0 && (
<div className="flex items-center justify-between">
<span className="text-muted-foreground">{t('Kinds')}</span>
<span className="font-mono text-xs">{token.kinds.join(', ')}</span>
</div>
)}
</div>
<Button variant="outline" onClick={onCopy} className="w-full">
<Copy className="h-4 w-4 mr-2" />
{t('Copy Token')}
</Button>
</div>
)
}

View File

@@ -50,6 +50,7 @@ export const StorageKey = {
GRAPH_QUERIES_ENABLED: 'graphQueriesEnabled',
SOCIAL_GRAPH_PROXIMITY: 'socialGraphProximity',
SOCIAL_GRAPH_INCLUDE_MODE: 'socialGraphIncludeMode',
NRC_ONLY_CONFIG_SYNC: 'nrcOnlyConfigSync',
DEFAULT_SHOW_NSFW: 'defaultShowNsfw', // deprecated
PINNED_PUBKEYS: 'pinnedPubkeys', // deprecated
MEDIA_UPLOAD_SERVICE: 'mediaUploadService', // deprecated

View File

@@ -0,0 +1,653 @@
/**
* NRC (Nostr Relay Connect) Provider
*
* Manages NRC state for both:
* - Listener mode: Accept connections from other devices
* - Client mode: Connect to and sync from other devices
*/
import { createContext, useContext, useState, useEffect, useCallback, ReactNode } from 'react'
import { Filter, Event } from 'nostr-tools'
import { useNostr } from './NostrProvider'
import client from '@/services/client.service'
import indexedDb from '@/services/indexed-db.service'
import {
NRCConnection,
NRCListenerConfig,
generateConnectionURI,
getNRCListenerService,
syncFromRemote,
testConnection,
parseConnectionURI,
requestRemoteIDs,
sendEventsToRemote,
EventManifestEntry
} from '@/services/nrc'
import type { SyncProgress, RemoteConnection } from '@/services/nrc'
// Kinds to sync bidirectionally
const SYNC_KINDS = [0, 3, 10000, 10001, 10002, 10003, 10012, 30002]
// Storage keys
const STORAGE_KEY_ENABLED = 'nrc:enabled'
const STORAGE_KEY_CONNECTIONS = 'nrc:connections'
const STORAGE_KEY_REMOTE_CONNECTIONS = 'nrc:remoteConnections'
const STORAGE_KEY_RENDEZVOUS_URL = 'nrc:rendezvousUrl'
// Default rendezvous relay
const DEFAULT_RENDEZVOUS_URL = 'wss://relay.damus.io'
interface NRCContextType {
// Listener State (this device accepts connections)
isEnabled: boolean
isListening: boolean
isConnected: boolean
connections: NRCConnection[] // Devices authorized to connect to us
activeSessions: number
rendezvousUrl: string
// Client State (this device connects to others)
remoteConnections: RemoteConnection[] // Devices we connect to
isSyncing: boolean
syncProgress: SyncProgress | null
// Listener Actions
enable: () => Promise<void>
disable: () => void
addConnection: (label: string) => Promise<{ uri: string; connection: NRCConnection }>
removeConnection: (id: string) => Promise<void>
getConnectionURI: (connection: NRCConnection) => string
setRendezvousUrl: (url: string) => void
// Client Actions
addRemoteConnection: (uri: string, label: string) => Promise<RemoteConnection>
removeRemoteConnection: (id: string) => Promise<void>
testRemoteConnection: (id: string) => Promise<boolean>
syncFromDevice: (id: string, filters?: Filter[]) => Promise<Event[]>
syncAllRemotes: (filters?: Filter[]) => Promise<Event[]>
}
const NRCContext = createContext<NRCContextType | undefined>(undefined)
export const useNRC = () => {
const context = useContext(NRCContext)
if (!context) {
throw new Error('useNRC must be used within an NRCProvider')
}
return context
}
interface NRCProviderProps {
children: ReactNode
}
export function NRCProvider({ children }: NRCProviderProps) {
const { pubkey } = useNostr()
// ===== Listener State =====
const [isEnabled, setIsEnabled] = useState<boolean>(() => {
const stored = localStorage.getItem(STORAGE_KEY_ENABLED)
return stored === 'true'
})
const [connections, setConnections] = useState<NRCConnection[]>(() => {
const stored = localStorage.getItem(STORAGE_KEY_CONNECTIONS)
if (stored) {
try {
return JSON.parse(stored)
} catch {
return []
}
}
return []
})
const [rendezvousUrl, setRendezvousUrlState] = useState<string>(() => {
return localStorage.getItem(STORAGE_KEY_RENDEZVOUS_URL) || DEFAULT_RENDEZVOUS_URL
})
const [isListening, setIsListening] = useState(false)
const [isConnected, setIsConnected] = useState(false)
const [activeSessions, setActiveSessions] = useState(0)
// ===== Client State =====
const [remoteConnections, setRemoteConnections] = useState<RemoteConnection[]>(() => {
const stored = localStorage.getItem(STORAGE_KEY_REMOTE_CONNECTIONS)
if (stored) {
try {
return JSON.parse(stored)
} catch {
return []
}
}
return []
})
const [isSyncing, setIsSyncing] = useState(false)
const [syncProgress, setSyncProgress] = useState<SyncProgress | null>(null)
const listenerService = getNRCListenerService()
// ===== Persist State =====
useEffect(() => {
localStorage.setItem(STORAGE_KEY_ENABLED, String(isEnabled))
}, [isEnabled])
useEffect(() => {
localStorage.setItem(STORAGE_KEY_CONNECTIONS, JSON.stringify(connections))
}, [connections])
useEffect(() => {
localStorage.setItem(STORAGE_KEY_REMOTE_CONNECTIONS, JSON.stringify(remoteConnections))
}, [remoteConnections])
useEffect(() => {
localStorage.setItem(STORAGE_KEY_RENDEZVOUS_URL, rendezvousUrl)
}, [rendezvousUrl])
// ===== Listener Logic =====
const buildAuthorizedSecrets = useCallback((): Map<string, string> => {
const map = new Map<string, string>()
for (const conn of connections) {
if (conn.secret && conn.clientPubkey) {
map.set(conn.clientPubkey, conn.label)
}
}
return map
}, [connections])
useEffect(() => {
if (!isEnabled || !client.signer || !pubkey) {
if (listenerService.isRunning()) {
listenerService.stop()
setIsListening(false)
setIsConnected(false)
setActiveSessions(0)
}
return
}
// Stop existing listener before starting with new config
if (listenerService.isRunning()) {
listenerService.stop()
}
let statusInterval: ReturnType<typeof setInterval> | null = null
const startListener = async () => {
try {
const config: NRCListenerConfig = {
rendezvousUrl,
signer: client.signer!,
authorizedSecrets: buildAuthorizedSecrets()
}
console.log('[NRC] Starting listener with', config.authorizedSecrets.size, 'authorized clients')
listenerService.setOnSessionChange((count) => {
setActiveSessions(count)
})
await listenerService.start(config)
setIsListening(true)
setIsConnected(listenerService.isConnected())
statusInterval = setInterval(() => {
setIsConnected(listenerService.isConnected())
setActiveSessions(listenerService.getActiveSessionCount())
}, 5000)
} catch (error) {
console.error('[NRC] Failed to start listener:', error)
setIsListening(false)
setIsConnected(false)
}
}
startListener()
return () => {
if (statusInterval) {
clearInterval(statusInterval)
}
listenerService.stop()
setIsListening(false)
setIsConnected(false)
setActiveSessions(0)
}
}, [isEnabled, pubkey, rendezvousUrl, buildAuthorizedSecrets])
useEffect(() => {
if (!isEnabled || !client.signer || !pubkey) return
}, [connections, isEnabled, pubkey])
// ===== Auto-sync remote connections (bidirectional) =====
// Sync interval: 15 minutes
const AUTO_SYNC_INTERVAL = 15 * 60 * 1000
// Minimum time between syncs for the same connection: 5 minutes
const MIN_SYNC_INTERVAL = 5 * 60 * 1000
/**
* Get local events for sync kinds and build manifest
*/
const getLocalEventsAndManifest = async (): Promise<{
events: Event[]
manifest: EventManifestEntry[]
}> => {
const events = await indexedDb.queryEventsForNRC([{ kinds: SYNC_KINDS, limit: 1000 }])
const manifest: EventManifestEntry[] = events.map((e) => ({
kind: e.kind,
id: e.id,
created_at: e.created_at,
d: e.tags.find((t) => t[0] === 'd')?.[1]
}))
return { events, manifest }
}
/**
* Diff manifests to find what each side needs
* For replaceable events: compare by (kind, pubkey, d) and use newer created_at
*/
const diffManifests = (
local: EventManifestEntry[],
remote: EventManifestEntry[],
localEvents: Event[]
): { toSend: Event[]; toFetch: string[] } => {
// Build maps keyed by (kind, d) for replaceable events
const localMap = new Map<string, EventManifestEntry>()
const localEventsMap = new Map<string, Event>()
for (let i = 0; i < local.length; i++) {
const entry = local[i]
const key = `${entry.kind}:${entry.d || ''}`
const existing = localMap.get(key)
// Keep the newer one
if (!existing || entry.created_at > existing.created_at) {
localMap.set(key, entry)
localEventsMap.set(entry.id, localEvents[i])
}
}
const remoteMap = new Map<string, EventManifestEntry>()
for (const entry of remote) {
const key = `${entry.kind}:${entry.d || ''}`
const existing = remoteMap.get(key)
if (!existing || entry.created_at > existing.created_at) {
remoteMap.set(key, entry)
}
}
const toSend: Event[] = []
const toFetch: string[] = []
// Find events we have that are newer than remote's (or remote doesn't have)
for (const [key, localEntry] of localMap) {
const remoteEntry = remoteMap.get(key)
if (!remoteEntry || localEntry.created_at > remoteEntry.created_at) {
const event = localEventsMap.get(localEntry.id)
if (event) {
toSend.push(event)
}
}
}
// Find events remote has that are newer than ours (or we don't have)
for (const [key, remoteEntry] of remoteMap) {
const localEntry = localMap.get(key)
if (!localEntry || remoteEntry.created_at > localEntry.created_at) {
toFetch.push(remoteEntry.id)
}
}
return { toSend, toFetch }
}
useEffect(() => {
// Only auto-sync if we have remote connections and a signer
if (remoteConnections.length === 0 || !client.signer || !pubkey) {
return
}
// Don't auto-sync if already syncing
if (isSyncing) {
return
}
const bidirectionalSync = async () => {
const now = Date.now()
// Find connections that need syncing
const needsSync = remoteConnections.filter(
(c) => !c.lastSync || (now - c.lastSync) > MIN_SYNC_INTERVAL
)
if (needsSync.length === 0) {
return
}
console.log(`[NRC] Bidirectional sync: ${needsSync.length} connection(s) need syncing`)
for (const remote of needsSync) {
if (isSyncing) break
try {
console.log(`[NRC] Bidirectional sync with ${remote.label}...`)
setIsSyncing(true)
setSyncProgress({ phase: 'connecting', eventsReceived: 0 })
// Step 1: Get remote's event IDs
setSyncProgress({ phase: 'requesting', eventsReceived: 0, message: 'Getting remote event list...' })
const remoteManifest = await requestRemoteIDs(
remote.uri,
[{ kinds: SYNC_KINDS, limit: 1000 }]
)
console.log(`[NRC] Remote has ${remoteManifest.length} events`)
// Step 2: Get our local events and manifest
const { events: localEvents, manifest: localManifest } = await getLocalEventsAndManifest()
console.log(`[NRC] Local has ${localManifest.length} events`)
// Step 3: Diff to find what each side needs
const { toSend, toFetch } = diffManifests(localManifest, remoteManifest, localEvents)
console.log(`[NRC] Diff: sending ${toSend.length}, fetching ${toFetch.length}`)
let eventsSent = 0
let eventsReceived = 0
// Step 4: Send events remote needs
if (toSend.length > 0) {
setSyncProgress({ phase: 'sending', eventsReceived: 0, eventsSent: 0, message: `Sending ${toSend.length} events...` })
eventsSent = await sendEventsToRemote(
remote.uri,
toSend,
(progress) => setSyncProgress({ ...progress, message: `Sending events... (${progress.eventsSent || 0}/${toSend.length})` })
)
console.log(`[NRC] Sent ${eventsSent} events to ${remote.label}`)
}
// Step 5: Fetch events we need using regular filter queries
if (toFetch.length > 0) {
setSyncProgress({ phase: 'receiving', eventsReceived: 0, eventsSent, message: `Fetching ${toFetch.length} events...` })
// Fetch by ID in batches (relay may limit number of IDs per filter)
const BATCH_SIZE = 50
const fetchedEvents: Event[] = []
for (let i = 0; i < toFetch.length; i += BATCH_SIZE) {
const batch = toFetch.slice(i, i + BATCH_SIZE)
const events = await syncFromRemote(
remote.uri,
[{ ids: batch }],
(progress) => setSyncProgress({
...progress,
eventsSent,
message: `Fetching events... (${fetchedEvents.length + progress.eventsReceived}/${toFetch.length})`
})
)
fetchedEvents.push(...events)
}
// Store fetched events
for (const event of fetchedEvents) {
try {
await indexedDb.putReplaceableEvent(event)
} catch {
// Ignore storage errors
}
}
eventsReceived = fetchedEvents.length
console.log(`[NRC] Received ${eventsReceived} events from ${remote.label}`)
}
// Update last sync time
setRemoteConnections((prev) =>
prev.map((c) =>
c.id === remote.id
? { ...c, lastSync: Date.now(), eventCount: eventsReceived }
: c
)
)
console.log(`[NRC] Bidirectional sync complete with ${remote.label}: sent ${eventsSent}, received ${eventsReceived}`)
} catch (err) {
console.error(`[NRC] Bidirectional sync failed for ${remote.label}:`, err)
} finally {
setIsSyncing(false)
setSyncProgress(null)
}
}
}
// Run initial sync after a short delay
const initialTimer = setTimeout(bidirectionalSync, 3000)
// Set up periodic sync
const intervalTimer = setInterval(bidirectionalSync, AUTO_SYNC_INTERVAL)
return () => {
clearTimeout(initialTimer)
clearInterval(intervalTimer)
}
}, [remoteConnections.length, pubkey, isSyncing])
// ===== Listener Actions =====
const enable = useCallback(async () => {
if (!client.signer) {
throw new Error('Signer required to enable NRC')
}
setIsEnabled(true)
}, [])
const disable = useCallback(() => {
setIsEnabled(false)
listenerService.stop()
setIsListening(false)
setIsConnected(false)
setActiveSessions(0)
}, [])
const addConnection = useCallback(
async (label: string): Promise<{ uri: string; connection: NRCConnection }> => {
if (!pubkey) {
throw new Error('Not logged in')
}
const id = crypto.randomUUID()
const createdAt = Date.now()
const result = generateConnectionURI(pubkey, rendezvousUrl, undefined, label)
const uri = result.uri
const connection: NRCConnection = {
id,
label,
secret: result.secret,
clientPubkey: result.clientPubkey,
createdAt
}
setConnections((prev) => [...prev, connection])
return { uri, connection }
},
[pubkey, rendezvousUrl]
)
const removeConnection = useCallback(async (id: string) => {
setConnections((prev) => prev.filter((c) => c.id !== id))
}, [])
const getConnectionURI = useCallback(
(connection: NRCConnection): string => {
if (!pubkey) {
throw new Error('Not logged in')
}
if (!connection.secret) {
throw new Error('Connection has no secret')
}
const result = generateConnectionURI(
pubkey,
rendezvousUrl,
connection.secret,
connection.label
)
return result.uri
},
[pubkey, rendezvousUrl]
)
const setRendezvousUrl = useCallback((url: string) => {
setRendezvousUrlState(url)
}, [])
// ===== Client Actions =====
const addRemoteConnection = useCallback(
async (uri: string, label: string): Promise<RemoteConnection> => {
// Validate and parse the URI
const parsed = parseConnectionURI(uri)
const remoteConnection: RemoteConnection = {
id: crypto.randomUUID(),
uri,
label,
relayPubkey: parsed.relayPubkey,
rendezvousUrl: parsed.rendezvousUrl
}
setRemoteConnections((prev) => [...prev, remoteConnection])
return remoteConnection
},
[]
)
const removeRemoteConnection = useCallback(async (id: string) => {
setRemoteConnections((prev) => prev.filter((c) => c.id !== id))
}, [])
const syncFromDevice = useCallback(
async (id: string, filters?: Filter[]): Promise<Event[]> => {
const remote = remoteConnections.find((c) => c.id === id)
if (!remote) {
throw new Error('Remote connection not found')
}
setIsSyncing(true)
setSyncProgress({ phase: 'connecting', eventsReceived: 0 })
try {
// Default filters: sync everything
const syncFilters = filters || [
{ kinds: [0, 3, 10000, 10001, 10002, 10003, 10012, 30002], limit: 1000 }
]
const events = await syncFromRemote(
remote.uri,
syncFilters,
(progress) => setSyncProgress(progress)
)
// Store synced events in IndexedDB
for (const event of events) {
try {
await indexedDb.putReplaceableEvent(event)
} catch (err) {
console.warn('[NRC] Failed to store event:', err)
}
}
// Update last sync time
setRemoteConnections((prev) =>
prev.map((c) =>
c.id === id ? { ...c, lastSync: Date.now(), eventCount: events.length } : c
)
)
return events
} finally {
setIsSyncing(false)
setSyncProgress(null)
}
},
[remoteConnections]
)
const syncAllRemotes = useCallback(
async (filters?: Filter[]): Promise<Event[]> => {
const allEvents: Event[] = []
for (const remote of remoteConnections) {
try {
const events = await syncFromDevice(remote.id, filters)
allEvents.push(...events)
} catch (error) {
console.error(`[NRC] Failed to sync from ${remote.label}:`, error)
}
}
return allEvents
},
[remoteConnections, syncFromDevice]
)
const testRemoteConnection = useCallback(
async (id: string): Promise<boolean> => {
const remote = remoteConnections.find((c) => c.id === id)
if (!remote) {
throw new Error('Remote connection not found')
}
setIsSyncing(true)
setSyncProgress({ phase: 'connecting', eventsReceived: 0, message: 'Testing connection...' })
try {
const result = await testConnection(
remote.uri,
(progress) => setSyncProgress(progress)
)
// Update connection to mark it as tested
setRemoteConnections((prev) =>
prev.map((c) =>
c.id === id ? { ...c, lastSync: Date.now(), eventCount: 0 } : c
)
)
return result
} finally {
setIsSyncing(false)
setSyncProgress(null)
}
},
[remoteConnections]
)
const value: NRCContextType = {
// Listener
isEnabled,
isListening,
isConnected,
connections,
activeSessions,
rendezvousUrl,
enable,
disable,
addConnection,
removeConnection,
getConnectionURI,
setRendezvousUrl,
// Client
remoteConnections,
isSyncing,
syncProgress,
addRemoteConnection,
removeRemoteConnection,
testRemoteConnection,
syncFromDevice,
syncAllRemotes
}
return <NRCContext.Provider value={value}>{children}</NRCContext.Provider>
}

View File

@@ -1,18 +1,12 @@
/**
* NIP-46 Bunker Signer with Cashu Token Authentication
* NIP-46 Bunker Signer
*
* Implements remote signing via NIP-46 protocol with Cashu access tokens
* for authorization. The signer connects to a bunker WebSocket and
* Implements remote signing via NIP-46 protocol.
* The signer connects to a bunker WebSocket and
* requests signing operations.
*
* Token flow:
* 1. Connect to bunker with X-Cashu-Token header
* 2. Send NIP-46 requests encrypted with NIP-04
* 3. Receive signed events from bunker
*/
import { ISigner, TDraftEvent } from '@/types'
import cashuTokenService, { TCashuToken, TokenScope } from '@/services/cashu-token.service'
import * as utils from '@noble/curves/abstract/utils'
import { secp256k1 } from '@noble/curves/secp256k1'
import { Event, VerifiedEvent, getPublicKey as nGetPublicKey, nip04, finalizeEvent } from 'nostr-tools'
@@ -61,13 +55,12 @@ function generateRequestId(): string {
}
/**
* Parse a bunker URL (bunker://<pubkey>?relay=<url>&secret=<secret>&cat=<token>).
* Parse a bunker URL (bunker://<pubkey>?relay=<url>&secret=<secret>).
*/
export function parseBunkerUrl(url: string): {
pubkey: string
relays: string[]
secret?: string
catToken?: string
} {
if (!url.startsWith('bunker://')) {
throw new Error('Invalid bunker URL: must start with bunker://')
@@ -83,7 +76,6 @@ export function parseBunkerUrl(url: string): {
const params = new URLSearchParams(queryPart || '')
const relays = params.getAll('relay')
const secret = params.get('secret') || undefined
const catToken = params.get('cat') || undefined
if (relays.length === 0) {
throw new Error('Invalid bunker URL: no relay specified')
@@ -92,8 +84,7 @@ export function parseBunkerUrl(url: string): {
return {
pubkey: pubkeyPart,
relays,
secret,
catToken
secret
}
}
@@ -173,8 +164,6 @@ export class BunkerSigner implements ISigner {
private ws: WebSocket | null = null
private pendingRequests = new Map<string, PendingRequest>()
private connected = false
private token: TCashuToken | null = null
private mintUrl: string | null = null
private requestTimeout = 30000 // 30 seconds
// Whether we're waiting for signer to connect (reverse flow)
@@ -186,22 +175,12 @@ export class BunkerSigner implements ISigner {
* @param bunkerPubkey - The bunker's public key (hex)
* @param relayUrls - Relay URLs to connect to
* @param connectionSecret - Optional connection secret for initial handshake
* @param catToken - Optional CAT token (encoded string) for authorization
*/
constructor(bunkerPubkey: string, relayUrls: string[], connectionSecret?: string, catToken?: string) {
constructor(bunkerPubkey: string, relayUrls: string[], connectionSecret?: string) {
this.bunkerPubkey = bunkerPubkey
this.relayUrls = relayUrls
this.connectionSecret = connectionSecret
// Decode CAT token if provided
if (catToken) {
try {
this.token = cashuTokenService.decodeToken(catToken)
} catch (err) {
console.warn('Failed to decode CAT token from URL:', err)
}
}
// Generate local ephemeral keypair for NIP-46 communication
this.localPrivkey = secp256k1.utils.randomPrivateKey()
this.localPubkey = nGetPublicKey(this.localPrivkey)
@@ -263,7 +242,6 @@ export class BunkerSigner implements ISigner {
* Connect to relay and wait for signer to initiate connection.
*/
private async connectAndWait(relayUrl: string): Promise<void> {
await this.acquireTokenIfNeeded(relayUrl)
await this.connectToRelayAndListen(relayUrl)
}
@@ -281,14 +259,6 @@ export class BunkerSigner implements ISigner {
wsUrl = 'wss://' + relayUrl
}
// Add token if available
if (this.token) {
const tokenEncoded = cashuTokenService.encodeToken(this.token)
const url = new URL(wsUrl)
url.searchParams.set('token', tokenEncoded)
wsUrl = url.toString()
}
const ws = new WebSocket(wsUrl)
const timeout = setTimeout(() => {
@@ -341,43 +311,10 @@ export class BunkerSigner implements ISigner {
return this.localPubkey
}
/**
* Set the Cashu token for authentication.
*/
setToken(token: TCashuToken) {
this.token = token
}
/**
* Set the mint URL for token refresh.
*/
setMintUrl(url: string) {
this.mintUrl = url
cashuTokenService.setMint(url)
}
/**
* Initialize connection to the bunker.
*/
async init(): Promise<void> {
// Check for stored token
const stored = cashuTokenService.loadTokens(this.bunkerPubkey)
if (stored?.current && !cashuTokenService.needsRefresh(stored.current)) {
this.token = stored.current
}
// Try to acquire token for each relay if we don't have one
if (!this.token) {
for (const relayUrl of this.relayUrls) {
try {
await this.acquireTokenIfNeeded(relayUrl)
if (this.token) break
} catch (err) {
console.warn(`Failed to acquire token for ${relayUrl}:`, err)
}
}
}
// Connect to first available relay
for (const relayUrl of this.relayUrls) {
try {
@@ -396,74 +333,6 @@ export class BunkerSigner implements ISigner {
await this.connect()
}
/**
* Check if relay requires Cashu token and acquire one if needed.
*/
private async acquireTokenIfNeeded(relayUrl: string): Promise<void> {
// Convert to HTTP URL for mint endpoints
let mintUrl = relayUrl
if (relayUrl.startsWith('ws://')) {
mintUrl = 'http://' + relayUrl.slice(5)
} else if (relayUrl.startsWith('wss://')) {
mintUrl = 'https://' + relayUrl.slice(6)
} else if (!relayUrl.startsWith('http://') && !relayUrl.startsWith('https://')) {
mintUrl = 'https://' + relayUrl
}
mintUrl = mintUrl.replace(/\/$/, '')
try {
// Check if relay has Cashu mint endpoints
const infoResponse = await fetch(`${mintUrl}/cashu/info`)
if (!infoResponse.ok) {
console.log(`Relay ${relayUrl} does not support Cashu tokens`)
return
}
await infoResponse.json() // Validate JSON response
console.log(`Relay ${relayUrl} requires Cashu token, acquiring...`)
// Configure the mint
this.mintUrl = mintUrl
cashuTokenService.setMint(mintUrl)
// Create NIP-98 auth signer using our local ephemeral key
const signHttpAuth = async (url: string, method: string): Promise<string> => {
const authEvent: TDraftEvent = {
kind: 27235,
created_at: Math.floor(Date.now() / 1000),
content: '',
tags: [
['u', url],
['method', method]
]
}
const signedAuth = finalizeEvent(authEvent, this.localPrivkey)
// Encode as base64url for NIP-98 header
const eventJson = JSON.stringify(signedAuth)
const base64 = btoa(eventJson)
.replace(/\+/g, '-')
.replace(/\//g, '_')
.replace(/=+$/, '')
return `Nostr ${base64}`
}
// Request token with NIP-46 scope
const token = await cashuTokenService.requestToken(
TokenScope.NIP46,
utils.hexToBytes(this.localPubkey),
signHttpAuth,
[24133] // NIP-46 kind
)
this.token = token
cashuTokenService.storeTokens(this.bunkerPubkey, token)
console.log(`Acquired Cashu token for ${relayUrl}, expires: ${new Date(token.expiry * 1000).toISOString()}`)
} catch (err) {
// Relay doesn't support Cashu or request failed - continue without token
console.warn(`Could not acquire Cashu token for ${relayUrl}:`, err)
}
}
/**
* Connect to a relay WebSocket.
*/
@@ -479,16 +348,6 @@ export class BunkerSigner implements ISigner {
wsUrl = 'wss://' + relayUrl
}
// Add Cashu token header if available
// Note: WebSocket API doesn't support custom headers directly,
// so we'll need to pass token as a subprotocol or query param
if (this.token) {
const tokenEncoded = cashuTokenService.encodeToken(this.token)
const url = new URL(wsUrl)
url.searchParams.set('token', tokenEncoded)
wsUrl = url.toString()
}
const ws = new WebSocket(wsUrl)
const timeout = setTimeout(() => {
@@ -642,16 +501,12 @@ export class BunkerSigner implements ISigner {
// Encrypt with NIP-04 to the bunker's pubkey
const encrypted = await nip04.encrypt(this.localPrivkey, this.bunkerPubkey, JSON.stringify(request))
// Create NIP-46 request event with optional CAT tag
const tags: string[][] = [['p', this.bunkerPubkey]]
if (this.token) {
tags.push(['cat', cashuTokenService.encodeToken(this.token)])
}
// Create NIP-46 request event
const draftEvent: TDraftEvent = {
kind: 24133,
created_at: Math.floor(Date.now() / 1000),
content: encrypted,
tags
tags: [['p', this.bunkerPubkey]]
}
const signedEvent = finalizeEvent(draftEvent, this.localPrivkey)
@@ -748,47 +603,6 @@ export class BunkerSigner implements ISigner {
return this.connected
}
/**
* Get the current token.
*/
getToken(): TCashuToken | null {
return this.token
}
/**
* Request a new token from the mint.
* Requires a signing function for NIP-98 auth.
*/
async refreshToken(
signHttpAuth: (url: string, method: string) => Promise<string>,
userPubkey: Uint8Array
): Promise<TCashuToken> {
if (!this.mintUrl) {
throw new Error('Mint URL not configured')
}
const token = await cashuTokenService.requestToken(
TokenScope.NIP46,
userPubkey,
signHttpAuth,
[24133] // NIP-46 kind
)
this.token = token
// Store the new token
const existing = cashuTokenService.loadTokens(this.bunkerPubkey)
if (existing?.current && cashuTokenService.verifyToken(existing.current)) {
// Current still valid, store new as next
cashuTokenService.storeTokens(this.bunkerPubkey, existing.current, token)
} else {
// Current expired or invalid, use new as current
cashuTokenService.storeTokens(this.bunkerPubkey, token)
}
return token
}
/**
* Disconnect from the bunker.
*/

View File

@@ -491,8 +491,8 @@ export function NostrProvider({ children }: { children: React.ReactNode }) {
const bunkerLogin = async (bunkerUrl: string) => {
try {
const { pubkey: bunkerPubkey, relays, secret, catToken } = parseBunkerUrl(bunkerUrl)
const bunkerSigner = new BunkerSigner(bunkerPubkey, relays, secret, catToken)
const { pubkey: bunkerPubkey, relays, secret } = parseBunkerUrl(bunkerUrl)
const bunkerSigner = new BunkerSigner(bunkerPubkey, relays, secret)
await bunkerSigner.init()
const pubkey = await bunkerSigner.getPublicKey()
return login(bunkerSigner, {
@@ -500,8 +500,7 @@ export function NostrProvider({ children }: { children: React.ReactNode }) {
signerType: 'bunker',
bunkerPubkey,
bunkerRelays: relays,
bunkerSecret: secret,
bunkerCatToken: catToken
bunkerSecret: secret
})
} catch (err) {
toast.error(t('Bunker login failed') + ': ' + (err as Error).message)
@@ -578,8 +577,7 @@ export function NostrProvider({ children }: { children: React.ReactNode }) {
const bunkerSigner = new BunkerSigner(
account.bunkerPubkey,
account.bunkerRelays,
account.bunkerSecret,
account.bunkerCatToken
account.bunkerSecret
)
await bunkerSigner.init()
return login(bunkerSigner, account)

View File

@@ -45,7 +45,8 @@ function getCurrentSettings(): TSyncSettings {
filterOutOnionRelays: storage.getFilterOutOnionRelays(),
quickReaction: storage.getQuickReaction(),
quickReactionEmoji: storage.getQuickReactionEmoji(),
noteListMode: storage.getNoteListMode()
noteListMode: storage.getNoteListMode(),
nrcOnlyConfigSync: storage.getNrcOnlyConfigSync()
}
}
@@ -113,6 +114,9 @@ function applySettings(settings: TSyncSettings) {
if (settings.noteListMode !== undefined) {
storage.setNoteListMode(settings.noteListMode)
}
if (settings.nrcOnlyConfigSync !== undefined) {
storage.setNrcOnlyConfigSync(settings.nrcOnlyConfigSync)
}
}
export function SettingsSyncProvider({ children }: { children: React.ReactNode }) {
@@ -155,6 +159,9 @@ export function SettingsSyncProvider({ children }: { children: React.ReactNode }
const syncSettings = useCallback(async () => {
if (!pubkey || !account) return
// Skip relay-based settings sync if NRC-only config sync is enabled
if (storage.getNrcOnlyConfigSync()) return
const currentSettings = getCurrentSettings()
const settingsJson = JSON.stringify(currentSettings)
@@ -192,6 +199,13 @@ export function SettingsSyncProvider({ children }: { children: React.ReactNode }
return
}
// Skip relay-based settings sync if NRC-only config sync is enabled
// (settings will sync via NRC instead)
if (storage.getNrcOnlyConfigSync()) {
lastSyncedSettingsRef.current = JSON.stringify(getCurrentSettings())
return
}
const loadRemoteSettings = async () => {
setIsLoading(true)
try {

View File

@@ -1,458 +0,0 @@
/**
* Cashu Token Service
*
* Manages Cashu access tokens for bunker authentication.
* Handles token issuance, storage, and two-token rotation (current + next).
*
* Token flow:
* 1. Generate random secret and blinding factor
* 2. Compute blinded message B_ = hash_to_curve(secret) + r*G
* 3. Submit B_ to mint with NIP-98 auth
* 4. Receive blinded signature C_
* 5. Unblind: C = C_ - r*K (where K is mint's pubkey)
* 6. Store token {secret, C, keysetId, expiry, ...}
*/
import * as utils from '@noble/curves/abstract/utils'
import { secp256k1 } from '@noble/curves/secp256k1'
import { sha256 } from '@noble/hashes/sha256'
// Token scopes
export const TokenScope = {
RELAY: 'relay',
NIP46: 'nip46',
BLOSSOM: 'blossom',
API: 'api'
} as const
export type TTokenScope = (typeof TokenScope)[keyof typeof TokenScope]
// Token format matching ORLY's token.Token
export type TCashuToken = {
keysetId: string // k - keyset identifier
secret: Uint8Array // s - 32-byte random secret
signature: Uint8Array // c - 33-byte signature point (compressed)
pubkey: Uint8Array // p - 32-byte user pubkey
expiry: number // e - Unix timestamp
scope: TTokenScope // sc - token scope
kinds?: number[] // kinds - permitted event kinds
kindRanges?: [number, number][] // kind_ranges - permitted ranges
}
// Keyset info from mint
export type TKeysetInfo = {
id: string
publicKey: string // hex-encoded mint public key
active: boolean
expiresAt?: number
}
// Mint info
export type TMintInfo = {
name: string
version: string
pubkey: string
keysets: TKeysetInfo[]
}
// Blinding result
type BlindResult = {
B_: Uint8Array // Blinded point (33 bytes compressed)
secret: Uint8Array // Original secret
r: Uint8Array // Blinding factor scalar
}
// Storage key prefix
const STORAGE_PREFIX = 'cashu_token_'
/**
* Hash a message to a point on secp256k1 using try-and-increment.
* Algorithm matches ORLY's Go implementation exactly:
* 1. msgHash = SHA256(domain_separator || message)
* 2. For counter in 0..65535:
* a. counterBytes = counter as 4-byte little-endian
* b. hash = SHA256(msgHash || counterBytes)
* c. compressed = 0x02 || hash
* d. If valid secp256k1 point, return compressed
*/
function hashToCurve(message: Uint8Array): Uint8Array {
const domainSeparator = new TextEncoder().encode('Secp256k1_HashToCurve_Cashu_')
const msgHash = sha256(new Uint8Array([...domainSeparator, ...message]))
// Try incrementing counter until we get a valid point
for (let counter = 0; counter < 65536; counter++) {
// 4-byte little-endian counter (matching ORLY's binary.LittleEndian.PutUint32)
const counterBytes = new Uint8Array(4)
new DataView(counterBytes.buffer).setUint32(0, counter, true) // true = little-endian
// msgHash THEN counterBytes (matching ORLY's append order)
const toHash = new Uint8Array([...msgHash, ...counterBytes])
const hash = sha256(toHash)
// Only try 0x02 prefix (even Y coordinate)
const compressed = new Uint8Array([0x02, ...hash])
try {
// Validate this is a valid point
const point = secp256k1.ProjectivePoint.fromHex(compressed)
if (!point.equals(secp256k1.ProjectivePoint.ZERO)) {
return compressed
}
} catch {
// Not a valid point, continue
}
}
throw new Error('Failed to hash to curve after 65536 attempts')
}
/**
* Create a blinded message from a secret.
* B_ = Y + r*G where Y = hash_to_curve(secret)
*/
function blind(secret: Uint8Array): BlindResult {
// Generate random blinding factor r
const r = secp256k1.utils.randomPrivateKey()
// Y = hash_to_curve(secret)
const Y = secp256k1.ProjectivePoint.fromHex(hashToCurve(secret))
// r*G
const rG = secp256k1.ProjectivePoint.BASE.multiply(utils.bytesToNumberBE(r))
// B_ = Y + r*G
const B_ = Y.add(rG)
return {
B_: B_.toRawBytes(true), // Compressed format
secret,
r
}
}
/**
* Unblind the signature to get the final signature.
* C = C_ - r*K where K is the mint's public key
*/
function unblind(C_: Uint8Array, r: Uint8Array, K: Uint8Array): Uint8Array {
const C_point = secp256k1.ProjectivePoint.fromHex(C_)
const K_point = secp256k1.ProjectivePoint.fromHex(K)
// r*K
const rK = K_point.multiply(utils.bytesToNumberBE(r))
// C = C_ - r*K
const C = C_point.subtract(rK)
return C.toRawBytes(true)
}
/**
* Verify a token signature locally.
* Checks that C = k*Y where Y = hash_to_curve(secret) and k is unknown.
* We verify using DLEQ proof or by checking C matches our expectations.
*/
function verifyToken(token: TCashuToken, _mintPubkey: Uint8Array): boolean {
try {
// Basic validation
if (token.expiry < Date.now() / 1000) {
return false
}
// Verify signature is a valid point
secp256k1.ProjectivePoint.fromHex(token.signature)
// Could implement full DLEQ verification here if needed
return true
} catch {
return false
}
}
/**
* Encode a token to the Cashu format (cashuA prefix + base64url).
*/
function encodeToken(token: TCashuToken): string {
const tokenData = {
k: token.keysetId,
s: utils.bytesToHex(token.secret),
c: utils.bytesToHex(token.signature),
p: utils.bytesToHex(token.pubkey),
e: token.expiry,
sc: token.scope,
kinds: token.kinds,
kind_ranges: token.kindRanges
}
const json = JSON.stringify(tokenData)
// Use base64url encoding
const base64 = btoa(json)
.replace(/\+/g, '-')
.replace(/\//g, '_')
.replace(/=+$/, '')
return 'cashuA' + base64
}
/**
* Decode a token from the Cashu format.
*/
function decodeToken(encoded: string): TCashuToken {
if (!encoded.startsWith('cashuA')) {
throw new Error('Invalid token prefix, expected cashuA')
}
const base64url = encoded.slice(6)
// Convert base64url to base64
let base64 = base64url.replace(/-/g, '+').replace(/_/g, '/')
// Add padding if needed
while (base64.length % 4 !== 0) {
base64 += '='
}
const json = atob(base64)
const data = JSON.parse(json)
return {
keysetId: data.k,
secret: utils.hexToBytes(data.s),
signature: utils.hexToBytes(data.c),
pubkey: utils.hexToBytes(data.p),
expiry: data.e,
scope: data.sc,
kinds: data.kinds,
kindRanges: data.kind_ranges
}
}
/**
* Cashu Token Service - manages token lifecycle for bunker auth.
*/
class CashuTokenService {
private mintUrl: string | null = null
private mintPubkey: Uint8Array | null = null
private activeKeysetId: string | null = null
/**
* Configure the mint endpoint.
*/
setMint(url: string) {
this.mintUrl = url.replace(/\/$/, '')
}
/**
* Fetch mint info and keysets.
*/
async fetchMintInfo(): Promise<TMintInfo> {
if (!this.mintUrl) {
throw new Error('Mint URL not configured')
}
const response = await fetch(`${this.mintUrl}/cashu/info`)
if (!response.ok) {
throw new Error(`Failed to fetch mint info: ${response.statusText}`)
}
const info = await response.json()
this.mintPubkey = utils.hexToBytes(info.pubkey)
// Also fetch keysets
const keysetsResponse = await fetch(`${this.mintUrl}/cashu/keysets`)
if (keysetsResponse.ok) {
const keysetsData = await keysetsResponse.json()
info.keysets = keysetsData.keysets
// Find active keyset
const active = keysetsData.keysets.find((k: TKeysetInfo) => k.active)
if (active) {
this.activeKeysetId = active.id
}
}
return info
}
/**
* Request a new token from the mint.
* Requires NIP-98 auth via the signHttpAuth function.
*/
async requestToken(
scope: TTokenScope,
userPubkey: Uint8Array,
signHttpAuth: (url: string, method: string) => Promise<string>,
kinds?: number[],
kindRanges?: [number, number][]
): Promise<TCashuToken> {
if (!this.mintUrl) {
throw new Error('Mint URL not configured')
}
// Generate secret and blind it
const secret = crypto.getRandomValues(new Uint8Array(32))
const blindResult = blind(secret)
// Create request
const requestBody = {
blinded_message: utils.bytesToHex(blindResult.B_),
scope,
kinds,
kind_ranges: kindRanges
}
// Get NIP-98 auth header
const authUrl = `${this.mintUrl}/cashu/mint`
const authHeader = await signHttpAuth(authUrl, 'POST')
// Submit to mint
const response = await fetch(authUrl, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
Authorization: authHeader
},
body: JSON.stringify(requestBody)
})
if (!response.ok) {
const error = await response.text()
throw new Error(`Mint request failed: ${error}`)
}
const result = await response.json()
// Unblind the signature
const C_ = utils.hexToBytes(result.blinded_signature)
const K = utils.hexToBytes(result.mint_pubkey)
const signature = unblind(C_, blindResult.r, K)
const token: TCashuToken = {
keysetId: result.keyset_id,
secret: blindResult.secret,
signature,
pubkey: userPubkey,
expiry: result.expiry,
scope,
kinds,
kindRanges
}
return token
}
/**
* Store tokens for a specific bunker.
* Maintains current and next token for rotation.
*/
storeTokens(bunkerPubkey: string, current: TCashuToken, next?: TCashuToken) {
const key = `${STORAGE_PREFIX}${bunkerPubkey}`
const data = {
current: encodeToken(current),
next: next ? encodeToken(next) : undefined,
storedAt: Date.now()
}
localStorage.setItem(key, JSON.stringify(data))
}
/**
* Load tokens for a specific bunker.
*/
loadTokens(bunkerPubkey: string): { current?: TCashuToken; next?: TCashuToken } | null {
const key = `${STORAGE_PREFIX}${bunkerPubkey}`
const stored = localStorage.getItem(key)
if (!stored) {
return null
}
try {
const data = JSON.parse(stored)
return {
current: data.current ? decodeToken(data.current) : undefined,
next: data.next ? decodeToken(data.next) : undefined
}
} catch {
return null
}
}
/**
* Get the active token for a bunker, handling rotation if needed.
*/
getActiveToken(bunkerPubkey: string): TCashuToken | null {
const tokens = this.loadTokens(bunkerPubkey)
if (!tokens) {
return null
}
const now = Date.now() / 1000
// If current is valid, use it
if (tokens.current && tokens.current.expiry > now) {
return tokens.current
}
// Current expired, try to promote next
if (tokens.next && tokens.next.expiry > now) {
// Promote next to current
this.storeTokens(bunkerPubkey, tokens.next)
return tokens.next
}
// Both expired
return null
}
/**
* Check if token needs refresh (< 1 day until expiry).
*/
needsRefresh(token: TCashuToken): boolean {
const now = Date.now() / 1000
const oneDaySeconds = 24 * 60 * 60
return token.expiry - now < oneDaySeconds
}
/**
* Clear tokens for a bunker.
*/
clearTokens(bunkerPubkey: string) {
const key = `${STORAGE_PREFIX}${bunkerPubkey}`
localStorage.removeItem(key)
}
/**
* Encode a token for transmission (e.g., in headers).
*/
encodeToken(token: TCashuToken): string {
return encodeToken(token)
}
/**
* Decode a token string.
*/
decodeToken(encoded: string): TCashuToken {
return decodeToken(encoded)
}
/**
* Verify a token is valid.
*/
verifyToken(token: TCashuToken): boolean {
if (!this.mintPubkey) {
// Can't verify without mint pubkey, assume valid if not expired
return token.expiry > Date.now() / 1000
}
return verifyToken(token, this.mintPubkey)
}
/**
* Get the active keyset ID.
*/
getActiveKeysetId(): string | null {
return this.activeKeysetId
}
}
// Export singleton instance
const cashuTokenService = new CashuTokenService()
export default cashuTokenService
// Export utilities
export { encodeToken, decodeToken, hashToCurve, blind, unblind }

View File

@@ -95,6 +95,19 @@ class ClientService extends EventTarget {
}
}
// NRC-only config sync: don't publish config events to relays, only sync via NRC
const CONFIG_KINDS = [
kinds.Contacts, // 3
kinds.Mutelist, // 10000
kinds.RelayList, // 10002
30002, // Relay sets
ExtendedKind.FAVORITE_RELAYS, // 10012
30078 // Application data (settings sync)
]
if (storage.getNrcOnlyConfigSync() && CONFIG_KINDS.includes(event.kind)) {
return [] // No relays - NRC will sync this event to paired devices
}
const relaySet = new Set<string>()
if (specifiedRelayUrls?.length) {
specifiedRelayUrls.forEach((url) => relaySet.add(url))

View File

@@ -1,7 +1,7 @@
import { ExtendedKind } from '@/constants'
import { tagNameEquals } from '@/lib/tag'
import { TDMDeletedState, TRelayInfo } from '@/types'
import { Event, kinds } from 'nostr-tools'
import { Event, Filter, kinds, matchFilters } from 'nostr-tools'
type TValue<T = any> = {
key: string
@@ -1014,6 +1014,84 @@ class IndexedDbService {
}
}
/**
* Query all events across all stores for NRC sync.
* Returns events matching the provided filters.
*
* Note: This method queries all event-containing stores and filters
* client-side using matchFilters. Device-specific event filtering
* should be done by the caller.
*/
async queryEventsForNRC(filters: Filter[]): Promise<Event[]> {
await this.initPromise
if (!this.db) {
return []
}
// List of stores that contain Event objects
const eventStores = [
StoreNames.PROFILE_EVENTS,
StoreNames.RELAY_LIST_EVENTS,
StoreNames.FOLLOW_LIST_EVENTS,
StoreNames.MUTE_LIST_EVENTS,
StoreNames.BOOKMARK_LIST_EVENTS,
StoreNames.BLOSSOM_SERVER_LIST_EVENTS,
StoreNames.USER_EMOJI_LIST_EVENTS,
StoreNames.EMOJI_SET_EVENTS,
StoreNames.PIN_LIST_EVENTS,
StoreNames.PINNED_USERS_EVENTS,
StoreNames.FAVORITE_RELAYS,
StoreNames.RELAY_SETS,
StoreNames.DM_EVENTS
]
const allEvents: Event[] = []
// Query each store
const transaction = this.db.transaction(eventStores, 'readonly')
await Promise.all(
eventStores.map(
(storeName) =>
new Promise<void>((resolve) => {
const store = transaction.objectStore(storeName)
const request = store.openCursor()
request.onsuccess = (event) => {
const cursor = (event.target as IDBRequest).result
if (cursor) {
const value = cursor.value as TValue<Event | null>
if (value.value) {
// Check if event matches any of the filters
if (matchFilters(filters, value.value)) {
allEvents.push(value.value)
}
}
cursor.continue()
} else {
resolve()
}
}
request.onerror = () => {
resolve() // Continue even if one store fails
}
})
)
)
// Sort by created_at descending (newest first)
allEvents.sort((a, b) => b.created_at - a.created_at)
// Apply limit from filters if specified
const limit = Math.min(...filters.map((f) => f.limit ?? Infinity))
if (limit !== Infinity && limit > 0) {
return allEvents.slice(0, limit)
}
return allEvents
}
private async cleanUp() {
await this.initPromise
if (!this.db) {

View File

@@ -63,6 +63,7 @@ class LocalStorageService {
private graphQueriesEnabled: boolean = true
private socialGraphProximity: number | null = null
private socialGraphIncludeMode: boolean = true // true = include only, false = exclude
private nrcOnlyConfigSync: boolean = false
constructor() {
if (!LocalStorageService.instance) {
@@ -264,6 +265,9 @@ class LocalStorageService {
this.socialGraphIncludeMode =
window.localStorage.getItem(StorageKey.SOCIAL_GRAPH_INCLUDE_MODE) !== 'false'
this.nrcOnlyConfigSync =
window.localStorage.getItem(StorageKey.NRC_ONLY_CONFIG_SYNC) === 'true'
// Clean up deprecated data
window.localStorage.removeItem(StorageKey.PINNED_PUBKEYS)
window.localStorage.removeItem(StorageKey.ACCOUNT_PROFILE_EVENT_MAP)
@@ -686,6 +690,15 @@ class LocalStorageService {
this.socialGraphIncludeMode = include
window.localStorage.setItem(StorageKey.SOCIAL_GRAPH_INCLUDE_MODE, include.toString())
}
getNrcOnlyConfigSync() {
return this.nrcOnlyConfigSync
}
setNrcOnlyConfigSync(nrcOnly: boolean) {
this.nrcOnlyConfigSync = nrcOnly
window.localStorage.setItem(StorageKey.NRC_ONLY_CONFIG_SYNC, nrcOnly.toString())
}
}
const instance = new LocalStorageService()

View File

@@ -0,0 +1,6 @@
export * from './nrc-types'
export * from './nrc-uri'
export * from './nrc-session'
export { NRCListenerService, getNRCListenerService, default as nrcListenerService } from './nrc-listener.service'
export { NRCClient, syncFromRemote, testConnection, requestRemoteIDs, sendEventsToRemote } from './nrc-client.service'
export type { SyncProgress, RemoteConnection } from './nrc-client.service'

View File

@@ -0,0 +1,790 @@
/**
* NRC (Nostr Relay Connect) Client Service
*
* Connects to a remote NRC listener and syncs events.
* Uses the nostr+relayconnect:// URI scheme to establish encrypted
* communication through a rendezvous relay.
*/
import { Event, Filter } from 'nostr-tools'
import * as nip44 from 'nostr-tools/nip44'
import * as utils from '@noble/curves/abstract/utils'
import { finalizeEvent } from 'nostr-tools'
import {
KIND_NRC_REQUEST,
KIND_NRC_RESPONSE,
RequestMessage,
ResponseMessage,
ParsedConnectionURI,
EventManifestEntry
} from './nrc-types'
import { parseConnectionURI, deriveConversationKey } from './nrc-uri'
/**
* Generate a random subscription ID
*/
function generateSubId(): string {
const bytes = crypto.getRandomValues(new Uint8Array(8))
return utils.bytesToHex(bytes)
}
/**
* Generate a random session ID
*/
function generateSessionId(): string {
return crypto.randomUUID()
}
/**
* Sync progress callback
*/
export interface SyncProgress {
phase: 'connecting' | 'requesting' | 'receiving' | 'sending' | 'complete' | 'error'
eventsReceived: number
eventsSent?: number
message?: string
}
/**
* Remote connection state
*/
export interface RemoteConnection {
id: string
uri: string
label: string
relayPubkey: string
rendezvousUrl: string
lastSync?: number
eventCount?: number
}
// Chunk buffer for reassembling large messages
interface ChunkBuffer {
chunks: Map<number, string>
total: number
receivedAt: number
}
// Default sync timeout: 60 seconds
const DEFAULT_SYNC_TIMEOUT = 60000
/**
* NRC Client for connecting to remote devices
*/
export class NRCClient {
private uri: ParsedConnectionURI
private ws: WebSocket | null = null
private sessionId: string
private connected = false
private subId: string | null = null
private pendingEvents: Event[] = []
private onProgress?: (progress: SyncProgress) => void
private resolveSync?: (events: Event[]) => void
private rejectSync?: (error: Error) => void
private chunkBuffers: Map<string, ChunkBuffer> = new Map()
private syncTimeout: ReturnType<typeof setTimeout> | null = null
private lastActivityTime: number = 0
constructor(connectionUri: string) {
this.uri = parseConnectionURI(connectionUri)
this.sessionId = generateSessionId()
}
/**
* Get the relay pubkey this client connects to
*/
getRelayPubkey(): string {
return this.uri.relayPubkey
}
/**
* Get the rendezvous URL
*/
getRendezvousUrl(): string {
return this.uri.rendezvousUrl
}
/**
* Connect to the rendezvous relay and sync events
*/
async sync(
filters: Filter[],
onProgress?: (progress: SyncProgress) => void,
timeout: number = DEFAULT_SYNC_TIMEOUT
): Promise<Event[]> {
this.onProgress = onProgress
this.pendingEvents = []
this.chunkBuffers.clear()
this.lastActivityTime = Date.now()
return new Promise<Event[]>((resolve, reject) => {
this.resolveSync = resolve
this.rejectSync = reject
// Set up sync timeout
this.syncTimeout = setTimeout(() => {
const timeSinceActivity = Date.now() - this.lastActivityTime
if (timeSinceActivity > 30000) {
// No activity for 30s, likely stalled
console.error('[NRC Client] Sync timeout - no activity for 30s')
this.disconnect()
reject(new Error('Sync timeout - connection stalled'))
} else {
// Still receiving data, extend timeout
console.log('[NRC Client] Sync still active, extending timeout')
this.syncTimeout = setTimeout(() => {
this.disconnect()
reject(new Error('Sync timeout'))
}, timeout)
}
}, timeout)
this.connect()
.then(() => {
this.sendREQ(filters)
})
.catch((err) => {
this.clearSyncTimeout()
reject(err)
})
})
}
// State for IDS request
private idsMode = false
private resolveIDs?: (manifest: EventManifestEntry[]) => void
private rejectIDs?: (error: Error) => void
// State for sending events
private sendingEvents = false
private eventsSentCount = 0
private eventsToSend: Event[] = []
private resolveSend?: (count: number) => void
/**
* Request event IDs from remote (for diffing)
*/
async requestIDs(
filters: Filter[],
onProgress?: (progress: SyncProgress) => void,
timeout: number = DEFAULT_SYNC_TIMEOUT
): Promise<EventManifestEntry[]> {
this.onProgress = onProgress
this.chunkBuffers.clear()
this.lastActivityTime = Date.now()
this.idsMode = true
return new Promise<EventManifestEntry[]>((resolve, reject) => {
this.resolveIDs = resolve
this.rejectIDs = reject
this.syncTimeout = setTimeout(() => {
this.disconnect()
reject(new Error('IDS request timeout'))
}, timeout)
this.connect()
.then(() => {
this.sendIDSRequest(filters)
})
.catch((err) => {
this.clearSyncTimeout()
reject(err)
})
})
}
/**
* Send IDS request
*/
private sendIDSRequest(filters: Filter[]): void {
if (!this.ws || !this.connected) {
this.rejectIDs?.(new Error('Not connected'))
return
}
this.onProgress?.({
phase: 'requesting',
eventsReceived: 0,
message: 'Requesting event IDs...'
})
this.subId = generateSubId()
const request: RequestMessage = {
type: 'IDS',
payload: ['IDS', this.subId, ...filters]
}
this.sendEncryptedRequest(request).catch((err) => {
console.error('[NRC Client] Failed to send IDS:', err)
this.rejectIDs?.(err)
})
}
/**
* Send events to remote device
*/
async sendEvents(
events: Event[],
onProgress?: (progress: SyncProgress) => void,
timeout: number = DEFAULT_SYNC_TIMEOUT
): Promise<number> {
if (events.length === 0) return 0
this.onProgress = onProgress
this.chunkBuffers.clear()
this.lastActivityTime = Date.now()
this.sendingEvents = true
this.eventsSentCount = 0
this.eventsToSend = [...events]
return new Promise<number>((resolve, reject) => {
this.resolveSend = resolve
this.syncTimeout = setTimeout(() => {
this.disconnect()
reject(new Error('Send events timeout'))
}, timeout)
this.connect()
.then(() => {
this.sendNextEvent()
})
.catch((err) => {
this.clearSyncTimeout()
reject(err)
})
})
}
/**
* Send the next event in the queue
*/
private sendNextEvent(): void {
if (this.eventsToSend.length === 0) {
// All done
this.clearSyncTimeout()
this.onProgress?.({
phase: 'complete',
eventsReceived: 0,
eventsSent: this.eventsSentCount,
message: `Sent ${this.eventsSentCount} events`
})
this.resolveSend?.(this.eventsSentCount)
this.disconnect()
return
}
const event = this.eventsToSend.shift()!
this.onProgress?.({
phase: 'sending',
eventsReceived: 0,
eventsSent: this.eventsSentCount,
message: `Sending event ${this.eventsSentCount + 1}...`
})
const request: RequestMessage = {
type: 'EVENT',
payload: ['EVENT', event]
}
this.sendEncryptedRequest(request).catch((err) => {
console.error('[NRC Client] Failed to send EVENT:', err)
// Continue with next event even if this one failed
this.sendNextEvent()
})
}
/**
* Clear the sync timeout
*/
private clearSyncTimeout(): void {
if (this.syncTimeout) {
clearTimeout(this.syncTimeout)
this.syncTimeout = null
}
}
/**
* Update last activity time (called when receiving data)
*/
private updateActivity(): void {
this.lastActivityTime = Date.now()
}
/**
* Connect to the rendezvous relay
*/
private async connect(): Promise<void> {
if (this.connected) return
this.onProgress?.({
phase: 'connecting',
eventsReceived: 0,
message: 'Connecting to rendezvous relay...'
})
const relayUrl = this.uri.rendezvousUrl
return new Promise<void>((resolve, reject) => {
// Normalize WebSocket URL
let wsUrl = relayUrl
if (relayUrl.startsWith('http://')) {
wsUrl = 'ws://' + relayUrl.slice(7)
} else if (relayUrl.startsWith('https://')) {
wsUrl = 'wss://' + relayUrl.slice(8)
} else if (!relayUrl.startsWith('ws://') && !relayUrl.startsWith('wss://')) {
wsUrl = 'wss://' + relayUrl
}
console.log(`[NRC Client] Connecting to: ${wsUrl}`)
const ws = new WebSocket(wsUrl)
const timeout = setTimeout(() => {
ws.close()
reject(new Error('Connection timeout'))
}, 10000)
ws.onopen = () => {
clearTimeout(timeout)
this.ws = ws
this.connected = true
// Subscribe to responses for our client pubkey
const responseSubId = generateSubId()
const clientPubkey = this.uri.clientPubkey
if (!clientPubkey) {
reject(new Error('Client pubkey not available'))
return
}
ws.send(
JSON.stringify([
'REQ',
responseSubId,
{
kinds: [KIND_NRC_RESPONSE],
'#p': [clientPubkey],
since: Math.floor(Date.now() / 1000) - 60
}
])
)
console.log(`[NRC Client] Connected, subscribed for responses to ${clientPubkey.slice(0, 8)}...`)
resolve()
}
ws.onerror = (error) => {
clearTimeout(timeout)
console.error('[NRC Client] WebSocket error:', error)
reject(new Error('WebSocket error'))
}
ws.onclose = () => {
this.connected = false
this.ws = null
console.log('[NRC Client] WebSocket closed')
}
ws.onmessage = (event) => {
this.handleMessage(event.data)
}
})
}
/**
* Send a REQ message to the remote listener
*/
private sendREQ(filters: Filter[]): void {
if (!this.ws || !this.connected) {
this.rejectSync?.(new Error('Not connected'))
return
}
console.log(`[NRC Client] Sending REQ to listener pubkey: ${this.uri.relayPubkey?.slice(0, 8)}...`)
console.log(`[NRC Client] Our client pubkey: ${this.uri.clientPubkey?.slice(0, 8)}...`)
console.log(`[NRC Client] Filters:`, JSON.stringify(filters))
this.onProgress?.({
phase: 'requesting',
eventsReceived: 0,
message: 'Requesting events...'
})
this.subId = generateSubId()
const request: RequestMessage = {
type: 'REQ',
payload: ['REQ', this.subId, ...filters]
}
this.sendEncryptedRequest(request).catch((err) => {
console.error('[NRC Client] Failed to send request:', err)
this.rejectSync?.(err)
})
}
/**
* Send an encrypted request to the remote listener
*/
private async sendEncryptedRequest(request: RequestMessage): Promise<void> {
if (!this.ws) {
throw new Error('Not connected')
}
if (!this.uri.clientPrivkey || !this.uri.clientPubkey) {
throw new Error('Missing keys')
}
const plaintext = JSON.stringify(request)
// Derive conversation key
const conversationKey = deriveConversationKey(
this.uri.clientPrivkey,
this.uri.relayPubkey
)
const encrypted = nip44.v2.encrypt(plaintext, conversationKey)
// Build the request event
const unsignedEvent = {
kind: KIND_NRC_REQUEST,
content: encrypted,
tags: [
['p', this.uri.relayPubkey],
['encryption', 'nip44_v2'],
['session', this.sessionId]
],
created_at: Math.floor(Date.now() / 1000),
pubkey: this.uri.clientPubkey
}
const signedEvent = finalizeEvent(unsignedEvent, this.uri.clientPrivkey)
// Send to rendezvous relay
this.ws.send(JSON.stringify(['EVENT', signedEvent]))
console.log(`[NRC Client] Sent encrypted REQ, event id: ${signedEvent.id?.slice(0, 8)}..., p-tag: ${this.uri.relayPubkey?.slice(0, 8)}...`)
}
/**
* Handle incoming WebSocket messages
*/
private handleMessage(data: string): void {
try {
const msg = JSON.parse(data)
if (!Array.isArray(msg)) return
const [type, ...rest] = msg
if (type === 'EVENT') {
const [subId, event] = rest as [string, Event]
console.log(`[NRC Client] Received EVENT on sub ${subId}, kind ${event.kind}, from ${event.pubkey?.slice(0, 8)}...`)
if (event.kind === KIND_NRC_RESPONSE) {
// Check p-tag to see who it's addressed to
const pTag = event.tags.find(t => t[0] === 'p')?.[1]
console.log(`[NRC Client] Response p-tag: ${pTag?.slice(0, 8)}..., our pubkey: ${this.uri.clientPubkey?.slice(0, 8)}...`)
this.handleResponse(event)
} else {
console.log(`[NRC Client] Ignoring event kind ${event.kind}`)
}
} else if (type === 'EOSE') {
console.log('[NRC Client] Received EOSE from relay subscription')
} else if (type === 'OK') {
console.log('[NRC Client] Event published:', rest)
} else if (type === 'NOTICE') {
console.log('[NRC Client] Relay notice:', rest[0])
}
} catch (err) {
console.error('[NRC Client] Failed to parse message:', err)
}
}
/**
* Handle a response event from the remote listener
*/
private handleResponse(event: Event): void {
console.log(`[NRC Client] Attempting to decrypt response from ${event.pubkey?.slice(0, 8)}...`)
this.decryptAndProcessResponse(event).catch((err) => {
console.error('[NRC Client] Failed to handle response:', err)
})
}
/**
* Decrypt and process a response event
*/
private async decryptAndProcessResponse(event: Event): Promise<void> {
if (!this.uri.clientPrivkey) {
throw new Error('Missing private key for decryption')
}
const conversationKey = deriveConversationKey(
this.uri.clientPrivkey,
this.uri.relayPubkey
)
const plaintext = nip44.v2.decrypt(event.content, conversationKey)
const response: ResponseMessage = JSON.parse(plaintext)
console.log(`[NRC Client] Received response: ${response.type}`)
// Handle chunked messages
if (response.type === 'CHUNK') {
this.handleChunk(response)
return
}
this.processResponse(response)
}
/**
* Handle a chunk message and reassemble when complete
*/
private handleChunk(response: ResponseMessage): void {
const chunk = response.payload[0] as {
type: 'CHUNK'
messageId: string
index: number
total: number
data: string
}
if (!chunk || chunk.type !== 'CHUNK') {
console.error('[NRC Client] Invalid chunk message')
return
}
const { messageId, index, total, data } = chunk
// Get or create buffer for this message
let buffer = this.chunkBuffers.get(messageId)
if (!buffer) {
buffer = {
chunks: new Map(),
total,
receivedAt: Date.now()
}
this.chunkBuffers.set(messageId, buffer)
}
// Store the chunk
buffer.chunks.set(index, data)
this.updateActivity()
console.log(`[NRC Client] Received chunk ${index + 1}/${total} for message ${messageId.slice(0, 8)}`)
// Check if we have all chunks
if (buffer.chunks.size === buffer.total) {
// Reassemble the message
const parts: string[] = []
for (let i = 0; i < buffer.total; i++) {
const part = buffer.chunks.get(i)
if (!part) {
console.error(`[NRC Client] Missing chunk ${i} for message ${messageId}`)
this.chunkBuffers.delete(messageId)
return
}
parts.push(part)
}
// Decode from base64
const encoded = parts.join('')
try {
const plaintext = decodeURIComponent(escape(atob(encoded)))
const reassembled: ResponseMessage = JSON.parse(plaintext)
console.log(`[NRC Client] Reassembled chunked message: ${reassembled.type}`)
this.processResponse(reassembled)
} catch (err) {
console.error('[NRC Client] Failed to reassemble chunked message:', err)
}
// Clean up buffer
this.chunkBuffers.delete(messageId)
}
// Clean up old buffers (older than 60 seconds)
const now = Date.now()
for (const [id, buf] of this.chunkBuffers) {
if (now - buf.receivedAt > 60000) {
console.warn(`[NRC Client] Discarding stale chunk buffer: ${id}`)
this.chunkBuffers.delete(id)
}
}
}
/**
* Process a complete response message
*/
private processResponse(response: ResponseMessage): void {
this.updateActivity()
switch (response.type) {
case 'EVENT': {
// Extract the event from payload: ["EVENT", subId, eventObject]
const [, , syncedEvent] = response.payload as [string, string, Event]
if (syncedEvent) {
this.pendingEvents.push(syncedEvent)
this.onProgress?.({
phase: 'receiving',
eventsReceived: this.pendingEvents.length,
message: `Received ${this.pendingEvents.length} events...`
})
}
break
}
case 'EOSE': {
console.log(`[NRC Client] EOSE received, got ${this.pendingEvents.length} events`)
this.complete()
break
}
case 'NOTICE': {
const [, message] = response.payload as [string, string]
console.log(`[NRC Client] Notice: ${message}`)
this.onProgress?.({
phase: 'error',
eventsReceived: this.pendingEvents.length,
message: message
})
break
}
case 'OK': {
// Response to EVENT publish
if (this.sendingEvents) {
const [, eventId, success, message] = response.payload as [string, string, boolean, string]
if (success) {
this.eventsSentCount++
console.log(`[NRC Client] Event ${eventId?.slice(0, 8)} stored successfully`)
} else {
console.warn(`[NRC Client] Event ${eventId?.slice(0, 8)} failed: ${message}`)
}
// Send next event
this.sendNextEvent()
}
break
}
case 'IDS': {
// Response to IDS request - contains event manifest
if (this.idsMode) {
const [, , manifest] = response.payload as [string, string, EventManifestEntry[]]
console.log(`[NRC Client] Received IDS response with ${manifest?.length || 0} entries`)
this.clearSyncTimeout()
this.resolveIDs?.(manifest || [])
this.disconnect()
}
break
}
default:
console.log(`[NRC Client] Unknown response type: ${response.type}`)
}
}
/**
* Complete the sync operation
*/
private complete(): void {
this.clearSyncTimeout()
this.onProgress?.({
phase: 'complete',
eventsReceived: this.pendingEvents.length,
message: `Synced ${this.pendingEvents.length} events`
})
this.resolveSync?.(this.pendingEvents)
this.disconnect()
}
/**
* Disconnect from the rendezvous relay
*/
disconnect(): void {
this.clearSyncTimeout()
if (this.ws) {
this.ws.close()
this.ws = null
}
this.connected = false
}
}
/**
* Sync events from a remote device
*
* @param connectionUri - The nostr+relayconnect:// URI
* @param filters - Nostr filters for events to sync
* @param onProgress - Optional progress callback
* @returns Array of synced events
*/
export async function syncFromRemote(
connectionUri: string,
filters: Filter[],
onProgress?: (progress: SyncProgress) => void
): Promise<Event[]> {
const client = new NRCClient(connectionUri)
return client.sync(filters, onProgress)
}
/**
* Test connection to a remote device
* Performs a minimal sync (kind 0 with limit 1) to verify the connection works
*
* @param connectionUri - The nostr+relayconnect:// URI
* @param onProgress - Optional progress callback
* @returns true if connection successful
*/
export async function testConnection(
connectionUri: string,
onProgress?: (progress: SyncProgress) => void
): Promise<boolean> {
const client = new NRCClient(connectionUri)
try {
// Request just one profile event to test the full round-trip
const events = await client.sync(
[{ kinds: [0], limit: 1 }],
onProgress,
15000 // 15 second timeout for test
)
console.log(`[NRC] Test connection successful, received ${events.length} events`)
return true
} catch (err) {
console.error('[NRC] Test connection failed:', err)
throw err
}
}
/**
* Request event IDs from a remote device (for diffing)
*
* @param connectionUri - The nostr+relayconnect:// URI
* @param filters - Filters to match events
* @param onProgress - Optional progress callback
* @returns Array of event manifest entries (id, kind, created_at, d)
*/
export async function requestRemoteIDs(
connectionUri: string,
filters: Filter[],
onProgress?: (progress: SyncProgress) => void
): Promise<EventManifestEntry[]> {
const client = new NRCClient(connectionUri)
return client.requestIDs(filters, onProgress)
}
/**
* Send events to a remote device
*
* @param connectionUri - The nostr+relayconnect:// URI
* @param events - Events to send
* @param onProgress - Optional progress callback
* @returns Number of events successfully stored
*/
export async function sendEventsToRemote(
connectionUri: string,
events: Event[],
onProgress?: (progress: SyncProgress) => void
): Promise<number> {
const client = new NRCClient(connectionUri)
return client.sendEvents(events, onProgress)
}

View File

@@ -0,0 +1,683 @@
/**
* NRC (Nostr Relay Connect) Listener Service
*
* Listens for NRC requests (kind 24891) on a rendezvous relay and responds
* with events from the local IndexedDB. This allows other user clients to
* sync their data through this client.
*
* Protocol:
* - Client sends kind 24891 request with encrypted REQ/CLOSE message
* - This listener decrypts, queries local storage, and responds with kind 24892
* - All content is NIP-44 encrypted end-to-end
*/
import { Event, Filter } from 'nostr-tools'
import * as utils from '@noble/curves/abstract/utils'
import indexedDb from '@/services/indexed-db.service'
import {
KIND_NRC_REQUEST,
KIND_NRC_RESPONSE,
NRCListenerConfig,
RequestMessage,
ResponseMessage,
AuthResult,
NRCSession,
isDeviceSpecificEvent,
EventManifestEntry
} from './nrc-types'
import { NRCSessionManager } from './nrc-session'
/**
* Generate a random subscription ID
*/
function generateSubId(): string {
const bytes = crypto.getRandomValues(new Uint8Array(8))
return utils.bytesToHex(bytes)
}
/**
* NRC Listener Service
*
* Listens for incoming NRC requests and responds with local events.
*/
export class NRCListenerService {
private config: NRCListenerConfig | null = null
private sessions: NRCSessionManager
private ws: WebSocket | null = null
private subId: string | null = null
private connected = false
private running = false
private reconnectTimeout: ReturnType<typeof setTimeout> | null = null
private reconnectDelay = 1000 // Start with 1 second
private maxReconnectDelay = 30000 // Max 30 seconds
private listenerPubkey: string | null = null
// Event callbacks
private onSessionChange?: (count: number) => void
constructor() {
this.sessions = new NRCSessionManager()
}
/**
* Set callback for session count changes
*/
setOnSessionChange(callback: (count: number) => void): void {
this.onSessionChange = callback
}
/**
* Start listening for NRC requests
*/
async start(config: NRCListenerConfig): Promise<void> {
if (this.running) {
console.warn('[NRC] Listener already running')
return
}
this.config = config
this.running = true
// Get our public key
this.listenerPubkey = await config.signer.getPublicKey()
// Start session cleanup
this.sessions.start()
// Connect to rendezvous relay
await this.connectToRelay()
}
/**
* Stop listening
*/
stop(): void {
this.running = false
if (this.reconnectTimeout) {
clearTimeout(this.reconnectTimeout)
this.reconnectTimeout = null
}
if (this.ws) {
// Unsubscribe
if (this.subId) {
try {
this.ws.send(JSON.stringify(['CLOSE', this.subId]))
} catch {
// Ignore errors when closing
}
}
this.ws.close()
this.ws = null
}
this.sessions.stop()
this.connected = false
this.subId = null
console.log('[NRC] Listener stopped')
}
/**
* Check if listener is running
*/
isRunning(): boolean {
return this.running
}
/**
* Check if connected to rendezvous relay
*/
isConnected(): boolean {
return this.connected
}
/**
* Get active session count
*/
getActiveSessionCount(): number {
return this.sessions.getActiveSessionCount()
}
/**
* Connect to the rendezvous relay
*/
private async connectToRelay(): Promise<void> {
if (!this.config || !this.running) return Promise.resolve()
const relayUrl = this.config.rendezvousUrl
return new Promise<void>((resolve, reject) => {
// Normalize WebSocket URL
let wsUrl = relayUrl
if (relayUrl.startsWith('http://')) {
wsUrl = 'ws://' + relayUrl.slice(7)
} else if (relayUrl.startsWith('https://')) {
wsUrl = 'wss://' + relayUrl.slice(8)
} else if (!relayUrl.startsWith('ws://') && !relayUrl.startsWith('wss://')) {
wsUrl = 'wss://' + relayUrl
}
console.log(`[NRC] Connecting to rendezvous relay: ${wsUrl}`)
const ws = new WebSocket(wsUrl)
const timeout = setTimeout(() => {
ws.close()
reject(new Error('Connection timeout'))
}, 10000)
ws.onopen = () => {
clearTimeout(timeout)
this.ws = ws
this.connected = true
this.reconnectDelay = 1000 // Reset reconnect delay on success
// Subscribe to NRC requests for our pubkey
this.subId = generateSubId()
ws.send(
JSON.stringify([
'REQ',
this.subId,
{
kinds: [KIND_NRC_REQUEST],
'#p': [this.listenerPubkey],
since: Math.floor(Date.now() / 1000) - 60
}
])
)
console.log(`[NRC] Connected and subscribed with subId: ${this.subId}, listening for pubkey: ${this.listenerPubkey}`)
resolve()
}
ws.onerror = (error) => {
clearTimeout(timeout)
console.error('[NRC] WebSocket error:', error)
reject(new Error('WebSocket error'))
}
ws.onclose = () => {
this.connected = false
this.ws = null
this.subId = null
console.log('[NRC] WebSocket closed')
// Attempt reconnection if still running
if (this.running) {
this.scheduleReconnect()
}
}
ws.onmessage = (event) => {
this.handleMessage(event.data)
}
}).catch((error) => {
console.error('[NRC] Failed to connect:', error)
if (this.running) {
this.scheduleReconnect()
}
})
}
/**
* Schedule reconnection with exponential backoff
*/
private scheduleReconnect(): void {
if (this.reconnectTimeout || !this.running) return
console.log(`[NRC] Scheduling reconnect in ${this.reconnectDelay}ms`)
this.reconnectTimeout = setTimeout(() => {
this.reconnectTimeout = null
this.connectToRelay()
}, this.reconnectDelay)
// Exponential backoff
this.reconnectDelay = Math.min(this.reconnectDelay * 2, this.maxReconnectDelay)
}
/**
* Handle incoming WebSocket message
*/
private handleMessage(data: string): void {
try {
const msg = JSON.parse(data)
if (!Array.isArray(msg)) return
const [type, ...rest] = msg
if (type === 'EVENT') {
const [, event] = rest as [string, Event]
if (event.kind === KIND_NRC_REQUEST) {
console.log('[NRC] Received NRC request from pubkey:', event.pubkey)
this.handleRequest(event).catch((err) => {
console.error('[NRC] Error handling request:', err)
})
}
} else if (type === 'EOSE') {
// End of stored events, listener is now live
console.log('[NRC] Received EOSE, now listening for live events')
} else if (type === 'NOTICE') {
console.log('[NRC] Relay notice:', rest[0])
} else if (type === 'OK') {
// Event published successfully
} else if (type === 'CLOSED') {
console.log('[NRC] Subscription closed:', rest)
}
} catch (err) {
console.error('[NRC] Failed to parse message:', err)
}
}
/**
* Handle an NRC request event
*/
private async handleRequest(event: Event): Promise<void> {
if (!this.config) return
// Extract session ID from tags (used for correlation but we use pubkey-based sessions)
const sessionTag = event.tags.find((t) => t[0] === 'session')
const _sessionId = sessionTag?.[1]
void _sessionId // Suppress unused variable warning
try {
// Authorize the request
const authResult = await this.authorize(event)
// Get or create session
const session = this.sessions.getOrCreateSession(
event.pubkey,
undefined, // We use signer's nip44 methods instead of conversationKey
authResult.deviceName
)
// Notify session change
this.onSessionChange?.(this.sessions.getActiveSessionCount())
// Decrypt the content using signer
const plaintext = await this.decrypt(event.pubkey, event.content)
const request: RequestMessage = JSON.parse(plaintext)
console.log('[NRC] Received request:', request.type)
// Handle the request based on type
switch (request.type) {
case 'REQ':
await this.handleREQ(event, session, request.payload)
break
case 'CLOSE':
await this.handleCLOSE(session, request.payload)
break
case 'EVENT':
await this.handleEVENT(event, session, request.payload)
break
case 'IDS':
// Return just event IDs matching filters (for diffing)
await this.handleIDS(event, session, request.payload)
break
case 'COUNT':
// Not implemented
await this.sendError(event, session, 'COUNT not supported')
break
default:
await this.sendError(event, session, `Unknown message type: ${request.type}`)
}
} catch (err) {
console.error('[NRC] Request handling failed:', err)
// Try to send error response (best effort)
try {
await this.sendErrorBestEffort(event, `Request failed: ${err instanceof Error ? err.message : 'Unknown error'}`)
} catch {
// Ignore errors when sending error response
}
}
}
/**
* Authorize an incoming request
*/
private async authorize(event: Event): Promise<AuthResult> {
if (!this.config) {
throw new Error('Listener not configured')
}
// Secret-based auth: check if pubkey is authorized
const deviceName = this.config.authorizedSecrets.get(event.pubkey)
if (!deviceName) {
console.log('[NRC] Unauthorized pubkey:', event.pubkey)
console.log('[NRC] Authorized pubkeys:', Array.from(this.config.authorizedSecrets.keys()))
console.log('[NRC] Authorized pubkeys (full):', JSON.stringify(Array.from(this.config.authorizedSecrets.entries())))
throw new Error('Unauthorized: unknown client pubkey')
}
return {
deviceName
}
}
/**
* Decrypt content using the signer's NIP-44 implementation
*/
private async decrypt(clientPubkey: string, ciphertext: string): Promise<string> {
if (!this.config) {
throw new Error('Listener not configured')
}
if (!this.config.signer.nip44Decrypt) {
throw new Error('Signer does not support NIP-44 decryption')
}
return this.config.signer.nip44Decrypt(clientPubkey, ciphertext)
}
/**
* Encrypt content using the signer's NIP-44 implementation
*/
private async encrypt(clientPubkey: string, plaintext: string): Promise<string> {
if (!this.config) {
throw new Error('Listener not configured')
}
if (!this.config.signer.nip44Encrypt) {
throw new Error('Signer does not support NIP-44 encryption')
}
return this.config.signer.nip44Encrypt(clientPubkey, plaintext)
}
// Max chunk size (accounting for encryption overhead and event wrapper)
// NIP-44 adds ~100 bytes overhead, plus base64 encoding increases size by ~33%
private static readonly MAX_CHUNK_SIZE = 40000 // ~40KB chunks to stay safely under 65KB limit
/**
* Handle REQ message - query local storage and respond
*/
private async handleREQ(
reqEvent: Event,
session: NRCSession,
payload: unknown[]
): Promise<void> {
// Parse REQ: ["REQ", subId, filter1, filter2, ...]
if (payload.length < 2) {
await this.sendError(reqEvent, session, 'Invalid REQ: missing subscription ID or filters')
return
}
const [, subId, ...filterObjs] = payload as [string, string, ...Filter[]]
// Add subscription to session
const subscription = this.sessions.addSubscription(session.id, subId, filterObjs)
if (!subscription) {
await this.sendError(reqEvent, session, 'Too many subscriptions')
return
}
// Query local events matching the filters
const events = await this.queryLocalEvents(filterObjs)
console.log(`[NRC] Found ${events.length} events matching filters`)
// Send each matching event
for (const evt of events) {
const response: ResponseMessage = {
type: 'EVENT',
payload: ['EVENT', subId, evt]
}
try {
await this.sendResponseChunked(reqEvent, session, response)
this.sessions.incrementEventCount(session.id, subId)
} catch (err) {
console.error(`[NRC] Failed to send event ${evt.id?.slice(0, 8)}:`, err)
}
}
// Send EOSE
const eoseResponse: ResponseMessage = {
type: 'EOSE',
payload: ['EOSE', subId]
}
await this.sendResponse(reqEvent, session, eoseResponse)
this.sessions.markEOSE(session.id, subId)
console.log(`[NRC] Sent EOSE for subscription ${subId}`)
}
/**
* Handle CLOSE message
*/
private async handleCLOSE(session: NRCSession, payload: unknown[]): Promise<void> {
// Parse CLOSE: ["CLOSE", subId]
const [, subId] = payload as [string, string]
if (subId) {
this.sessions.removeSubscription(session.id, subId)
}
}
/**
* Handle EVENT message - store an event from the remote device
*/
private async handleEVENT(
reqEvent: Event,
session: NRCSession,
payload: unknown[]
): Promise<void> {
// Parse EVENT: ["EVENT", eventObject]
const [, eventToStore] = payload as [string, Event]
if (!eventToStore || !eventToStore.id || !eventToStore.sig) {
await this.sendError(reqEvent, session, 'Invalid EVENT: missing event data')
return
}
try {
// Store the event in IndexedDB
await indexedDb.putReplaceableEvent(eventToStore)
console.log(`[NRC] Stored event ${eventToStore.id.slice(0, 8)} kind ${eventToStore.kind} from ${session.deviceName}`)
// Send OK response
const response: ResponseMessage = {
type: 'OK',
payload: ['OK', eventToStore.id, true, '']
}
await this.sendResponse(reqEvent, session, response)
} catch (err) {
console.error('[NRC] Failed to store event:', err)
const response: ResponseMessage = {
type: 'OK',
payload: ['OK', eventToStore.id, false, `Failed to store: ${err instanceof Error ? err.message : 'Unknown error'}`]
}
await this.sendResponse(reqEvent, session, response)
}
}
/**
* Handle IDS message - return event IDs matching filters (for diffing)
* Similar to REQ but returns only IDs, not full events
*/
private async handleIDS(
reqEvent: Event,
session: NRCSession,
payload: unknown[]
): Promise<void> {
// Parse IDS: ["IDS", subId, filter1, filter2, ...]
if (payload.length < 2) {
await this.sendError(reqEvent, session, 'Invalid IDS: missing subscription ID or filters')
return
}
const [, subId, ...filterObjs] = payload as [string, string, ...Filter[]]
// Query local events matching the filters
const events = await this.queryLocalEvents(filterObjs)
console.log(`[NRC] Found ${events.length} events for IDS request`)
// Build manifest of event IDs with metadata for diffing
const manifest: EventManifestEntry[] = events.map((evt) => ({
kind: evt.kind,
id: evt.id,
created_at: evt.created_at,
d: evt.tags.find((t) => t[0] === 'd')?.[1]
}))
// Send IDS response with the manifest
const response: ResponseMessage = {
type: 'IDS',
payload: ['IDS', subId, manifest]
}
await this.sendResponseChunked(reqEvent, session, response)
console.log(`[NRC] Sent IDS response with ${manifest.length} entries`)
}
/**
* Query local IndexedDB for events matching filters
*/
private async queryLocalEvents(filters: Filter[]): Promise<Event[]> {
// Get all events from IndexedDB and filter
const allEvents = await indexedDb.queryEventsForNRC(filters)
// Filter out device-specific events
return allEvents.filter((evt) => !isDeviceSpecificEvent(evt))
}
/**
* Send an encrypted response
*/
private async sendResponse(
reqEvent: Event,
session: NRCSession,
response: ResponseMessage
): Promise<void> {
if (!this.ws || !this.config || !this.listenerPubkey) {
throw new Error('Not connected')
}
// Encrypt the response using signer
const plaintext = JSON.stringify(response)
const encrypted = await this.encrypt(session.clientPubkey, plaintext)
// Build the response event
const unsignedEvent = {
kind: KIND_NRC_RESPONSE,
content: encrypted,
tags: [
['p', reqEvent.pubkey],
['encryption', 'nip44_v2'],
['session', session.id],
['e', reqEvent.id]
],
created_at: Math.floor(Date.now() / 1000)
}
// Sign with our signer
const signedEvent = await this.config.signer.signEvent(unsignedEvent)
// Publish to rendezvous relay
this.ws.send(JSON.stringify(['EVENT', signedEvent]))
}
/**
* Send a response, chunking if necessary for large payloads
*/
private async sendResponseChunked(
reqEvent: Event,
session: NRCSession,
response: ResponseMessage
): Promise<void> {
const plaintext = JSON.stringify(response)
// If small enough, send directly
if (plaintext.length <= NRCListenerService.MAX_CHUNK_SIZE) {
await this.sendResponse(reqEvent, session, response)
return
}
// Need to chunk - convert to base64 for safe transmission
const encoded = btoa(unescape(encodeURIComponent(plaintext)))
const chunks: string[] = []
// Split into chunks
for (let i = 0; i < encoded.length; i += NRCListenerService.MAX_CHUNK_SIZE) {
chunks.push(encoded.slice(i, i + NRCListenerService.MAX_CHUNK_SIZE))
}
const messageId = crypto.randomUUID()
console.log(`[NRC] Chunking large message (${plaintext.length} bytes) into ${chunks.length} chunks`)
// Send each chunk
for (let i = 0; i < chunks.length; i++) {
const chunkResponse: ResponseMessage = {
type: 'CHUNK',
payload: [{
type: 'CHUNK',
messageId,
index: i,
total: chunks.length,
data: chunks[i]
}]
}
await this.sendResponse(reqEvent, session, chunkResponse)
}
}
/**
* Send an error response
*/
private async sendError(
reqEvent: Event,
session: NRCSession,
message: string
): Promise<void> {
const response: ResponseMessage = {
type: 'NOTICE',
payload: ['NOTICE', message]
}
await this.sendResponse(reqEvent, session, response)
}
/**
* Send error response with best-effort encryption
*/
private async sendErrorBestEffort(reqEvent: Event, message: string): Promise<void> {
if (!this.ws || !this.config || !this.listenerPubkey) {
return
}
try {
const response: ResponseMessage = {
type: 'NOTICE',
payload: ['NOTICE', message]
}
const plaintext = JSON.stringify(response)
const encrypted = await this.encrypt(reqEvent.pubkey, plaintext)
const unsignedEvent = {
kind: KIND_NRC_RESPONSE,
content: encrypted,
tags: [
['p', reqEvent.pubkey],
['encryption', 'nip44_v2'],
['e', reqEvent.id]
],
created_at: Math.floor(Date.now() / 1000)
}
const signedEvent = await this.config.signer.signEvent(unsignedEvent)
this.ws.send(JSON.stringify(['EVENT', signedEvent]))
} catch {
// Best effort - ignore errors
}
}
}
// Singleton instance
let instance: NRCListenerService | null = null
export function getNRCListenerService(): NRCListenerService {
if (!instance) {
instance = new NRCListenerService()
}
return instance
}
export default getNRCListenerService()

View File

@@ -0,0 +1,238 @@
import { Filter } from 'nostr-tools'
import { NRCSession, NRCSubscription } from './nrc-types'
// Default session timeout: 30 minutes
const DEFAULT_SESSION_TIMEOUT = 30 * 60 * 1000
// Default max subscriptions per session
const DEFAULT_MAX_SUBSCRIPTIONS = 100
/**
* Generate a unique session ID
*/
function generateSessionId(): string {
return crypto.randomUUID()
}
/**
* Session manager for tracking NRC client sessions
*/
export class NRCSessionManager {
private sessions: Map<string, NRCSession> = new Map()
private sessionTimeout: number
private maxSubscriptions: number
private cleanupInterval: ReturnType<typeof setInterval> | null = null
constructor(
sessionTimeout: number = DEFAULT_SESSION_TIMEOUT,
maxSubscriptions: number = DEFAULT_MAX_SUBSCRIPTIONS
) {
this.sessionTimeout = sessionTimeout
this.maxSubscriptions = maxSubscriptions
}
/**
* Start the cleanup interval for expired sessions
*/
start(): void {
if (this.cleanupInterval) return
// Run cleanup every 5 minutes
this.cleanupInterval = setInterval(() => {
this.cleanupExpiredSessions()
}, 5 * 60 * 1000)
}
/**
* Stop the cleanup interval
*/
stop(): void {
if (this.cleanupInterval) {
clearInterval(this.cleanupInterval)
this.cleanupInterval = null
}
this.sessions.clear()
}
/**
* Get or create a session for a client
*/
getOrCreateSession(
clientPubkey: string,
conversationKey: Uint8Array | undefined,
deviceName?: string
): NRCSession {
// Check if session exists for this client
for (const session of this.sessions.values()) {
if (session.clientPubkey === clientPubkey) {
// Update last activity and return existing session
session.lastActivity = Date.now()
return session
}
}
// Create new session
const session: NRCSession = {
id: generateSessionId(),
clientPubkey,
conversationKey,
deviceName,
createdAt: Date.now(),
lastActivity: Date.now(),
subscriptions: new Map()
}
this.sessions.set(session.id, session)
return session
}
/**
* Get a session by ID
*/
getSession(sessionId: string): NRCSession | undefined {
return this.sessions.get(sessionId)
}
/**
* Get a session by client pubkey
*/
getSessionByClientPubkey(clientPubkey: string): NRCSession | undefined {
for (const session of this.sessions.values()) {
if (session.clientPubkey === clientPubkey) {
return session
}
}
return undefined
}
/**
* Touch a session to update last activity
*/
touchSession(sessionId: string): void {
const session = this.sessions.get(sessionId)
if (session) {
session.lastActivity = Date.now()
}
}
/**
* Add a subscription to a session
*/
addSubscription(
sessionId: string,
subId: string,
filters: Filter[]
): NRCSubscription | null {
const session = this.sessions.get(sessionId)
if (!session) return null
// Check subscription limit
if (session.subscriptions.size >= this.maxSubscriptions) {
return null
}
const subscription: NRCSubscription = {
id: subId,
filters,
createdAt: Date.now(),
eventCount: 0,
eoseSent: false
}
session.subscriptions.set(subId, subscription)
session.lastActivity = Date.now()
return subscription
}
/**
* Get a subscription from a session
*/
getSubscription(sessionId: string, subId: string): NRCSubscription | undefined {
const session = this.sessions.get(sessionId)
return session?.subscriptions.get(subId)
}
/**
* Remove a subscription from a session
*/
removeSubscription(sessionId: string, subId: string): boolean {
const session = this.sessions.get(sessionId)
if (!session) return false
const deleted = session.subscriptions.delete(subId)
if (deleted) {
session.lastActivity = Date.now()
}
return deleted
}
/**
* Mark EOSE sent for a subscription
*/
markEOSE(sessionId: string, subId: string): void {
const subscription = this.getSubscription(sessionId, subId)
if (subscription) {
subscription.eoseSent = true
}
}
/**
* Increment event count for a subscription
*/
incrementEventCount(sessionId: string, subId: string): void {
const subscription = this.getSubscription(sessionId, subId)
if (subscription) {
subscription.eventCount++
}
}
/**
* Remove a session
*/
removeSession(sessionId: string): boolean {
return this.sessions.delete(sessionId)
}
/**
* Get the count of active sessions
*/
getActiveSessionCount(): number {
return this.sessions.size
}
/**
* Get all active sessions
*/
getAllSessions(): NRCSession[] {
return Array.from(this.sessions.values())
}
/**
* Clean up expired sessions
*/
private cleanupExpiredSessions(): void {
const now = Date.now()
const expiredSessionIds: string[] = []
for (const [sessionId, session] of this.sessions) {
if (now - session.lastActivity > this.sessionTimeout) {
expiredSessionIds.push(sessionId)
}
}
for (const sessionId of expiredSessionIds) {
this.sessions.delete(sessionId)
console.log(`[NRC] Cleaned up expired session: ${sessionId}`)
}
}
/**
* Check if a session is expired
*/
isSessionExpired(sessionId: string): boolean {
const session = this.sessions.get(sessionId)
if (!session) return true
return Date.now() - session.lastActivity > this.sessionTimeout
}
}

View File

@@ -0,0 +1,118 @@
import { Filter, Event } from 'nostr-tools'
import { ISigner } from '@/types'
// NRC Event Kinds
export const KIND_NRC_REQUEST = 24891
export const KIND_NRC_RESPONSE = 24892
// Session types
export interface NRCSession {
id: string
clientPubkey: string
conversationKey?: Uint8Array // Optional - only set when using direct key access
deviceName?: string
createdAt: number
lastActivity: number
subscriptions: Map<string, NRCSubscription>
}
export interface NRCSubscription {
id: string
filters: Filter[]
createdAt: number
eventCount: number
eoseSent: boolean
}
// Message types (encrypted content)
export interface RequestMessage {
type: 'REQ' | 'CLOSE' | 'EVENT' | 'COUNT' | 'IDS'
payload: unknown[]
}
export interface ResponseMessage {
type: 'EVENT' | 'EOSE' | 'OK' | 'NOTICE' | 'CLOSED' | 'COUNT' | 'CHUNK' | 'IDS'
payload: unknown[]
}
// ===== Sync Types =====
/**
* Event manifest entry - describes an event we have
* Used by IDS request/response for diffing
*/
export interface EventManifestEntry {
kind: number
id: string
created_at: number
d?: string // For parameterized replaceable events (kinds 30000-39999)
}
// Chunked message for large payloads
export interface ChunkMessage {
type: 'CHUNK'
messageId: string // Unique ID for this chunked message
index: number // 0-based chunk index
total: number // Total number of chunks
data: string // Base64 encoded chunk data
}
// Helper to check if a message is a chunk
export function isChunkMessage(msg: ResponseMessage): msg is ResponseMessage & { payload: [ChunkMessage] } {
return msg.type === 'CHUNK'
}
// Connection management
export interface NRCConnection {
id: string
label: string
secret?: string // For secret-based auth
clientPubkey?: string // Derived from secret
createdAt: number
lastUsed?: number
}
// Listener configuration
export interface NRCListenerConfig {
rendezvousUrl: string
signer: ISigner
authorizedSecrets: Map<string, string> // clientPubkey → deviceName
sessionTimeout?: number // Session inactivity timeout in ms (default 30 min)
maxSubscriptionsPerSession?: number // Max subscriptions per session (default 100)
}
// Authorization result
export interface AuthResult {
conversationKey?: Uint8Array // Optional - only set when using direct key access
deviceName: string
}
// Parsed connection URI
export interface ParsedConnectionURI {
relayPubkey: string // Hex pubkey of the listening relay/client
rendezvousUrl: string // URL of the rendezvous relay
// For secret-based auth
secret?: string // 32-byte hex secret
clientPubkey?: string // Derived pubkey from secret
clientPrivkey?: Uint8Array // Derived private key from secret
// Optional
deviceName?: string
}
// Listener state for React context
export interface NRCListenerState {
isEnabled: boolean
isListening: boolean
connections: NRCConnection[]
activeSessions: number
rendezvousUrl: string
}
// Event with simplified typing for storage queries
export type StoredEvent = Event
// Device-specific event check
export function isDeviceSpecificEvent(event: Event): boolean {
const dTag = event.tags.find((t) => t[0] === 'd')?.[1]
return dTag?.startsWith('device:') ?? false
}

147
src/services/nrc/nrc-uri.ts Normal file
View File

@@ -0,0 +1,147 @@
import * as utils from '@noble/curves/abstract/utils'
import { getPublicKey } from 'nostr-tools'
import * as nip44 from 'nostr-tools/nip44'
import { ParsedConnectionURI } from './nrc-types'
/**
* Generate a random 32-byte secret as hex string
*/
export function generateSecret(): string {
const bytes = new Uint8Array(32)
crypto.getRandomValues(bytes)
return utils.bytesToHex(bytes)
}
/**
* Derive a keypair from a 32-byte secret
* Returns the private key bytes and public key hex
*/
export function deriveKeypairFromSecret(secretHex: string): {
privkey: Uint8Array
pubkey: string
} {
const privkey = utils.hexToBytes(secretHex)
const pubkey = getPublicKey(privkey)
return { privkey, pubkey }
}
/**
* Derive conversation key for NIP-44 encryption
*/
export function deriveConversationKey(
ourPrivkey: Uint8Array,
theirPubkey: string
): Uint8Array {
return nip44.v2.utils.getConversationKey(ourPrivkey, theirPubkey)
}
/**
* Generate a secret-based NRC connection URI
*
* @param relayPubkey - The public key of the listening client/relay
* @param rendezvousUrl - The URL of the rendezvous relay
* @param secret - Optional 32-byte hex secret (generated if not provided)
* @param deviceName - Optional device name for identification
* @returns The connection URI and the secret used
*/
export function generateConnectionURI(
relayPubkey: string,
rendezvousUrl: string,
secret?: string,
deviceName?: string
): { uri: string; secret: string; clientPubkey: string } {
const secretHex = secret || generateSecret()
const { pubkey: clientPubkey } = deriveKeypairFromSecret(secretHex)
// Build URI
const params = new URLSearchParams()
params.set('relay', rendezvousUrl)
params.set('secret', secretHex)
if (deviceName) {
params.set('name', deviceName)
}
const uri = `nostr+relayconnect://${relayPubkey}?${params.toString()}`
return { uri, secret: secretHex, clientPubkey }
}
/**
* Parse an NRC connection URI
*
* @param uri - The nostr+relayconnect:// URI to parse
* @returns Parsed connection parameters
* @throws Error if URI is invalid
*/
export function parseConnectionURI(uri: string): ParsedConnectionURI {
// Parse as URL
let url: URL
try {
url = new URL(uri)
} catch {
throw new Error('Invalid URI format')
}
// Validate scheme
if (url.protocol !== 'nostr+relayconnect:') {
throw new Error('Invalid URI scheme, expected nostr+relayconnect://')
}
// Extract relay pubkey from host (should be 64 hex chars)
const relayPubkey = url.hostname
if (!/^[0-9a-fA-F]{64}$/.test(relayPubkey)) {
throw new Error('Invalid relay pubkey in URI')
}
// Extract rendezvous relay URL
const rendezvousUrl = url.searchParams.get('relay')
if (!rendezvousUrl) {
throw new Error('Missing relay parameter in URI')
}
// Validate rendezvous URL
try {
new URL(rendezvousUrl)
} catch {
throw new Error('Invalid rendezvous relay URL')
}
// Extract device name (optional)
const deviceName = url.searchParams.get('name') || undefined
// Secret-based auth
const secret = url.searchParams.get('secret')
if (!secret) {
throw new Error('Missing secret parameter in URI')
}
// Validate secret format (64 hex chars = 32 bytes)
if (!/^[0-9a-fA-F]{64}$/.test(secret)) {
throw new Error('Invalid secret format, expected 64 hex characters')
}
// Derive keypair from secret
const { privkey, pubkey } = deriveKeypairFromSecret(secret)
return {
relayPubkey,
rendezvousUrl,
secret,
clientPubkey: pubkey,
clientPrivkey: privkey,
deviceName
}
}
/**
* Validate a connection URI without fully parsing it
* Returns true if the URI appears valid, false otherwise
*/
export function isValidConnectionURI(uri: string): boolean {
try {
parseConnectionURI(uri)
return true
} catch {
return false
}
}

View File

@@ -123,7 +123,6 @@ export type TAccount = {
bunkerPubkey?: string
bunkerRelays?: string[]
bunkerSecret?: string
bunkerCatToken?: string
}
export type TAccountPointer = Pick<TAccount, 'pubkey' | 'signerType'>
@@ -236,6 +235,7 @@ export type TSyncSettings = {
quickReactionEmoji?: string | TEmoji
noteListMode?: TNoteListMode
preferNip44?: boolean
nrcOnlyConfigSync?: boolean
}
// DM types