Skip to content

Infisical is the open-source platform for securing secrets, certificates, access, and AI Agents.

fix(billing): surface license server errors and route last-product removal to cancel

Tre Dubravaef090e3982d9
diff --git a/backend/src/services/license-client/license-client-backends.ts b/backend/src/services/license-client/license-client-backends.ts
index 836123edbe..c7f8c95efb 100644
--- a/backend/src/services/license-client/license-client-backends.ts
+++ b/backend/src/services/license-client/license-client-backends.ts
@@ -1,5 +1,7 @@
import jwt from "jsonwebtoken";
+import { BadRequestError, InternalServerError } from "@app/lib/errors";
+
import {
billingProfileResponseSchema,
catalogResponseSchema,
@@ -55,6 +57,21 @@ const mintServiceToken = (signingKey: string): string =>
expiresIn: "2m"
});
+// Surface the license server's message on 4xx (caller-actionable, e.g. "cannot remove the last
+// product; cancel the subscription instead"); when it has none, fall back to the generic error
+// default rather than a status code the customer can't act on. 5xx bodies may carry internal detail,
+// so those stay generic.
+const throwIfResponseError = async (res: Response): Promise<void> => {
+ if (res.ok) {
+ return;
+ }
+ if (res.status >= 400 && res.status < 500) {
+ const body = (await res.json().catch(() => null)) as { message?: string } | null;
+ throw new BadRequestError({ message: body?.message });
+ }
+ throw new InternalServerError({ message: "Billing service error" });
+};
+
export const licenseServerBackend = (
serverUrl: string,
signingKey: string,
@@ -77,9 +94,7 @@ export const licenseServerBackend = (
headers: { Authorization: `Bearer ${mintServiceToken(signingKey)}` },
redirect: "manual"
});
- if (!res.ok) {
- throw new Error(`license server responded with ${res.status}`);
- }
+ await throwIfResponseError(res);
const body: unknown = await res.json();
return entitlementsResponseSchema.parse(body);
},
@@ -92,9 +107,7 @@ export const licenseServerBackend = (
headers: { Authorization: `Bearer ${mintServiceToken(signingKey)}` },
redirect: "manual"
});
- if (!res.ok) {
- throw new Error(`license server responded with ${res.status}`);
- }
+ await throwIfResponseError(res);
},
fetchCatalog: async (): Promise<TCatalogResponse> => {
@@ -104,9 +117,7 @@ export const licenseServerBackend = (
headers: { Authorization: `Bearer ${mintServiceToken(signingKey)}` },
redirect: "manual"
});
- if (!res.ok) {
- throw new Error(`license server responded with ${res.status}`);
- }
+ await throwIfResponseError(res);
const body: unknown = await res.json();
return catalogResponseSchema.parse(body);
},
@@ -125,9 +136,7 @@ export const licenseServerBackend = (
if (res.status === 404) {
return null;
}
- if (!res.ok) {
- throw new Error(`license server responded with ${res.status}`);
- }
+ await throwIfResponseError(res);
const body: unknown = await res.json();
const parsed = subscriptionResponseSchema.safeParse(body);
@@ -153,9 +162,7 @@ export const licenseServerBackend = (
if (res.status === 404) {
return null;
}
- if (!res.ok) {
- throw new Error(`license server responded with ${res.status}`);
- }
+ await throwIfResponseError(res);
const body: unknown = await res.json();
return cloudPlanResponseSchema.parse(body);
},
@@ -173,9 +180,7 @@ export const licenseServerBackend = (
if (res.status === 404) {
return null;
}
- if (!res.ok) {
- throw new Error(`license server responded with ${res.status}`);
- }
+ await throwIfResponseError(res);
const body: unknown = await res.json();
return billingProfileResponseSchema.parse(body);
},
@@ -189,9 +194,7 @@ export const licenseServerBackend = (
body: JSON.stringify(payload),
redirect: "manual"
});
- if (!res.ok) {
- throw new Error(`license server responded with ${res.status}`);
- }
+ await throwIfResponseError(res);
const body: unknown = await res.json();
return checkoutResultSchema.parse(body);
},
@@ -205,9 +208,7 @@ export const licenseServerBackend = (
body: JSON.stringify(payload),
redirect: "manual"
});
- if (!res.ok) {
- throw new Error(`license server responded with ${res.status}`);
- }
+ await throwIfResponseError(res);
const body: unknown = await res.json();
return sessionResponseSchema.parse(body);
},
@@ -224,9 +225,7 @@ export const licenseServerBackend = (
body: JSON.stringify(payload),
redirect: "manual"
});
- if (!res.ok) {
- throw new Error(`license server responded with ${res.status}`);
- }
+ await throwIfResponseError(res);
const body: unknown = await res.json();
return subscriptionPreviewResponseSchema.parse(body);
},
@@ -240,9 +239,7 @@ export const licenseServerBackend = (
body: JSON.stringify(payload),
redirect: "manual"
});
- if (!res.ok) {
- throw new Error(`license server responded with ${res.status}`);
- }
+ await throwIfResponseError(res);
const body: unknown = await res.json();
return checkoutResultSchema.parse(body);
},
@@ -255,9 +252,7 @@ export const licenseServerBackend = (
headers: { Authorization: `Bearer ${mintServiceToken(signingKey)}` },
redirect: "manual"
});
- if (!res.ok) {
- throw new Error(`license server responded with ${res.status}`);
- }
+ await throwIfResponseError(res);
const body: unknown = await res.json();
return checkoutResultSchema.parse(body);
},
@@ -270,9 +265,7 @@ export const licenseServerBackend = (
headers: { Authorization: `Bearer ${mintServiceToken(signingKey)}` },
redirect: "manual"
});
- if (!res.ok) {
- throw new Error(`license server responded with ${res.status}`);
- }
+ await throwIfResponseError(res);
const body: unknown = await res.json();
return checkoutResultSchema.parse(body);
},
@@ -285,9 +278,7 @@ export const licenseServerBackend = (
headers: { Authorization: `Bearer ${mintServiceToken(signingKey)}` },
redirect: "manual"
});
- if (!res.ok) {
- throw new Error(`license server responded with ${res.status}`);
- }
+ await throwIfResponseError(res);
const body: unknown = await res.json();
return checkoutResultSchema.parse(body);
}
@@ -318,9 +309,7 @@ export const licenseServerSelfHostedBackend = (
headers: { Authorization: `Bearer ${licenseKey}` },
redirect: "manual"
});
- if (!res.ok) {
- throw new Error(`license server responded with ${res.status}`);
- }
+ await throwIfResponseError(res);
const body: unknown = await res.json();
return entitlementsResponseSchema.parse(body);
},
@@ -332,9 +321,7 @@ export const licenseServerSelfHostedBackend = (
headers: { Authorization: `Bearer ${licenseKey}` },
redirect: "manual"
});
- if (!res.ok) {
- throw new Error(`license server responded with ${res.status}`);
- }
+ await throwIfResponseError(res);
},
fetchCatalog: async (): Promise<TCatalogResponse> => {
@@ -344,9 +331,7 @@ export const licenseServerSelfHostedBackend = (
headers: { Authorization: `Bearer ${licenseKey}` },
redirect: "manual"
});
- if (!res.ok) {
- throw new Error(`license server responded with ${res.status}`);
- }
+ await throwIfResponseError(res);
const body: unknown = await res.json();
return catalogResponseSchema.parse(body);
},
@@ -362,9 +347,7 @@ export const licenseServerSelfHostedBackend = (
if (res.status === 404) {
return null;
}
- if (!res.ok) {
- throw new Error(`license server responded with ${res.status}`);
- }
+ await throwIfResponseError(res);
const body: unknown = await res.json();
const parsed = subscriptionResponseSchema.safeParse(body);
if (!parsed.success || !parsed.data.status) {
diff --git a/frontend/src/pages/organization/BillingV2Page/components/RemoveProductModal.tsx b/frontend/src/pages/organization/BillingV2Page/components/RemoveProductModal.tsx
index e6f7c7de71..0a6b0cba5f 100644
--- a/frontend/src/pages/organization/BillingV2Page/components/RemoveProductModal.tsx
+++ b/frontend/src/pages/organization/BillingV2Page/components/RemoveProductModal.tsx
@@ -1,5 +1,5 @@
import { useEffect } from "react";
-import { Trash2Icon } from "lucide-react";
+import { CalendarX2Icon, Trash2Icon } from "lucide-react";
import { createNotification } from "@app/components/notifications";
import {
@@ -15,6 +15,9 @@ import {
} from "@app/components/v3";
import {
BillingV2CatalogProduct,
+ useCancelBillingV2Subscription,
+ useGetBillingV2Catalog,
+ useGetBillingV2Overview,
usePreviewBillingV2Change,
useRemoveBillingV2Product
} from "@app/hooks/api";
@@ -24,21 +27,41 @@ import { fmtMoney } from "../billing-v2-data";
type Props = {
orgId: string;
product: BillingV2CatalogProduct;
- // Dismissed without removing (cancel / escape / overlay) — keep the management sheet open behind it.
+ // Dismissed without removing (cancel / escape / overlay); keep the management sheet open behind it.
onClose: () => void;
- // Removal succeeded — close the confirm and the management sheet it was opened from.
+ // Removal (or cancel) succeeded; close the confirm and the management sheet it was opened from.
onRemoved: () => void;
};
+const getServerMessage = (err: unknown): string | undefined =>
+ (err as { response?: { data?: { message?: string } } })?.response?.data?.message;
+
export const RemoveProductModal = ({ orgId, product, onClose, onRemoved }: Props) => {
+ // Both queries are already cached by the page (same orgId key), so this reuses that data rather
+ // than refetching. Stripe can't hold a zero-item subscription, so removing the only self-serve
+ // product is rejected by the license server; that case cancels the whole subscription instead.
+ const { data: overview } = useGetBillingV2Overview(orgId);
+ const { data: catalog = [] } = useGetBillingV2Catalog(orgId);
+ const subscriptionProductCount = catalog.filter(
+ (prod) => Boolean(prod.pro?.planKey) && Boolean(overview?.entitlements[prod.id]?.entitled)
+ ).length;
+ const isOnlyProduct = subscriptionProductCount <= 1;
+ const periodEndDate = overview?.nextBillingDate ?? null;
+
const preview = usePreviewBillingV2Change();
const removeProduct = useRemoveBillingV2Product();
+ const cancelSubscription = useCancelBillingV2Subscription();
// Preview the prorated credit once when the dialog opens, so the user confirms against real numbers.
+ // The last-product case can't be removed (it cancels instead), and previewing it would also 409, so
+ // skip the preview there.
useEffect(() => {
+ if (isOnlyProduct) {
+ return;
+ }
preview.mutate({ orgId, removeProductId: product.id });
// eslint-disable-next-line react-hooks/exhaustive-deps
- }, [orgId, product.id]);
+ }, [orgId, product.id, isOnlyProduct]);
const handleRemove = async () => {
try {
@@ -48,11 +71,72 @@ export const RemoveProductModal = ({ orgId, product, onClose, onRemoved }: Props
text: `${product.name} will be removed. It may take a moment to update here.`
});
onRemoved();
- } catch {
- createNotification({ type: "error", text: `Failed to remove ${product.name}.` });
+ } catch (err) {
+ createNotification({
+ type: "error",
+ text: getServerMessage(err) ?? `Failed to remove ${product.name}.`
+ });
+ }
+ };
+
+ const handleCancel = async () => {
+ try {
+ await cancelSubscription.mutateAsync({ orgId });
+ createNotification({
+ type: "success",
+ text: "Your subscription will be canceled at the end of the current billing period."
+ });
+ onRemoved();
+ } catch (err) {
+ createNotification({
+ type: "error",
+ text: getServerMessage(err) ?? "Failed to cancel your subscription."
+ });
}
};
+ if (isOnlyProduct) {
+ let periodClause = "at the end of your current billing period";
+ if (periodEndDate) {
+ periodClause = `on ${periodEndDate}`;
+ }
+
+ return (
+ <AlertDialog
+ open
+ onOpenChange={(isOpen) => {
+ if (!isOpen) {
+ onClose();
+ }
+ }}
+ >
+ <AlertDialogContent className="sm:max-w-xl!">
+ <AlertDialogHeader>
+ <AlertDialogMedia>
+ <CalendarX2Icon />
+ </AlertDialogMedia>
+ <AlertDialogTitle>Cancel your subscription?</AlertDialogTitle>
+ <AlertDialogDescription>
+ {product.name} is the only product on your subscription, so it cannot be removed on
+ its own. Canceling ends your whole subscription {periodClause}. You keep access until
+ then.
+ </AlertDialogDescription>
+ </AlertDialogHeader>
+ <AlertDialogFooter>
+ <AlertDialogCancel>Keep subscription</AlertDialogCancel>
+ <AlertDialogAction
+ variant="danger"
+ isDisabled={cancelSubscription.isPending}
+ onClick={handleCancel}
+ >
+ Cancel subscription
+ </AlertDialogAction>
+ </AlertDialogFooter>
+ </AlertDialogContent>
+ </AlertDialog>
+ );
+ }
+
const credit = preview.data ? Math.abs(preview.data.prorationAmount) : 0;
// Block while the credit preview is still in flight; a failed preview keeps the graceful