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
+187
View File
@@ -75,6 +75,193 @@ export async function savePreferencesAction(
* cascades to sessions, accounts, episodes, series, usage and preferences. The
* client signs out after a successful response.
*/
export interface ActiveSession {
id: string;
createdAt: string;
expiresAt: string;
ipAddress: string | null;
userAgent: string | null;
current: boolean;
}
/**
* List the signed-in devices for the current user.
*
* Sessions are read straight from the DB (not the cookie cache) so a revoked
* session disappears immediately rather than lingering for the 60s cache window.
*/
export async function listSessionsAction(): Promise<{
ok: boolean;
error?: string;
sessions?: ActiveSession[];
}> {
const session = await getServerSession();
if (!session) return { ok: false, error: "You must be signed in." };
const rows = await prisma.session.findMany({
where: { userId: session.user.id, expiresAt: { gt: new Date() } },
orderBy: { createdAt: "desc" },
select: {
id: true,
token: true,
createdAt: true,
expiresAt: true,
ipAddress: true,
userAgent: true,
},
});
return {
ok: true,
sessions: rows.map((r) => ({
id: r.id,
createdAt: r.createdAt.toISOString(),
expiresAt: r.expiresAt.toISOString(),
ipAddress: r.ipAddress,
userAgent: r.userAgent,
// Compare on the session token, never on the id: the token is what the
// cookie actually carries, so this is the reliable "this device" marker.
current: r.token === session.session.token,
})),
};
}
/**
* Revoke one of the current user's sessions (sign out that device).
*
* Scoped by userId so a session id belonging to someone else can never be
* revoked, and the current session is protected — signing yourself out from
* here would be indistinguishable from a bug. Use the normal sign-out for that.
*/
export async function revokeSessionAction(
sessionId: string
): Promise<{ ok: boolean; error?: string }> {
const session = await getServerSession();
if (!session) return { ok: false, error: "You must be signed in." };
const target = await prisma.session.findFirst({
where: { id: sessionId, userId: session.user.id },
select: { id: true, token: true },
});
if (!target) return { ok: false, error: "Session not found." };
if (target.token === session.session.token) {
return { ok: false, error: "That's your current device — use Sign out instead." };
}
await prisma.session.delete({ where: { id: target.id } });
revalidatePath("/settings");
return { ok: true };
}
/** Sign out every other device, keeping the current one. */
export async function revokeOtherSessionsAction(): Promise<{
ok: boolean;
error?: string;
count?: number;
}> {
const session = await getServerSession();
if (!session) return { ok: false, error: "You must be signed in." };
const res = await prisma.session.deleteMany({
where: { userId: session.user.id, token: { not: session.session.token } },
});
revalidatePath("/settings");
return { ok: true, count: res.count };
}
/**
* Export everything we hold about the current user, as JSON (GDPR access
* request, self-serve).
*
* Deliberately excludes credentials: the `account` table holds password hashes
* and OAuth tokens, and nothing there is user-facing data. Media is referenced
* by storage key rather than inlined so the payload stays a reasonable size.
*/
export async function exportMyDataAction(): Promise<{
ok: boolean;
error?: string;
json?: string;
}> {
const session = await getServerSession();
if (!session) return { ok: false, error: "You must be signed in." };
const userId = session.user.id;
const [user, preferences, episodes, series, subscriptions, usage, apiKeys, memberships] =
await Promise.all([
prisma.user.findUnique({
where: { id: userId },
select: {
id: true,
name: true,
email: true,
emailVerified: true,
image: true,
createdAt: true,
updatedAt: true,
},
}),
prisma.userPreferences.findUnique({ where: { userId } }),
prisma.episode.findMany({
where: { userId },
orderBy: { createdAt: "desc" },
select: {
id: true,
title: true,
topic: true,
tone: true,
format: true,
language: true,
targetLengthMin: true,
status: true,
shareId: true,
createdAt: true,
script: { select: { content: true } },
audioAsset: { select: { storageKey: true, durationSec: true, format: true } },
coverArt: { select: { storageKey: true } },
repurposed: { select: { type: true, content: true, createdAt: true } },
},
}),
prisma.series.findMany({ where: { userId } }),
prisma.subscription.findMany({
where: { referenceId: userId },
select: {
plan: true,
status: true,
billingInterval: true,
provider: true,
periodStart: true,
periodEnd: true,
cancelAtPeriodEnd: true,
createdAt: true,
},
}),
prisma.usageRecord.findMany({ where: { ownerId: userId, ownerType: "user" } }),
prisma.apiKey.findMany({
where: { userId },
select: { id: true, name: true, createdAt: true, revokedAt: true },
}),
prisma.member.findMany({
where: { userId },
select: { role: true, createdAt: true, organization: { select: { name: true } } },
}),
]);
const payload = {
exportedAt: new Date().toISOString(),
note: "Credentials and authentication tokens are intentionally excluded. Audio and cover art are referenced by storage key; download them from each episode page.",
user,
preferences,
episodes,
series,
subscriptions,
usage,
apiKeys,
memberships,
};
return { ok: true, json: JSON.stringify(payload, null, 2) };
}
export async function deleteAccountAction(
confirmEmail: string
): Promise<{ ok: boolean; error?: string }> {