Infisical is the open-source platform for securing secrets, certificates, access, and AI Agents.
TypeScript acmeagentsai-agentscertificate-managementdevsecopsenvironment-variableskubernetesopen-sourcepampkipostgresprivate-caprivileged-access-managementsecret-managementsecret-managersecretssecrets-managementsecuritysecurity-toolsvault
import { FastifyRequest } from "fastify";
import { z } from "zod";
import { BillingV2BreakdownDimension, BillingV2BreakdownScopeKind } from "@app/ee/services/license-v2/license-v2-types";
import { readLimit, writeLimit } from "@app/server/config/rateLimiter";
import { getTelemetryDistinctId } from "@app/server/lib/telemetry";
import { isUserSessionAuth } from "@app/server/plugins/auth/inject-identity";
import { verifyAuth } from "@app/server/plugins/auth/verify-auth";
import { AuthMode } from "@app/services/auth/auth-type";
import { isSuperAdmin } from "@app/services/super-admin/super-admin-fns";
import { PostHogEventTypes } from "@app/services/telemetry/telemetry-types";
// The license server joins this onto its configured portal origin, so it must be a single-rooted
// relative path. Reject protocol-relative ("//host", "/\\host") values that browsers can normalize
// into a host override and use to redirect users off Infisical after the Stripe flow.
const ReturnPathSchema = z
.string()
.trim()
.max(2048)
.startsWith("/")
.refine((path) => !path.startsWith("//") && !path.startsWith("/\\"), {
message: "must be a relative path"
})
.refine(
(path) =>
[...path].every((character) => {
const codePoint = character.charCodeAt(0);
return codePoint > 31 && codePoint !== 127 && character !== "\\";
}),
{ message: "must not contain control characters or backslashes" }
)
.transform((path) => {
const url = new URL(path, "https://infisical.invalid");
return `${url.pathname}${url.search}${url.hash}`;
})
.refine((path) => !path.split(/[?#]/)[0].includes("//"), {
message: "must not contain repeated path separators"
})
.optional();
const BillingV2DimSchema = z.object({
key: z.string(),
label: z.string(),
noun: z.string(),
monthly: z.number(),
annual: z.number(),
included: z.number(),
meteredMonthly: z.boolean().optional(),
meteredAnnual: z.boolean().optional()
});
const BillingV2CompareRowSchema = z.object({
label: z.string(),
// Cells keyed by plan tier so the UI renders one column per plan.
cells: z.record(z.string(), z.union([z.string(), z.number(), z.boolean()]))
});
// Deprecation detail shown to the user: formatted sunset date + whole days remaining (both nullable).
const BillingV2DeprecationSchema = z.object({
reason: z.string().optional(),
nextSteps: z.string().optional(),
date: z.string().nullable(),
daysLeft: z.number().nullable()
});
const BillingV2PlanSchema = z.object({
tier: z.string(),
name: z.string(),
selfServe: z.boolean(),
salesLed: z.boolean(),
trialable: z.boolean(),
upgradeable: z.boolean(),
trialDays: z.number(),
deprecated: z.boolean().optional(),
deprecation: BillingV2DeprecationSchema.optional(),
displayOrder: z.number().optional(),
feature: z.string().optional(),
base: z.object({ monthly: z.number(), annual: z.number() }).optional(),
dims: BillingV2DimSchema.array()
});
const BillingV2CatalogProductSchema = z.object({
id: z.string(),
name: z.string(),
icon: z.string(),
color: z.string(),
addon: z.boolean().optional(),
tagline: z.string().optional(),
deprecated: z.boolean().optional(),
deprecation: BillingV2DeprecationSchema.optional(),
displayOrder: z.number().optional(),
plans: BillingV2PlanSchema.array(),
includes: z.string().array().optional(),
compare: BillingV2CompareRowSchema.array().optional()
});
const BillingV2InvoiceSchema = z.object({
id: z.string(),
number: z.string(),
date: z.string(),
amount: z.number(),
paid: z.boolean(),
pdfUrl: z.string()
});
const BillingV2EntitlementDimSchema = z.object({
key: z.string(),
label: z.string(),
noun: z.string(),
unit: z.string(),
metered: z.boolean(),
cadence: z.enum(["monthly", "annual"]).nullable(),
used: z.number(),
limit: z.number().nullable(),
committed: z.number().nullable(),
commitAvailable: z.boolean(),
// Rates in dollars. per_resource dims: committedRate (annual) + onDemandRate (monthly overage);
// metered dims: rate (per-unit) + freeBand (included). onDemandAmount is the computed monthly
// overage cost.
committedRate: z.number().optional(),
onDemandRate: z.number().optional(),
rate: z.number().optional(),
freeBand: z.number().optional(),
onDemandAmount: z.number(),
canDecreaseNow: z.boolean().optional(),
renewalDate: z.string().nullable().optional(),
decreaseAllowedFrom: z.string().nullable().optional()
});
const BillingV2EntitlementSchema = z.object({
entitled: z.boolean(),
planTier: z.string().optional(),
// Product cadence + recurring amount + monthly on-demand overage; dimensions drives the usage bars.
cadence: z.enum(["monthly", "annual"]).nullable().optional(),
amount: z.number().optional(),
onDemandAmount: z.number().optional(),
dimensions: BillingV2EntitlementDimSchema.array().optional(),
// Trial state; trialEndsAt is a formatted date string.
status: z.string().optional(),
isTrialing: z.boolean().optional(),
trialEndsAt: z.string().nullable().optional(),
trialPlan: z.string().optional(),
trialPlanName: z.string().optional(),
trialPlanEndsAt: z.string().nullable().optional(),
trialPlanDaysLeft: z.number().nullable().optional(),
trialPaymentDueAt: z.string().nullable().optional(),
trialPlanPaymentDueAt: z.string().nullable().optional(),
renewsOn: z.string().nullable().optional(),
deprecation: BillingV2DeprecationSchema.extend({
kind: z.enum(["product", "plan"])
}).optional(),
limit: z.number().nullable().optional(),
used: z.number().optional(),
unit: z.string().nullable().optional()
});
const BillingV2TrialSchema = z.object({
productKey: z.string(),
planTier: z.string().nullable(),
basePlanTier: z.string().nullable(),
outcome: z.string(),
endedReason: z.string().nullable(),
endedDetail: z.string().nullable(),
endedAt: z.string().nullable(),
endedDaysAgo: z.number().nullable()
});
const BillingV2OverviewSchema = z.object({
isCloud: z.boolean(),
mode: z.enum(["self-serve", "managed"]),
subState: z.enum(["active", "trialing", "past-due", "suspended", "no-subscription"]),
planName: z.string(),
billing: z.object({
monthlyRecurring: z.number(),
annualCommitted: z.number(),
activeProductCount: z.number(),
nextCharge: z
.object({
amount: z.number(),
at: z.string(),
productKeys: z.string().array(),
cadence: z.enum(["monthly", "annual"]).nullable(),
hasUsage: z.boolean()
})
.nullable()
}),
payment: z.object({ brand: z.string(), last4: z.string(), expMonth: z.number(), expYear: z.number() }).nullable(),
billingDetails: z
.object({
name: z.string(),
email: z.string(),
address: z
.object({
// Each sub-field is nullish: Stripe/older license servers omit or null any unfilled line.
line1: z.string().nullish(),
line2: z.string().nullish(),
city: z.string().nullish(),
state: z.string().nullish(),
postalCode: z.string().nullish(),
country: z.string().nullish()
})
.nullable(),
taxIds: z.object({ type: z.string(), value: z.string() }).array()
})
.nullable(),
invoices: BillingV2InvoiceSchema.array(),
entitlements: z.record(BillingV2EntitlementSchema),
trialedProductKeys: z.string().array(),
trials: BillingV2TrialSchema.array(),
onDemandAmount: z.number(),
trialPaymentDue: z.object({ dueAt: z.string(), productKeys: z.string().array() }).nullable(),
paymentAlert: z.object({ state: z.enum(["needs_action", "failed"]), actionUrl: z.string() }).nullable(),
checkoutFrozen: z.boolean(),
selfServe: z.boolean()
});
const BillingV2BreakdownScopeSchema = z.object({
orgId: z.string().describe("ID of the organization the units were created in."),
name: z.string().describe("Display name of the organization."),
isRoot: z.boolean().describe("Whether this is the root organization of the billing tree."),
parentOrgName: z
.string()
.nullable()
.describe("Display name of the root organization this sub-organization belongs to; null on a root org."),
count: z.number().describe("Metered units attributed to this organization."),
orgLevelCount: z.number().describe("Units created on the organization itself rather than in a project."),
projects: z
.object({
id: z.string().describe("ID of the project the units were created in."),
name: z.string().describe("Display name of the project."),
count: z.number().describe("Metered units created in this project.")
})
.array()
.describe("Per-project split of this organization's units; empty when the dimension has no project detail.")
});
const BillingV2UsageBreakdownSchema = z.object({
dimensionKey: z.string().describe("The metered dimension this breakdown explains."),
total: z.number().describe("Live total for the dimension, counted the same way the meter counts it."),
userCount: z.number().describe("Human seats in the metered set; 0 for dimensions that count no users."),
scopedCount: z
.number()
.describe("The part of the total the scope tree accounts for; equals total for dimensions with no users."),
hasProjectDetail: z.boolean().describe("Whether units can be attributed to individual projects."),
unit: z.string().describe("Singular noun for what is counted, e.g. 'machine identity'."),
scopes: BillingV2BreakdownScopeSchema.array().describe("Organizations the total is drawn from, largest first.")
});
const BillingV2PreviewLineSchema = z.object({
description: z.string(),
amount: z.number(),
proration: z.boolean()
});
const BillingV2PreviewSchema = z.object({
currency: z.string(),
prorationAmount: z.number(),
additionalCharges: z.number(),
totalDueNow: z.number(),
nextInvoiceTotal: z.number(),
nextRecurringTotal: z.number(),
prorationDate: z.number().nullish(),
toPlanVersionId: z.string().nullish(),
lines: BillingV2PreviewLineSchema.array()
});
// Subscription mutations mirror the checkout result: the change applies in place and the affected
// subscription id comes back (the DB mirror catches up via webhook, so the UI refetches overview).
const BillingV2MutationResultSchema = z.object({ subscriptionId: z.string().optional() });
// Product and plan keys are short catalog identifiers (e.g. "secrets_manager", "advanced").
const BillingV2KeySchema = z.string().trim().min(1).max(64);
const BillingV2QuantitiesSchema = z.record(z.string().trim(), z.number().int().min(0));
const BillingV2CommitmentChangeSchema = z.object({
dimensionKey: z.string().trim(),
quantity: z.number().int().min(0)
});
export const registerLicenseV2Router = async (server: FastifyZodProvider) => {
const buildActor = (permission: FastifyRequest["permission"]) => ({
type: permission.type,
id: permission.id,
authMethod: permission.authMethod,
orgId: permission.orgId,
rootOrgId: permission.rootOrgId,
parentOrgId: permission.parentOrgId
});
server.route({
method: "GET",
url: "/:organizationId/billing/v2/overview",
config: {
rateLimit: readLimit
},
schema: {
params: z.object({ organizationId: z.string().trim() }),
response: {
200: z.object({ overview: BillingV2OverviewSchema })
}
},
onRequest: verifyAuth([AuthMode.JWT, AuthMode.OAUTH]),
handler: async (req) => {
return server.services.licenseV2.getOverview({
orgId: req.params.organizationId,
actor: buildActor(req.permission),
isInstanceAdmin: isSuperAdmin(req.auth)
});
}
});
server.route({
method: "GET",
url: "/:organizationId/billing/v2/organizations",
config: {
rateLimit: readLimit
},
schema: {
operationId: "listBillableOrganizations",
description:
"List the root organizations whose billing the caller may read. A self-hosted instance admin gets every organization on the instance, because one licence covers them all; everyone else gets only their own.",
params: z.object({ organizationId: z.string().trim().uuid() }),
querystring: z.object({
search: z
.string()
.trim()
.max(255)
.optional()
.describe("Match root organizations whose name or slug contains this."),
limit: z.coerce.number().int().min(1).max(1000).default(100).describe("Maximum organizations to return."),
offset: z.coerce.number().int().min(0).default(0).describe("Number of organizations to skip.")
}),
response: {
200: z.object({
organizations: z
.object({
id: z.string().describe("ID of the root organization."),
name: z.string().describe("Display name of the root organization."),
slug: z.string().describe("Slug of the root organization.")
})
.array(),
totalCount: z.number().describe("Root organizations matching the search, across every page.")
})
}
},
onRequest: verifyAuth([AuthMode.JWT, AuthMode.OAUTH]),
handler: async (req) => {
return server.services.licenseV2.getBillableOrganizations({
orgId: req.params.organizationId,
actor: buildActor(req.permission),
isInstanceAdmin: isSuperAdmin(req.auth),
search: req.query.search,
limit: req.query.limit,
offset: req.query.offset
});
}
});
server.route({
method: "GET",
url: "/:organizationId/billing/v2/breakdowns/:dimensionKey",
config: {
rateLimit: readLimit
},
schema: {
operationId: "getBillingUsageBreakdown",
description:
"Break one metered usage dimension down by the organizations and projects its units were created in.",
params: z.object({
organizationId: z.string().trim().uuid(),
dimensionKey: z.nativeEnum(BillingV2BreakdownDimension).describe("The metered dimension to break down.")
}),
querystring: z.object({
scope: z
.nativeEnum(BillingV2BreakdownScopeKind)
.default(BillingV2BreakdownScopeKind.Organization)
.describe(
"'instance' explains usage across the entire self-hosted licence; 'organization' explains one root organization's share of it."
)
}),
response: {
200: z.object({ breakdown: BillingV2UsageBreakdownSchema })
}
},
onRequest: verifyAuth([AuthMode.JWT, AuthMode.OAUTH]),
handler: async (req) => {
return server.services.licenseV2.getUsageBreakdown({
orgId: req.params.organizationId,
dimensionKey: req.params.dimensionKey,
actor: buildActor(req.permission),
isInstanceAdmin: isSuperAdmin(req.auth),
scope: req.query.scope
});
}
});
server.route({
method: "POST",
url: "/:organizationId/billing/v2/overview/refresh",
config: {
rateLimit: writeLimit
},
schema: {
params: z.object({ organizationId: z.string().trim() }),
response: {
200: z.object({ success: z.boolean() })
}
},
onRequest: verifyAuth([AuthMode.JWT]),
handler: async (req) => {
return server.services.licenseV2.refreshEntitlements({
orgId: req.params.organizationId,
actor: buildActor(req.permission)
});
}
});
server.route({
method: "GET",
url: "/:organizationId/billing/v2/catalog",
config: {
rateLimit: readLimit
},
schema: {
params: z.object({ organizationId: z.string().trim() }),
response: {
200: z.object({ products: BillingV2CatalogProductSchema.array() })
}
},
onRequest: verifyAuth([AuthMode.JWT, AuthMode.OAUTH]),
handler: async (req) => {
return server.services.licenseV2.getCatalog({
orgId: req.params.organizationId,
actor: buildActor(req.permission),
isInstanceAdmin: isSuperAdmin(req.auth)
});
}
});
server.route({
method: "POST",
url: "/:organizationId/billing/v2/portal-session",
config: {
rateLimit: writeLimit
},
schema: {
params: z.object({ organizationId: z.string().trim() }),
body: z.object({ returnPath: ReturnPathSchema }),
response: {
200: z.object({ url: z.string() })
}
},
onRequest: verifyAuth([AuthMode.JWT]),
handler: async (req) => {
return server.services.licenseV2.portalSession({
orgId: req.params.organizationId,
actor: buildActor(req.permission),
returnPath: req.body.returnPath
});
}
});
server.route({
method: "POST",
url: "/:organizationId/billing/v2/payment-method",
config: {
rateLimit: writeLimit
},
schema: {
params: z.object({ organizationId: z.string().trim() }),
body: z.object({ returnPath: ReturnPathSchema }),
response: {
200: z.object({ url: z.string() })
}
},
onRequest: verifyAuth([AuthMode.JWT]),
handler: async (req) => {
return server.services.licenseV2.addPaymentMethod({
orgId: req.params.organizationId,
actor: buildActor(req.permission),
returnPath: req.body.returnPath
});
}
});
server.route({
method: "POST",
url: "/:organizationId/billing/v2/subscription/preview",
config: {
rateLimit: writeLimit
},
schema: {
params: z.object({ organizationId: z.string().trim() }),
body: z
.object({
addProductId: z.string().trim().optional(),
plan: z.string().trim().optional(),
cadence: z.enum(["monthly", "annual"]).optional(),
quantities: BillingV2QuantitiesSchema.optional(),
removeProductId: z.string().trim().optional(),
commitmentChanges: BillingV2CommitmentChangeSchema.array().optional(),
upgradeProductId: BillingV2KeySchema.optional(),
upgradePlan: BillingV2KeySchema.optional()
})
.refine(
(b) =>
Boolean(b.addProductId) ||
Boolean(b.removeProductId) ||
Boolean(b.upgradeProductId) ||
Boolean(b.commitmentChanges?.length),
{ message: "provide a product to add, remove or upgrade, or a commitment change" }
)
.refine((b) => !b.upgradeProductId || Boolean(b.upgradePlan), {
message: "upgradePlan is required when upgradeProductId is set"
}),
response: {
200: z.object({ preview: BillingV2PreviewSchema })
}
},
onRequest: verifyAuth([AuthMode.JWT]),
handler: async (req) => {
return server.services.licenseV2.previewChange({
orgId: req.params.organizationId,
actor: buildActor(req.permission),
addProductId: req.body.addProductId,
plan: req.body.plan,
cadence: req.body.cadence,
quantities: req.body.quantities,
removeProductId: req.body.removeProductId,
commitmentChanges: req.body.commitmentChanges,
upgradeProductId: req.body.upgradeProductId,
upgradePlan: req.body.upgradePlan
});
}
});
server.route({
method: "POST",
url: "/:organizationId/billing/v2/subscription/products",
config: {
rateLimit: writeLimit
},
schema: {
params: z.object({ organizationId: z.string().trim() }),
body: z.object({
productId: z.string().trim(),
plan: z.string().trim().optional(),
cadence: z.enum(["monthly", "annual"]).optional(),
quantities: BillingV2QuantitiesSchema.optional(),
returnPath: ReturnPathSchema
}),
response: {
200: z.object({
outcome: z.enum(["checkout_created", "subscription_updated", "payment_action_required"]),
checkoutUrl: z.string().optional(),
paymentUrl: z.string().optional(),
subscriptionId: z.string().optional()
})
}
},
onRequest: verifyAuth([AuthMode.JWT]),
handler: async (req) => {
// A first-touch org has no Stripe customer yet, so the server needs an email. Take it from the
// authenticated user (JWT-only route) rather than trusting a client-supplied value.
const email = isUserSessionAuth(req.auth) ? (req.auth.user.email ?? undefined) : undefined;
const result = await server.services.licenseV2.buyProduct({
orgId: req.params.organizationId,
actor: buildActor(req.permission),
productId: req.body.productId,
plan: req.body.plan,
cadence: req.body.cadence,
quantities: req.body.quantities,
email,
returnPath: req.body.returnPath
});
if (result.outcome === "payment_action_required") {
return { outcome: result.outcome, paymentUrl: result.paymentUrl };
}
void server.services.telemetry
.sendPostHogEvents({
event:
result.outcome === "checkout_created"
? PostHogEventTypes.BillingCheckoutSessionCreated
: PostHogEventTypes.BillingProductActivated,
distinctId: getTelemetryDistinctId(req),
organizationId: req.params.organizationId,
properties: {
productId: req.body.productId,
plan: result.plan,
cadence: result.cadence,
...(result.outcome === "subscription_updated" ? { subscriptionId: result.subscriptionId } : {})
}
})
.catch(() => {});
return result.outcome === "checkout_created"
? { outcome: result.outcome, checkoutUrl: result.checkoutUrl }
: { outcome: result.outcome, subscriptionId: result.subscriptionId };
}
});
server.route({
method: "POST",
url: "/:organizationId/billing/v2/subscription/upgrade",
config: {
rateLimit: writeLimit
},
schema: {
params: z.object({ organizationId: z.string().trim() }),
body: z.object({
productId: BillingV2KeySchema,
plan: BillingV2KeySchema,
expectedPlanVersionId: z.string().trim().uuid(),
prorationDate: z.number().int().positive().optional()
}),
response: {
200: z.object({
outcome: z.enum(["upgraded", "payment_action_required"]),
paymentUrl: z.string().optional(),
subscriptionId: z.string().optional(),
fromPlanKey: z.string().optional(),
toPlanKey: z.string().optional()
})
}
},
onRequest: verifyAuth([AuthMode.JWT]),
handler: async (req) => {
const result = await server.services.licenseV2.upgradeProduct({
orgId: req.params.organizationId,
actor: buildActor(req.permission),
productId: req.body.productId,
plan: req.body.plan,
expectedPlanVersionId: req.body.expectedPlanVersionId,
prorationDate: req.body.prorationDate
});
// Nothing is upgraded until the bank approves the charge.
if (result.outcome === "payment_action_required") {
return result;
}
void server.services.telemetry
.sendPostHogEvents({
event: PostHogEventTypes.BillingPlanUpgraded,
distinctId: getTelemetryDistinctId(req),
organizationId: req.params.organizationId,
properties: {
productId: req.body.productId,
fromPlan: result.fromPlanKey,
toPlan: result.toPlanKey ?? req.body.plan,
subscriptionId: result.subscriptionId
}
})
.catch(() => {});
return result;
}
});
server.route({
method: "DELETE",
url: "/:organizationId/billing/v2/subscription/products/:productId",
config: {
rateLimit: writeLimit
},
schema: {
params: z.object({ organizationId: z.string().trim(), productId: z.string().trim() }),
response: {
200: BillingV2MutationResultSchema
}
},
onRequest: verifyAuth([AuthMode.JWT]),
handler: async (req) => {
return server.services.licenseV2.removeProduct({
orgId: req.params.organizationId,
actor: buildActor(req.permission),
productId: req.params.productId
});
}
});
// Start / change annual commitments across dimensions in one atomic call. Increase is charged now; a
// decrease is rejected unless the dimension's window is open (server-enforced).
server.route({
method: "PUT",
url: "/:organizationId/billing/v2/subscription/commitments",
config: {
rateLimit: writeLimit
},
schema: {
params: z.object({ organizationId: z.string().trim() }),
body: z.object({
changes: BillingV2CommitmentChangeSchema.array().min(1).max(20),
productId: z.string().trim()
}),
response: {
200: z.object({
outcome: z.enum(["checkout_created", "subscription_updated", "payment_action_required"]),
checkoutUrl: z.string().optional(),
paymentUrl: z.string().optional(),
subscriptionId: z.string().optional()
})
}
},
onRequest: verifyAuth([AuthMode.JWT]),
handler: async (req) => {
return server.services.licenseV2.changeCommitments({
orgId: req.params.organizationId,
actor: buildActor(req.permission),
changes: req.body.changes,
productId: req.body.productId
});
}
});
server.route({
method: "POST",
url: "/:organizationId/billing/v2/trial",
config: {
rateLimit: writeLimit
},
schema: {
params: z.object({ organizationId: z.string().trim() }),
body: z.object({
productId: z.string().trim().min(1).max(255),
plan: z.string().trim().min(1).max(255),
returnPath: ReturnPathSchema
}),
response: {
200: z.object({
outcome: z.enum(["trial_started", "awaiting_card"]),
cardSetupUrl: z.string().optional()
})
}
},
onRequest: verifyAuth([AuthMode.JWT]),
handler: async (req) => {
// A trial has no Stripe customer yet, so the server needs an email. Take it from the authenticated
// user (this route is JWT-only) rather than trusting a client-supplied value.
const email = isUserSessionAuth(req.auth) ? (req.auth.user.email ?? undefined) : undefined;
const result = await server.services.licenseV2.startTrial({
orgId: req.params.organizationId,
actor: buildActor(req.permission),
productId: req.body.productId,
plan: req.body.plan,
returnPath: req.body.returnPath,
email
});
// Split on outcome rather than passing it as a property: "awaiting_card" means no card was on
// file and the trial was NOT granted, so folding it into a "Trial Started" would overcount
// trials. The actual grant for that branch happens on the License Server after the card-setup
// checkout completes, which this service never observes, so neither event tracks conversion.
void server.services.telemetry
.sendPostHogEvents({
event:
result.outcome === "trial_started" ? PostHogEventTypes.TrialStarted : PostHogEventTypes.TrialCardRequired,
distinctId: getTelemetryDistinctId(req),
organizationId: req.params.organizationId,
properties: {
productId: req.body.productId,
plan: req.body.plan
}
})
.catch(() => {});
return result;
}
});
server.route({
method: "POST",
url: "/:organizationId/billing/v2/trial/cancel",
config: {
rateLimit: writeLimit
},
schema: {
params: z.object({ organizationId: z.string().trim() }),
body: z.object({
productId: z.string().trim()
}),
response: {
200: z.object({
outcome: z.literal("trial_completed")
})
}
},
onRequest: verifyAuth([AuthMode.JWT]),
handler: async (req) => {
return server.services.licenseV2.cancelTrial({
orgId: req.params.organizationId,
actor: buildActor(req.permission),
productId: req.body.productId
});
}
});
server.route({
method: "POST",
url: "/:organizationId/billing/v2/trial/confirm-payment",
config: {
rateLimit: writeLimit
},
schema: {
operationId: "confirmBillingTrialPayment",
description:
"Get the page where the customer approves a trial conversion charge their bank is holding (for example 3D Secure): a Stripe Checkout for a trial on the free tier, or the invoice of the held change for an upgrade trial. The trial converts once it is paid. Returns 'upgraded' with no redirect when the charge went through without needing approval.",
params: z.object({ organizationId: z.string().trim().uuid() }),
body: z.object({ returnPath: ReturnPathSchema }),
response: {
200: z.object({
outcome: z.enum(["checkout_created", "payment_action_required", "upgraded"]),
redirectUrl: z.string().optional()
})
}
},
onRequest: verifyAuth([AuthMode.JWT]),
handler: async (req) => {
return server.services.licenseV2.confirmTrialPayment({
orgId: req.params.organizationId,
actor: buildActor(req.permission),
returnPath: req.body.returnPath
});
}
});
server.route({
method: "POST",
url: "/:organizationId/billing/v2/subscription/cancel",
config: {
rateLimit: writeLimit
},
schema: {
params: z.object({ organizationId: z.string().trim() }),
response: {
200: BillingV2MutationResultSchema
}
},
onRequest: verifyAuth([AuthMode.JWT]),
handler: async (req) => {
return server.services.licenseV2.cancelSubscription({
orgId: req.params.organizationId,
actor: buildActor(req.permission)
});
}
});
server.route({
method: "POST",
url: "/:organizationId/billing/v2/subscription/resume",
config: {
rateLimit: writeLimit
},
schema: {
params: z.object({ organizationId: z.string().trim() }),
response: {
200: BillingV2MutationResultSchema
}
},
onRequest: verifyAuth([AuthMode.JWT]),
handler: async (req) => {
return server.services.licenseV2.resumeSubscription({
orgId: req.params.organizationId,
actor: buildActor(req.permission)
});
}
});
};