Open-source status page, incident response and uptime monitoring
TypeScript alertingincident-managementmcpmcp-servermonitoringmonitoring-as-codeobservabilityon-callopen-sourcesrestatus-pagestatuspagesynthetic-monitoringterraformtinybirdtursouptimeuptime-checkeruptime-monitor
fix: stripe addon (#2294)
Maximilian Kaske7a84903caa4c
diff --git a/packages/api/src/router/stripe/index.ts b/packages/api/src/router/stripe/index.tsindex 791c20c13..9a43c83df 100644--- a/packages/api/src/router/stripe/index.ts+++ b/packages/api/src/router/stripe/index.ts@@ -99,7 +99,6 @@ export const stripeRouter = createTRPCRouter({}),).mutation(async (opts) => {- console.log("getCheckoutSession");// The following code is duplicated we should extract itconst result = await opts.ctx.db.select()@@ -291,8 +290,6 @@ export const stripeRouter = createTRPCRouter({newValue,);- console.log("new Limits");-await opts.ctx.db.update(workspace).set({ limits: JSON.stringify(newLimits) })diff --git a/packages/api/src/router/stripe/utils.test.ts b/packages/api/src/router/stripe/utils.test.tsnew file mode 100644index 000000000..02299b1b9--- /dev/null+++ b/packages/api/src/router/stripe/utils.test.ts@@ -0,0 +1,101 @@+import { describe, expect, test } from "bun:test";++import { getLimits } from "@openstatus/db/src/schema/plan/utils";+import type Stripe from "stripe";++import { FEATURES, PLANS, buildLimitsFromSubscription } from "./utils";++// Derive test-env price ids from the source tables so the test breaks loudly+// (assertion failure) rather than silently if a price id changes.+const planPriceId = (plan: string) =>+ PLANS.find((p) => p.plan === plan)?.price.monthly.priceIds.test;+const featurePriceId = (feature: string) =>+ FEATURES.find((f) => f.feature === feature)?.price.monthly.priceIds.test;++const STARTER = planPriceId("starter");+const WHITE_LABEL = featurePriceId("white-label");+const STATUS_PAGES = featurePriceId("status-pages");++function subscriptionWith(+ items: { priceId: string | undefined; quantity?: number }[],+): Stripe.Subscription {+ return {+ items: {+ data: items.map(({ priceId, quantity }) => ({+ price: { id: priceId },+ quantity,+ })),+ },+ } as unknown as Stripe.Subscription;+}++describe("buildLimitsFromSubscription", () => {+ test("test price ids resolve from the source tables", () => {+ expect(STARTER).toBeDefined();+ expect(WHITE_LABEL).toBeDefined();+ expect(STATUS_PAGES).toBeDefined();+ });++ test("returns null when no plan line item is present", () => {+ expect(buildLimitsFromSubscription(subscriptionWith([]))).toBeNull();+ expect(+ buildLimitsFromSubscription(subscriptionWith([{ priceId: WHITE_LABEL }])),+ ).toBeNull();+ });++ test("plan item alone yields the plan baseline", () => {+ const built = buildLimitsFromSubscription(+ subscriptionWith([{ priceId: STARTER }]),+ );+ expect(built?.plan).toBe("starter");+ expect(built?.limits["white-label"]).toBe(false);+ });++ test("addon item flips its limit on top of the plan baseline", () => {+ const built = buildLimitsFromSubscription(+ subscriptionWith([{ priceId: STARTER }, { priceId: WHITE_LABEL }]),+ );+ expect(built?.plan).toBe("starter");+ // The regression: white-label must survive alongside the plan item.+ expect(built?.limits["white-label"]).toBe(true);+ });++ test("quantity addon adds to the plan default", () => {+ const planDefault = getLimits("starter")["status-pages"] as number;+ const built = buildLimitsFromSubscription(+ subscriptionWith([+ { priceId: STARTER },+ { priceId: STATUS_PAGES, quantity: 3 },+ ]),+ );+ expect(built?.limits["status-pages"]).toBe(planDefault + 3);+ });++ test("missing quantity on a numeric addon falls back to +1", () => {+ const planDefault = getLimits("starter")["status-pages"] as number;+ const built = buildLimitsFromSubscription(+ subscriptionWith([{ priceId: STARTER }, { priceId: STATUS_PAGES }]),+ );+ expect(built?.limits["status-pages"]).toBe(planDefault + 1);+ });++ test("repeated quantity addon items accumulate", () => {+ const planDefault = getLimits("starter")["status-pages"] as number;+ const built = buildLimitsFromSubscription(+ subscriptionWith([+ { priceId: STARTER },+ { priceId: STATUS_PAGES, quantity: 2 },+ { priceId: STATUS_PAGES, quantity: 3 },+ ]),+ );+ expect(built?.limits["status-pages"]).toBe(planDefault + 5);+ });++ test("throws on an unsupported price when a plan is present", () => {+ expect(() =>+ buildLimitsFromSubscription(+ subscriptionWith([{ priceId: STARTER }, { priceId: "price_unknown" }]),+ ),+ ).toThrow(/unsupported stripe price/i);+ });+});diff --git a/packages/api/src/router/stripe/utils.ts b/packages/api/src/router/stripe/utils.tsindex f90f78e53..76611ea16 100644--- a/packages/api/src/router/stripe/utils.ts+++ b/packages/api/src/router/stripe/utils.ts@@ -4,7 +4,51 @@ import type { WorkspacePlan } from "@openstatus/db/src/schema";import type {Addons,BillingInterval,+ Limits,} from "@openstatus/db/src/schema/plan/schema";+import {+ getLimits,+ updateAddonInLimits,+} from "@openstatus/db/src/schema/plan/utils";+import type Stripe from "stripe";++/**+ * Rebuild a workspace's limits from the full set of subscription line items.+ * The plan item sets the baseline; each addon item then re-applies its flag or+ * quantity on top, so purchased addons survive subscription updates instead of+ * being reset to the plan default. Returns null when no plan item is present.+ * Throws on a line item whose price is neither a known plan nor a known addon,+ * so misconfigured prices surface instead of silently drifting from billing.+ */+export function buildLimitsFromSubscription(+ subscription: Stripe.Subscription,+): { plan: WorkspacePlan; limits: Limits } | null {+ const detectedPlan = subscription.items.data+ .map((item) => getPlanFromPriceId(item.price.id))+ .find((plan) => plan !== undefined);++ if (!detectedPlan) return null;++ let limits: Limits = getLimits(detectedPlan.plan);++ for (const item of subscription.items.data) {+ if (getPlanFromPriceId(item.price.id)) continue;+ const feature = getFeatureFromPriceId(item.price.id);+ if (!feature) {+ throw new Error(+ `Unsupported Stripe price on subscription: ${item.price.id}`,+ );+ }+ // Accumulate onto the running value so repeated addon items add up; boolean+ // addons just flip on.+ const current = limits[feature.feature];+ const value =+ typeof current === "number" ? current + (item.quantity ?? 1) : true;+ limits = updateAddonInLimits(limits, feature.feature, value);+ }++ return { plan: detectedPlan.plan, limits };+}export const getPlanFromPriceId = (priceId: string) => {const env =@@ -19,8 +63,8 @@ export const getPlanFromPriceId = (priceId: string) => {export const getFeatureFromPriceId = (priceId: string) => {const env =process.env.NEXT_PUBLIC_VERCEL_ENV === "production" ? "production" : "test";- return FEATURES.find(- (feature) => feature.price.monthly.priceIds[env] === priceId,+ return FEATURES.find((feature) =>+ Object.values(feature.price).some((p) => p.priceIds[env] === priceId),);};diff --git a/packages/api/src/router/stripe/webhook.ts b/packages/api/src/router/stripe/webhook.tsindex a0f8b49d0..abb227292 100644--- a/packages/api/src/router/stripe/webhook.ts+++ b/packages/api/src/router/stripe/webhook.ts@@ -10,17 +10,28 @@ import {usersToWorkspaces,workspace,} from "@openstatus/db/src/schema";-import {- getLimits,- updateAddonInLimits,-} from "@openstatus/db/src/schema/plan/utils";+import { getLimits } from "@openstatus/db/src/schema/plan/utils";import { TRPCError } from "@trpc/server";import type Stripe from "stripe";import { z } from "zod";import { createTRPCRouter, publicProcedure } from "../../trpc";import { stripe } from "./shared";-import { getFeatureFromPriceId, getPlanFromPriceId } from "./utils";+import { buildLimitsFromSubscription } from "./utils";++// An unsupported price is a permanent misconfiguration; surface it as a 400 so+// Stripe stops retrying instead of hammering the endpoint on a 5xx.+function buildFromSubscriptionOrThrow(subscription: Stripe.Subscription) {+ try {+ return buildLimitsFromSubscription(subscription);+ } catch (e) {+ console.error(e);+ throw new TRPCError({+ code: "BAD_REQUEST",+ message: e instanceof Error ? e.message : "Invalid subscription",+ });+ }+}const webhookProcedure = publicProcedure.input(z.object({@@ -65,28 +76,22 @@ export const webhookRouter = createTRPCRouter({const ws = selectWorkspaceSchema.parse(result);const oldPlan = ws.plan;- let detectedPlan: ReturnType<typeof getPlanFromPriceId> = undefined;+ const built = buildFromSubscriptionOrThrow(subscription);- for (const item of subscription.items.data) {- const plan = getPlanFromPriceId(item.price.id);- if (plan) {- detectedPlan = plan;- break;- }- }-- if (!detectedPlan) {+ // Subscription has no recognized plan item (e.g. a standalone addon sub);+ // nothing to sync here, unlike sessionCompleted which always has a plan.+ if (!built) {return;}await opts.ctx.db.update(workspace).set({- plan: detectedPlan.plan,+ plan: built.plan,subscriptionId: subscription.id,endsAt: new Date(subscription.current_period_end * 1000),paidUntil: new Date(subscription.current_period_end * 1000),- limits: JSON.stringify(getLimits(detectedPlan.plan)),+ limits: JSON.stringify(built.limits),}).where(eq(workspace.id, result.id)).run();@@ -105,8 +110,8 @@ export const webhookRouter = createTRPCRouter({}}- const newPlan = detectedPlan?.plan ?? oldPlan;- if (detectedPlan && newPlan !== oldPlan) {+ const newPlan = built.plan;+ if (newPlan !== oldPlan) {const customer = await stripe.customers.retrieve(customerId);if (!customer.deleted && customer.email) {const userResult = await opts.ctx.db@@ -163,76 +168,43 @@ export const webhookRouter = createTRPCRouter({});}- for (const item of subscription.items.data) {- const plan = getPlanFromPriceId(item.price.id);- if (!plan) {- const feature = getFeatureFromPriceId(item.price.id);- if (feature) {- const _ws = await opts.ctx.db- .select()- .from(workspace)- .where(eq(workspace.stripeId, customerId))- .get();-- const ws = selectWorkspaceSchema.parse(_ws);-- const currentValue = ws.limits[feature.feature];- const newValue =- typeof currentValue === "boolean"- ? true- : typeof currentValue === "number"- ? currentValue + 1- : currentValue;-- const newLimits = updateAddonInLimits(- ws.limits,- feature.feature,- newValue,- );-- await opts.ctx.db- .update(workspace)- .set({- limits: JSON.stringify(newLimits),- })- .where(eq(workspace.id, result.id))- .run();- continue;- }- console.error("Invalid plan");- throw new TRPCError({- code: "BAD_REQUEST",- message: "Invalid plan",- });- }- await opts.ctx.db- .update(workspace)- .set({- plan: plan.plan,- subscriptionId: subscription.id,- endsAt: new Date(subscription.current_period_end * 1000),- paidUntil: new Date(subscription.current_period_end * 1000),- limits: JSON.stringify(getLimits(plan.plan)),- })- .where(eq(workspace.id, result.id))- .run();- const customer = await stripe.customers.retrieve(customerId);- if (!customer.deleted && customer.email) {- const userResult = await opts.ctx.db- .select()- .from(user)- .where(eq(user.email, customer.email))- .get();- if (!userResult) return;+ const built = buildFromSubscriptionOrThrow(subscription);+ if (!built) {+ console.error("Invalid plan");+ throw new TRPCError({+ code: "BAD_REQUEST",+ message: "Invalid plan",+ });+ }- const analytics = await setupAnalytics({- userId: `usr_${userResult.id}`,- email: userResult.email || undefined,- workspaceId: String(result.id),- plan: plan.plan,- });- await analytics.track(Events.UpgradeWorkspace);- }+ await opts.ctx.db+ .update(workspace)+ .set({+ plan: built.plan,+ subscriptionId: subscription.id,+ endsAt: new Date(subscription.current_period_end * 1000),+ paidUntil: new Date(subscription.current_period_end * 1000),+ limits: JSON.stringify(built.limits),+ })+ .where(eq(workspace.id, result.id))+ .run();++ const customer = await stripe.customers.retrieve(customerId);+ if (!customer.deleted && customer.email) {+ const userResult = await opts.ctx.db+ .select()+ .from(user)+ .where(eq(user.email, customer.email))+ .get();+ if (!userResult) return;++ const analytics = await setupAnalytics({+ userId: `usr_${userResult.id}`,+ email: userResult.email || undefined,+ workspaceId: String(result.id),+ plan: built.plan,+ });+ await analytics.track(Events.UpgradeWorkspace);}}),customerSubscriptionDeleted: webhookProcedure.mutation(async (opts) => {