Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
12 changes: 12 additions & 0 deletions src/test/checkout-security.test.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import { describe, expect, it } from "vitest";
import {
findCustomerOwnedByUser,
hasOpenSubscription,
isAllowedCheckoutRedirectUrl,
} from "../../supabase/functions/create-checkout/checkout-security";

Expand Down Expand Up @@ -28,4 +29,15 @@ describe("checkout security", () => {
expect(findCustomerOwnedByUser(customers, "user-123")).toBe("cus_correct");
expect(findCustomerOwnedByUser(customers, "missing-user")).toBeNull();
});

it("treats a subscription that can still bill as a reason to refuse another checkout", () => {
expect(hasOpenSubscription([{ status: "active" }, { status: "canceled" }])).toBe(true);
expect(hasOpenSubscription([{ status: "trialing" }])).toBe(true);
expect(hasOpenSubscription([{ status: "past_due" }])).toBe(true);
expect(hasOpenSubscription([{ status: "paused" }])).toBe(true);
expect(hasOpenSubscription([{ status: "unpaid" }])).toBe(true);
expect(hasOpenSubscription([{ status: "canceled" }, { status: "incomplete" }, { status: "incomplete_expired" }])).toBe(false);
expect(hasOpenSubscription([])).toBe(false);
expect(hasOpenSubscription(null)).toBe(false);
});
});
7 changes: 7 additions & 0 deletions supabase/functions/create-checkout/checkout-security.ts
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,13 @@ export function isAllowedCheckoutRedirectUrl(value: string): boolean {
}
}

const OPEN_SUBSCRIPTION_STATUSES = new Set(["active", "trialing", "past_due", "unpaid", "paused"]);

/** True when this user already has a Stripe subscription that can still bill them. */
export function hasOpenSubscription(rows: Array<{ status?: string | null }> | null | undefined): boolean {
return (rows ?? []).some((row) => typeof row.status === "string" && OPEN_SUBSCRIPTION_STATUSES.has(row.status));
}

export function findCustomerOwnedByUser(
customers: StripeCustomerLike[],
userId: string,
Expand Down
25 changes: 25 additions & 0 deletions supabase/functions/create-checkout/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ import { HttpError, jsonError, requireUser } from "../_shared/auth.ts";
import { getCorsHeaders } from "../_shared/cors.ts";
import {
findCustomerOwnedByUser,
hasOpenSubscription,
isAllowedCheckoutRedirectUrl,
} from "./checkout-security.ts";

Expand Down Expand Up @@ -249,6 +250,30 @@ export async function handleRequest(req: Request): Promise<Response> {

const resolvedPrice = await resolveCheckoutPriceId();

// A second Checkout session creates a second subscription on the same
// customer. Refuse while one can still bill, and send the student to
// Settings to manage the one they have.
const { data: existingSubscriptions, error: subscriptionReadError } = await supabase
.from("subscriptions")
.select("status")
.eq("user_id", user.id);
if (subscriptionReadError) {
console.error(`[CHECKOUT] Could not read subscriptions for ${user.id}: ${subscriptionReadError.code}`);
return new Response(JSON.stringify({ error: "Failed to create checkout session" }), {
status: 500,
headers: { ...corsHeaders, "Content-Type": "application/json" },
});
}
if (hasOpenSubscription(existingSubscriptions)) {
return new Response(JSON.stringify({
error: "You already have a subscription. Manage it from Settings.",
code: "already_subscribed",
}), {
status: 409,
headers: { ...corsHeaders, "Content-Type": "application/json" },
});
}

// Get or create Stripe customer
let customerId = await findCustomerIdByUser({ id: user.id, email: user.email });
if (!customerId) {
Expand Down
Loading