Skip to content

Rallly is an open-source scheduling and collaboration tool designed to make organizing events and meetings easier.

🔒️ Bind the Stripe checkout return endpoint to the signed-in user (#3251)

Luke Vella17353099d3db
diff --git a/apps/web/src/app/api/stripe/portal/route.ts b/apps/web/src/app/api/stripe/portal/route.ts
index bade34a81..0475c257f 100644
--- a/apps/web/src/app/api/stripe/portal/route.ts
+++ b/apps/web/src/app/api/stripe/portal/route.ts
@@ -3,7 +3,9 @@ import type { NextRequest } from "next/server";
import { NextResponse } from "next/server";
import { createStripePortalSession } from "@/features/billing/mutations";
+import { subscriptionCheckoutMetadataSchema } from "@/features/billing/schema";
import { getStripe } from "@/features/billing/service";
+import { getSession } from "@/lib/auth";
/**
* Checkout return endpoint. Stripe redirects the browser here after payment
@@ -18,10 +20,27 @@ export async function GET(request: NextRequest) {
return NextResponse.json({ error: "Missing session_id" }, { status: 400 });
}
+ const userSession = await getSession();
+
+ if (!userSession?.user || userSession.user.isGuest) {
+ return NextResponse.redirect(
+ new URL("/login", request.nextUrl.origin).toString(),
+ );
+ }
+
let customerId: string;
try {
const session = await getStripe().checkout.sessions.retrieve(sessionId);
+
+ const metadata = subscriptionCheckoutMetadataSchema.safeParse(
+ session.metadata,
+ );
+
+ if (!metadata.success || metadata.data.userId !== userSession.user.id) {
+ return NextResponse.json({ error: "Not found" }, { status: 404 });
+ }
+
if (typeof session.customer !== "string") {
Sentry.captureException(new Error("Invalid customer ID in session"));
return NextResponse.json(
diff --git a/apps/web/tests/stripe-portal-auth.spec.ts b/apps/web/tests/stripe-portal-auth.spec.ts
new file mode 100644
index 000000000..c5d8bb6fb
--- /dev/null
+++ b/apps/web/tests/stripe-portal-auth.spec.ts
@@ -0,0 +1,21 @@
+import { expect, test } from "@playwright/test";
+
+test("the checkout return endpoint rejects an anonymous caller", async ({
+ request,
+}) => {
+ const res = await request.get(
+ "/api/stripe/portal?session_id=cs_test_someone_elses_session",
+ { maxRedirects: 0 },
+ );
+
+ expect(res.status()).toBe(307);
+ expect(res.headers().location).toContain("/login");
+ expect(res.headers().location).not.toContain("stripe.com");
+});
+
+test("the checkout return endpoint still requires a session id", async ({
+ request,
+}) => {
+ const res = await request.get("/api/stripe/portal", { maxRedirects: 0 });
+ expect(res.status()).toBe(400);
+});