feat: Cloudflare Turnstile on auth, CSP fixes, admin/SEO/analytics additions
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>
This commit is contained in:
co-authored by
Claude Opus 5
parent
35379212fb
commit
3e9ba07175
@@ -2,20 +2,7 @@
|
||||
|
||||
import Link from "next/link";
|
||||
import { usePathname } from "next/navigation";
|
||||
import {
|
||||
LayoutDashboard,
|
||||
TrendingUp,
|
||||
BarChart3,
|
||||
Users,
|
||||
CreditCard,
|
||||
ListChecks,
|
||||
Activity,
|
||||
Webhook,
|
||||
ShieldAlert,
|
||||
Flag,
|
||||
ScrollText,
|
||||
Settings,
|
||||
} from "lucide-react";
|
||||
import { LayoutDashboard, TrendingUp, BarChart3, Users, CreditCard, ListChecks, Activity, Webhook, ShieldAlert, Flag, ScrollText, Settings, Building2 } from "lucide-react";
|
||||
import { cn } from "@/lib/utils";
|
||||
|
||||
interface Item {
|
||||
@@ -38,6 +25,7 @@ const GROUPS: { label: string; items: Item[] }[] = [
|
||||
label: "Operations",
|
||||
items: [
|
||||
{ label: "Users", href: "/admin/users", icon: Users },
|
||||
{ label: "Organizations", href: "/admin/organizations", icon: Building2 },
|
||||
{ label: "Subscriptions", href: "/admin/subscriptions", icon: CreditCard },
|
||||
{ label: "Jobs", href: "/admin/jobs", icon: ListChecks },
|
||||
{ label: "System health", href: "/admin/health", icon: Activity },
|
||||
|
||||
@@ -2,7 +2,7 @@
|
||||
|
||||
import { useState } from "react";
|
||||
import { useRouter } from "next/navigation";
|
||||
import { LogIn, ShieldCheck, ShieldOff, Ban, UserCheck, Gift } from "lucide-react";
|
||||
import { LogIn, ShieldCheck, ShieldOff, Ban, UserCheck, Gift, Download, Trash2 } from "lucide-react";
|
||||
import { toast } from "sonner";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { Label } from "@/components/ui/label";
|
||||
@@ -19,6 +19,8 @@ import {
|
||||
banUserAction,
|
||||
setRoleAction,
|
||||
compPlanAction,
|
||||
deleteUserAction,
|
||||
exportUserDataAction,
|
||||
} from "@/app/(admin)/admin/actions";
|
||||
|
||||
type CompPlan = "creator" | "pro" | "agency";
|
||||
@@ -31,6 +33,7 @@ export function UserDetailActions({
|
||||
}) {
|
||||
const router = useRouter();
|
||||
const [impersonating, setImpersonating] = useState(false);
|
||||
const [exporting, setExporting] = useState(false);
|
||||
const [compPlan, setCompPlan] = useState<CompPlan>("pro");
|
||||
const [compInterval, setCompInterval] = useState<CompInterval>("month");
|
||||
|
||||
@@ -44,6 +47,23 @@ export function UserDetailActions({
|
||||
}
|
||||
}
|
||||
|
||||
async function exportData() {
|
||||
setExporting(true);
|
||||
const res = await exportUserDataAction(user.id);
|
||||
setExporting(false);
|
||||
if (!res.ok || !res.json) {
|
||||
toast.error(res.error ?? "Could not export");
|
||||
return;
|
||||
}
|
||||
const url = URL.createObjectURL(new Blob([res.json], { type: "application/json" }));
|
||||
const a = document.createElement("a");
|
||||
a.href = url;
|
||||
a.download = `user-${user.id}-export.json`;
|
||||
a.click();
|
||||
URL.revokeObjectURL(url);
|
||||
toast.success("Export downloaded");
|
||||
}
|
||||
|
||||
async function impersonate() {
|
||||
setImpersonating(true);
|
||||
try {
|
||||
@@ -159,6 +179,29 @@ export function UserDetailActions({
|
||||
onConfirm={() => banUserAction(user.id, true)}
|
||||
/>
|
||||
)}
|
||||
|
||||
<Button variant="outline" size="sm" onClick={exportData} disabled={exporting}>
|
||||
<Download className="h-4 w-4" />
|
||||
{exporting ? "Exporting…" : "Export data"}
|
||||
</Button>
|
||||
|
||||
<ConfirmDialog
|
||||
trigger={
|
||||
<Button variant="destructive" size="sm">
|
||||
<Trash2 className="h-4 w-4" /> Delete
|
||||
</Button>
|
||||
}
|
||||
title="Permanently delete this user?"
|
||||
description="Erases the account and every episode, script, series, API key and usage record it owns. This cannot be undone — export their data first if this is a GDPR request."
|
||||
confirmLabel="Delete permanently"
|
||||
successMessage="User deleted"
|
||||
onConfirm={async () => {
|
||||
const res = await deleteUserAction(user.id);
|
||||
// The user page no longer exists once the row is gone.
|
||||
if (res.ok) router.push("/admin/users");
|
||||
return res;
|
||||
}}
|
||||
/>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -0,0 +1,51 @@
|
||||
"use client";
|
||||
|
||||
import Script from "next/script";
|
||||
import { ANALYTICS_PROXY_PATH, redactPayload, type UmamiPayload } from "@/lib/analytics";
|
||||
|
||||
/** Name of the global the tracker's `data-before-send` hook resolves. */
|
||||
const BEFORE_SEND = "__umamiBeforeSend";
|
||||
|
||||
declare global {
|
||||
interface Window {
|
||||
[BEFORE_SEND]?: (type: string, payload: UmamiPayload) => UmamiPayload;
|
||||
}
|
||||
}
|
||||
|
||||
// Registered at module scope rather than in an effect: the tracker reads
|
||||
// `window[BEFORE_SEND]` at send time, and this client chunk is evaluated before
|
||||
// next/script injects the tag, so there is no window in which an unredacted
|
||||
// event could slip out.
|
||||
if (typeof window !== "undefined") {
|
||||
window[BEFORE_SEND] = (_type, payload) => redactPayload(payload);
|
||||
}
|
||||
|
||||
/**
|
||||
* Self-hosted Umami analytics.
|
||||
*
|
||||
* The tracker and its beacon are both served from this origin via the
|
||||
* `/_a` rewrite in next.config.mjs. That matters for more than ad-blockers: the
|
||||
* CSP in middleware.ts uses `'strict-dynamic'`, which makes browsers ignore host
|
||||
* allowlists in `script-src` entirely — so allowlisting the Umami domain there
|
||||
* would not have worked, and `connect-src 'self'` would still have blocked the
|
||||
* beacon. Proxying keeps both same-origin and the policy unrelaxed.
|
||||
*/
|
||||
export function UmamiAnalytics({ websiteId }: { websiteId: string }) {
|
||||
return (
|
||||
<Script
|
||||
src={`${ANALYTICS_PROXY_PATH}/script.js`}
|
||||
strategy="afterInteractive"
|
||||
data-website-id={websiteId}
|
||||
// Point the beacon at the proxied path instead of letting the tracker
|
||||
// derive it from its own src.
|
||||
data-host-url={ANALYTICS_PROXY_PATH}
|
||||
// Drop query strings and fragments at the source. /reset-password carries a
|
||||
// live reset token in `?token=` and /sign-in carries `?redirect=`.
|
||||
data-exclude-search="true"
|
||||
data-exclude-hash="true"
|
||||
data-before-send={BEFORE_SEND}
|
||||
// Honour the browser's Do Not Track signal.
|
||||
data-do-not-track="true"
|
||||
/>
|
||||
);
|
||||
}
|
||||
@@ -2,7 +2,7 @@
|
||||
|
||||
import { useState } from "react";
|
||||
import { useRouter } from "next/navigation";
|
||||
import { Loader2, Save } from "lucide-react";
|
||||
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";
|
||||
@@ -20,7 +20,16 @@ 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 } from "@/app/(app)/settings/actions";
|
||||
import {
|
||||
savePreferencesAction,
|
||||
deleteAccountAction,
|
||||
listSessionsAction,
|
||||
revokeSessionAction,
|
||||
revokeOtherSessionsAction,
|
||||
exportMyDataAction,
|
||||
type ActiveSession,
|
||||
} from "@/app/(app)/settings/actions";
|
||||
import { Badge } from "@/components/ui/badge";
|
||||
|
||||
const NO_VOICE = "__none__";
|
||||
|
||||
@@ -252,6 +261,10 @@ export function SettingsClient({
|
||||
</CardContent>
|
||||
</Card>
|
||||
|
||||
<SessionsCard />
|
||||
|
||||
<DataExportCard />
|
||||
|
||||
<Card className="border-destructive/30">
|
||||
<CardHeader>
|
||||
<CardTitle className="text-destructive">Danger zone</CardTitle>
|
||||
@@ -294,3 +307,190 @@ export function SettingsClient({
|
||||
</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>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -2,7 +2,7 @@
|
||||
|
||||
import { useState } from "react";
|
||||
import { useRouter } from "next/navigation";
|
||||
import { Loader2, UserPlus, Building2, Save, Mic, Plus } from "lucide-react";
|
||||
import { Loader2, UserPlus, Building2, Save, Mic, Plus, Trash2, MailX, Clock } from "lucide-react";
|
||||
import { toast } from "sonner";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { Input } from "@/components/ui/input";
|
||||
@@ -12,7 +12,21 @@ import { Badge } from "@/components/ui/badge";
|
||||
import { Card, CardContent, CardHeader, CardTitle, CardDescription } from "@/components/ui/card";
|
||||
import { Avatar, AvatarFallback } from "@/components/ui/avatar";
|
||||
import { authClient } from "@/lib/auth/auth-client";
|
||||
import { inviteMemberAction, saveBrandingAction } from "@/app/(app)/team/actions";
|
||||
import {
|
||||
inviteMemberAction,
|
||||
saveBrandingAction,
|
||||
removeMemberAction,
|
||||
updateMemberRoleAction,
|
||||
revokeInvitationAction,
|
||||
} from "@/app/(app)/team/actions";
|
||||
import {
|
||||
Select,
|
||||
SelectContent,
|
||||
SelectItem,
|
||||
SelectTrigger,
|
||||
SelectValue,
|
||||
} from "@/components/ui/select";
|
||||
import { ConfirmDialog } from "@/components/admin/ui/confirm-dialog";
|
||||
|
||||
/**
|
||||
* Pure client-side #rrggbb → "H S% L%" converter for the live branding preview.
|
||||
@@ -51,6 +65,7 @@ function hexToHslTriplet(hex: string): string | null {
|
||||
|
||||
interface Member {
|
||||
id: string;
|
||||
userId: string;
|
||||
name: string;
|
||||
email: string;
|
||||
role: string;
|
||||
@@ -62,14 +77,25 @@ interface Branding {
|
||||
removePoweredBy: boolean;
|
||||
}
|
||||
|
||||
export interface Invitation {
|
||||
id: string;
|
||||
email: string;
|
||||
role: string;
|
||||
expiresAt: string;
|
||||
}
|
||||
|
||||
export function TeamClient({
|
||||
org,
|
||||
members,
|
||||
invitations,
|
||||
currentUserId,
|
||||
branding,
|
||||
seats,
|
||||
}: {
|
||||
org: { id: string; name: string } | null;
|
||||
members: Member[];
|
||||
invitations: Invitation[];
|
||||
currentUserId: string;
|
||||
branding: Branding | null;
|
||||
seats: number;
|
||||
}) {
|
||||
@@ -79,7 +105,13 @@ export function TeamClient({
|
||||
|
||||
return (
|
||||
<div className="space-y-6">
|
||||
<MembersCard orgId={org.id} members={members} seats={seats} />
|
||||
<MembersCard
|
||||
orgId={org.id}
|
||||
members={members}
|
||||
invitations={invitations}
|
||||
currentUserId={currentUserId}
|
||||
seats={seats}
|
||||
/>
|
||||
<BrandingCard orgId={org.id} branding={branding} />
|
||||
</div>
|
||||
);
|
||||
@@ -129,15 +161,49 @@ function CreateWorkspace() {
|
||||
);
|
||||
}
|
||||
|
||||
function MembersCard({ orgId, members, seats }: { orgId: string; members: Member[]; seats: number }) {
|
||||
function MembersCard({
|
||||
orgId,
|
||||
members,
|
||||
invitations,
|
||||
currentUserId,
|
||||
seats,
|
||||
}: {
|
||||
orgId: string;
|
||||
members: Member[];
|
||||
invitations: Invitation[];
|
||||
currentUserId: string;
|
||||
seats: number;
|
||||
}) {
|
||||
const router = useRouter();
|
||||
const [email, setEmail] = useState("");
|
||||
const [busy, setBusy] = useState(false);
|
||||
const [rowBusy, setRowBusy] = useState<string | null>(null);
|
||||
|
||||
// A pending invite holds a seat, so it counts towards the cap — this mirrors
|
||||
// the server-side check in inviteMemberAction.
|
||||
const used = members.length + invitations.length;
|
||||
const owners = members.filter((m) => m.role === "owner").length;
|
||||
|
||||
async function run(
|
||||
id: string,
|
||||
action: () => Promise<{ ok: boolean; error?: string }>,
|
||||
msg: string
|
||||
) {
|
||||
setRowBusy(id);
|
||||
const res = await action();
|
||||
setRowBusy(null);
|
||||
if (!res.ok) {
|
||||
toast.error(res.error ?? "Failed");
|
||||
return;
|
||||
}
|
||||
toast.success(msg);
|
||||
router.refresh();
|
||||
}
|
||||
|
||||
async function invite(e: React.FormEvent) {
|
||||
e.preventDefault();
|
||||
// Fast UX guard only — the server action is the real seat-limit authority.
|
||||
if (members.length >= seats) {
|
||||
if (used >= seats) {
|
||||
toast.error(`Your plan includes ${seats} seats.`);
|
||||
return;
|
||||
}
|
||||
@@ -159,7 +225,7 @@ function MembersCard({ orgId, members, seats }: { orgId: string; members: Member
|
||||
<CardTitle className="flex items-center justify-between">
|
||||
<span>Members</span>
|
||||
<Badge variant="secondary">
|
||||
{members.length} / {seats} seats
|
||||
{used} / {seats} seats
|
||||
</Badge>
|
||||
</CardTitle>
|
||||
</CardHeader>
|
||||
@@ -174,10 +240,91 @@ function MembersCard({ orgId, members, seats }: { orgId: string; members: Member
|
||||
<p className="truncate text-sm font-medium">{m.name}</p>
|
||||
<p className="truncate text-xs text-muted-foreground">{m.email}</p>
|
||||
</div>
|
||||
<Badge variant="outline" className="capitalize">{m.role}</Badge>
|
||||
{m.userId === currentUserId ? (
|
||||
<Badge variant="outline" className="capitalize">
|
||||
{m.role} (you)
|
||||
</Badge>
|
||||
) : (
|
||||
<div className="flex items-center gap-2">
|
||||
<Select
|
||||
value={m.role}
|
||||
disabled={rowBusy === m.id}
|
||||
onValueChange={(role) =>
|
||||
run(
|
||||
m.id,
|
||||
() =>
|
||||
updateMemberRoleAction(
|
||||
orgId,
|
||||
m.id,
|
||||
role as "owner" | "admin" | "member"
|
||||
),
|
||||
"Role updated"
|
||||
)
|
||||
}
|
||||
>
|
||||
<SelectTrigger className="h-8 w-28 capitalize">
|
||||
<SelectValue />
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
<SelectItem value="owner">Owner</SelectItem>
|
||||
<SelectItem value="admin">Admin</SelectItem>
|
||||
<SelectItem value="member">Member</SelectItem>
|
||||
</SelectContent>
|
||||
</Select>
|
||||
<ConfirmDialog
|
||||
trigger={
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="icon"
|
||||
className="h-8 w-8 text-destructive"
|
||||
disabled={rowBusy === m.id || (m.role === "owner" && owners <= 1)}
|
||||
aria-label={`Remove ${m.name}`}
|
||||
>
|
||||
<Trash2 className="h-4 w-4" />
|
||||
</Button>
|
||||
}
|
||||
title={`Remove ${m.name}?`}
|
||||
description="They lose access to this workspace immediately and their seat is freed. Their own episodes are not deleted."
|
||||
confirmLabel="Remove"
|
||||
onConfirm={() => removeMemberAction(orgId, m.id)}
|
||||
/>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
|
||||
{invitations.length > 0 ? (
|
||||
<div className="space-y-2">
|
||||
<p className="text-xs font-medium text-muted-foreground">
|
||||
Pending invitations ({invitations.length})
|
||||
</p>
|
||||
<div className="divide-y rounded-2xl border border-dashed">
|
||||
{invitations.map((inv) => (
|
||||
<div key={inv.id} className="flex items-center gap-3 p-3">
|
||||
<Clock className="h-4 w-4 shrink-0 text-muted-foreground" />
|
||||
<div className="min-w-0 flex-1">
|
||||
<p className="truncate text-sm">{inv.email}</p>
|
||||
<p className="text-xs text-muted-foreground">
|
||||
Expires {new Date(inv.expiresAt).toLocaleDateString()} · holds a seat
|
||||
</p>
|
||||
</div>
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="sm"
|
||||
disabled={rowBusy === inv.id}
|
||||
onClick={() =>
|
||||
run(inv.id, () => revokeInvitationAction(orgId, inv.id), "Invitation revoked")
|
||||
}
|
||||
>
|
||||
<MailX className="h-4 w-4" />
|
||||
Revoke
|
||||
</Button>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
) : null}
|
||||
<form onSubmit={invite} className="flex gap-2">
|
||||
<Input
|
||||
type="email"
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
"use client";
|
||||
|
||||
import { useState } from "react";
|
||||
import { useRef, useState } from "react";
|
||||
import Link from "next/link";
|
||||
import { Loader2, MailCheck } from "lucide-react";
|
||||
import { toast } from "sonner";
|
||||
@@ -9,21 +9,31 @@ import { Input } from "@/components/ui/input";
|
||||
import { Label } from "@/components/ui/label";
|
||||
import { Card, CardContent, CardHeader, CardTitle, CardDescription } from "@/components/ui/card";
|
||||
import { authClient } from "@/lib/auth/auth-client";
|
||||
import { Turnstile, type TurnstileHandle } from "./turnstile";
|
||||
|
||||
export function ForgotPasswordForm() {
|
||||
export function ForgotPasswordForm({ turnstileSiteKey }: { turnstileSiteKey: string | null }) {
|
||||
const [loading, setLoading] = useState(false);
|
||||
const [sent, setSent] = useState(false);
|
||||
// See sign-in-form: rendered only when configured, verified server-side.
|
||||
const [captchaToken, setCaptchaToken] = useState("");
|
||||
const turnstileRef = useRef<TurnstileHandle>(null);
|
||||
const captchaRequired = !!turnstileSiteKey;
|
||||
|
||||
async function onSubmit(e: React.FormEvent<HTMLFormElement>) {
|
||||
e.preventDefault();
|
||||
setLoading(true);
|
||||
const form = new FormData(e.currentTarget);
|
||||
const { error } = await authClient.requestPasswordReset({
|
||||
email: String(form.get("email")),
|
||||
redirectTo: "/reset-password",
|
||||
});
|
||||
const { error } = await authClient.requestPasswordReset(
|
||||
{
|
||||
email: String(form.get("email")),
|
||||
redirectTo: "/reset-password",
|
||||
},
|
||||
captchaRequired ? { headers: { "x-captcha-response": captchaToken } } : undefined
|
||||
);
|
||||
setLoading(false);
|
||||
if (error) {
|
||||
// Single-use token: re-challenge so the retry fails on its real cause.
|
||||
turnstileRef.current?.reset();
|
||||
toast.error(error.message ?? "Something went wrong");
|
||||
return;
|
||||
}
|
||||
@@ -62,7 +72,20 @@ export function ForgotPasswordForm() {
|
||||
<Label htmlFor="email">Email</Label>
|
||||
<Input id="email" name="email" type="email" autoComplete="email" required />
|
||||
</div>
|
||||
<Button type="submit" className="w-full" disabled={loading}>
|
||||
{turnstileSiteKey && (
|
||||
<Turnstile
|
||||
ref={turnstileRef}
|
||||
siteKey={turnstileSiteKey}
|
||||
onToken={setCaptchaToken}
|
||||
onError={() => toast.error("Could not load the security check. Please refresh.")}
|
||||
className="flex justify-center"
|
||||
/>
|
||||
)}
|
||||
<Button
|
||||
type="submit"
|
||||
className="w-full"
|
||||
disabled={loading || (captchaRequired && !captchaToken)}
|
||||
>
|
||||
{loading && <Loader2 className="h-4 w-4 animate-spin" />}
|
||||
Send reset link
|
||||
</Button>
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
"use client";
|
||||
|
||||
import { useState } from "react";
|
||||
import { useRef, useState } from "react";
|
||||
import Link from "next/link";
|
||||
import { useRouter, useSearchParams } from "next/navigation";
|
||||
import { Loader2 } from "lucide-react";
|
||||
@@ -12,23 +12,42 @@ import { Card, CardContent, CardHeader, CardTitle, CardDescription } from "@/com
|
||||
import { signIn } from "@/lib/auth/auth-client";
|
||||
import { safeRedirect } from "@/lib/utils";
|
||||
import { GoogleButton } from "./google-button";
|
||||
import { Turnstile, type TurnstileHandle } from "./turnstile";
|
||||
|
||||
export function SignInForm({ googleEnabled }: { googleEnabled: boolean }) {
|
||||
export function SignInForm({
|
||||
googleEnabled,
|
||||
turnstileSiteKey,
|
||||
}: {
|
||||
googleEnabled: boolean;
|
||||
turnstileSiteKey: string | null;
|
||||
}) {
|
||||
const router = useRouter();
|
||||
const params = useSearchParams();
|
||||
// Validate the ?redirect param to prevent open-redirect attacks.
|
||||
const redirectTo = safeRedirect(params.get("redirect"));
|
||||
const [loading, setLoading] = useState(false);
|
||||
// Turnstile is only rendered when configured; when it is, a solved token is
|
||||
// required before the form can be submitted. The server rejects a missing or
|
||||
// reused token regardless, so this is UX, not the security boundary.
|
||||
const [captchaToken, setCaptchaToken] = useState("");
|
||||
const turnstileRef = useRef<TurnstileHandle>(null);
|
||||
const captchaRequired = !!turnstileSiteKey;
|
||||
|
||||
async function onSubmit(e: React.FormEvent<HTMLFormElement>) {
|
||||
e.preventDefault();
|
||||
setLoading(true);
|
||||
const form = new FormData(e.currentTarget);
|
||||
const { error } = await signIn.email({
|
||||
email: String(form.get("email")),
|
||||
password: String(form.get("password")),
|
||||
});
|
||||
const { error } = await signIn.email(
|
||||
{
|
||||
email: String(form.get("email")),
|
||||
password: String(form.get("password")),
|
||||
},
|
||||
captchaRequired ? { headers: { "x-captcha-response": captchaToken } } : undefined
|
||||
);
|
||||
if (error) {
|
||||
// Turnstile tokens are single-use — issue a fresh challenge for the retry,
|
||||
// otherwise the next submit fails verification instead of on credentials.
|
||||
turnstileRef.current?.reset();
|
||||
toast.error(error.message ?? "Invalid email or password");
|
||||
setLoading(false);
|
||||
return;
|
||||
@@ -71,7 +90,20 @@ export function SignInForm({ googleEnabled }: { googleEnabled: boolean }) {
|
||||
</div>
|
||||
<Input id="password" name="password" type="password" autoComplete="current-password" required />
|
||||
</div>
|
||||
<Button type="submit" className="w-full" disabled={loading}>
|
||||
{turnstileSiteKey && (
|
||||
<Turnstile
|
||||
ref={turnstileRef}
|
||||
siteKey={turnstileSiteKey}
|
||||
onToken={setCaptchaToken}
|
||||
onError={() => toast.error("Could not load the security check. Please refresh.")}
|
||||
className="flex justify-center"
|
||||
/>
|
||||
)}
|
||||
<Button
|
||||
type="submit"
|
||||
className="w-full"
|
||||
disabled={loading || (captchaRequired && !captchaToken)}
|
||||
>
|
||||
{loading && <Loader2 className="h-4 w-4 animate-spin" />}
|
||||
Sign in
|
||||
</Button>
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
"use client";
|
||||
|
||||
import { useState } from "react";
|
||||
import { useRef, useState } from "react";
|
||||
import Link from "next/link";
|
||||
import { useRouter } from "next/navigation";
|
||||
import { Loader2 } from "lucide-react";
|
||||
@@ -11,21 +11,37 @@ import { Label } from "@/components/ui/label";
|
||||
import { Card, CardContent, CardHeader, CardTitle, CardDescription } from "@/components/ui/card";
|
||||
import { signUp } from "@/lib/auth/auth-client";
|
||||
import { GoogleButton } from "./google-button";
|
||||
import { Turnstile, type TurnstileHandle } from "./turnstile";
|
||||
|
||||
export function SignUpForm({ googleEnabled }: { googleEnabled: boolean }) {
|
||||
export function SignUpForm({
|
||||
googleEnabled,
|
||||
turnstileSiteKey,
|
||||
}: {
|
||||
googleEnabled: boolean;
|
||||
turnstileSiteKey: string | null;
|
||||
}) {
|
||||
const router = useRouter();
|
||||
const [loading, setLoading] = useState(false);
|
||||
// See sign-in-form: rendered only when configured, verified server-side.
|
||||
const [captchaToken, setCaptchaToken] = useState("");
|
||||
const turnstileRef = useRef<TurnstileHandle>(null);
|
||||
const captchaRequired = !!turnstileSiteKey;
|
||||
|
||||
async function onSubmit(e: React.FormEvent<HTMLFormElement>) {
|
||||
e.preventDefault();
|
||||
setLoading(true);
|
||||
const form = new FormData(e.currentTarget);
|
||||
const { error } = await signUp.email({
|
||||
name: String(form.get("name")),
|
||||
email: String(form.get("email")),
|
||||
password: String(form.get("password")),
|
||||
});
|
||||
const { error } = await signUp.email(
|
||||
{
|
||||
name: String(form.get("name")),
|
||||
email: String(form.get("email")),
|
||||
password: String(form.get("password")),
|
||||
},
|
||||
captchaRequired ? { headers: { "x-captcha-response": captchaToken } } : undefined
|
||||
);
|
||||
if (error) {
|
||||
// Single-use token: re-challenge so the retry fails on its real cause.
|
||||
turnstileRef.current?.reset();
|
||||
// Accepted tradeoff (L8): the raw Better Auth message can reveal that an
|
||||
// email is already registered (account enumeration). We keep the specific
|
||||
// message for UX clarity; the signup endpoint is rate-limited server-side.
|
||||
@@ -79,7 +95,20 @@ export function SignUpForm({ googleEnabled }: { googleEnabled: boolean }) {
|
||||
/>
|
||||
<p className="text-xs text-muted-foreground">At least 8 characters.</p>
|
||||
</div>
|
||||
<Button type="submit" className="w-full" disabled={loading}>
|
||||
{turnstileSiteKey && (
|
||||
<Turnstile
|
||||
ref={turnstileRef}
|
||||
siteKey={turnstileSiteKey}
|
||||
onToken={setCaptchaToken}
|
||||
onError={() => toast.error("Could not load the security check. Please refresh.")}
|
||||
className="flex justify-center"
|
||||
/>
|
||||
)}
|
||||
<Button
|
||||
type="submit"
|
||||
className="w-full"
|
||||
disabled={loading || (captchaRequired && !captchaToken)}
|
||||
>
|
||||
{loading && <Loader2 className="h-4 w-4 animate-spin" />}
|
||||
Create account
|
||||
</Button>
|
||||
|
||||
@@ -0,0 +1,146 @@
|
||||
"use client";
|
||||
|
||||
import { forwardRef, useEffect, useImperativeHandle, useRef } from "react";
|
||||
|
||||
const SCRIPT_ID = "cf-turnstile-script";
|
||||
const SCRIPT_SRC = "https://challenges.cloudflare.com/turnstile/v0/api.js?render=explicit";
|
||||
|
||||
type TurnstileApi = {
|
||||
render: (el: HTMLElement, opts: Record<string, unknown>) => string;
|
||||
reset: (id: string) => void;
|
||||
remove: (id: string) => void;
|
||||
};
|
||||
|
||||
declare global {
|
||||
// eslint-disable-next-line no-var
|
||||
var turnstile: TurnstileApi | undefined;
|
||||
}
|
||||
|
||||
/**
|
||||
* Load Cloudflare's script once per page, no matter how many widgets mount.
|
||||
* `render=explicit` keeps control in our hands so the widget can be reset —
|
||||
* Turnstile tokens are single-use, so every failed submit needs a fresh one.
|
||||
*/
|
||||
let scriptPromise: Promise<void> | null = null;
|
||||
function loadTurnstileScript(): Promise<void> {
|
||||
if (typeof window === "undefined") return Promise.resolve();
|
||||
if (window.turnstile) return Promise.resolve();
|
||||
if (scriptPromise) return scriptPromise;
|
||||
|
||||
scriptPromise = new Promise<void>((resolve, reject) => {
|
||||
const existing = document.getElementById(SCRIPT_ID) as HTMLScriptElement | null;
|
||||
if (existing) {
|
||||
existing.addEventListener("load", () => resolve());
|
||||
existing.addEventListener("error", () => reject(new Error("Turnstile failed to load")));
|
||||
return;
|
||||
}
|
||||
const script = document.createElement("script");
|
||||
script.id = SCRIPT_ID;
|
||||
script.src = SCRIPT_SRC;
|
||||
script.async = true;
|
||||
script.defer = true;
|
||||
script.onload = () => resolve();
|
||||
script.onerror = () => {
|
||||
// Allow a later mount to retry (e.g. the user was briefly offline).
|
||||
scriptPromise = null;
|
||||
reject(new Error("Turnstile failed to load"));
|
||||
};
|
||||
document.head.appendChild(script);
|
||||
});
|
||||
return scriptPromise;
|
||||
}
|
||||
|
||||
/**
|
||||
* `script.onload` does not guarantee `window.turnstile` is assigned yet, and the
|
||||
* original code silently gave up forever when it wasn't — the widget would just
|
||||
* never appear. Poll briefly instead so a slow parse still resolves.
|
||||
*/
|
||||
async function waitForTurnstileApi(timeoutMs = 10_000): Promise<void> {
|
||||
const deadline = Date.now() + timeoutMs;
|
||||
while (!window.turnstile && Date.now() < deadline) {
|
||||
await new Promise((r) => setTimeout(r, 50));
|
||||
}
|
||||
}
|
||||
|
||||
export type TurnstileHandle = { reset: () => void };
|
||||
|
||||
type TurnstileProps = {
|
||||
siteKey: string;
|
||||
/** Fires with the solved token, or "" whenever the token becomes unusable. */
|
||||
onToken: (token: string) => void;
|
||||
onError?: () => void;
|
||||
className?: string;
|
||||
};
|
||||
|
||||
/**
|
||||
* Renders the Turnstile challenge. The parent owns the token and must send it
|
||||
* as the `x-captcha-response` header; verification happens server-side in
|
||||
* `lib/auth/auth.ts`.
|
||||
*/
|
||||
export const Turnstile = forwardRef<TurnstileHandle, TurnstileProps>(function Turnstile(
|
||||
{ siteKey, onToken, onError, className },
|
||||
ref
|
||||
) {
|
||||
const containerRef = useRef<HTMLDivElement>(null);
|
||||
const widgetIdRef = useRef<string | null>(null);
|
||||
|
||||
// Hold the callbacks in refs so re-renders never tear down the widget —
|
||||
// re-rendering it would drop a token the user already solved.
|
||||
const onTokenRef = useRef(onToken);
|
||||
const onErrorRef = useRef(onError);
|
||||
onTokenRef.current = onToken;
|
||||
onErrorRef.current = onError;
|
||||
|
||||
useImperativeHandle(
|
||||
ref,
|
||||
() => ({
|
||||
reset() {
|
||||
if (widgetIdRef.current && window.turnstile) {
|
||||
window.turnstile.reset(widgetIdRef.current);
|
||||
onTokenRef.current("");
|
||||
}
|
||||
},
|
||||
}),
|
||||
[]
|
||||
);
|
||||
|
||||
useEffect(() => {
|
||||
let cancelled = false;
|
||||
|
||||
loadTurnstileScript()
|
||||
.then(() => waitForTurnstileApi())
|
||||
.then(() => {
|
||||
if (cancelled || widgetIdRef.current || !containerRef.current || !window.turnstile) return;
|
||||
widgetIdRef.current = window.turnstile.render(containerRef.current, {
|
||||
sitekey: siteKey,
|
||||
// The auth screens render outside next-themes' provider, so let the
|
||||
// widget follow the OS colour scheme instead of the app's theme.
|
||||
theme: "auto",
|
||||
callback: (token: string) => onTokenRef.current(token),
|
||||
// Any of these means we no longer hold a usable token.
|
||||
"error-callback": () => {
|
||||
onTokenRef.current("");
|
||||
onErrorRef.current?.();
|
||||
},
|
||||
"expired-callback": () => onTokenRef.current(""),
|
||||
"timeout-callback": () => onTokenRef.current(""),
|
||||
});
|
||||
})
|
||||
.catch(() => onErrorRef.current?.());
|
||||
|
||||
return () => {
|
||||
cancelled = true;
|
||||
const id = widgetIdRef.current;
|
||||
widgetIdRef.current = null;
|
||||
if (id && window.turnstile) {
|
||||
try {
|
||||
window.turnstile.remove(id);
|
||||
} catch {
|
||||
// Widget already gone (e.g. React 18/19 StrictMode double-invoke).
|
||||
}
|
||||
}
|
||||
};
|
||||
}, [siteKey]);
|
||||
|
||||
return <div ref={containerRef} className={className} />;
|
||||
});
|
||||
@@ -1,23 +1,50 @@
|
||||
import { JsonLd } from "@/components/seo/json-ld";
|
||||
import { breadcrumbSchema, graph, webPageSchema } from "@/lib/schema";
|
||||
import { toIsoDate } from "@/lib/seo";
|
||||
|
||||
export interface LegalSection {
|
||||
heading: string;
|
||||
paragraphs: string[];
|
||||
bullets?: string[];
|
||||
}
|
||||
|
||||
/** Shared layout for long-form legal documents (Privacy, Terms). */
|
||||
/**
|
||||
* Shared layout for long-form legal documents (Privacy, Terms, …).
|
||||
*
|
||||
* Also emits the page's structured data: every legal page has the same shape, so
|
||||
* the WebPage + BreadcrumbList nodes are built here from `path`/`description`
|
||||
* rather than repeated in each of the six route files.
|
||||
*/
|
||||
export function LegalDoc({
|
||||
title,
|
||||
updated,
|
||||
intro,
|
||||
sections,
|
||||
path,
|
||||
description,
|
||||
}: {
|
||||
title: string;
|
||||
updated: string;
|
||||
intro: string;
|
||||
sections: LegalSection[];
|
||||
/** Root-relative URL of this document, e.g. "/terms". */
|
||||
path: string;
|
||||
/** Same one-line summary used for the page's meta description. */
|
||||
description: string;
|
||||
}) {
|
||||
const dateModified = toIsoDate(updated);
|
||||
|
||||
return (
|
||||
<div className="container max-w-3xl py-20 md:py-24">
|
||||
<JsonLd
|
||||
data={graph(
|
||||
{
|
||||
...webPageSchema({ path, name: title, description }),
|
||||
...(dateModified ? { dateModified } : {}),
|
||||
},
|
||||
breadcrumbSchema([{ name: title, path }])
|
||||
)}
|
||||
/>
|
||||
<p className="text-[13px] font-semibold uppercase tracking-[0.04em] text-brand">Legal</p>
|
||||
<h1 className="mt-3 font-display text-4xl font-extrabold tracking-tight md:text-5xl">
|
||||
{title}
|
||||
|
||||
@@ -0,0 +1,23 @@
|
||||
/**
|
||||
* Renders a JSON-LD structured-data block.
|
||||
*
|
||||
* No CSP nonce is applied — deliberately. `application/ld+json` is a data block,
|
||||
* not an executable script: browsers bail out of script preparation before the
|
||||
* `script-src` check runs, so the strict nonce policy set in middleware.ts never
|
||||
* blocks it. Threading a nonce through would require reading `headers()`, which
|
||||
* would opt every marketing page out of static rendering for no benefit.
|
||||
*
|
||||
* The payload is serialized with `<` escaped so a value containing "</script>"
|
||||
* cannot break out of the block.
|
||||
*/
|
||||
export function JsonLd({ data }: { data: Record<string, unknown> | Record<string, unknown>[] }) {
|
||||
return (
|
||||
<script
|
||||
type="application/ld+json"
|
||||
// eslint-disable-next-line react/no-danger
|
||||
dangerouslySetInnerHTML={{
|
||||
__html: JSON.stringify(data).replace(/</g, "\\u003c"),
|
||||
}}
|
||||
/>
|
||||
);
|
||||
}
|
||||
Reference in New Issue
Block a user