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:
@@ -20,8 +20,12 @@ import type { PlanKey } from "@/lib/billing/plans";
|
||||
|
||||
type ActionResult = { ok: true; url?: string } | { ok: false; error: string };
|
||||
|
||||
// Billing calls hit upstream providers (Stripe/PayPal) whose error messages can
|
||||
// contain sensitive/verbose detail. Log the real error server-side, but return a
|
||||
// single generic message to the client so nothing upstream leaks to end users.
|
||||
function errMsg(e: unknown): string {
|
||||
return e instanceof Error ? e.message : "Something went wrong";
|
||||
console.error("[billing] action failed", e);
|
||||
return "Something went wrong with billing. Please try again.";
|
||||
}
|
||||
|
||||
export async function startStripeCheckoutAction(
|
||||
|
||||
+56
-25
@@ -5,9 +5,11 @@ import { z } from "zod";
|
||||
import type { Prisma } from "@prisma/client";
|
||||
import { getServerSession } from "@/lib/auth/guards";
|
||||
import { prisma } from "@/lib/db";
|
||||
import { subjectHasFeature } from "@/lib/billing/subscription";
|
||||
import { enforceLimit, LimitExceededError } from "@/lib/usage/limits";
|
||||
import { getEffectivePlan, subjectHasFeature } from "@/lib/billing/subscription";
|
||||
import { reserveLimit, LimitExceededError } from "@/lib/usage/limits";
|
||||
import { refundUsage } from "@/lib/usage/meter";
|
||||
import { enqueueEpisodeGeneration } from "@/lib/queue/pgboss";
|
||||
import type { UsageMetric } from "@/lib/billing/plans";
|
||||
import { FORMAT_SPEAKERS } from "@/lib/episodes/options";
|
||||
import { DEFAULT_VOICE_IDS, VOICE_CATALOG } from "@/lib/ai/voices";
|
||||
import { isFlagEnabled } from "@/lib/flags";
|
||||
@@ -62,17 +64,41 @@ export async function generateFromSeriesAction(
|
||||
return { ok: false, error: "Episode generation is temporarily paused. Please try again shortly." };
|
||||
}
|
||||
|
||||
// `index` is client-supplied and only TS-typed — validate it at runtime.
|
||||
if (!Number.isInteger(index) || index < 0) {
|
||||
return { ok: false, error: "Invalid episode index." };
|
||||
}
|
||||
|
||||
const series = await prisma.series.findUnique({ where: { id: seriesId } });
|
||||
if (!series || series.userId !== session.user.id) return { ok: false, error: "Not allowed." };
|
||||
if (!series || (series.userId !== session.user.id && session.user.role !== "admin")) {
|
||||
return { ok: false, error: "Not allowed." };
|
||||
}
|
||||
|
||||
const episodes = (series.plan as unknown as { title: string; topic: string; summary: string }[]) ?? [];
|
||||
const item = episodes[index];
|
||||
if (!item) return { ok: false, error: "Episode not found in plan." };
|
||||
|
||||
// Bill the generation against the org that OWNS the series (the resource being
|
||||
// acted on), and stamp the new episode with that same org, so the billing
|
||||
// subject and the episode's organizationId are always consistent — regardless
|
||||
// of the caller's currently-active org. getEffectivePlan verifies membership of
|
||||
// series.organizationId internally and falls back to the user subject otherwise.
|
||||
const orgId = series.organizationId ?? undefined;
|
||||
const { subjectId, subjectType } = await getEffectivePlan(session.user.id, orgId);
|
||||
|
||||
// Reserve quota atomically up front (a series generation consumes script +
|
||||
// audio). The worker won't re-meter; refund below if create/enqueue fails.
|
||||
const reserved: UsageMetric[] = [];
|
||||
const refundReserved = async () => {
|
||||
for (const m of reserved) await refundUsage(subjectId, subjectType, m);
|
||||
};
|
||||
try {
|
||||
await enforceLimit(session.user.id, "script", session.session.activeOrganizationId);
|
||||
await enforceLimit(session.user.id, "audio", session.session.activeOrganizationId);
|
||||
await reserveLimit(session.user.id, "script", orgId);
|
||||
reserved.push("script");
|
||||
await reserveLimit(session.user.id, "audio", orgId);
|
||||
reserved.push("audio");
|
||||
} catch (err) {
|
||||
await refundReserved();
|
||||
if (err instanceof LimitExceededError) {
|
||||
return { ok: false, error: `Monthly ${err.check.metric} limit reached.` };
|
||||
}
|
||||
@@ -85,25 +111,30 @@ export async function generateFromSeriesAction(
|
||||
elevenVoiceId: DEFAULT_VOICE_IDS[s.speakerKey] ?? VOICE_CATALOG[i % VOICE_CATALOG.length].id,
|
||||
}));
|
||||
|
||||
const episode = await prisma.episode.create({
|
||||
data: {
|
||||
userId: session.user.id,
|
||||
organizationId: series.organizationId ?? undefined,
|
||||
seriesId: series.id,
|
||||
title: item.title,
|
||||
topic: item.topic,
|
||||
tone: "Conversational",
|
||||
format: "SOLO",
|
||||
language: "en",
|
||||
targetLengthMin: 10,
|
||||
status: "QUEUED",
|
||||
stage: "Queued for generation",
|
||||
speakers: { create: speakers },
|
||||
jobs: { create: { type: "full", status: "queued" } },
|
||||
},
|
||||
});
|
||||
await enqueueEpisodeGeneration({ episodeId: episode.id, type: "full" });
|
||||
try {
|
||||
const episode = await prisma.episode.create({
|
||||
data: {
|
||||
userId: session.user.id,
|
||||
organizationId: orgId,
|
||||
seriesId: series.id,
|
||||
title: item.title,
|
||||
topic: item.topic,
|
||||
tone: "Conversational",
|
||||
format: "SOLO",
|
||||
language: "en",
|
||||
targetLengthMin: 10,
|
||||
status: "QUEUED",
|
||||
stage: "Queued for generation",
|
||||
speakers: { create: speakers },
|
||||
jobs: { create: { type: "full", status: "queued" } },
|
||||
},
|
||||
});
|
||||
await enqueueEpisodeGeneration({ episodeId: episode.id, type: "full" });
|
||||
|
||||
revalidatePath(`/series/${seriesId}`);
|
||||
return { ok: true, episodeId: episode.id };
|
||||
revalidatePath(`/series/${seriesId}`);
|
||||
return { ok: true, episodeId: episode.id };
|
||||
} catch (err) {
|
||||
await refundReserved();
|
||||
throw err;
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user