Skip to content
Closed
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
62 changes: 61 additions & 1 deletion supabase/functions/create-checkout/auth_test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@ for (const [key, value] of Object.entries({
STRIPE_SECRET_KEY: "sk_test_not_used",
})) Deno.env.set(key, value);

const { handleRequest } = await import("./index.ts");
const { handleRequest, subscriptionStillPaid } = await import("./index.ts");

const send = (authorization?: string) =>
new Request("http://127.0.0.1/functions/v1/create-checkout", {
Expand All @@ -38,3 +38,63 @@ Deno.test("create-checkout lets a valid token through to request validation", as
authCalls: 1,
}]);
});

Deno.test("subscriptionStillPaid blocks only an active or trialing period that has not ended", () => {
const future = "2099-01-01T00:00:00.000Z";
const past = "2000-01-01T00:00:00.000Z";
const now = Date.parse("2026-10-22T00:00:00.000Z");
if (!subscriptionStillPaid({ status: "active", current_period_end: future }, now)) throw new Error("active future");
if (!subscriptionStillPaid({ status: "trialing", current_period_end: future }, now)) throw new Error("trialing future");
if (subscriptionStillPaid({ status: "active", current_period_end: past }, now)) throw new Error("active past");
if (subscriptionStillPaid({ status: "canceled", current_period_end: future }, now)) throw new Error("canceled");
if (subscriptionStillPaid({ status: "past_due", current_period_end: future }, now)) throw new Error("past_due");
if (subscriptionStillPaid(null, now)) throw new Error("missing row");
});

const sendCheckout = (authorization?: string) =>
new Request("http://127.0.0.1/functions/v1/create-checkout", {
method: "POST",
headers: {
"Content-Type": "application/json",
...(authorization === undefined ? {} : { Authorization: authorization }),
},
body: JSON.stringify({
successUrl: "https://debate.pi-stack.org/app/settings?checkout=success",
cancelUrl: "https://debate.pi-stack.org/app/settings?checkout=canceled",
}),
});

Deno.test("create-checkout refuses a second purchase while Pro is still paid", async () => {
const calls: string[] = [];
await runBearerCases(handleRequest, sendCheckout, [{
label: "already subscribed",
authorization: `Bearer ${VALID_TOKEN}`,
status: 409,
body: { error: "You already have an active Pro subscription.", code: "ALREADY_SUBSCRIBED" },
authCalls: 1,
}], (url) => {
calls.push(url.pathname);
if (url.pathname.endsWith("/rest/v1/subscriptions")) {
return Response.json({ status: "active", current_period_end: "2099-01-01T00:00:00.000Z" });
}
throw new Error(`Unexpected request: ${url}`);
});
if (calls.some((path) => path.includes("stripe") || path.includes("checkout"))) {
throw new Error(`Stripe was contacted: ${calls.join(", ")}`);
}
});

Deno.test("create-checkout fails closed when the subscription lookup errors", async () => {
await runBearerCases(handleRequest, sendCheckout, [{
label: "lookup failed",
authorization: `Bearer ${VALID_TOKEN}`,
status: 503,
body: { error: "Could not confirm your subscription. Try again in a moment." },
authCalls: 1,
}], (url) => {
if (url.pathname.endsWith("/rest/v1/subscriptions")) {
return Response.json({ message: "db down" }, { status: 500 });
}
throw new Error(`Unexpected request: ${url}`);
});
});
48 changes: 48 additions & 0 deletions supabase/functions/create-checkout/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -122,6 +122,35 @@ async function resolveCheckoutPriceId(): Promise<{ id: string; source: string }>
);
}

const BLOCKING_SUBSCRIPTION_STATUSES = new Set(["active", "trialing"]);

/** A paid period that has not ended yet. Past or missing end dates do not block a new checkout. */
export function subscriptionStillPaid(
row: { status?: string | null; current_period_end?: string | null } | null,
now = Date.now(),
): boolean {
if (!row?.status || !BLOCKING_SUBSCRIPTION_STATUSES.has(row.status)) return false;
const end = Date.parse(row.current_period_end ?? "");
return Number.isFinite(end) && end > now;
}

async function findBlockingSubscription(userId: string): Promise<"subscribed" | "clear" | "lookup_failed"> {
const { data, error } = await supabase
.from("subscriptions")
.select("status, current_period_end")
.eq("user_id", userId)
.in("status", ["active", "trialing"])
.order("current_period_end", { ascending: false })
.limit(1)
.maybeSingle();

if (error) {
console.error(`[CHECKOUT] Active subscription lookup failed for ${userId}: ${error.code ?? "unknown"}`);
return "lookup_failed";
}
return subscriptionStillPaid(data) ? "subscribed" : "clear";
}

async function findCustomerIdByUser(user: { id: string; email?: string | null }): Promise<string | null> {
const { data: existingSub, error: subLookupError } = await supabase
.from("subscriptions")
Expand Down Expand Up @@ -247,6 +276,25 @@ export async function handleRequest(req: Request): Promise<Response> {
});
}

const alreadySubscribed = await findBlockingSubscription(user.id);
if (alreadySubscribed === "lookup_failed") {
return new Response(JSON.stringify({
error: "Could not confirm your subscription. Try again in a moment.",
}), {
status: 503,
headers: { ...corsHeaders, "Content-Type": "application/json" },
});
}
if (alreadySubscribed === "subscribed") {
return new Response(JSON.stringify({
error: "You already have an active Pro subscription.",
code: "ALREADY_SUBSCRIBED",
}), {
status: 409,
headers: { ...corsHeaders, "Content-Type": "application/json" },
});
}

const resolvedPrice = await resolveCheckoutPriceId();

// Get or create Stripe customer
Expand Down
Loading