release gate / check (push) Failing after 6m56s
Transactional mail now goes out as the Superbrain HTML design
(internal/mailer/template.html, embedded verbatim) with a plain-text
alternative: multipart/alternative (plain first per RFC 2046), random
boundary, CRLF normalization and SMTP dot-stuffing. Render() fills the
{{placeholders}} with HTML-escaped values and removes optional sections
(CTA + fallback link, note block, footer links, address) when empty;
anchor drift fails the unit tests and degrades to plain text at send
time, never blocking delivery. Password reset gets the headline,
first-name greeting, "Choose a new password" button (Outlook VML
fallback) and expiry/single-use note; notification and agent emails
render title-as-headline with body paragraphs.
The template's footer links are now real pages:
- /help: public help center (10 topic sections + FAQ accordion), linked
from the login page.
- /unsubscribe?token=...: public confirmation page; the HMAC-signed user
id (notify.UnsubscribeToken, domain-separated, stable, no stored row)
IS the credential. POST /api/notifications/unsubscribe accepts the
RFC 8058 one-click shape (token in query, form body ignored) and the
browser JSON shape; it disables the user's enabled email channels and
pauses enabled agent email tasks addressed to their own email
(idempotent, re-enableable, per-client rate limited, audit logged).
- Email preferences deep-links to /settings?tab=notifications; Settings
now honors ?tab=<section> (unknown values fall back to profile).
notify.FooterLinks is the single eligibility point: preferences + help
whenever NEXTAUTH_URL is set; unsubscribe ONLY when the recipient is the
owner's own account email — third-party channel addresses and agent
recipients never receive a link that changes someone else's settings,
and transactional mail (password reset) never carries unsubscribe.
Owner-addressed mail also carries List-Unsubscribe +
List-Unsubscribe-Post headers.
Verified: Go build/vet/unit green; new TestUnsubscribeFlow integration
test pins footer + headers, blast radius (slack channel and third-party
task survive), one-click + JSON paths, idempotence, tampered tokens and
the third-party/transactional exclusions; notifications, phase-2,
password-reset and agent suites green; web lint/SSR-lint/build 0 errors;
full browser regressions pass; live smoke of /help, /unsubscribe states,
the settings deep-link auth gate and bad-token 400 through the proxy.
310 lines
16 KiB
TypeScript
310 lines
16 KiB
TypeScript
'use client'
|
|
|
|
import { useState, useEffect, useCallback, Fragment } from 'react'
|
|
import { useSession } from 'next-auth/react'
|
|
import { useSearchParams } from 'next/navigation'
|
|
import { Button } from '@/components/ui/button'
|
|
import { Input } from '@/components/ui/input'
|
|
import { Tabs, TabsList, TabsTrigger, TabsContent } from '@/components/ui/tabs'
|
|
import { User, Mail, Server, Cloud, Shield, Bell, Sparkles, Bot, KeyRound, PlugZap, FolderSync, CalendarDays, BookUser, ArrowLeft, Check, X, AlertTriangle } from 'lucide-react'
|
|
import { toast } from 'sonner'
|
|
import { invalidateReference } from '@/lib/reference-data'
|
|
import { NotificationsSettings } from '@/components/notifications-settings'
|
|
import { AutomationsSettings } from '@/components/automations-settings'
|
|
import { AiSettings } from '@/components/ai-settings'
|
|
import { ApiKeysSettings } from '@/components/api-keys-settings'
|
|
import { McpSettings } from '@/components/mcp-settings'
|
|
import { WebdavSettings } from '@/components/webdav-settings'
|
|
import { CalDavSettings } from '@/components/caldav-settings'
|
|
import { CardDavSettings } from '@/components/carddav-settings'
|
|
import type { OidcStatus } from '@/lib/oidc-config'
|
|
import { cn } from '@/lib/utils'
|
|
import { useMediaQuery } from '@/lib/use-media-query'
|
|
|
|
|
|
// Settings are grouped by purpose, not a flat strip: account, the external
|
|
// services that feed your data, the assistant/automation surface, and
|
|
// machine/developer access. Each item keeps its Radix tab value so deep
|
|
// links and the browser suites' role="tab" locators are unchanged.
|
|
const NAV_GROUPS = [
|
|
{ label: 'Account', items: [
|
|
{ value: 'profile', label: 'Profile', icon: User },
|
|
{ value: 'oidc', label: 'Sign-in', icon: Shield },
|
|
] },
|
|
{ label: 'Connections', items: [
|
|
{ value: 'webdav', label: 'WebDAV', icon: FolderSync },
|
|
{ value: 'caldav', label: 'CalDAV', icon: CalendarDays },
|
|
{ value: 'carddav', label: 'CardDAV', icon: BookUser },
|
|
{ value: 'nextcloud', label: 'Contacts sync', icon: Cloud },
|
|
{ value: 'imap', label: 'IMAP', icon: Mail },
|
|
] },
|
|
{ label: 'AI & Automation', items: [
|
|
{ value: 'ai', label: 'AI', icon: Bot },
|
|
{ value: 'mcp', label: 'MCP', icon: PlugZap },
|
|
{ value: 'automations', label: 'Automations', icon: Sparkles },
|
|
{ value: 'notifications', label: 'Notifications', icon: Bell },
|
|
] },
|
|
{ label: 'Developer', items: [
|
|
{ value: 'api-keys', label: 'API Keys', icon: KeyRound },
|
|
] },
|
|
]
|
|
|
|
export function SettingsClient({ oidc, callbackUrl }: { oidc: OidcStatus; callbackUrl: string }) {
|
|
const { data: session } = useSession()
|
|
// ?tab=<value> deep links (email footer "Email preferences" lands on
|
|
// notifications). Unknown values fall back to profile; the Radix tab
|
|
// values stay the canonical section ids.
|
|
const requestedTab = useSearchParams().get('tab') ?? ''
|
|
const initialSection = NAV_GROUPS.some(g => g.items.some(i => i.value === requestedTab))
|
|
? requestedTab
|
|
: 'profile'
|
|
const [imapConfig, setImapConfig] = useState({ host: '', port: 993, tls: true, username: '', password: '', folder: 'INBOX' })
|
|
const [ncConfig, setNcConfig] = useState({ nextcloudUrl: '', cardDavPath: '', username: '', password: '' })
|
|
const [savingImap, setSavingImap] = useState(false)
|
|
const [testingImap, setTestingImap] = useState(false)
|
|
const [syncingContacts, setSyncingContacts] = useState(false)
|
|
const [section, setSection] = useState(initialSection)
|
|
// Below md the grouped nav becomes a list -> detail flow (same
|
|
// master-detail pattern as collections/tags/contacts); at md+ the
|
|
// nav and the selected panel sit side by side. A deep link opens the
|
|
// detail pane directly on narrow screens.
|
|
const isNarrow = useMediaQuery('(max-width: 767px)')
|
|
const [mobileDetail, setMobileDetail] = useState(initialSection !== 'profile')
|
|
|
|
useEffect(() => {
|
|
fetch('/api/settings/imap').then(r => r.json()).then(data => {
|
|
if (data) setImapConfig(prev => ({ ...prev, host: data.host ?? '', port: data.port ?? 993, tls: data.tls ?? true, username: data.username ?? '', folder: data.folder ?? 'INBOX' }))
|
|
}).catch(() => {})
|
|
}, [])
|
|
|
|
// Every action clears its spinner in finally and tolerates non-JSON or
|
|
// failed network responses, so no state can stick after an outage.
|
|
const saveImap = async () => {
|
|
setSavingImap(true)
|
|
try {
|
|
const res = await fetch('/api/settings/imap', {
|
|
method: 'POST',
|
|
headers: { 'Content-Type': 'application/json' },
|
|
// tls is forced on: legacy stored configs with tls=false migrate to
|
|
// verified TLS on the next save (review NET-02).
|
|
body: JSON.stringify({ ...imapConfig, tls: true }),
|
|
})
|
|
if (res.ok) toast.success('IMAP settings saved')
|
|
else toast.error((await res.json().catch(() => null))?.error ?? 'Failed to save')
|
|
} catch { toast.error('Failed to save') }
|
|
finally { setSavingImap(false) }
|
|
}
|
|
|
|
const testImap = async () => {
|
|
setTestingImap(true)
|
|
try {
|
|
const res = await fetch('/api/imap/test', {
|
|
method: 'POST',
|
|
headers: { 'Content-Type': 'application/json' },
|
|
body: JSON.stringify({ ...imapConfig, tls: true }),
|
|
})
|
|
const data = await res.json().catch(() => null)
|
|
if (res.ok && data?.ok) toast.success('Connection successful!')
|
|
else toast.error(data?.error ?? 'Connection failed')
|
|
} catch { toast.error('Connection failed') }
|
|
finally { setTestingImap(false) }
|
|
}
|
|
|
|
const syncContacts = async () => {
|
|
if (!ncConfig.nextcloudUrl || !ncConfig.username || !ncConfig.password) {
|
|
toast.error('Fill in Nextcloud URL, username, and password')
|
|
return
|
|
}
|
|
setSyncingContacts(true)
|
|
try {
|
|
const res = await fetch('/api/contacts/sync', {
|
|
method: 'POST',
|
|
headers: { 'Content-Type': 'application/json' },
|
|
body: JSON.stringify(ncConfig),
|
|
})
|
|
const data = await res.json().catch(() => null)
|
|
if (res.ok && data?.synced !== undefined) {
|
|
// Review CR-07: the sync mirrors the address book — remotely deleted
|
|
// contacts are removed too (scoped to this source, never from partial
|
|
// responses). Surface both counts so the policy is visible.
|
|
const removed = typeof data.removed === 'number' && data.removed > 0 ? `, removed ${data.removed} deleted on the server` : ''
|
|
toast.success(`Synced ${data.synced} contacts${removed}`)
|
|
invalidateReference('contacts')
|
|
}
|
|
else toast.error(data?.error ?? 'Sync failed')
|
|
} catch { toast.error('Sync failed') }
|
|
finally { setSyncingContacts(false) }
|
|
}
|
|
|
|
return (
|
|
<div className="max-w-5xl space-y-6">
|
|
<div>
|
|
<h1 className="font-display text-2xl font-bold tracking-tight">Settings</h1>
|
|
<p className="text-sm text-muted-foreground mt-1">Configure your integrations and preferences</p>
|
|
</div>
|
|
|
|
<Tabs
|
|
value={section}
|
|
onValueChange={(v) => { setSection(v); if (isNarrow) setMobileDetail(true) }}
|
|
orientation="vertical"
|
|
className="w-full"
|
|
>
|
|
<div className="flex flex-col gap-6 md:flex-row md:gap-8">
|
|
<TabsList
|
|
aria-label="Settings sections"
|
|
className={cn(
|
|
'flex h-auto w-full flex-col items-stretch justify-start gap-0.5 rounded-lg border bg-card/50 p-2 md:w-56 md:shrink-0',
|
|
isNarrow && mobileDetail && 'hidden'
|
|
)}
|
|
>
|
|
{NAV_GROUPS.map((g) => (
|
|
<Fragment key={g.label}>
|
|
<div className="px-3 pb-1 pt-3 text-[11px] font-semibold uppercase tracking-wider text-muted-foreground first:pt-1">{g.label}</div>
|
|
{g.items.map((it) => (
|
|
<TabsTrigger
|
|
key={it.value}
|
|
value={it.value}
|
|
className="w-full justify-start gap-2 rounded-md px-3 py-2 data-[state=active]:bg-accent data-[state=active]:text-accent-foreground data-[state=active]:shadow-none"
|
|
>
|
|
<it.icon className="h-3.5 w-3.5 shrink-0" /> {it.label}
|
|
</TabsTrigger>
|
|
))}
|
|
</Fragment>
|
|
))}
|
|
</TabsList>
|
|
|
|
<div className={cn('min-w-0 flex-1', isNarrow && !mobileDetail && 'hidden')}>
|
|
{isNarrow && mobileDetail && (
|
|
<Button variant="ghost" size="sm" className="mb-3 -ml-2 gap-1 text-muted-foreground" onClick={() => setMobileDetail(false)}>
|
|
<ArrowLeft className="h-4 w-4" /> All settings
|
|
</Button>
|
|
)}
|
|
<TabsContent value="profile" className="mt-0 space-y-4">
|
|
<div className="flex items-center gap-4">
|
|
<div className="h-16 w-16 rounded-full bg-primary/20 flex items-center justify-center text-2xl font-bold text-primary">
|
|
{(session?.user?.name ?? session?.user?.email ?? '?')[0]?.toUpperCase()}
|
|
</div>
|
|
<div>
|
|
<p className="font-medium">{session?.user?.name ?? 'User'}</p>
|
|
<p className="text-sm text-muted-foreground" suppressHydrationWarning>{session?.user?.email}</p>
|
|
</div>
|
|
</div>
|
|
</TabsContent>
|
|
<TabsContent value="oidc" className="mt-0 space-y-4">
|
|
<div className="rounded-lg border p-4 space-y-3">
|
|
<h3 className="font-medium flex items-center gap-2"><Shield className="h-4 w-4" /> Sign-in (OIDC)</h3>
|
|
<p className="text-sm text-muted-foreground">Authelia single sign-on, configured via environment variables (read-only)</p>
|
|
<div className={`flex items-start gap-2 rounded-md p-3 text-sm ${oidc.enabled ? 'bg-green-500/10 text-green-700 dark:text-green-400' : 'bg-amber-500/10 text-amber-800 dark:text-amber-300'}`}>
|
|
{oidc.enabled ? <Check className="h-4 w-4 mt-0.5 shrink-0" /> : <AlertTriangle className="h-4 w-4 mt-0.5 shrink-0" />}
|
|
<span>
|
|
{oidc.enabled
|
|
? <>Configured for <span className="font-mono break-all">{oidc.issuer}</span>. Authelia sign-in is enabled.</>
|
|
: <>Not connected. Authelia sign-in is disabled until all three variables below hold real values. Users can sign in with email and password meanwhile. Setup guide: <span className="font-mono">docs/AUTHELIA.md</span></>}
|
|
</span>
|
|
</div>
|
|
<div className="space-y-2">
|
|
{([['OIDC_ISSUER', oidc.issuerSet], ['OIDC_CLIENT_ID', oidc.clientIdSet], ['OIDC_CLIENT_SECRET', oidc.clientSecretSet]] as const).map(([name, set]) => (
|
|
<div key={name} className="flex items-center gap-2">
|
|
<span className="text-xs font-mono bg-muted px-2 py-1 rounded">{name}</span>
|
|
<span className="text-sm text-muted-foreground">{set ? 'Set' : 'Not set'}</span>
|
|
{set ? <Check className="h-4 w-4 text-green-500" /> : <X className="h-4 w-4 text-muted-foreground" />}
|
|
</div>
|
|
))}
|
|
</div>
|
|
<div className="space-y-1 pt-2 border-t">
|
|
<p className="text-xs font-medium text-muted-foreground">Redirect URI to register in Authelia</p>
|
|
<p className="text-xs font-mono bg-muted px-2 py-1.5 rounded break-all" suppressHydrationWarning>{callbackUrl}</p>
|
|
</div>
|
|
</div>
|
|
</TabsContent>
|
|
<TabsContent value="webdav" className="mt-0 space-y-4">
|
|
<WebdavSettings />
|
|
</TabsContent>
|
|
<TabsContent value="caldav" className="mt-0 space-y-4">
|
|
<CalDavSettings />
|
|
</TabsContent>
|
|
<TabsContent value="carddav" className="mt-0 space-y-4">
|
|
<CardDavSettings />
|
|
</TabsContent>
|
|
<TabsContent value="nextcloud" className="mt-0 space-y-4">
|
|
<div className="rounded-lg border p-4 space-y-3">
|
|
<h3 className="font-medium flex items-center gap-2"><Cloud className="h-4 w-4" /> Contacts sync (Nextcloud)</h3>
|
|
<div className="grid grid-cols-2 gap-3">
|
|
<div className="col-span-2">
|
|
<label className="text-xs font-medium text-muted-foreground">Nextcloud URL</label>
|
|
<Input value={ncConfig.nextcloudUrl} onChange={(e: React.ChangeEvent<HTMLInputElement>) => setNcConfig(p => ({ ...p, nextcloudUrl: e.target.value }))} placeholder="https://nextcloud.example.com" />
|
|
</div>
|
|
<div className="col-span-2">
|
|
<label className="text-xs font-medium text-muted-foreground">CardDAV Path (optional)</label>
|
|
<Input value={ncConfig.cardDavPath} onChange={(e: React.ChangeEvent<HTMLInputElement>) => setNcConfig(p => ({ ...p, cardDavPath: e.target.value }))} placeholder="/remote.php/dav/addressbooks/users/USER/contacts/" />
|
|
</div>
|
|
<div>
|
|
<label className="text-xs font-medium text-muted-foreground">Username</label>
|
|
<Input value={ncConfig.username} onChange={(e: React.ChangeEvent<HTMLInputElement>) => setNcConfig(p => ({ ...p, username: e.target.value }))} />
|
|
</div>
|
|
<div>
|
|
<label className="text-xs font-medium text-muted-foreground">App Password</label>
|
|
<Input type="password" value={ncConfig.password} onChange={(e: React.ChangeEvent<HTMLInputElement>) => setNcConfig(p => ({ ...p, password: e.target.value }))} />
|
|
</div>
|
|
</div>
|
|
<Button onClick={syncContacts} loading={syncingContacts}>Sync Contacts Now</Button>
|
|
</div>
|
|
</TabsContent>
|
|
<TabsContent value="imap" className="mt-0 space-y-4">
|
|
<div className="rounded-lg border p-4 space-y-3">
|
|
<h3 className="font-medium flex items-center gap-2"><Server className="h-4 w-4" /> IMAP Configuration</h3>
|
|
<div className="grid grid-cols-2 gap-3">
|
|
<div>
|
|
<label className="text-xs font-medium text-muted-foreground">Host</label>
|
|
<Input value={imapConfig.host} onChange={(e: React.ChangeEvent<HTMLInputElement>) => setImapConfig(p => ({ ...p, host: e.target.value }))} placeholder="imap.example.com" />
|
|
</div>
|
|
<div>
|
|
<label className="text-xs font-medium text-muted-foreground">Port</label>
|
|
<Input type="number" value={imapConfig.port} onChange={(e: React.ChangeEvent<HTMLInputElement>) => setImapConfig(p => ({ ...p, port: parseInt(e.target.value) || 993 }))} />
|
|
</div>
|
|
<div>
|
|
<label className="text-xs font-medium text-muted-foreground">Username</label>
|
|
<Input value={imapConfig.username} onChange={(e: React.ChangeEvent<HTMLInputElement>) => setImapConfig(p => ({ ...p, username: e.target.value }))} />
|
|
</div>
|
|
<div>
|
|
<label className="text-xs font-medium text-muted-foreground">Password</label>
|
|
<Input type="password" value={imapConfig.password} onChange={(e: React.ChangeEvent<HTMLInputElement>) => setImapConfig(p => ({ ...p, password: e.target.value }))} />
|
|
</div>
|
|
<div>
|
|
<label className="text-xs font-medium text-muted-foreground">Folder</label>
|
|
<Input value={imapConfig.folder} onChange={(e: React.ChangeEvent<HTMLInputElement>) => setImapConfig(p => ({ ...p, folder: e.target.value }))} />
|
|
</div>
|
|
<div className="flex items-end">
|
|
{/* Review NET-02: mailbox logins always run over verified TLS;
|
|
the backend rejects insecure settings, so there is no toggle. */}
|
|
<p className="text-sm text-muted-foreground">TLS is required (implicit TLS, port 993 by default)</p>
|
|
</div>
|
|
</div>
|
|
<div className="flex gap-2">
|
|
<Button onClick={testImap} variant="outline" loading={testingImap}>Test Connection</Button>
|
|
<Button onClick={saveImap} loading={savingImap}>Save IMAP Settings</Button>
|
|
</div>
|
|
</div>
|
|
</TabsContent>
|
|
<TabsContent value="ai" className="mt-0 space-y-4">
|
|
<AiSettings />
|
|
</TabsContent>
|
|
<TabsContent value="mcp" className="mt-0 space-y-4">
|
|
<McpSettings />
|
|
</TabsContent>
|
|
<TabsContent value="automations" className="mt-0 space-y-4">
|
|
<AutomationsSettings />
|
|
</TabsContent>
|
|
<TabsContent value="notifications" className="mt-0 space-y-4">
|
|
<NotificationsSettings />
|
|
</TabsContent>
|
|
<TabsContent value="api-keys" className="mt-0 space-y-4">
|
|
<ApiKeysSettings />
|
|
</TabsContent>
|
|
</div>
|
|
</div>
|
|
</Tabs>
|
|
</div>
|
|
)
|
|
}
|