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:
Leon Serfaty
2026-09-07 11:10:55 -04:00
co-authored by Claude Opus 5
parent 35379212fb
commit 3e9ba07175
96 changed files with 3982 additions and 576 deletions
+154 -7
View File
@@ -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"