Files
superbrain/web/components/nextcloud-settings.tsx
T
Andrew S Erwin 084a1167da Unified Nextcloud connect: one credential connects files, calendars and contacts
POST /api/nextcloud/connect composes the three per-user DAV roots
server-side, verifies the credential against each protocol in parallel
(netguard-pinned, sharing the siblings' /test budgets) BEFORE storing
anything, and creates one ordinary sibling connection per protocol that
passes. Orchestration, not a fourth connector: every sibling plan gate,
validation (incl. CardDAV https/443), cap and projection applies; partial
success is a 200 with per-connector created|exists|gated|error results;
repeat calls are idempotent by composed URL. GET /api/nextcloud/status
serves the new Settings -> Nextcloud tab (origin hint + allowed flags +
masked connections); the UI fires the existing /sync surfaces right after
connect so collections materialize immediately. Contacts sync untouched;
no schema change.

Tests: unified Nextcloud fake (sibling fakes re-rooted to Nextcloud paths
on one origin) covering happy path, idempotency, wrong-password-stores-
nothing, owner scoping, partial plan gate + restore; browser regression
for the full connect/sync/idempotent/Manage flow.
2026-11-23 13:07:39 -06:00

245 lines
12 KiB
TypeScript

'use client'
// Settings → Nextcloud: ONE credential entry connects files (WebDAV),
// calendars (CalDAV) and contacts (CardDAV) at once. The server composes
// the per-user DAV roots, verifies the credential against each protocol
// and stores ordinary sibling connections — this tab orchestrates, then
// fires the existing /sync surfaces so collections materialize immediately.
// House disciplines: the password is write-only (never prefilled, cleared
// after submit), plan gates and failures surface the server's message
// verbatim (the UI never guesses entitlements), and partial success is a
// first-class outcome — a carddav-only plan still connects contacts.
// Ongoing management stays in the per-protocol tabs; the separate Contacts
// sync (Contact rows) is a different feature and is untouched.
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 { AlertTriangle, BookUser, CalendarDays, Cloud, FolderSync, Loader2, RefreshCw } from 'lucide-react'
import { toast } from 'sonner'
import { SafeDate } from '@/components/safe-format'
type Connection = {
id: string; name: string; url: string; username: string
enabled: boolean; lastSyncedAt: string | null; lastError: string | null
}
type Part = { allowed: boolean; connections: Connection[] }
type Status = { origin: string; files: Part; calendars: Part; contacts: Part }
type ConnectResult = { status: 'created' | 'exists' | 'gated' | 'error'; id?: string; name?: string; url?: string; error?: string }
type SyncResult = { ok: boolean; files?: number; calendars?: number; events?: number; books?: number; cards?: number; created?: number; error?: string }
const CONNECTORS = [
{ key: 'files' as const, label: 'Files', proto: 'webdav', tab: 'webdav', icon: FolderSync, hint: 'One Collection, one bookmark per file.' },
{ key: 'calendars' as const, label: 'Calendars', proto: 'caldav', tab: 'caldav', icon: CalendarDays, hint: 'One Collection per server calendar, one bookmark per event.' },
{ key: 'contacts' as const, label: 'Contacts', proto: 'carddav', tab: 'carddav', icon: BookUser, hint: 'One Collection per address book, one bookmark per contact.' },
]
async function api(path: string, init?: RequestInit): Promise<Response> {
return fetch(path, { headers: { 'Content-Type': 'application/json' }, cache: 'no-store', ...init })
}
export function NextcloudSettings({ onManage }: { onManage?: (tab: string) => void }) {
const { data: session } = useSession()
const [status, setStatus] = useState<Status | null>(null)
const [loading, setLoading] = useState(true)
const [url, setUrl] = useState('')
const [username, setUsername] = useState('')
const [password, setPassword] = useState('')
const [connecting, setConnecting] = useState(false)
const [results, setResults] = useState<Record<string, ConnectResult> | null>(null)
const [syncs, setSyncs] = useState<Record<string, SyncResult | 'pending'>>({})
const emailLocal = (session?.user?.email ?? '').split('@')[0]
const reload = useCallback(() =>
api('/api/nextcloud/status')
.then(r => r.json())
.then((data: Status) => {
setStatus(data)
// Prefill the deployment's origin hint (Core) and the viewer's email
// local-part once; the person can still edit both fields.
setUrl(prev => prev || data?.origin || '')
setUsername(prev => prev || emailLocal)
})
.catch(() => toast.error('Could not load Nextcloud status'))
.finally(() => setLoading(false)), [emailLocal])
useEffect(() => { reload() }, [reload])
const connect = async () => {
setConnecting(true)
setResults(null)
setSyncs({})
try {
const res = await api('/api/nextcloud/connect', {
method: 'POST',
body: JSON.stringify({ url: url.trim(), username: username.trim(), password }),
})
const data = await res.json().catch(() => null)
if (!res.ok) { toast.error(data?.error ?? 'Could not connect'); return }
const results = (data?.results ?? {}) as Record<string, ConnectResult>
setResults(results)
setPassword('') // write-only: never keep the plaintext around
const created = CONNECTORS.filter(c => results[c.key]?.status === 'created')
if (created.length === 0) {
toast.success('Nextcloud account processed')
} else {
toast.success(`${created.length} connection${created.length === 1 ? '' : 's'} created — syncing`)
}
// Materialize through the EXISTING per-protocol sync surfaces, in
// parallel — their limiters, budgets and timeouts stay authoritative.
setSyncs(Object.fromEntries(created.map(c => [c.key, 'pending' as const])))
await Promise.allSettled(created.map(async c => {
const id = results[c.key].id
try {
const sr = await api(`/api/${c.proto}/connections/${id}/sync`, { method: 'POST', body: '{}' })
const sd = await sr.json().catch(() => null)
setSyncs(prev => ({ ...prev, [c.key]: (sd as SyncResult) ?? { ok: false, error: 'Network error' } }))
} catch {
setSyncs(prev => ({ ...prev, [c.key]: { ok: false, error: 'Network error' } }))
}
}))
await reload()
} catch { toast.error('Could not connect') }
finally { setConnecting(false) }
}
if (loading || !status) {
return (
<div className="rounded-lg border p-4 flex items-center gap-2 text-sm text-muted-foreground">
<Loader2 className="h-4 w-4 animate-spin" /> Loading Nextcloud status…
</div>
)
}
const allGated = CONNECTORS.every(c => !status[c.key].allowed)
return (
<div className="rounded-lg border p-4 space-y-4">
<div>
<h3 className="font-medium flex items-center gap-2"><Cloud className="h-4 w-4" /> Nextcloud</h3>
<p className="text-sm text-muted-foreground mt-1">
Connect your Nextcloud account once — files, calendars and contacts become Collections
of bookmarks, re-checked in the background every 30 minutes. The password is encrypted
at rest and never shown again.
</p>
</div>
{allGated && (
<div className="flex items-start gap-2 rounded-md border border-amber-500/40 bg-amber-500/10 p-3 text-xs">
<AlertTriangle className="h-4 w-4 shrink-0 text-amber-600 dark:text-amber-400" />
<p>Nextcloud connections are not available on your current plan.</p>
</div>
)}
{!allGated && (
<div className="space-y-3 rounded-md border border-dashed p-3">
<div>
<label className="text-xs font-medium">Server URL</label>
<Input value={url} onChange={e => setUrl(e.target.value)} placeholder="https://cloud.example.com" maxLength={2048} />
<p className="mt-1 text-xs text-muted-foreground">
Your Nextcloud origin{status.origin ? ' — suggested by this deployment' : ''}. A pasted DAV link works too.
</p>
</div>
<div className="grid grid-cols-2 gap-3">
<div>
<label className="text-xs font-medium">Username</label>
<Input value={username} onChange={e => setUsername(e.target.value)} placeholder="erwin" maxLength={200} />
</div>
<div>
<label className="text-xs font-medium">App password</label>
<Input type="password" value={password} onChange={e => setPassword(e.target.value)} placeholder="Account or app password" maxLength={2000} />
</div>
</div>
<p className="text-xs text-muted-foreground">
Tip: with two-factor login, create an app password in Nextcloud (Settings → Security → Devices).
Each part connects only if your plan includes it.
</p>
<div className="flex justify-end">
<Button onClick={connect} loading={connecting} disabled={!url.trim() || !username.trim() || !password}>
<RefreshCw className="h-4 w-4 mr-1" /> Connect files, calendars &amp; contacts
</Button>
</div>
</div>
)}
{results && (
<ul className="divide-y rounded-md border">
{CONNECTORS.map(c => {
const r = results[c.key]
if (!r) return null
const sync = syncs[c.key]
return (
<li key={c.key} className="p-3 space-y-1">
<div className="flex items-center gap-2 text-sm font-medium">
<c.icon className="h-4 w-4 text-muted-foreground" /> {c.label}
{r.status === 'created' && <Badge variant="outline" className="text-[10px]">connected</Badge>}
{r.status === 'exists' && <Badge variant="outline" className="text-[10px]">already connected</Badge>}
{r.status === 'gated' && <Badge variant="outline" className="text-[10px] text-amber-600 dark:text-amber-400">plan</Badge>}
{r.status === 'error' && <Badge variant="outline" className="text-[10px] text-destructive">failed</Badge>}
{onManage && (r.status === 'created' || r.status === 'exists') && (
<Button size="sm" variant="ghost" className="ml-auto" onClick={() => onManage(c.tab)}>Manage</Button>
)}
</div>
{r.status === 'gated' && <p className="text-xs text-amber-600 dark:text-amber-400">{r.error}</p>}
{r.status === 'error' && <p className="text-xs text-destructive">{r.error}</p>}
{r.status === 'created' && sync === 'pending' && (
<p className="text-xs text-muted-foreground flex items-center gap-1"><Loader2 className="h-3 w-3 animate-spin" /> Syncing…</p>
)}
{r.status === 'created' && sync && sync !== 'pending' && (
sync.ok
? <p className="text-xs text-muted-foreground">{syncSummary(c.key, sync)}</p>
: <p className="text-xs text-destructive">{sync.error ?? 'Sync failed'} — retry from the {c.label} tab.</p>
)}
{r.status === 'exists' && <p className="text-xs text-muted-foreground">Kept the existing connection; sync it from the {c.label} tab.</p>}
</li>
)
})}
</ul>
)}
<div className="space-y-2">
{CONNECTORS.map(c => {
const part = status[c.key]
return (
<div key={c.key} className="rounded-md border p-3 space-y-2">
<div className="flex items-center gap-2">
<c.icon className="h-4 w-4 text-muted-foreground" />
<span className="text-sm font-medium">{c.label}</span>
{!part.allowed && <Badge variant="outline" className="text-[10px] text-amber-600 dark:text-amber-400">not on your plan</Badge>}
{onManage && part.connections.length > 0 && (
<Button size="sm" variant="ghost" className="ml-auto" onClick={() => onManage(c.tab)}>Manage</Button>
)}
</div>
<p className="text-xs text-muted-foreground">{c.hint}</p>
{part.connections.length === 0
? <p className="text-xs text-muted-foreground">Not connected yet.</p>
: (
<ul className="space-y-1">
{part.connections.map(conn => (
<li key={conn.id} className="text-xs">
<span className="font-medium">{conn.name}</span>
<span className="text-muted-foreground">
{' — '}{conn.lastSyncedAt ? <>last synced <SafeDate date={conn.lastSyncedAt} localize /></> : 'not synced yet'}
</span>
{conn.lastError && <p className="text-destructive">{conn.lastError}</p>}
</li>
))}
</ul>
)}
</div>
)
})}
</div>
</div>
)
}
function syncSummary(key: 'files' | 'calendars' | 'contacts', s: SyncResult): string {
const created = s.created ? ` (${s.created} new)` : ''
if (key === 'files') return `${s.files ?? 0} files${created}`
if (key === 'calendars') return `${s.events ?? 0} events across ${s.calendars ?? 0} calendars${created}`
return `${s.cards ?? 0} contacts in ${s.books ?? 0} address books${created}`
}