'use client' // Settings → CardDAV: connect external CardDAV address books (any RFC 6352 // service). Each server address book materializes as its own Collection // whose members are bookmarks — one per contact, carrying the card's DAV // .vcf URL — refreshed by the background engine and on demand via Sync. // House disciplines, identical to the WebDAV/CalDAV siblings: passwords are // write-only (never prefilled; the mask round-trips unchanged), every // mutating PATCH carries the row version (409 reloads), and plan or dial // failures surface the server's message — the UI never guesses. When the // deployment serves NEXTCLOUD_URL (the Core shape), the list arrives with a // ready-made suggestion; the prefill composes the address-book home with // the username so the URL shown is the URL saved. import { useCallback, useEffect, useState } from 'react' import { useSession } from 'next-auth/react' import { Button } from '@/components/ui/button' import { Input } from '@/components/ui/input' import { Badge } from '@/components/ui/badge' import { Switch } from '@/components/ui/switch' import { Dialog, DialogContent, DialogHeader, DialogTitle } from '@/components/ui/dialog' import { AlertTriangle, BookUser, Cloud, FlaskConical, Loader2, Plus, RefreshCw, Trash2 } from 'lucide-react' import { toast } from 'sonner' import { SafeDate } from '@/components/safe-format' const KEY_MASK = '••••••••' type AddressbookRef = { href: string; name: string; collectionId: string | null } type CardDavConnection = { id: string; name: string; url: string; username: string secret: string; enabled: boolean; addressbooks: AddressbookRef[] lastSyncedAt: string | null; lastError: string | null; version: number } type Suggestion = { kind: string; name: string; url: string } type TestResult = { ok: boolean; addressbooks?: string[]; error?: string } type SyncResult = { ok: boolean; books?: number; cards?: number; created?: number; reused?: number; updated?: number; kept?: number; removed?: number; truncated?: boolean; error?: string } type FormState = { id: string | null; version: number name: string; url: string; username: string password: string; hasStoredSecret: boolean } const emptyForm: FormState = { id: null, version: 0, name: '', url: '', username: '', password: '', hasStoredSecret: false } async function api(path: string, init?: RequestInit): Promise { return fetch(path, { headers: { 'Content-Type': 'application/json' }, cache: 'no-store', ...init }) } export function CardDavSettings() { const { data: session } = useSession() const [connections, setConnections] = useState([]) const [suggestions, setSuggestions] = useState([]) const [allowed, setAllowed] = useState(true) const [loading, setLoading] = useState(true) const [form, setForm] = useState(null) const [saving, setSaving] = useState(false) const [testing, setTesting] = useState(null) const [syncing, setSyncing] = useState(null) const [results, setResults] = useState>({}) const reload = useCallback(() => api('/api/carddav/connections') .then(r => r.json()) .then(data => { setConnections(Array.isArray(data?.connections) ? data.connections : []) setSuggestions(Array.isArray(data?.suggestions) ? data.suggestions : []) setAllowed(data?.allowed === true) }) .catch(() => toast.error('Could not load CardDAV connections')) .finally(() => setLoading(false)), []) useEffect(() => { reload() }, [reload]) const openCreate = () => setForm({ ...emptyForm }) const openSuggestion = (s: Suggestion) => { const email = session?.user?.email ?? '' const username = email ? email.split('@')[0] : '' // Compose visibly: the suggestion hands us the address-book home // prefix, so the URL in the form is already the URL that gets saved. setForm({ ...emptyForm, name: s.name, username, url: username ? s.url + username + '/' : s.url }) } const openEdit = (c: CardDavConnection) => setForm({ id: c.id, version: c.version, name: c.name, url: c.url, username: c.username, password: '', hasStoredSecret: c.secret === KEY_MASK, }) const save = async () => { if (!form) return const body: Record = { name: form.name.trim(), url: form.url.trim(), username: form.username.trim(), } // Write-only password: send only what the user typed; the mask (or an // empty field) tells the server to keep the stored value. if (form.password) body.password = form.password setSaving(true) try { const res = form.id ? await api(`/api/carddav/connections/${form.id}`, { method: 'PATCH', body: JSON.stringify({ ...body, version: form.version }) }) : await api('/api/carddav/connections', { method: 'POST', body: JSON.stringify(body) }) const data = await res.json().catch(() => null) if (res.status === 409) { toast.error('Connection changed elsewhere — reloaded') await reload() setForm(null) return } if (!res.ok) { toast.error(data?.error ?? 'Could not save the connection'); return } toast.success(form.id ? 'Connection updated' : 'Address book connected — sync it to materialize the collections') setForm(null) await reload() } catch { toast.error('Could not save the connection') } finally { setSaving(false) } } const test = async (c: CardDavConnection) => { setTesting(c.id) try { const res = await api(`/api/carddav/connections/${c.id}/test`, { method: 'POST', body: '{}' }) const data = await res.json().catch(() => null) setResults(prev => ({ ...prev, [c.id]: { ...prev[c.id], test: (data as TestResult) ?? { ok: false, error: 'Network error' } } })) if (data?.ok) toast.success(`${data.addressbooks?.length ?? 0} address book${data.addressbooks?.length === 1 ? '' : 's'} found`) } catch { setResults(prev => ({ ...prev, [c.id]: { ...prev[c.id], test: { ok: false, error: 'Network error' } } })) } finally { setTesting(null) } } const sync = async (c: CardDavConnection) => { setSyncing(c.id) try { const res = await api(`/api/carddav/connections/${c.id}/sync`, { method: 'POST', body: '{}' }) const data = await res.json().catch(() => null) setResults(prev => ({ ...prev, [c.id]: { ...prev[c.id], sync: (data as SyncResult) ?? { ok: false, error: 'Network error' } } })) if (data?.ok) toast.success(`Synced ${data.cards} contact${data.cards === 1 ? '' : 's'} from ${data.books} address book${data.books === 1 ? '' : 's'}`) await reload() } catch { setResults(prev => ({ ...prev, [c.id]: { ...prev[c.id], sync: { ok: false, error: 'Network error' } } })) } finally { setSyncing(null) } } const toggle = async (c: CardDavConnection) => { const res = await api(`/api/carddav/connections/${c.id}`, { method: 'PATCH', body: JSON.stringify({ enabled: !c.enabled, version: c.version }), }) if (res.status === 409) { toast.error('Connection changed elsewhere — reloaded'); await reload(); return } if (!res.ok) { toast.error((await res.json().catch(() => null))?.error ?? 'Could not update'); return } await reload() } const remove = async (c: CardDavConnection) => { const res = await api(`/api/carddav/connections/${c.id}`, { method: 'DELETE' }) if (res.ok) { toast.success(`Removed ${c.name} — the address book collections and their bookmarks stay`); await reload() } else toast.error((await res.json().catch(() => null))?.error ?? 'Could not remove') } if (loading) { return (
Loading CardDAV connections…
) } return (

CardDAV address books

Connect an address book from any CardDAV service. Each book becomes a Collection, one bookmark per contact, re-checked in the background every 30 minutes. Passwords are encrypted at rest and never shown again. (This is separate from the Contacts page, which feeds contact-linking.)

{allowed && }
{!allowed && (

CardDAV address books are not available on your current plan. Existing connections stay but no longer sync.

)} {suggestions.length > 0 && allowed && (
{suggestions.map(s => (

{s.name} detected on this server

{s.url}

))}
)} {connections.length === 0 ? (

No CardDAV address books connected.

) : (
    {connections.map(c => { const r = results[c.id] const failure = r?.sync && !r.sync.ok ? r.sync.error : r?.test && !r.test.ok ? r.test.error : null return (
  • toggle(c)} aria-label={`Enable ${c.name}`} /> {c.name} {Array.isArray(c.addressbooks) && c.addressbooks.length > 0 && {c.addressbooks.length} books}

    {c.username}@{c.url}

    {Array.isArray(c.addressbooks) && c.addressbooks.length > 0 && (

    Books: {c.addressbooks.map(k => k.name).join(', ')}

    )}

    {c.lastSyncedAt ? <>Last synced : 'Not synced yet — use Sync to materialize the collections'}

    {!failure && c.lastError && (

    {c.lastError}

    )} {failure &&

    {failure}

    } {r?.sync?.ok && (

    {r.sync.cards} contacts across {r.sync.books ?? 0} books: {r.sync.created ?? 0} created, {r.sync.reused ?? 0} reused,{" "} {r.sync.updated ?? 0} changed, {r.sync.removed ?? 0} detached {r.sync.truncated && ' — a listing was capped; nothing was treated as deleted'}

    )} {r?.test?.ok && (

    Found: {r.test.addressbooks?.join(', ') || 'no address books'}

    )}
  • ) })}
)} { if (!open) setForm(null) }}> {form?.id ? 'Edit CardDAV connection' : 'Connect a CardDAV address book'} {form && (
setForm({ ...form, name: e.target.value })} placeholder="e.g. House contacts" maxLength={100} />
setForm({ ...form, url: e.target.value })} placeholder="https://cloud.example.com/remote.php/dav/addressbooks/users/username/contacts" />

One address book or a home holding several, on an https endpoint (CardDAV credentials never travel to other ports or plaintext). Discovery is network-guarded and never follows redirects.

setForm({ ...form, username: e.target.value })} placeholder="erwin" maxLength={200} />
setForm({ ...form, password: e.target.value })} placeholder={form.hasStoredSecret ? `${KEY_MASK} (leave blank to keep)` : 'Account or app password'} maxLength={2000} />
{form.hasStoredSecret &&

Stored credentials are never shown; blank keeps the current one.

}

Tip: services that use two-factor login usually need an app password here (in Nextcloud: Settings → Security → Devices).

)}
) }