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

123 lines
4.5 KiB
TypeScript

/**
* Umami (self-hosted) analytics configuration and payload redaction.
*
* Two deliberate choices are encoded here:
*
* 1. The tracker is served same-origin through a rewrite (see `ANALYTICS_PROXY_PATH`
* and next.config.mjs) rather than from the Umami host directly. That keeps the
* strict CSP in middleware.ts untouched — `script-src`/`connect-src` stay
* `'self'` — and stops content blockers from dropping the request.
*
* 2. Nothing that identifies a user's content ever reaches the analytics database.
* See `redactUrl` / `redactTitle`.
*/
/** Same-origin prefix the tracker and its beacon are proxied through. */
export const ANALYTICS_PROXY_PATH = "/_a";
export interface UmamiConfig {
/** Origin of the Umami instance, e.g. "https://analytics.example.com". */
hostUrl: string;
websiteId: string;
}
/**
* Resolve the Umami config from the environment. Returns null when either value
* is absent, which disables analytics entirely (the default in development).
*
* Both are read at build time for statically rendered pages, so they must be
* present as build args in Docker — see the Dockerfile.
*/
export function umamiConfig(): UmamiConfig | null {
const hostUrl = process.env.UMAMI_HOST_URL?.trim().replace(/\/+$/, "");
const websiteId = process.env.UMAMI_WEBSITE_ID?.trim();
if (!hostUrl || !websiteId) return null;
return { hostUrl, websiteId };
}
/**
* Path segments that are opaque identifiers rather than page names.
*
* Sending them would put episode IDs, series IDs and — worst — unlisted share
* IDs into the analytics database. Share links are secret by design, so leaking
* one there effectively publishes it. Collapsing them also makes the reports
* useful: one "/episodes/[id]" row instead of thousands of singletons.
*/
export function redactPath(pathname: string): string {
const seg = pathname.split("/").filter(Boolean);
// "/episodes/new" is a real page; "/episodes/<cuid>" is not.
if (seg[0] === "episodes" && seg[1] && seg[1] !== "new") seg[1] = "[id]";
else if (seg[0] === "series" && seg[1]) seg[1] = "[id]";
else if (seg[0] === "p" && seg[1]) seg[1] = "[shareId]";
else if (seg[0] === "admin" && seg[1] === "users" && seg[2]) seg[2] = "[id]";
return `/${seg.join("/")}`;
}
/**
* Redact a full URL: collapse identifier segments and drop the query string and
* hash outright.
*
* The query string is the sharper hazard — /reset-password carries a live
* password-reset token in `?token=`, and /sign-in carries the visitor's intended
* destination in `?redirect=`. `data-exclude-search` already strips it; this is
* the second line of defence, and it also covers the referrer field, which the
* tracker fills from the previous URL.
*/
export function redactUrl(raw: string): string {
if (!raw) return raw;
try {
// Bare paths are the common case; the base only matters for absolute URLs.
const url = new URL(raw, "http://localhost");
const path = redactPath(url.pathname);
return url.origin === "http://localhost" && !raw.startsWith("http")
? path
: `${url.origin}${path}`;
} catch {
// Unparseable — return just the redacted path portion, never the raw value.
return redactPath(raw.split(/[?#]/)[0]);
}
}
/** Whether a path carries user content that its <title> would expose. */
function isRedacted(pathname: string): boolean {
return redactPath(pathname) !== pathname;
}
/**
* Page titles on detail routes are the user's own content — `generateMetadata`
* returns the episode or series title verbatim. Swap those for the route name so
* the reports stay readable without storing anyone's content.
*/
export function redactTitle(title: string, url: string): string {
let pathname: string;
try {
pathname = new URL(url, "http://localhost").pathname;
} catch {
pathname = url.split(/[?#]/)[0];
}
return isRedacted(pathname) ? `${redactPath(pathname)} · Podcast Distribution AI` : title;
}
/** The Umami event payload we are allowed to inspect and rewrite. */
export interface UmamiPayload {
url?: string;
referrer?: string;
title?: string;
[key: string]: unknown;
}
/** Apply every redaction rule to one outgoing event payload. */
export function redactPayload(payload: UmamiPayload): UmamiPayload {
const url = payload.url ? redactUrl(payload.url) : payload.url;
return {
...payload,
...(url !== undefined ? { url } : {}),
...(payload.referrer ? { referrer: redactUrl(payload.referrer) } : {}),
...(payload.title && payload.url
? { title: redactTitle(payload.title, payload.url) }
: {}),
};
}