Rallly is an open-source scheduling and collaboration tool designed to make organizing events and meetings easier.
TypeScript i18nextnext-authnextjspostgresqlprismareact-emailt3-stacktailwindcsstrpcturborepotypescriptzod
♻️ Replace UI-initiated Stripe customer portal opens with a server action (#2547)
Luke Vella1a7cf8f38c34
diff --git a/apps/web/src/app/[locale]/(space)/settings/billing/page-client.tsx b/apps/web/src/app/[locale]/(space)/settings/billing/page-client.tsxindex 0f63c3ccb..9a26333f2 100644--- a/apps/web/src/app/[locale]/(space)/settings/billing/page-client.tsx+++ b/apps/web/src/app/[locale]/(space)/settings/billing/page-client.tsx@@ -36,11 +36,13 @@ import {EmptyStateIcon,EmptyStateTitle,} from "@/components/empty-state";+import { openCustomerPortalAction } from "@/features/billing/actions";import { SubscriptionStatusLabel } from "@/features/billing/components/subscription-status-label";import { showPayWall } from "@/features/billing/paywall-store";import { useSpace } from "@/features/space/client";import type { SpaceTier } from "@/features/space/schema";import { Trans } from "@/i18n/client";+import { useSafeAction } from "@/lib/safe-action/client";import { trpc } from "@/trpc/client";import { BillingPlan } from "./components/billing-plan";import { ManageSeatsDialog } from "./components/manage-seats-dialog";@@ -74,6 +76,7 @@ export function BillingPageClient() {function BillingPageContent({ tier }: { tier: SpaceTier }) {const searchParams = useSearchParams();+ const openCustomerPortal = useSafeAction(openCustomerPortalAction);const [subscription] = trpc.billing.getSubscription.useSuspenseQuery();const [seats] = trpc.spaces.getSeats.useSuspenseQuery();@@ -126,13 +129,13 @@ function BillingPageContent({ tier }: { tier: SpaceTier }) {<div>{subscription ? (<div className="flex justify-between gap-2">- <a- href="/api/stripe/portal"- className={buttonVariants()}+ <Button+ loading={openCustomerPortal.isExecuting}onClick={() => {posthog?.capture("space_billing:billing_portal_button_click",);+ openCustomerPortal.execute({});}}><Icon>@@ -142,7 +145,7 @@ function BillingPageContent({ tier }: { tier: SpaceTier }) {i18nKey="manageSubscription"defaults="Manage Subscription"/>- </a>+ </Button><ManageSeatsDialogusedSeats={seats.used}currentSeats={seats.total}diff --git a/apps/web/src/app/api/stripe/portal/helpers/create-portal-session.ts b/apps/web/src/app/api/stripe/portal/helpers/create-portal-session.tsdeleted file mode 100644index 39609a6af..000000000--- a/apps/web/src/app/api/stripe/portal/helpers/create-portal-session.ts+++ /dev/null@@ -1,82 +0,0 @@-import { stripe } from "@rallly/billing";-import { prisma } from "@rallly/database";-import { absoluteUrl } from "@rallly/utils/absolute-url";-import * as Sentry from "@sentry/nextjs";-import type { NextRequest } from "next/server";-import { NextResponse } from "next/server";--import { getSession } from "@/lib/auth";--export function createStripePortalSessionHandler(path = "") {- return async (request: NextRequest) => {- const sessionId = request.nextUrl.searchParams.get("session_id");- const returnPath =- request.nextUrl.searchParams.get("return_path") ?? "/settings/billing";-- let customerId: string | undefined;-- if (sessionId) {- try {- const session = await stripe.checkout.sessions.retrieve(sessionId);- if (typeof session.customer !== "string") {- Sentry.captureException(new Error("Invalid customer ID in session"));- return NextResponse.json(- { error: "Invalid customer ID in session" },- { status: 400 },- );- }- customerId = session.customer;- } catch (error) {- Sentry.captureException(error);- return NextResponse.json(- { error: "Failed to retrieve session" },- { status: 500 },- );- }- } else {- const userSession = await getSession();- if (!userSession?.user || userSession.user.email === null) {- const url = new URL(absoluteUrl("/login"));- url.searchParams.set("redirectTo", request.nextUrl.pathname);- return NextResponse.redirect(url, 302);- }- try {- const user = await prisma.user.findUnique({- where: {- id: userSession.user.id,- },- select: {- customerId: true,- },- });- customerId = user?.customerId ?? undefined;- } catch (error) {- Sentry.captureException(error);- return NextResponse.json(- { error: "Failed to retrieve user" },- { status: 500 },- );- }- }-- if (!customerId) {- return NextResponse.json({- error: "No customer ID found",- });- }-- try {- const portalSession = await stripe.billingPortal.sessions.create({- customer: customerId,- return_url: returnPath ? absoluteUrl(returnPath) : undefined,- });- return NextResponse.redirect(portalSession.url + path);- } catch (error) {- Sentry.captureException(error);- return NextResponse.json(- { error: "Failed to create portal session" },- { status: 500 },- );- }- };-}diff --git a/apps/web/src/app/api/stripe/portal/payment-methods/route.ts b/apps/web/src/app/api/stripe/portal/payment-methods/route.tsdeleted file mode 100644index a61531321..000000000--- a/apps/web/src/app/api/stripe/portal/payment-methods/route.ts+++ /dev/null@@ -1,3 +0,0 @@-import { createStripePortalSessionHandler } from "../helpers/create-portal-session";--export const GET = createStripePortalSessionHandler("/payment-methods");diff --git a/apps/web/src/app/api/stripe/portal/route.ts b/apps/web/src/app/api/stripe/portal/route.tsindex a0d9201c0..a4d52dc54 100644--- a/apps/web/src/app/api/stripe/portal/route.ts+++ b/apps/web/src/app/api/stripe/portal/route.ts@@ -1,3 +1,52 @@-import { createStripePortalSessionHandler } from "./helpers/create-portal-session";+import { stripe } from "@rallly/billing";+import * as Sentry from "@sentry/nextjs";+import type { NextRequest } from "next/server";+import { NextResponse } from "next/server";-export const GET = createStripePortalSessionHandler();+import { createStripePortalSession } from "@/features/billing/portal";++/**+ * Checkout return endpoint. Stripe redirects the browser here after payment+ * (success_url) with a session_id, which lets us resolve the customer before+ * the webhook has written customerId to the user. UI-initiated portal opens+ * go through openCustomerPortalAction instead.+ */+export async function GET(request: NextRequest) {+ const sessionId = request.nextUrl.searchParams.get("session_id");++ if (!sessionId) {+ return NextResponse.json({ error: "Missing session_id" }, { status: 400 });+ }++ let customerId: string;++ try {+ const session = await stripe.checkout.sessions.retrieve(sessionId);+ if (typeof session.customer !== "string") {+ Sentry.captureException(new Error("Invalid customer ID in session"));+ return NextResponse.json(+ { error: "Invalid customer ID in session" },+ { status: 400 },+ );+ }+ customerId = session.customer;+ } catch (error) {+ Sentry.captureException(error);+ return NextResponse.json(+ { error: "Failed to retrieve session" },+ { status: 500 },+ );+ }++ try {+ return NextResponse.redirect(+ await createStripePortalSession({ customerId }),+ );+ } catch (error) {+ Sentry.captureException(error);+ return NextResponse.json(+ { error: "Failed to create portal session" },+ { status: 500 },+ );+ }+}diff --git a/apps/web/src/features/billing/actions.ts b/apps/web/src/features/billing/actions.tsindex 338223430..cdc7db30b 100644--- a/apps/web/src/features/billing/actions.ts+++ b/apps/web/src/features/billing/actions.ts@@ -4,6 +4,7 @@ import { getProPricing, stripe } from "@rallly/billing";import { absoluteUrl } from "@rallly/utils/absolute-url";import { redirect } from "next/navigation";import * as z from "zod";+import { createStripePortalSession } from "@/features/billing/portal";import type { CustomerMetadata } from "@/features/billing/schema";import { getActiveSpaceForUser } from "@/features/space/data";import type {@@ -12,13 +13,21 @@ import type {} from "@/features/subscription/schema";import { AppError } from "@/lib/errors";import { authActionClient } from "@/lib/safe-action/server";+import { validateRedirectUrl } from "@/utils/redirect";++const returnPathSchema = z+ .string()+ .refine(+ (path) => validateRedirectUrl(path) !== undefined,+ "returnPath must be an app-relative path",+ );export const upgradeToProAction = authActionClient.metadata({ actionName: "upgrade_to_pro" }).inputSchema(z.object({period: z.enum(["monthly", "yearly"]).optional(),- returnPath: z.string().startsWith("/").optional(),+ returnPath: returnPathSchema.optional(),}),).action(async ({ ctx, parsedInput }) => {@@ -40,7 +49,16 @@ export const upgradeToProAction = authActionClientif (space.tier === "pro") {// User already has an active subscription. Take them to customer portal- redirect("/api/stripe/portal");+ if (!ctx.user.customerId) {+ throw new AppError({+ code: "NOT_FOUND",+ message: "No customer ID found",+ });+ }++ redirect(+ await createStripePortalSession({ customerId: ctx.user.customerId }),+ );}const { period, returnPath } = parsedInput;@@ -122,3 +140,26 @@ export const upgradeToProAction = authActionClientredirect(checkoutSession.url);});++export const openCustomerPortalAction = authActionClient+ .metadata({ actionName: "open_customer_portal" })+ .inputSchema(+ z.object({+ returnPath: returnPathSchema.optional(),+ }),+ )+ .action(async ({ ctx, parsedInput }) => {+ if (!ctx.user.customerId) {+ throw new AppError({+ code: "NOT_FOUND",+ message: "No customer ID found",+ });+ }++ redirect(+ await createStripePortalSession({+ customerId: ctx.user.customerId,+ returnPath: parsedInput.returnPath,+ }),+ );+ });diff --git a/apps/web/src/features/billing/portal.ts b/apps/web/src/features/billing/portal.tsindex 0d06e948a..65dcb8364 100644--- a/apps/web/src/features/billing/portal.ts+++ b/apps/web/src/features/billing/portal.ts@@ -6,6 +6,20 @@ import {} from "@rallly/billing/lib/portal";import { absoluteUrl } from "@rallly/utils/absolute-url";+export async function createStripePortalSession({+ customerId,+ returnPath = "/settings/billing",+}: {+ customerId: string;+ returnPath?: string;+}) {+ const portalSession = await stripe.billingPortal.sessions.create({+ customer: customerId,+ return_url: absoluteUrl(returnPath),+ });+ return portalSession.url;+}+async function createSeatUpdateBillingConfig() {const pricing = await getProPricing();diff --git a/apps/web/src/utils/redirect.ts b/apps/web/src/utils/redirect.tsindex 2354c664b..b23980a8b 100644--- a/apps/web/src/utils/redirect.ts+++ b/apps/web/src/utils/redirect.ts@@ -1,6 +1,12 @@+// A leading-"/" check alone is not enough: the WHATWG URL parser resolves+// "//evil.com", "/\evil.com" and even "/\t/evil.com" (tabs/newlines are+// stripped) to an external origin. Resolving against a sentinel origin uses+// the same parser the redirect will, so nothing can slip through.+const PROBE_ORIGIN = "https://redirect-probe.invalid";+/*** Validates a redirect URL to prevent open redirect attacks.- * Only allows relative URLs starting with "/" but not "//" (protocol-relative).+ * Only allows app-relative URLs that cannot resolve to another origin.** @param redirectTo - The redirect URL to validate* @returns The valid redirect URL or undefined if invalid@@ -12,16 +18,21 @@ export function validateRedirectUrl(return undefined;}- // Trim whitespaceconst trimmed = redirectTo.trim();- // Only allow relative URLs starting with "/" but not "//"- if (trimmed.startsWith("/") && !trimmed.startsWith("//")) {- return trimmed;+ if (!trimmed.startsWith("/")) {+ return undefined;+ }++ try {+ if (new URL(trimmed, PROBE_ORIGIN).origin !== PROBE_ORIGIN) {+ return undefined;+ }+ } catch {+ return undefined;}- // Return undefined for invalid redirects, let caller decide the default- return undefined;+ return trimmed;}/**