Turnstile bot protection (sign-in, sign-up, password-reset): - Register Better Auth's captcha plugin with the cloudflare-turnstile provider; endpoints listed explicitly rather than relying on defaults. /reset-password is intentionally excluded — it is reached only via a single-use emailed token. - Add an explicit-render Turnstile widget component. Tokens are single-use, so each form resets the challenge after a failed submit; submit stays disabled until a token is held. - Read the site key server-side and pass it down as a prop, so rotating it does not require a rebuild. - Fail fast in production when TURNSTILE_SECRET_KEY is missing, and when a secret is set without a site key (that combination would demand a token no form can produce, locking every user out). - Pass a throwaway secret during `next build` in the Dockerfile, mirroring the existing BETTER_AUTH_SECRET treatment, so image builds don't need it. CSP fixes in middleware (these blocked Turnstile entirely): - Add frame-src for challenges.cloudflare.com. Without it the widget's iframe fell back to default-src 'self' and was blocked outright. - Allow 'unsafe-eval' and websockets in DEVELOPMENT only. `next dev` compiles with eval(), so the strict policy threw EvalError and killed hydration — no client JS ran at all, which also meant form submit handlers never fired. Production policy is unchanged and still strict. Also included (concurrent work in the tree): - Admin organizations pages and lib/admin/orgs. - Episode moderation migration, SEO metadata (sitemap, robots, JSON-LD, OG/Twitter images, manifest), Umami analytics, not-found page. Local dev database: docker-compose.dev.yml provisions Postgres 18 on port 5443 (5432-5442 are in use by other local projects). Note: `npx tsc --noEmit` currently fails in app/(app)/team/page.tsx — an `invitations` prop the component does not accept. This predates the commit and will fail `next build` until fixed. Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
497 lines
17 KiB
TypeScript
497 lines
17 KiB
TypeScript
"use client";
|
|
|
|
import { useState } from "react";
|
|
import { useRouter } from "next/navigation";
|
|
import { Loader2, Save, Monitor, LogOut, Download, ShieldCheck } from "lucide-react";
|
|
import { toast } from "sonner";
|
|
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 {
|
|
Select,
|
|
SelectContent,
|
|
SelectItem,
|
|
SelectTrigger,
|
|
SelectValue,
|
|
} from "@/components/ui/select";
|
|
import { Card, CardContent, CardHeader, CardTitle, CardDescription } from "@/components/ui/card";
|
|
import { ConfirmDialog } from "@/components/admin/ui/confirm-dialog";
|
|
import { authClient, signOut } from "@/lib/auth/auth-client";
|
|
import { VOICE_CATALOG } from "@/lib/ai/voices";
|
|
import { LANGUAGES } from "@/lib/episodes/options";
|
|
import {
|
|
savePreferencesAction,
|
|
deleteAccountAction,
|
|
listSessionsAction,
|
|
revokeSessionAction,
|
|
revokeOtherSessionsAction,
|
|
exportMyDataAction,
|
|
type ActiveSession,
|
|
} from "@/app/(app)/settings/actions";
|
|
import { Badge } from "@/components/ui/badge";
|
|
|
|
const NO_VOICE = "__none__";
|
|
|
|
interface Preferences {
|
|
defaultVoiceId: string | null;
|
|
defaultLanguage: string;
|
|
emailOnEpisodeReady: boolean;
|
|
productEmails: boolean;
|
|
}
|
|
|
|
export function SettingsClient({
|
|
name,
|
|
email,
|
|
preferences,
|
|
}: {
|
|
name: string;
|
|
email: string;
|
|
preferences: Preferences;
|
|
}) {
|
|
const router = useRouter();
|
|
const [displayName, setDisplayName] = useState(name);
|
|
const [savingProfile, setSavingProfile] = useState(false);
|
|
const [savingPw, setSavingPw] = useState(false);
|
|
|
|
// Defaults
|
|
const [voiceId, setVoiceId] = useState(preferences.defaultVoiceId ?? NO_VOICE);
|
|
const [language, setLanguage] = useState(preferences.defaultLanguage);
|
|
const [savingDefaults, setSavingDefaults] = useState(false);
|
|
|
|
// Notifications
|
|
const [emailOnReady, setEmailOnReady] = useState(preferences.emailOnEpisodeReady);
|
|
const [productEmails, setProductEmails] = useState(preferences.productEmails);
|
|
const [savingNotif, setSavingNotif] = useState(false);
|
|
|
|
// Danger zone
|
|
const [confirmEmail, setConfirmEmail] = useState("");
|
|
|
|
async function saveProfile(e: React.FormEvent) {
|
|
e.preventDefault();
|
|
setSavingProfile(true);
|
|
const { error } = await authClient.updateUser({ name: displayName });
|
|
setSavingProfile(false);
|
|
if (error) toast.error(error.message ?? "Could not update");
|
|
else {
|
|
toast.success("Profile updated");
|
|
router.refresh();
|
|
}
|
|
}
|
|
|
|
async function changePassword(e: React.FormEvent<HTMLFormElement>) {
|
|
e.preventDefault();
|
|
const form = new FormData(e.currentTarget);
|
|
setSavingPw(true);
|
|
const { error } = await authClient.changePassword({
|
|
currentPassword: String(form.get("current")),
|
|
newPassword: String(form.get("new")),
|
|
revokeOtherSessions: true,
|
|
});
|
|
setSavingPw(false);
|
|
if (error) toast.error(error.message ?? "Could not change password");
|
|
else {
|
|
toast.success("Password changed");
|
|
e.currentTarget.reset();
|
|
}
|
|
}
|
|
|
|
async function saveDefaults() {
|
|
setSavingDefaults(true);
|
|
const res = await savePreferencesAction({
|
|
defaultVoiceId: voiceId === NO_VOICE ? null : voiceId,
|
|
defaultLanguage: language,
|
|
});
|
|
setSavingDefaults(false);
|
|
if (res.ok) toast.success("Defaults saved");
|
|
else toast.error(res.error ?? "Could not save");
|
|
}
|
|
|
|
async function saveNotifications(next: Partial<Preferences>) {
|
|
const emailVal = next.emailOnEpisodeReady ?? emailOnReady;
|
|
const productVal = next.productEmails ?? productEmails;
|
|
setEmailOnReady(emailVal);
|
|
setProductEmails(productVal);
|
|
setSavingNotif(true);
|
|
const res = await savePreferencesAction({
|
|
emailOnEpisodeReady: emailVal,
|
|
productEmails: productVal,
|
|
});
|
|
setSavingNotif(false);
|
|
if (!res.ok) {
|
|
toast.error(res.error ?? "Could not save");
|
|
// Revert optimistic state.
|
|
setEmailOnReady(preferences.emailOnEpisodeReady);
|
|
setProductEmails(preferences.productEmails);
|
|
} else {
|
|
toast.success("Notification preferences saved");
|
|
}
|
|
}
|
|
|
|
return (
|
|
<div className="max-w-xl space-y-6">
|
|
<Card>
|
|
<CardHeader>
|
|
<CardTitle>Profile</CardTitle>
|
|
<CardDescription>Update your name and see your email.</CardDescription>
|
|
</CardHeader>
|
|
<CardContent>
|
|
<form onSubmit={saveProfile} className="space-y-4">
|
|
<div className="space-y-2">
|
|
<Label htmlFor="name">Name</Label>
|
|
<Input id="name" value={displayName} onChange={(e) => setDisplayName(e.target.value)} />
|
|
</div>
|
|
<div className="space-y-2">
|
|
<Label>Email</Label>
|
|
<Input value={email} disabled />
|
|
</div>
|
|
<Button type="submit" disabled={savingProfile}>
|
|
{savingProfile && <Loader2 className="h-4 w-4 animate-spin" />}
|
|
Save profile
|
|
</Button>
|
|
</form>
|
|
</CardContent>
|
|
</Card>
|
|
|
|
<Card>
|
|
<CardHeader>
|
|
<CardTitle>Password</CardTitle>
|
|
<CardDescription>Change your account password.</CardDescription>
|
|
</CardHeader>
|
|
<CardContent>
|
|
<form onSubmit={changePassword} className="space-y-4">
|
|
<div className="space-y-2">
|
|
<Label htmlFor="current">Current password</Label>
|
|
<Input id="current" name="current" type="password" required />
|
|
</div>
|
|
<div className="space-y-2">
|
|
<Label htmlFor="new">New password</Label>
|
|
<Input id="new" name="new" type="password" minLength={8} required />
|
|
</div>
|
|
<Button type="submit" disabled={savingPw}>
|
|
{savingPw && <Loader2 className="h-4 w-4 animate-spin" />}
|
|
Change password
|
|
</Button>
|
|
</form>
|
|
</CardContent>
|
|
</Card>
|
|
|
|
<Card>
|
|
<CardHeader>
|
|
<CardTitle>Defaults</CardTitle>
|
|
<CardDescription>
|
|
Pre-select a voice and language when creating new episodes.
|
|
</CardDescription>
|
|
</CardHeader>
|
|
<CardContent className="space-y-4">
|
|
<div className="space-y-2">
|
|
<Label htmlFor="default-voice">Default host voice</Label>
|
|
<Select value={voiceId} onValueChange={setVoiceId}>
|
|
<SelectTrigger id="default-voice">
|
|
<SelectValue placeholder="Choose a voice" />
|
|
</SelectTrigger>
|
|
<SelectContent>
|
|
<SelectItem value={NO_VOICE}>No default (choose each time)</SelectItem>
|
|
{VOICE_CATALOG.map((v) => (
|
|
<SelectItem key={v.id} value={v.id}>
|
|
{v.name}
|
|
{v.accent ? ` · ${v.accent}` : ""}
|
|
{v.description ? ` — ${v.description}` : ""}
|
|
</SelectItem>
|
|
))}
|
|
</SelectContent>
|
|
</Select>
|
|
</div>
|
|
<div className="space-y-2">
|
|
<Label htmlFor="default-language">Default language</Label>
|
|
<Select value={language} onValueChange={setLanguage}>
|
|
<SelectTrigger id="default-language">
|
|
<SelectValue placeholder="Choose a language" />
|
|
</SelectTrigger>
|
|
<SelectContent>
|
|
{LANGUAGES.map((l) => (
|
|
<SelectItem key={l.code} value={l.code}>
|
|
{l.label}
|
|
</SelectItem>
|
|
))}
|
|
</SelectContent>
|
|
</Select>
|
|
</div>
|
|
<Button onClick={saveDefaults} disabled={savingDefaults}>
|
|
{savingDefaults ? <Loader2 className="h-4 w-4 animate-spin" /> : <Save className="h-4 w-4" />}
|
|
Save defaults
|
|
</Button>
|
|
</CardContent>
|
|
</Card>
|
|
|
|
<Card>
|
|
<CardHeader>
|
|
<CardTitle>Notifications</CardTitle>
|
|
<CardDescription>Choose which emails you want to receive.</CardDescription>
|
|
</CardHeader>
|
|
<CardContent className="space-y-1">
|
|
<div className="flex items-center justify-between gap-4 py-3">
|
|
<div className="space-y-0.5">
|
|
<p className="text-sm font-semibold">Episode ready</p>
|
|
<p className="text-xs text-muted-foreground">
|
|
Email me when an episode finishes generating.
|
|
</p>
|
|
</div>
|
|
<Switch
|
|
checked={emailOnReady}
|
|
disabled={savingNotif}
|
|
onCheckedChange={(v) => saveNotifications({ emailOnEpisodeReady: v })}
|
|
aria-label="Email me when an episode is ready"
|
|
/>
|
|
</div>
|
|
<div className="flex items-center justify-between gap-4 border-t py-3">
|
|
<div className="space-y-0.5">
|
|
<p className="text-sm font-semibold">Product updates</p>
|
|
<p className="text-xs text-muted-foreground">
|
|
Occasional product news, tips and announcements.
|
|
</p>
|
|
</div>
|
|
<Switch
|
|
checked={productEmails}
|
|
disabled={savingNotif}
|
|
onCheckedChange={(v) => saveNotifications({ productEmails: v })}
|
|
aria-label="Receive product update emails"
|
|
/>
|
|
</div>
|
|
</CardContent>
|
|
</Card>
|
|
|
|
<SessionsCard />
|
|
|
|
<DataExportCard />
|
|
|
|
<Card className="border-destructive/30">
|
|
<CardHeader>
|
|
<CardTitle className="text-destructive">Danger zone</CardTitle>
|
|
<CardDescription>
|
|
Permanently delete your account and all of your episodes. This cannot be undone.
|
|
</CardDescription>
|
|
</CardHeader>
|
|
<CardContent>
|
|
<ConfirmDialog
|
|
trigger={<Button variant="destructive">Delete account</Button>}
|
|
title="Delete your account?"
|
|
description="This permanently deletes your account, every episode, series, and all generated content. This action is irreversible."
|
|
confirmLabel="Delete my account"
|
|
successMessage="Account deleted"
|
|
body={
|
|
<div className="space-y-2">
|
|
<Label htmlFor="confirm-email">
|
|
Type <span className="font-semibold text-foreground">{email}</span> to confirm
|
|
</Label>
|
|
<Input
|
|
id="confirm-email"
|
|
value={confirmEmail}
|
|
onChange={(e) => setConfirmEmail(e.target.value)}
|
|
placeholder={email}
|
|
autoComplete="off"
|
|
/>
|
|
</div>
|
|
}
|
|
onConfirm={async () => {
|
|
const res = await deleteAccountAction(confirmEmail);
|
|
if (res.ok) {
|
|
await signOut();
|
|
router.push("/");
|
|
}
|
|
return res;
|
|
}}
|
|
/>
|
|
</CardContent>
|
|
</Card>
|
|
</div>
|
|
);
|
|
}
|
|
|
|
/**
|
|
* Best-effort, dependency-free user-agent summary. Deliberately coarse: this is
|
|
* a recognition aid ("is that my laptop?"), not analytics, so an unknown agent
|
|
* degrading to "Unknown browser" is fine.
|
|
*/
|
|
function describeUserAgent(ua: string | null): { browser: string; os: string } {
|
|
if (!ua) return { browser: "Unknown browser", os: "unknown device" };
|
|
const browser = /Edg\//.test(ua)
|
|
? "Edge"
|
|
: /OPR\//.test(ua)
|
|
? "Opera"
|
|
: /Chrome\//.test(ua)
|
|
? "Chrome"
|
|
: /Safari\//.test(ua)
|
|
? "Safari"
|
|
: /Firefox\//.test(ua)
|
|
? "Firefox"
|
|
: "Unknown browser";
|
|
const os = /Windows/.test(ua)
|
|
? "Windows"
|
|
: /Android/.test(ua)
|
|
? "Android"
|
|
: /iPhone|iPad|iOS/.test(ua)
|
|
? "iOS"
|
|
: /Mac OS X|Macintosh/.test(ua)
|
|
? "macOS"
|
|
: /Linux/.test(ua)
|
|
? "Linux"
|
|
: "unknown device";
|
|
return { browser, os };
|
|
}
|
|
|
|
/** Signed-in devices, with per-device and bulk revocation. */
|
|
function SessionsCard() {
|
|
const [sessions, setSessions] = useState<ActiveSession[] | null>(null);
|
|
const [loading, setLoading] = useState(false);
|
|
const [busy, setBusy] = useState<string | null>(null);
|
|
|
|
async function load() {
|
|
setLoading(true);
|
|
const res = await listSessionsAction();
|
|
setLoading(false);
|
|
if (!res.ok || !res.sessions) {
|
|
toast.error(res.error ?? "Could not load sessions");
|
|
return;
|
|
}
|
|
setSessions(res.sessions);
|
|
}
|
|
|
|
async function revoke(id: string) {
|
|
setBusy(id);
|
|
const res = await revokeSessionAction(id);
|
|
setBusy(null);
|
|
if (!res.ok) {
|
|
toast.error(res.error ?? "Could not sign out that device");
|
|
return;
|
|
}
|
|
toast.success("Device signed out");
|
|
await load();
|
|
}
|
|
|
|
async function revokeOthers() {
|
|
setBusy("all");
|
|
const res = await revokeOtherSessionsAction();
|
|
setBusy(null);
|
|
if (!res.ok) {
|
|
toast.error(res.error ?? "Failed");
|
|
return;
|
|
}
|
|
toast.success(res.count ? "Signed out " + res.count + " other device(s)" : "No other devices");
|
|
await load();
|
|
}
|
|
|
|
const others = sessions?.filter((x) => !x.current) ?? [];
|
|
|
|
return (
|
|
<Card>
|
|
<CardHeader>
|
|
<CardTitle className="flex items-center gap-2">
|
|
<ShieldCheck className="h-4 w-4" />
|
|
Active sessions
|
|
</CardTitle>
|
|
<CardDescription>
|
|
Devices currently signed in to your account. Sign out anything you don't recognise.
|
|
</CardDescription>
|
|
</CardHeader>
|
|
<CardContent className="space-y-3">
|
|
{sessions === null ? (
|
|
<Button variant="outline" onClick={load} disabled={loading}>
|
|
{loading ? <Loader2 className="h-4 w-4 animate-spin" /> : <Monitor className="h-4 w-4" />}
|
|
Show active sessions
|
|
</Button>
|
|
) : (
|
|
<>
|
|
<div className="divide-y rounded-2xl border">
|
|
{sessions.map((x) => {
|
|
const parts = describeUserAgent(x.userAgent);
|
|
return (
|
|
<div key={x.id} className="flex items-center gap-3 p-3">
|
|
<Monitor className="h-4 w-4 shrink-0 text-muted-foreground" />
|
|
<div className="min-w-0 flex-1">
|
|
<p className="truncate text-sm font-medium">
|
|
{`${parts.browser} on ${parts.os}`}
|
|
{x.current ? (
|
|
<Badge variant="secondary" className="ml-2">
|
|
This device
|
|
</Badge>
|
|
) : null}
|
|
</p>
|
|
<p className="truncate text-xs text-muted-foreground">
|
|
{x.ipAddress ?? "unknown IP"} · signed in{" "}
|
|
{new Date(x.createdAt).toLocaleDateString()}
|
|
</p>
|
|
</div>
|
|
{x.current ? null : (
|
|
<Button
|
|
variant="ghost"
|
|
size="sm"
|
|
disabled={busy === x.id}
|
|
onClick={() => revoke(x.id)}
|
|
>
|
|
<LogOut className="h-4 w-4" />
|
|
Sign out
|
|
</Button>
|
|
)}
|
|
</div>
|
|
);
|
|
})}
|
|
</div>
|
|
{others.length > 0 ? (
|
|
<Button variant="outline" onClick={revokeOthers} disabled={busy === "all"}>
|
|
{busy === "all" ? <Loader2 className="h-4 w-4 animate-spin" /> : null}
|
|
Sign out all other devices ({others.length})
|
|
</Button>
|
|
) : null}
|
|
</>
|
|
)}
|
|
</CardContent>
|
|
</Card>
|
|
);
|
|
}
|
|
|
|
/** Self-serve GDPR access request: download everything we hold, as JSON. */
|
|
function DataExportCard() {
|
|
const [busy, setBusy] = useState(false);
|
|
|
|
async function download() {
|
|
setBusy(true);
|
|
const res = await exportMyDataAction();
|
|
setBusy(false);
|
|
if (!res.ok || !res.json) {
|
|
toast.error(res.error ?? "Could not export your data");
|
|
return;
|
|
}
|
|
// Build the file in the browser so the JSON never has to round-trip through
|
|
// a route handler that would need its own authorization.
|
|
const url = URL.createObjectURL(new Blob([res.json], { type: "application/json" }));
|
|
const a = document.createElement("a");
|
|
a.href = url;
|
|
a.download = `podcast-distribution-ai-export-${new Date().toISOString().slice(0, 10)}.json`;
|
|
a.click();
|
|
URL.revokeObjectURL(url);
|
|
toast.success("Export downloaded");
|
|
}
|
|
|
|
return (
|
|
<Card>
|
|
<CardHeader>
|
|
<CardTitle className="flex items-center gap-2">
|
|
<Download className="h-4 w-4" />
|
|
Export your data
|
|
</CardTitle>
|
|
<CardDescription>
|
|
Download your profile, episodes, scripts, series, usage and billing history as JSON.
|
|
Passwords and access tokens are excluded.
|
|
</CardDescription>
|
|
</CardHeader>
|
|
<CardContent>
|
|
<Button variant="outline" onClick={download} disabled={busy}>
|
|
{busy ? <Loader2 className="h-4 w-4 animate-spin" /> : <Download className="h-4 w-4" />}
|
|
Download my data
|
|
</Button>
|
|
</CardContent>
|
|
</Card>
|
|
);
|
|
}
|