Skip to content

armgit / Cap

Public Imported from GitHub
0

Open source Loom alternative. Beautiful, shareable screen recordings.

fix(billing): validate priceId against allowlist and sanitize quantity at checkout endpoints (#2222)

massmarketconsumer-archa802d7103db3
diff --git a/apps/web/__tests__/unit/mobile-checkout.test.ts b/apps/web/__tests__/unit/mobile-checkout.test.ts
index 5eecd2e22..c74f55175 100644
--- a/apps/web/__tests__/unit/mobile-checkout.test.ts
+++ b/apps/web/__tests__/unit/mobile-checkout.test.ts
@@ -22,6 +22,7 @@ vi.mock("@cap/utils", () => ({
sessions: { create: checkoutMocks.create },
},
}),
+ isValidStripePlanPriceId: (id: string) => id === "price_pro",
}));
vi.mock("@/lib/server-analytics", () => ({
@@ -79,6 +80,19 @@ describe("checkout redirects", () => {
});
});
+ it("rejects non-allowlisted arbitrary priceId with 400", async () => {
+ const response = await startGuestCheckout(
+ makeGuestCheckoutRequest({
+ priceId: "price_arbitrary_attacker_id",
+ quantity: 1,
+ }),
+ );
+
+ expect(response.status).toBe(400);
+ expect(await response.json()).toEqual({ error: "Invalid priceId" });
+ expect(checkoutMocks.create).not.toHaveBeenCalled();
+ });
+
it("sends mobile checkout results through the HTTPS completion route", () => {
expect(getCheckoutRedirectUrls("mobile", "https://cap.so/")).toEqual({
successUrl: "https://cap.so/mobile/checkout/complete?checkout=success",
diff --git a/apps/web/__tests__/unit/subscribe-checkout.test.ts b/apps/web/__tests__/unit/subscribe-checkout.test.ts
new file mode 100644
index 000000000..20892bf2c
--- /dev/null
+++ b/apps/web/__tests__/unit/subscribe-checkout.test.ts
@@ -0,0 +1,134 @@
+import { beforeEach, describe, expect, it, vi } from "vitest";
+import { isValidStripePlanPriceId, STRIPE_PLAN_IDS } from "@cap/utils";
+import { POST as subscribe } from "@/app/api/settings/billing/subscribe/route";
+
+const checkoutMocks = vi.hoisted(() => ({
+ create: vi.fn(),
+ track: vi.fn(() => Promise.resolve()),
+ getCurrentUser: vi.fn(),
+ dbUpdate: vi.fn(),
+}));
+
+vi.mock("@cap/env", () => ({
+ buildEnv: { NEXT_PUBLIC_IS_CAP: "true" },
+ serverEnv: () => ({ WEB_URL: "https://cap.so" }),
+}));
+
+vi.mock("@cap/database/auth/session", () => ({
+ getCurrentUser: checkoutMocks.getCurrentUser,
+}));
+
+vi.mock("@cap/database", () => ({
+ db: () => ({
+ update: () => ({
+ set: () => ({
+ where: checkoutMocks.dbUpdate,
+ }),
+ }),
+ }),
+}));
+
+vi.mock("@cap/database/schema", () => ({
+ users: { id: "id" },
+}));
+
+vi.mock("@cap/utils", async (importOriginal) => {
+ const actual = await importOriginal<typeof import("@cap/utils")>();
+ return {
+ ...actual,
+ stripe: () => ({
+ customers: {
+ list: vi.fn().mockResolvedValue({ data: [] }),
+ create: vi.fn().mockResolvedValue({ id: "cus_new" }),
+ update: vi.fn().mockResolvedValue({ id: "cus_new" }),
+ },
+ checkout: {
+ sessions: { create: checkoutMocks.create },
+ },
+ }),
+ userIsPro: vi.fn().mockReturnValue(false),
+ };
+});
+
+vi.mock("@/lib/server-analytics", () => ({
+ trackServerEvent: checkoutMocks.track,
+}));
+
+const makeSubscribeRequest = (body: Record<string, unknown>) =>
+ new Request("https://cap.so/api/settings/billing/subscribe", {
+ method: "POST",
+ headers: { "Content-Type": "application/json" },
+ body: JSON.stringify(body),
+ }) as unknown as import("next/server").NextRequest;
+
+describe("Stripe plan allowlist", () => {
+ it("accepts only legitimate Pro plan price IDs", () => {
+ expect(isValidStripePlanPriceId(STRIPE_PLAN_IDS.development.yearly)).toBe(
+ true,
+ );
+ expect(isValidStripePlanPriceId(STRIPE_PLAN_IDS.development.monthly)).toBe(
+ true,
+ );
+ expect(isValidStripePlanPriceId(STRIPE_PLAN_IDS.production.yearly)).toBe(
+ true,
+ );
+ expect(isValidStripePlanPriceId(STRIPE_PLAN_IDS.production.monthly)).toBe(
+ true,
+ );
+
+ expect(isValidStripePlanPriceId("price_arbitrary_attacker_id")).toBe(false);
+ expect(isValidStripePlanPriceId("price_free_tier")).toBe(false);
+ expect(isValidStripePlanPriceId("")).toBe(false);
+ });
+});
+
+describe("POST /api/settings/billing/subscribe", () => {
+ beforeEach(() => {
+ vi.clearAllMocks();
+ checkoutMocks.getCurrentUser.mockResolvedValue({
+ id: "user_123",
+ email: "[email protected]",
+ stripeCustomerId: "cus_123",
+ });
+ checkoutMocks.create.mockResolvedValue({
+ id: "cs_test",
+ url: "https://pay.cap.so/session",
+ });
+ });
+
+ it("rejects arbitrary price IDs with 400", async () => {
+ const response = await subscribe(
+ makeSubscribeRequest({
+ priceId: "price_arbitrary_malicious",
+ quantity: 1,
+ }),
+ );
+
+ expect(response.status).toBe(400);
+ expect(await response.json()).toEqual({
+ error: true,
+ message: "Invalid priceId",
+ });
+ expect(checkoutMocks.create).not.toHaveBeenCalled();
+ });
+
+ it("accepts valid Pro plan price ID and creates checkout session", async () => {
+ const response = await subscribe(
+ makeSubscribeRequest({
+ priceId: STRIPE_PLAN_IDS.development.monthly,
+ quantity: 2,
+ }),
+ );
+
+ expect(response.status).toBe(200);
+ expect(checkoutMocks.create).toHaveBeenCalledWith(
+ expect.objectContaining({
+ customer: "cus_123",
+ line_items: [
+ { price: STRIPE_PLAN_IDS.development.monthly, quantity: 2 },
+ ],
+ mode: "subscription",
+ }),
+ );
+ });
+});
diff --git a/apps/web/app/api/desktop/[...route]/root.ts b/apps/web/app/api/desktop/[...route]/root.ts
index 9c14a656c..5af87f039 100644
--- a/apps/web/app/api/desktop/[...route]/root.ts
+++ b/apps/web/app/api/desktop/[...route]/root.ts
@@ -10,6 +10,7 @@ import {
} from "@cap/database/schema";
import { serverEnv } from "@cap/env";
import {
+ isValidStripePlanPriceId,
isProSubscription,
STRIPE_AVAILABLE,
stripe,
@@ -705,7 +706,9 @@ app.post(
zValidator(
"json",
z.object({
- priceId: z.string(),
+ priceId: z.string().refine((id) => isValidStripePlanPriceId(id), {
+ message: "Invalid priceId",
+ }),
platform: z.literal("mobile").optional(),
}),
),
diff --git a/apps/web/app/api/settings/billing/guest-checkout/route.ts b/apps/web/app/api/settings/billing/guest-checkout/route.ts
index 6726ae711..0caaa2ccd 100644
--- a/apps/web/app/api/settings/billing/guest-checkout/route.ts
+++ b/apps/web/app/api/settings/billing/guest-checkout/route.ts
@@ -1,5 +1,5 @@
import { serverEnv } from "@cap/env";
-import { stripe } from "@cap/utils";
+import { isValidStripePlanPriceId, stripe } from "@cap/utils";
import type { NextRequest } from "next/server";
import { getCheckoutRedirectUrls } from "@/lib/mobile-checkout";
import { trackServerEvent } from "@/lib/server-analytics";
@@ -11,11 +11,23 @@ export async function POST(request: NextRequest) {
console.log("Received guest checkout request:", { priceId, quantity });
- if (!priceId) {
- console.error("Missing required priceId");
- return Response.json({ error: "priceId is required" }, { status: 400 });
+ if (
+ !priceId ||
+ typeof priceId !== "string" ||
+ !isValidStripePlanPriceId(priceId)
+ ) {
+ console.error("Invalid or missing priceId");
+ return Response.json({ error: "Invalid priceId" }, { status: 400 });
}
+ const safeQuantity =
+ typeof quantity === "number" &&
+ Number.isInteger(quantity) &&
+ quantity >= 1 &&
+ quantity <= 1000
+ ? quantity
+ : 1;
+
try {
console.log("Creating guest checkout session");
const redirects = getCheckoutRedirectUrls(
@@ -23,7 +35,7 @@ export async function POST(request: NextRequest) {
serverEnv().WEB_URL,
);
const checkoutSession = await stripe().checkout.sessions.create({
- line_items: [{ price: priceId, quantity: quantity || 1 }],
+ line_items: [{ price: priceId, quantity: safeQuantity }],
mode: "subscription",
success_url: redirects.successUrl,
cancel_url: redirects.cancelUrl,
diff --git a/apps/web/app/api/settings/billing/subscribe/route.ts b/apps/web/app/api/settings/billing/subscribe/route.ts
index 397662e77..379b0e432 100644
--- a/apps/web/app/api/settings/billing/subscribe/route.ts
+++ b/apps/web/app/api/settings/billing/subscribe/route.ts
@@ -2,7 +2,7 @@ import { db } from "@cap/database";
import { getCurrentUser } from "@cap/database/auth/session";
import { users } from "@cap/database/schema";
import { serverEnv } from "@cap/env";
-import { stripe, userIsPro } from "@cap/utils";
+import { isValidStripePlanPriceId, stripe, userIsPro } from "@cap/utils";
import { eq } from "drizzle-orm";
import type { NextRequest } from "next/server";
import type Stripe from "stripe";
@@ -13,11 +13,26 @@ export async function POST(request: NextRequest) {
let customerId = user?.stripeCustomerId;
const { priceId, quantity, isOnBoarding } = await request.json();
- if (!priceId) {
- console.error("Price ID not found");
- return Response.json({ error: true }, { status: 400 });
+ if (
+ !priceId ||
+ typeof priceId !== "string" ||
+ !isValidStripePlanPriceId(priceId)
+ ) {
+ console.error("Invalid or missing priceId");
+ return Response.json(
+ { error: true, message: "Invalid priceId" },
+ { status: 400 },
+ );
}
+ const safeQuantity =
+ typeof quantity === "number" &&
+ Number.isInteger(quantity) &&
+ quantity >= 1 &&
+ quantity <= 1000
+ ? quantity
+ : 1;
+
if (!user) {
console.error("User not found");
return Response.json({ error: true, auth: false }, { status: 401 });
@@ -65,7 +80,7 @@ export async function POST(request: NextRequest) {
const checkoutSession = await stripe().checkout.sessions.create({
customer: customerId as string,
- line_items: [{ price: priceId, quantity: quantity }],
+ line_items: [{ price: priceId, quantity: safeQuantity }],
mode: "subscription",
success_url: isOnBoarding
? `${serverEnv().WEB_URL}/dashboard/settings/organization?upgrade=true&session_id={CHECKOUT_SESSION_ID}`
@@ -84,7 +99,7 @@ export async function POST(request: NextRequest) {
if (checkoutSession.url) {
trackServerEvent(user.id, "checkout_started", {
price_id: priceId,
- quantity: quantity,
+ quantity: safeQuantity,
platform: "web",
});
diff --git a/packages/utils/src/constants/plans.ts b/packages/utils/src/constants/plans.ts
index 92c4ebcdb..749702e5f 100644
--- a/packages/utils/src/constants/plans.ts
+++ b/packages/utils/src/constants/plans.ts
@@ -16,6 +16,24 @@ export const STRIPE_PLAN_IDS = {
},
};
+export const VALID_STRIPE_PLAN_PRICE_IDS = new Set<string>([
+ STRIPE_PLAN_IDS.development.yearly,
+ STRIPE_PLAN_IDS.development.monthly,
+ STRIPE_PLAN_IDS.production.yearly,
+ STRIPE_PLAN_IDS.production.monthly,
+]);
+
+export const isValidStripePlanPriceId = (
+ priceId: string,
+ environment?: "development" | "production",
+): boolean => {
+ if (environment) {
+ const envPlans = STRIPE_PLAN_IDS[environment];
+ return priceId === envPlans.yearly || priceId === envPlans.monthly;
+ }
+ return VALID_STRIPE_PLAN_PRICE_IDS.has(priceId);
+};
+
export const STRIPE_SIGNED_BAA_PRICE_IDS: Record<string, string> = {
development: "price_1U5xKIFJxA1XpeSsdg4Q8H3Z",
production: "price_1U6C99FJxA1XpeSsUg1rXHo2",