Files
Leon SerfatyandClaude Opus 5 3e9ba07175 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>
2026-09-07 11:10:55 -04:00

133 lines
5.0 KiB
TypeScript

import type { Metadata } from "next";
import { notFound } from "next/navigation";
import Link from "next/link";
import { Mic2, Repeat } from "lucide-react";
import { requireAuth } from "@/lib/auth/guards";
import { prisma } from "@/lib/db";
import { PageHeader } from "@/components/app/page-header";
import { GenerationProgress } from "@/components/app/generation-progress";
import { ScriptEditor } from "@/components/app/script-editor";
import { AudioPlayer } from "@/components/app/audio-player";
import { EpisodeActions } from "@/components/app/episode-actions";
import { Card, CardContent } from "@/components/ui/card";
import { Button } from "@/components/ui/button";
import type { StructuredScript } from "@/lib/ai/types";
export async function generateMetadata({
params,
}: {
params: Promise<{ id: string }>;
}): Promise<Metadata> {
const { id } = await params;
// Title only — this is an authed page and the route group is already noindex.
const episode = await prisma.episode.findUnique({ where: { id }, select: { title: true } });
return { title: episode?.title ?? "Episode" };
}
export default async function EpisodePage({ params }: { params: Promise<{ id: string }> }) {
const { id } = await params;
const session = await requireAuth();
const episode = await prisma.episode.findUnique({
where: { id },
include: { script: true, audioAsset: true, coverArt: true, speakers: true },
});
if (!episode) notFound();
if (episode.userId !== session.user.id && session.user.role !== "admin") notFound();
const inProgress = !["READY", "FAILED"].includes(episode.status);
const speakerNames: Record<string, string> = {};
for (const s of episode.speakers) speakerNames[s.speakerKey] = s.displayName;
return (
<>
<PageHeader
title={episode.title}
description={`${episode.format.replace("_", "-").toLowerCase()} · ${episode.language.toUpperCase()} · ${episode.targetLengthMin} min`}
action={
!inProgress && !episode.moderatedAt ? (
<EpisodeActions episodeId={episode.id} initialShareId={episode.shareId} />
) : undefined
}
/>
{episode.moderatedAt ? (
<div className="mb-6 rounded-2xl border border-destructive/30 bg-destructive/5 p-4">
<p className="font-medium text-destructive">This episode was removed</p>
<p className="mt-1 text-sm text-muted-foreground">
It was reviewed against our Acceptable Use Policy and taken down on{" "}
{episode.moderatedAt.toLocaleDateString()}. Its public link and downloads are
disabled. If you think this was a mistake, reply to your support thread and we
will take another look.
</p>
</div>
) : null}
{episode.status === "FAILED" || inProgress ? (
<GenerationProgress
episodeId={episode.id}
initialStatus={episode.status}
initialStage={episode.stage}
initialError={episode.errorMessage}
/>
) : (
<div className="grid gap-6 lg:grid-cols-3">
<div className="space-y-6 lg:col-span-1">
<Card className="overflow-hidden">
<div className="aspect-square bg-muted">
{episode.coverArt ? (
// eslint-disable-next-line @next/next/no-img-element
<img
src={`/api/assets/${episode.coverArt.storageKey}`}
alt={episode.title}
className="h-full w-full object-cover"
/>
) : (
<div className="flex h-full w-full items-center justify-center text-muted-foreground">
<Mic2 className="h-10 w-10" />
</div>
)}
</div>
</Card>
{episode.audioAsset && (
<Card>
<CardContent className="pt-6">
<AudioPlayer
storageKey={episode.audioAsset.storageKey}
durationSec={episode.audioAsset.durationSec}
episodeId={episode.id}
/>
</CardContent>
</Card>
)}
<Button asChild variant="outline" className="w-full">
<Link href={`/episodes/${episode.id}/repurpose`}>
<Repeat className="h-4 w-4" /> Repurpose content
</Link>
</Button>
</div>
<div className="lg:col-span-2">
{episode.script ? (
<ScriptEditor
key={episode.script.version}
episodeId={episode.id}
script={episode.script.content as unknown as StructuredScript}
speakerNames={speakerNames}
/>
) : (
<Card>
<CardContent className="py-12 text-center text-muted-foreground">
No script available.
</CardContent>
</Card>
)}
</div>
</div>
)}
</>
);
}