Security & robustness hardening pass

Cross-cutting input-validation, isolation, and DoS-resistance fixes across
the app, API, billing, queue, and infra layers.

- Runtime validation (zod) for client-supplied admin actions (role/plan/
  limits), series generation index, and all pg-boss queue payloads
- Auth: require email verification before sign-in; reject weak/placeholder/
  short BETTER_AUTH_SECRET in production
- Billing: sanitize Stripe/PayPal errors (log server-side, generic to client);
  race-safe subscription upsert; only count "processed" webhook events as
  handled; verify org membership in getEffectivePlan to block plan escalation
- Series generation: reserve usage up front and refund on failure; bill the
  owning org, not the caller's active org
- Injection defenses: HTML-escape user fields in emails, strip CR/LF from
  subject/recipient, validate ElevenLabs voiceId before URL interpolation
- Media routes: stream off disk instead of buffering whole files; rate-limit
  anonymous public audio/cover endpoints by client IP
This commit is contained in:
Leon Serfaty
2026-06-20 20:59:03 -04:00
parent cd1d6a1a28
commit 51c541ad22
21 changed files with 489 additions and 152 deletions
+52 -6
View File
@@ -1,13 +1,58 @@
import { RateLimiterMemory } from "rate-limiter-flexible";
import { Pool } from "pg";
import {
RateLimiterMemory,
RateLimiterPostgres,
type RateLimiterAbstract,
} from "rate-limiter-flexible";
// In-memory limiters (no Redis). Fine for a single-instance Plesk deployment;
// swap for RateLimiterPostgres if the app is ever scaled to multiple nodes.
const limiters = new Map<string, RateLimiterMemory>();
/**
* 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;
function getLimiter(name: string, points: number, durationSec: number): RateLimiterMemory {
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) {
limiter = new RateLimiterMemory({ points, duration: durationSec });
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;
@@ -41,4 +86,5 @@ export const LIMITS = {
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
} as const;