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>
94 lines
3.6 KiB
TypeScript
94 lines
3.6 KiB
TypeScript
import { Pool } from "pg";
|
|
import {
|
|
RateLimiterMemory,
|
|
RateLimiterPostgres,
|
|
type RateLimiterAbstract,
|
|
} from "rate-limiter-flexible";
|
|
|
|
/**
|
|
* Backend selection (default = in-memory):
|
|
*
|
|
* - DEFAULT: RateLimiterMemory — per-process counters. Fine for a single
|
|
* instance (the Plesk VPS). No DB connection is ever opened in this mode.
|
|
* - OPT-IN: set RATE_LIMIT_BACKEND="postgres" *and* provide DATABASE_URL to
|
|
* share limits across multiple instances via RateLimiterPostgres. The
|
|
* limiter table ("rate_limits") is created automatically by
|
|
* rate-limiter-flexible on first use, so no migration is required.
|
|
*
|
|
* The pg Pool is created lazily on first consume — importing this module never
|
|
* connects to the database, so memory mode stays connection-free.
|
|
*/
|
|
const usePostgres =
|
|
process.env.RATE_LIMIT_BACKEND === "postgres" && !!process.env.DATABASE_URL;
|
|
|
|
const limiters = new Map<string, RateLimiterAbstract>();
|
|
|
|
// Lazily-created shared pg Pool. Constructing it does NOT open a connection
|
|
// (pg connects on first query), and it is only built when a Postgres-backed
|
|
// limiter is first needed — so memory mode never creates a pool.
|
|
let pgPool: Pool | null = null;
|
|
function getPool(): Pool {
|
|
if (!pgPool) {
|
|
pgPool = new Pool({ connectionString: process.env.DATABASE_URL });
|
|
}
|
|
return pgPool;
|
|
}
|
|
|
|
function getLimiter(name: string, points: number, durationSec: number): RateLimiterAbstract {
|
|
let limiter = limiters.get(name);
|
|
if (!limiter) {
|
|
if (usePostgres) {
|
|
// The constructor opens the (lazy) pool and ensures the backing table
|
|
// exists; ready before the first consume() thanks to the insurance limiter.
|
|
limiter = new RateLimiterPostgres({
|
|
storeClient: getPool(),
|
|
tableName: "rate_limits",
|
|
keyPrefix: name,
|
|
points,
|
|
duration: durationSec,
|
|
// If Postgres is briefly unreachable, degrade to per-process counting
|
|
// instead of failing the request outright.
|
|
insuranceLimiter: new RateLimiterMemory({ points, duration: durationSec }),
|
|
});
|
|
} else {
|
|
limiter = new RateLimiterMemory({ points, duration: durationSec });
|
|
}
|
|
limiters.set(name, limiter);
|
|
}
|
|
return limiter;
|
|
}
|
|
|
|
export interface RateLimitResult {
|
|
ok: boolean;
|
|
retryAfterSec?: number;
|
|
}
|
|
|
|
/** Consume one unit for `key` under a named bucket; returns ok=false when throttled. */
|
|
export async function rateLimit(
|
|
bucket: string,
|
|
key: string,
|
|
opts: { points: number; durationSec: number }
|
|
): Promise<RateLimitResult> {
|
|
const limiter = getLimiter(bucket, opts.points, opts.durationSec);
|
|
try {
|
|
await limiter.consume(key);
|
|
return { ok: true };
|
|
} catch (res) {
|
|
const retryAfterSec = Math.ceil((res as { msBeforeNext?: number }).msBeforeNext ?? 1000) / 1000;
|
|
return { ok: false, retryAfterSec: Math.ceil(retryAfterSec) };
|
|
}
|
|
}
|
|
|
|
// Common presets.
|
|
export const LIMITS = {
|
|
generation: { points: 10, durationSec: 60 }, // 10 generations / min / user
|
|
repurpose: { points: 15, durationSec: 60 },
|
|
api: { points: 60, durationSec: 60 }, // 60 API calls / min / key (writes)
|
|
read: { points: 120, durationSec: 60 }, // 120 read/list calls / min / key
|
|
stream: { points: 30, durationSec: 60 }, // SSE (re)connects / min / user
|
|
publicMedia: { points: 120, durationSec: 60 }, // anon audio/cover (Range) reqs / min / IP
|
|
seriesPlan: { points: 5, durationSec: 3600 }, // season plans / hr / user (uncapped GPT-4o call)
|
|
export: { points: 10, durationSec: 60 }, // zip exports / min / user (buffers MP3 in memory)
|
|
webhook: { points: 60, durationSec: 60 }, // anon webhook posts / min / IP
|
|
} as const;
|