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
+134 -1
View File
@@ -1,10 +1,30 @@
import { betterAuth } from "better-auth";
import { prismaAdapter } from "better-auth/adapters/prisma";
import { admin, organization } from "better-auth/plugins";
import { admin, captcha, organization } from "better-auth/plugins";
import { nextCookies } from "better-auth/next-js";
import { createAuthMiddleware, APIError } from "better-auth/api";
import { prisma } from "@/lib/db";
import { sendEmail, emailLayout } from "@/lib/email";
/**
* Enforce the `signups_enabled` kill-switch on the REAL registration path.
*
* The sign-up page also checks this flag, but that only hides the form — a
* client can still POST /api/auth/sign-up/email directly. This is the actual
* boundary. `@/lib/flags` is imported dynamically because it pulls in
* `server-only`, which throws when lib/* is loaded outside Next's RSC bundler
* (the worker runs under plain tsx); a lazy import keeps that cost off the
* module graph until an actual sign-up is attempted.
*/
async function assertSignupsEnabled(): Promise<void> {
const { isFlagEnabled } = await import("@/lib/flags");
if (!(await isFlagEnabled("signups_enabled"))) {
throw new APIError("FORBIDDEN", {
message: "Sign-ups are currently paused. Please check back soon.",
});
}
}
const appUrl = process.env.NEXT_PUBLIC_APP_URL || "http://localhost:3000";
const googleConfigured = !!(process.env.GOOGLE_CLIENT_ID && process.env.GOOGLE_CLIENT_SECRET);
@@ -24,6 +44,81 @@ if (secretIsWeak && process.env.NODE_ENV === "production") {
);
}
/**
* Guard impersonation — the single most powerful action in the platform.
*
* Two problems with leaving this to the better-auth admin plugin alone:
* 1. It is the ONLY admin mutation with no entry in our audit log, so a
* compromised admin account can read every user's data untraceably.
* 2. Nothing stops one admin impersonating another, which is lateral
* movement between privileged accounts rather than support access.
*
* Enforcing it here (rather than in the server action) means a direct POST to
* /api/auth/admin/impersonate-user is covered too.
*/
async function guardImpersonation(headers: Headers, targetUserId: unknown): Promise<void> {
if (typeof targetUserId !== "string" || !targetUserId) {
throw new APIError("BAD_REQUEST", { message: "A target user id is required." });
}
// `auth` is referenced lazily: this runs per-request, long after module init.
const session = await auth.api.getSession({ headers });
if (!session || session.user.role !== "admin") {
throw new APIError("FORBIDDEN", { message: "Not allowed." });
}
const target = await prisma.user.findUnique({
where: { id: targetUserId },
select: { id: true, role: true, email: true },
});
if (!target) throw new APIError("NOT_FOUND", { message: "User not found." });
if (target.role === "admin") {
throw new APIError("FORBIDDEN", {
message: "Admins cannot impersonate other admins.",
});
}
await prisma.auditLog.create({
data: {
actorId: session.user.id,
actorType: "admin",
action: "user.impersonate",
target: target.id,
metadata: { targetEmail: target.email },
},
});
}
/**
* Cloudflare Turnstile — bot protection on the public auth endpoints.
*
* The plugin verifies the `x-captcha-response` header server-side against
* Cloudflare's siteverify API BEFORE the handler runs, so it is the real
* boundary: hiding/!rendering the widget client-side proves nothing, and a
* bot POSTing straight to /api/auth/sign-in/email is rejected here.
*
* Enabled whenever TURNSTILE_SECRET_KEY is set. Required in production so a
* misconfigured deploy cannot silently ship with bot protection switched off
* (same fail-fast posture as BETTER_AUTH_SECRET above); left optional in
* dev/test so local work stays frictionless without Cloudflare keys.
*/
const turnstileSecretKey = process.env.TURNSTILE_SECRET_KEY?.trim();
const turnstileEnabled = !!turnstileSecretKey;
if (!turnstileEnabled && process.env.NODE_ENV === "production") {
throw new Error(
"TURNSTILE_SECRET_KEY must be set in production — Turnstile guards the sign-in, sign-up and password-reset endpoints."
);
}
// Guard the asymmetric misconfiguration: with a secret but no site key the server
// would demand a captcha token that no form can produce, locking every user out
// of sign-in. Fail the boot (and the production build) instead of shipping that.
if (
turnstileEnabled &&
!process.env.NEXT_PUBLIC_TURNSTILE_SITE_KEY?.trim() &&
process.env.NODE_ENV === "production"
) {
throw new Error(
"NEXT_PUBLIC_TURNSTILE_SITE_KEY must be set alongside TURNSTILE_SECRET_KEY — without it the auth forms cannot render the Turnstile widget and every sign-in would be rejected."
);
}
export const auth = betterAuth({
appName: "Podcast Distribution AI",
secret: process.env.BETTER_AUTH_SECRET,
@@ -93,6 +188,30 @@ export const auth = betterAuth({
accountLinking: { enabled: true, trustedProviders: ["google"] },
},
hooks: {
before: createAuthMiddleware(async (ctx) => {
if (ctx.path === "/sign-up/email") await assertSignupsEnabled();
if (ctx.path === "/admin/impersonate-user") {
await guardImpersonation(ctx.headers ?? new Headers(), (ctx.body as { userId?: unknown } | undefined)?.userId);
}
}),
},
// Catch-all: a user row is only ever created by registration, so this also
// covers first-time Google sign-in, which does not hit /sign-up/email.
// (scripts/create-admin.ts and scripts/seed-demo.ts write via Prisma directly
// and are intentionally unaffected.)
databaseHooks: {
user: {
create: {
before: async (user) => {
await assertSignupsEnabled();
return { data: user };
},
},
},
},
plugins: [
admin({ defaultRole: "user", adminRoles: ["admin"] }),
organization({
@@ -100,6 +219,20 @@ export const auth = betterAuth({
// Agency seat cap is enforced in app logic against the subscription's seat count.
membershipLimit: 5,
}),
// Bot protection. Endpoints listed explicitly rather than relying on the
// plugin default so adding one is a deliberate, reviewable change.
// `/reset-password` is intentionally absent: it is reached only with a
// single-use token emailed to a verified address, and challenging it would
// break the emailed-link flow.
...(turnstileEnabled
? [
captcha({
provider: "cloudflare-turnstile",
secretKey: turnstileSecretKey!,
endpoints: ["/sign-in/email", "/sign-up/email", "/request-password-reset"],
}),
]
: []),
// Must remain last: lets Server Actions / route handlers set auth cookies.
nextCookies(),
],
+16
View File
@@ -0,0 +1,16 @@
/**
* Cloudflare Turnstile site key, resolved server-side.
*
* Read at request time and passed down to the auth forms as a prop (the same
* pattern `googleEnabled` uses) rather than referenced inside a client
* component. `NEXT_PUBLIC_*` values referenced in client code are inlined at
* BUILD time, which would bake the key into the Docker image and require a
* rebuild to rotate it; reading it here keeps it a runtime concern.
*
* Null when unset — the forms then render without a challenge. The server-side
* enforcement in `lib/auth/auth.ts` is keyed off TURNSTILE_SECRET_KEY, which is
* mandatory in production.
*/
export function getTurnstileSiteKey(): string | null {
return process.env.NEXT_PUBLIC_TURNSTILE_SITE_KEY?.trim() || null;
}