Skip to content

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

feat: removed all license v2 read mode and old code

=cfda6bdcc945
diff --git a/backend/e2e-test/license-dal.spec.ts b/backend/e2e-test/license-dal.spec.ts
index dbd744e794..0176858ba6 100644
--- a/backend/e2e-test/license-dal.spec.ts
+++ b/backend/e2e-test/license-dal.spec.ts
@@ -205,21 +205,18 @@ describe("license-dal billable org-actor count", () => {
});
// Billable identities: i1 (SM), i4 (KMS via group), i3 (projectless root), i5 (projectless sub-org).
- // Excluded: i2 (PAM only).
- test("countOfOrgIdentities counts only billable identities, including sub-orgs", async () => {
- const count = await licenseDAL.countOfOrgIdentities(ROOT_ORG_ID, testDb);
- expect(count).toBe(4);
- });
-
+ // Excluded: i2 (PAM only). Counted here through the combined total (5 users + 4 identities), since
+ // the identity-only counter has no callers.
test("countOrgUsersAndIdentities returns the combined billable total", async () => {
const count = await licenseDAL.countOrgUsersAndIdentities(ROOT_ORG_ID, testDb);
expect(count).toBe(9);
});
test("scoping to an unrelated org yields zero", async () => {
- const users = await licenseDAL.countOfOrgMembers(randomUUID(), testDb);
- const identities = await licenseDAL.countOfOrgIdentities(randomUUID(), testDb);
+ const unrelatedOrgId = randomUUID();
+ const users = await licenseDAL.countOfOrgMembers(unrelatedOrgId, testDb);
+ const usersAndIdentities = await licenseDAL.countOrgUsersAndIdentities(unrelatedOrgId, testDb);
expect(users).toBe(0);
- expect(identities).toBe(0);
+ expect(usersAndIdentities).toBe(0);
});
});
diff --git a/backend/src/db/migrations/20260404140729_seed-email-domains-from-sso.ts b/backend/src/db/migrations/20260404140729_seed-email-domains-from-sso.ts
index e47c7eea8d..77308d2d5b 100644
--- a/backend/src/db/migrations/20260404140729_seed-email-domains-from-sso.ts
+++ b/backend/src/db/migrations/20260404140729_seed-email-domains-from-sso.ts
@@ -66,9 +66,9 @@ export async function up(knex: Knex): Promise<void> {
const log = (msg: string) => console.log(`[auto domain seeding] ${msg}`);
// Only run for non-cloud (self-hosted) environments
- // Cloud environments have LICENSE_SERVER_KEY set
- if (process.env.LICENSE_SERVER_KEY) {
- log("Skipping — cloud environment (LICENSE_SERVER_KEY set)");
+ // Cloud environments have LICENSE_SERVER_V2_SERVICE_KEY set
+ if (process.env.LICENSE_SERVER_V2_SERVICE_KEY) {
+ log("Skipping — cloud environment (LICENSE_SERVER_V2_SERVICE_KEY set)");
return;
}
diff --git a/backend/src/db/migrations/utils/env-config.ts b/backend/src/db/migrations/utils/env-config.ts
index 5f70b912a5..a18c0714a3 100644
--- a/backend/src/db/migrations/utils/env-config.ts
+++ b/backend/src/db/migrations/utils/env-config.ts
@@ -28,14 +28,9 @@ const envSchema = z
HSM_SLOT: z.coerce.number().optional().default(0),
LICENSE_SERVER_URL: zpStr(z.string().optional().default("https://portal.infisical.com")),
- LICENSE_SERVER_KEY: zpStr(z.string().optional()),
+ LICENSE_SERVER_V2_SERVICE_KEY: zpStr(z.string().optional()),
LICENSE_KEY: zpStr(z.string().optional()),
LICENSE_KEY_OFFLINE: zpStr(z.string().optional()),
- LICENSE_SERVER_V2_MODE: z.enum(["off", "read-compare", "on"]).default("off"),
- DISABLE_LICENSE_V1_CLOUD: z
- .enum(["true", "false"])
- .default("false")
- .transform((val) => val === "true"),
INTERNAL_REGION: zpStr(z.enum(["us", "eu"]).optional()),
SITE_URL: zpStr(z.string().transform((val) => (val ? removeTrailingSlash(val) : val))).optional()
@@ -43,6 +38,8 @@ const envSchema = z
// To ensure that basic encryption is always possible.
.transform((data) => ({
...data,
+ // Mirrors env.ts: only cloud holds the License Server service key.
+ isCloud: Boolean(data.LICENSE_SERVER_V2_SERVICE_KEY),
isHsmConfigured:
Boolean(data.HSM_LIB_PATH) && Boolean(data.HSM_PIN) && Boolean(data.HSM_KEY_LABEL) && data.HSM_SLOT !== undefined
}));
diff --git a/backend/src/ee/routes/v1/license-router.ts b/backend/src/ee/routes/v1/license-router.ts
index c3c48bdc9f..aba03bbb48 100644
--- a/backend/src/ee/routes/v1/license-router.ts
+++ b/backend/src/ee/routes/v1/license-router.ts
@@ -3,38 +3,14 @@
// TODO(akhilmhdh): Fix this when license service gets it type
import { z } from "zod";
-import { readLimit, writeLimit } from "@app/server/config/rateLimiter";
+import { readLimit } from "@app/server/config/rateLimiter";
import { verifyAuth } from "@app/server/plugins/auth/verify-auth";
import { AuthMode } from "@app/services/auth/auth-type";
+// Plan reads only. The cloud billing surface (checkout, portal, payment methods, tax ids, invoices)
+// lives on the License Server v2 routes in license-v2-router; the License Server v1 endpoints these
+// used to call are decommissioned.
export const registerLicenseRouter = async (server: FastifyZodProvider) => {
- server.route({
- method: "GET",
- url: "/:organizationId/plans/table",
- config: {
- rateLimit: readLimit
- },
- schema: {
- querystring: z.object({ billingCycle: z.enum(["monthly", "yearly"]) }),
- params: z.object({ organizationId: z.string().trim() }),
- response: {
- 200: z.any()
- }
- },
- onRequest: verifyAuth([AuthMode.JWT]),
- handler: async (req) => {
- const data = await server.services.license.getOrgPlansTableByBillCycle({
- actorId: req.permission.id,
- actor: req.permission.type,
- actorOrgId: req.permission.orgId,
- orgId: req.params.organizationId,
- actorAuthMethod: req.permission.authMethod,
- billingCycle: req.query.billingCycle
- });
- return data;
- }
- });
-
server.route({
method: "GET",
url: "/:organizationId/plan",
@@ -94,390 +70,4 @@ export const registerLicenseRouter = async (server: FastifyZodProvider) => {
return data;
}
});
-
- server.route({
- method: "POST",
- url: "/:organizationId/session/trial",
- config: {
- rateLimit: writeLimit
- },
- schema: {
- params: z.object({ organizationId: z.string().trim() }),
- body: z.object({ success_url: z.string().trim() }),
- response: {
- 200: z.any()
- }
- },
- onRequest: verifyAuth([AuthMode.JWT]),
- handler: async (req) => {
- const data = await server.services.license.startOrgTrial({
- actorId: req.permission.id,
- actor: req.permission.type,
- actorOrgId: req.permission.orgId,
- orgId: req.params.organizationId,
- actorAuthMethod: req.permission.authMethod,
- success_url: req.body.success_url
- });
- return data;
- }
- });
-
- server.route({
- url: "/:organizationId/customer-portal-session",
- method: "POST",
- config: {
- rateLimit: writeLimit
- },
- schema: {
- params: z.object({ organizationId: z.string().trim() }),
- response: {
- 200: z.any()
- }
- },
- onRequest: verifyAuth([AuthMode.JWT]),
- handler: async (req) => {
- const data = await server.services.license.createOrganizationPortalSession({
- actorId: req.permission.id,
- actor: req.permission.type,
- actorOrgId: req.permission.orgId,
- actorAuthMethod: req.permission.authMethod,
- orgId: req.params.organizationId
- });
- return data;
- }
- });
-
- server.route({
- method: "GET",
- url: "/:organizationId/plan/billing",
- config: {
- rateLimit: readLimit
- },
- schema: {
- params: z.object({ organizationId: z.string().trim() }),
- response: {
- 200: z.any()
- }
- },
- onRequest: verifyAuth([AuthMode.JWT]),
- handler: async (req) => {
- const data = await server.services.license.getOrgBillingInfo({
- actorId: req.permission.id,
- actor: req.permission.type,
- actorOrgId: req.permission.orgId,
- actorAuthMethod: req.permission.authMethod,
- orgId: req.params.organizationId
- });
- return data;
- }
- });
-
- server.route({
- method: "GET",
- url: "/:organizationId/plan/table",
- config: {
- rateLimit: readLimit
- },
- schema: {
- params: z.object({ organizationId: z.string().trim() }),
- response: {
- 200: z.any()
- }
- },
- onRequest: verifyAuth([AuthMode.JWT]),
- handler: async (req) => {
- const data = await server.services.license.getOrgPlanTable({
- actorId: req.permission.id,
- actor: req.permission.type,
- actorOrgId: req.permission.orgId,
- actorAuthMethod: req.permission.authMethod,
- orgId: req.params.organizationId
- });
- return data;
- }
- });
-
- server.route({
- method: "GET",
- url: "/:organizationId/billing-details",
- config: {
- rateLimit: readLimit
- },
- schema: {
- params: z.object({ organizationId: z.string().trim() }),
- response: {
- 200: z.any()
- }
- },
- onRequest: verifyAuth([AuthMode.JWT]),
- handler: async (req) => {
- const data = await server.services.license.getOrgBillingDetails({
- actorId: req.permission.id,
- actor: req.permission.type,
- actorOrgId: req.permission.orgId,
- actorAuthMethod: req.permission.authMethod,
- orgId: req.params.organizationId
- });
- return data;
- }
- });
-
- server.route({
- method: "PATCH",
- url: "/:organizationId/billing-details",
- config: {
- rateLimit: writeLimit
- },
- schema: {
- params: z.object({ organizationId: z.string().trim() }),
- body: z.object({
- email: z.string().trim().email().optional(),
- name: z.string().trim().optional()
- }),
- response: {
- 200: z.any()
- }
- },
- onRequest: verifyAuth([AuthMode.JWT]),
- handler: async (req) => {
- const data = await server.services.license.updateOrgBillingDetails({
- actorId: req.permission.id,
- actor: req.permission.type,
- actorOrgId: req.permission.orgId,
- actorAuthMethod: req.permission.authMethod,
- orgId: req.params.organizationId,
- name: req.body.name,
- email: req.body.email
- });
- return data;
- }
- });
-
- server.route({
- method: "GET",
- url: "/:organizationId/billing-details/payment-methods",
- config: {
- rateLimit: readLimit
- },
- schema: {
- params: z.object({ organizationId: z.string().trim() }),
- response: {
- 200: z.any()
- }
- },
- onRequest: verifyAuth([AuthMode.JWT]),
- handler: async (req) => {
- const data = await server.services.license.getOrgPmtMethods({
- actorId: req.permission.id,
- actor: req.permission.type,
- actorOrgId: req.permission.orgId,
- actorAuthMethod: req.permission.authMethod,
- orgId: req.params.organizationId
- });
- return data;
- }
- });
-
- server.route({
- method: "POST",
- url: "/:organizationId/billing-details/payment-methods",
- config: {
- rateLimit: writeLimit
- },
- schema: {
- params: z.object({ organizationId: z.string().trim() }),
- body: z.object({
- success_url: z.string().trim(),
- cancel_url: z.string().trim()
- }),
- response: {
- 200: z.any()
- }
- },
- onRequest: verifyAuth([AuthMode.JWT]),
- handler: async (req) => {
- const data = await server.services.license.addOrgPmtMethods({
- actorId: req.permission.id,
- actor: req.permission.type,
- actorOrgId: req.permission.orgId,
- actorAuthMethod: req.permission.authMethod,
- orgId: req.params.organizationId,
- success_url: req.body.success_url,
- cancel_url: req.body.cancel_url
- });
- return data;
- }
- });
-
- server.route({
- method: "DELETE",
- url: "/:organizationId/billing-details/payment-methods/:pmtMethodId",
- config: {
- rateLimit: writeLimit
- },
- schema: {
- params: z.object({
- organizationId: z.string().trim(),
- pmtMethodId: z.string().trim()
- }),
- response: {
- 200: z.any()
- }
- },
- onRequest: verifyAuth([AuthMode.JWT]),
- handler: async (req) => {
- const data = await server.services.license.delOrgPmtMethods({
- actorId: req.permission.id,
- actor: req.permission.type,
- actorAuthMethod: req.permission.authMethod,
- actorOrgId: req.permission.orgId,
- orgId: req.params.organizationId,
- pmtMethodId: req.params.pmtMethodId
- });
- return data;
- }
- });
-
- server.route({
- method: "GET",
- url: "/:organizationId/billing-details/tax-ids",
- config: {
- rateLimit: readLimit
- },
- schema: {
- params: z.object({
- organizationId: z.string().trim()
- }),
- response: {
- 200: z.any()
- }
- },
- onRequest: verifyAuth([AuthMode.JWT]),
- handler: async (req) => {
- const data = await server.services.license.getOrgTaxIds({
- actorId: req.permission.id,
- actor: req.permission.type,
- actorAuthMethod: req.permission.authMethod,
- actorOrgId: req.permission.orgId,
- orgId: req.params.organizationId
- });
- return data;
- }
- });
-
- server.route({
- method: "POST",
- url: "/:organizationId/billing-details/tax-ids",
- config: {
- rateLimit: writeLimit
- },
- schema: {
- params: z.object({
- organizationId: z.string().trim()
- }),
- body: z.object({
- type: z.string().trim(),
- value: z.string().trim()
- }),
- response: {
- 200: z.any()
- }
- },
- onRequest: verifyAuth([AuthMode.JWT]),
- handler: async (req) => {
- const data = await server.services.license.addOrgTaxId({
- actorId: req.permission.id,
- actor: req.permission.type,
- actorAuthMethod: req.permission.authMethod,
- actorOrgId: req.permission.orgId,
- orgId: req.params.organizationId,
- type: req.body.type,
- value: req.body.value
- });
- return data;
- }
- });
-
- server.route({
- method: "DELETE",
- url: "/:organizationId/billing-details/tax-ids/:taxId",
- config: {
- rateLimit: writeLimit
- },
- schema: {
- params: z.object({
- organizationId: z.string().trim(),
- taxId: z.string().trim()
- }),
- response: {
- 200: z.any()
- }
- },
- onRequest: verifyAuth([AuthMode.JWT]),
- handler: async (req) => {
- const data = await server.services.license.delOrgTaxId({
- actorId: req.permission.id,
- actor: req.permission.type,
- actorAuthMethod: req.permission.authMethod,
- actorOrgId: req.permission.orgId,
- orgId: req.params.organizationId,
- taxId: req.params.taxId
- });
- return data;
- }
- });
-
- server.route({
- method: "GET",
- url: "/:organizationId/invoices",
- config: {
- rateLimit: readLimit
- },
- schema: {
- params: z.object({
- organizationId: z.string().trim()
- }),
- response: {
- 200: z.any()
- }
- },
- onRequest: verifyAuth([AuthMode.JWT]),
- handler: async (req) => {
- const data = await server.services.license.getOrgTaxInvoices({
- actorId: req.permission.id,
- actor: req.permission.type,
- actorOrgId: req.permission.orgId,
- orgId: req.params.organizationId,
- actorAuthMethod: req.permission.authMethod
- });
- return data;
- }
- });
-
- server.route({
- method: "GET",
- url: "/:organizationId/licenses",
- config: {
- rateLimit: readLimit
- },
- schema: {
- params: z.object({
- organizationId: z.string().trim()
- }),
- response: {
- 200: z.any()
- }
- },
- onRequest: verifyAuth([AuthMode.JWT]),
- handler: async (req) => {
- const data = await server.services.license.getOrgLicenses({
- actorId: req.permission.id,
- actor: req.permission.type,
- actorOrgId: req.permission.orgId,
- actorAuthMethod: req.permission.authMethod,
- orgId: req.params.organizationId
- });
- return data;
- }
- });
};
diff --git a/backend/src/ee/routes/v1/license-v2-router.ts b/backend/src/ee/routes/v1/license-v2-router.ts
index 961a779937..1528e34a79 100644
--- a/backend/src/ee/routes/v1/license-v2-router.ts
+++ b/backend/src/ee/routes/v1/license-v2-router.ts
@@ -1,7 +1,6 @@
import { FastifyRequest } from "fastify";
import { z } from "zod";
-import { NotFoundError } from "@app/lib/errors";
import { readLimit, writeLimit } from "@app/server/config/rateLimiter";
import { verifyAuth } from "@app/server/plugins/auth/verify-auth";
import { AuthMode } from "@app/services/auth/auth-type";
@@ -200,13 +199,6 @@ const BillingV2CommitmentChangeSchema = z.object({
});
export const registerLicenseV2Router = async (server: FastifyZodProvider) => {
- // Every route is gated on LICENSE_SERVER_V2_MODE="on"; the billing surface is invisible until full v2 cutover.
- server.addHook("onRequest", async () => {
- if (!server.services.licenseV2.isEnabled()) {
- throw new NotFoundError({ message: "License Server v2 is not enabled" });
- }
- });
-
const buildActor = (permission: FastifyRequest["permission"]) => ({
type: permission.type,
id: permission.id,
diff --git a/backend/src/ee/services/license-v2/license-v2-service.ts b/backend/src/ee/services/license-v2/license-v2-service.ts
index d916706afd..0e455c3121 100644
--- a/backend/src/ee/services/license-v2/license-v2-service.ts
+++ b/backend/src/ee/services/license-v2/license-v2-service.ts
@@ -42,7 +42,7 @@ import {
} from "./license-v2-types";
type TLicenseV2ServiceFactoryDep = {
- envConfig: Pick<TEnvConfig, "LICENSE_SERVER_V2_MODE" | "LICENSE_KEY" | "SITE_URL">;
+ envConfig: Pick<TEnvConfig, "isCloud" | "SITE_URL">;
orgDAL: Pick<TOrgDALFactory, "findById">;
permissionService: Pick<TPermissionServiceFactory, "getOrgPermission">;
// Same metered-feature/count-fn pairs the usage pipeline registers; used to seed a purchase's initial
@@ -389,7 +389,10 @@ export const licenseV2ServiceFactory = ({
return { planTier: plan.tier, quantities, declaredUsage };
};
- const isSelfHostedLicense = Boolean(envConfig.LICENSE_KEY);
+ // Any non-cloud instance gets the read-only "managed" billing view: a self-hosted license is
+ // provisioned out-of-band, and an unlicensed instance has no billing surface to drive at all. Only
+ // cloud has per-org self-serve subscriptions.
+ const isSelfHostedLicense = !envConfig.isCloud;
const ensureBillingRead = async (orgId: string, actor: TGetBillingV2OverviewDTO["actor"]) => {
const { permission } = await permissionService.getOrgPermission({
@@ -1026,8 +1029,6 @@ export const licenseV2ServiceFactory = ({
};
return {
- // Billing surface (portal, checkout, overview) goes live only at full v2 cutover, not during read-compare.
- isEnabled: () => envConfig.LICENSE_SERVER_V2_MODE === "on",
getOverview,
refreshEntitlements,
getCatalog,
diff --git a/backend/src/ee/services/license/__mocks__/license-fns.ts b/backend/src/ee/services/license/__mocks__/license-fns.ts
index 52f75e3fdc..aca0234d07 100644
--- a/backend/src/ee/services/license/__mocks__/license-fns.ts
+++ b/backend/src/ee/services/license/__mocks__/license-fns.ts
@@ -51,8 +51,6 @@ export const getDefaultOnPremFeatures = () => {
};
};
-export const setupLicenseRequestWithStore = () => {};
-
export const getLicenseKeyConfig = () => {
return {
isValid: false
diff --git a/backend/src/ee/services/license/licence-enums.ts b/backend/src/ee/services/license/licence-enums.ts
deleted file mode 100644
index 06d9c9d56e..0000000000
--- a/backend/src/ee/services/license/licence-enums.ts
+++ /dev/null
@@ -1,25 +0,0 @@
-export const BillingPlanRows = {
- IdentityLimit: { name: "Organization identity limit", field: "identityLimit" },
- WorkspaceLimit: { name: "Project limit", field: "workspaceLimit" },
- EnvironmentLimit: { name: "Environment limit", field: "environmentLimit" },
- SecretVersioning: { name: "Secret versioning", field: "secretVersioning" },
- PitRecovery: { name: "Point in time recovery", field: "pitRecovery" },
- Rbac: { name: "RBAC", field: "rbac" },
- CustomRateLimits: { name: "Custom rate limits", field: "customRateLimits" },
- CustomAlerts: { name: "Custom alerts", field: "customAlerts" },
- AuditLogs: { name: "Audit logs", field: "auditLogs" },
- SamlSSO: { name: "SAML SSO", field: "samlSSO" },
- Hsm: { name: "Hardware Security Module (HSM)", field: "hsm" },
- OidcSSO: { name: "OIDC SSO", field: "oidcSSO" },
- SecretApproval: { name: "Secret approvals", field: "secretApproval" },
- SecretRotation: { name: "Secret rotation", field: "secretRotation" },
- InstanceUserManagement: { name: "Instance User Management", field: "instanceUserManagement" },
- ExternalKms: { name: "External KMS", field: "externalKms" },
- HoneyTokens: { name: "Honey Tokens", field: "honeyTokens" },
- SecretsBrokering: { name: "Secrets Brokering", field: "secretsBrokering" }
-} as const;
-
-export const BillingPlanTableHead = {
- Allowed: { name: "Allowed" },
- Used: { name: "Used" }
-} as const;
diff --git a/backend/src/ee/services/license/license-dal.ts b/backend/src/ee/services/license/license-dal.ts
index c4a5c12548..be495a3a95 100644
--- a/backend/src/ee/services/license/license-dal.ts
+++ b/backend/src/ee/services/license/license-dal.ts
@@ -184,15 +184,6 @@ export const licenseDALFactory = (db: TDbClient) => {
}
};
- const countOfOrgIdentities = async (orgId: string | null, tx?: Knex) => {
- try {
- const { identities } = await countBillableOrgActors(orgId, tx);
- return identities;
- } catch (error) {
- throw new DatabaseError({ error, name: "Count of Org Identities" });
- }
- };
-
const countOrgUsersAndIdentities = async (orgId: string | null, tx?: Knex) => {
try {
const { users, identities } = await countBillableOrgActors(orgId, tx);
@@ -202,5 +193,5 @@ export const licenseDALFactory = (db: TDbClient) => {
}
};
- return { countOfOrgMembers, countOrgUsersAndIdentities, countOfOrgIdentities };
+ return { countOfOrgMembers, countOrgUsersAndIdentities };
};
diff --git a/backend/src/ee/services/license/license-fns.ts b/backend/src/ee/services/license/license-fns.ts
index 612d2e7aea..5ed939f378 100644
--- a/backend/src/ee/services/license/license-fns.ts
+++ b/backend/src/ee/services/license/license-fns.ts
@@ -1,10 +1,6 @@
-import axios, { AxiosError } from "axios";
-
import { TLicenseServiceFactory } from "@app/ee/services/license/license-service";
import { getConfig, TEnvConfig } from "@app/lib/config/env";
-import { request } from "@app/lib/config/request";
import { BadRequestError } from "@app/lib/errors";
-import { logger } from "@app/lib/logger";
import { UserAliasType } from "@app/services/user-alias/user-alias-types";
import { LicenseType, TFeatureSet, TLicenseKeyConfig, TOfflineLicenseContents } from "./license-types";
@@ -133,75 +129,6 @@ export const getDefaultOnPremFeatures = (): TFeatureSet => ({
crossProjectSecretSharing: false
});
-export const setupLicenseRequestWithStore = (
- baseURL: string,
- refreshUrl: string,
- licenseKey: string,
- region?: string
-) => {
- let token: string;
- const licenseReq = axios.create({
- baseURL,
- timeout: 35 * 1000,
- headers: {
- "x-region": region
- }
- });
-
- const refreshLicense = async () => {
- const appCfg = getConfig();
- const {
- data: { token: authToken }
- } = await request.post<{ token: string }>(
- refreshUrl,
- {},
- {
- baseURL: appCfg.LICENSE_SERVER_URL,
- headers: {
- "X-API-KEY": licenseKey
- }
- }
- );
- token = authToken;
- return token;
- };
-
- licenseReq.interceptors.request.use(
- (config) => {
- if (token && config.headers) {
- // eslint-disable-next-line no-param-reassign
- config.headers.Authorization = `Bearer ${token}`;
- }
- return config;
- },
- (err) => Promise.reject(err)
- );
-
- licenseReq.interceptors.response.use(
- (response) => response,
- async (err) => {
- const originalRequest = (err as AxiosError).config;
- const errStatusCode = Number((err as AxiosError)?.response?.status);
- logger.error((err as AxiosError)?.response?.data, "License server call error");
- // eslint-disable-next-line
- if ((errStatusCode === 401 || errStatusCode === 403) && !(originalRequest as any)._retry) {
- // eslint-disable-next-line
- (originalRequest as any)._retry = true; // injected
-
- // refresh
- await refreshLicense();
-
- licenseReq.defaults.headers.common.Authorization = `Bearer ${token}`;
- return licenseReq(originalRequest!);
- }
-
- return Promise.reject(err);
- }
- );
-
- return { request: licenseReq, refreshLicense };
-};
-
export const throwOnPlanSeatLimitReached = async (
licenseService: Pick<TLicenseServiceFactory, "getPlan">,
orgId: string,
diff --git a/backend/src/ee/services/license/license-service.ts b/backend/src/ee/services/license/license-service.ts
index 6af04e4d87..608a5c32ee 100644
--- a/backend/src/ee/services/license/license-service.ts
+++ b/backend/src/ee/services/license/license-service.ts
@@ -1,11 +1,3 @@
-/* eslint-disable @typescript-eslint/no-unsafe-return */
-/* eslint-disable @typescript-eslint/no-unsafe-assignment */
-// eslint-disable @typescript-eslint/no-unsafe-assignment
-
-// TODO(akhilmhdh): With tony find out the api structure and fill it here
-
-import { ForbiddenError } from "@casl/ability";
-import { AxiosError } from "axios";
import { CronJob } from "cron";
import { Knex } from "knex";
@@ -19,66 +11,40 @@ import { logger } from "@app/lib/logger";
import { requestMemoKeys } from "@app/lib/request-context/memo-keys";
import { requestMemoize } from "@app/lib/request-context/request-memoizer";
import { UserIdentities } from "@app/services/license-client";
-import { projectV2ToFeatureSet } from "@app/services/license-client/dual-read/entitlement-projection";
+import { projectV2ToFeatureSet } from "@app/services/license-client/entitlement-projection";
import { TLicenseClientFactory } from "@app/services/license-client/license-client";
import { TUsageMeteringServiceFactory } from "@app/services/license-client/usage";
import { TOrgDALFactory } from "@app/services/org/org-dal";
import { TProjectDALFactory } from "@app/services/project/project-dal";
-import { OrgPermissionBillingActions, OrgPermissionSubjects } from "../permission/org-permission";
import { TPermissionServiceFactory } from "../permission/permission-service-types";
-import { BillingPlanRows, BillingPlanTableHead } from "./licence-enums";
import { TLicenseDALFactory } from "./license-dal";
-import { getDefaultOnPremFeatures, getLicenseKeyConfig, setupLicenseRequestWithStore } from "./license-fns";
+import { getDefaultOnPremFeatures, getLicenseKeyConfig } from "./license-fns";
import {
InstanceType,
LicenseType,
- TAddOrgPmtMethodDTO,
- TAddOrgTaxIdDTO,
- TCreateOrgPortalSession,
- TDelOrgPmtMethodDTO,
- TDelOrgTaxIdDTO,
TFeatureSet,
- TGetOrgBillInfoDTO,
- TGetOrgTaxIdDTO,
TOfflineLicense,
TOfflineLicenseContents,
- TOrgInvoiceDTO,
- TOrgLicensesDTO,
- TOrgPlanDTO,
- TOrgPlansTableDTO,
- TOrgPmtMethodsDTO,
- TPlanBillingInfo,
- TStartOrgTrialDTO,
- TUpdateOrgBillingDetailsDTO
+ TOrgPlanDTO
} from "./license-types";
type TLicenseServiceFactoryDep = {
- envConfig: Pick<
- TEnvConfig,
- | "LICENSE_SERVER_URL"
- | "LICENSE_SERVER_KEY"
- | "LICENSE_KEY"
- | "LICENSE_KEY_OFFLINE"
- | "INTERNAL_REGION"
- | "SITE_URL"
- | "LICENSE_SERVER_V2_MODE"
- | "LICENSE_SERVER_V2_SERVICE_KEY"
- | "DISABLE_LICENSE_V1_CLOUD"
- >;
- orgDAL: Pick<TOrgDALFactory, "findRootOrgDetails" | "countAllOrgMembers" | "findById">;
+ envConfig: Pick<TEnvConfig, "LICENSE_KEY" | "LICENSE_KEY_OFFLINE" | "LICENSE_SERVER_V2_SERVICE_KEY" | "isCloud">;
+ orgDAL: Pick<TOrgDALFactory, "findRootOrgDetails">;
permissionService: Pick<TPermissionServiceFactory, "getOrgPermission">;
- licenseDAL: TLicenseDALFactory;
+ licenseDAL: Pick<TLicenseDALFactory, "countOfOrgMembers" | "countOrgUsersAndIdentities">;
keyStore: Pick<TKeyStoreFactory, "setItemWithExpiry" | "setItemWithExpiryNX" | "getItems" | "deleteItem">;
- projectDAL: TProjectDALFactory;
- licenseClient?: Pick<TLicenseClientFactory, "getEntitlements" | "getSubscription" | "refreshEntitlements">;
+ projectDAL: Pick<TProjectDALFactory, "countOfBillableOrgProjects">;
+ licenseClient?: Pick<
+ TLicenseClientFactory,
+ "getEntitlements" | "getSubscription" | "refreshEntitlements" | "cancelSubscription" | "invalidateEntitlements"
+ >;
usageMeteringService?: Pick<TUsageMeteringServiceFactory, "emit" | "reconcile">;
};
export type TLicenseServiceFactory = ReturnType<typeof licenseServiceFactory>;
-const LICENSE_SERVER_CLOUD_LOGIN = "/api/auth/v1/license-server-login";
-
// A self-hosted v2 license is single-tenant: the license key identifies the tenant, so entitlement
// reads carry no real org id. This fixed id only keys the local entitlement cache for the instance.
const SELF_HOSTED_LICENSE_ORG_ID = "self-hosted";
@@ -95,22 +61,11 @@ export const licenseServiceFactory = ({
licenseClient,
usageMeteringService
}: TLicenseServiceFactoryDep) => {
- let isValidLicense = false;
let instanceType = InstanceType.OnPrem;
let onPremFeatures: TFeatureSet = getDefaultOnPremFeatures();
let selfHostedLicense: TOfflineLicense | null = null;
const licenseKeyConfig = getLicenseKeyConfig(envConfig);
- const licenseServerCloudApi = setupLicenseRequestWithStore(
- envConfig.LICENSE_SERVER_URL || "",
- LICENSE_SERVER_CLOUD_LOGIN,
- envConfig.LICENSE_SERVER_KEY || "",
- envConfig.INTERNAL_REGION
- );
-
- const isV1CloudKey = () =>
- instanceType === InstanceType.Cloud && envConfig.LICENSE_SERVER_KEY && envConfig.LICENSE_SERVER_V2_MODE !== "on";
-
// Self-hosted online license: project the license's entitlements (from License Server v2) into the v1
// feature shape and refresh the instance-wide onPremFeatures.
const syncSelfHostedFeatures = async (shouldThrow: boolean = false) => {
@@ -142,15 +97,6 @@ export const licenseServiceFactory = ({
if (envConfig.LICENSE_SERVER_V2_SERVICE_KEY) {
instanceType = InstanceType.Cloud;
logger.info(`Instance type: ${InstanceType.Cloud}`);
- isValidLicense = true;
- return;
- }
-
- if (envConfig.LICENSE_SERVER_KEY) {
- const token = await licenseServerCloudApi.refreshLicense();
- if (token) instanceType = InstanceType.Cloud;
- logger.info(`Instance type: ${InstanceType.Cloud}`);
- isValidLicense = true;
return;
}
@@ -160,15 +106,14 @@ export const licenseServiceFactory = ({
await syncSelfHostedFeatures(true);
instanceType = InstanceType.EnterpriseOnPrem;
logger.info(`Instance type: ${InstanceType.EnterpriseOnPrem}`);
- isValidLicense = true;
return;
}
if (licenseKeyConfig.isValid && licenseKeyConfig.type === LicenseType.Offline) {
let isValidOfflineLicense = true;
- const contents: TOfflineLicenseContents = JSON.parse(
+ const contents = JSON.parse(
Buffer.from(licenseKeyConfig.licenseKey, "base64").toString("utf8")
- );
+ ) as TOfflineLicenseContents;
const isVerified = await verifyOfflineLicense(JSON.stringify(contents.license), contents.signature);
if (!isVerified) {
@@ -199,15 +144,12 @@ export const licenseServiceFactory = ({
};
instanceType = InstanceType.EnterpriseOnPremOffline;
logger.info(`Instance type: ${InstanceType.EnterpriseOnPremOffline}`);
- isValidLicense = true;
selfHostedLicense = contents.license;
- return;
}
}
- // this means this is the self-hosted oss version
- // else it would reach catch statement
- isValidLicense = true;
+ // anything that reaches here without setting an instance type is the self-hosted OSS version,
+ // which keeps the default onPremFeatures.
} catch (error) {
logger.error(error, `init-license: encountered an error when init license`);
}
@@ -222,9 +164,9 @@ export const licenseServiceFactory = ({
}
};
- // Fetches the org's cloud plan fresh (v2 entitlements projected into the v1 shape, or the v1 plan),
- // enriches it with live usage counts, writes it to the plan cache, and returns it. Throws on any
- // failure — it never persists the free-tier fallback itself, so callers control that decision.
+ // Fetches the org's cloud plan fresh (v2 entitlements projected into the v1 shape), enriches it with
+ // live usage counts, writes it to the plan cache, and returns it. Throws on any failure — it never
+ // persists the free-tier fallback itself, so callers control that decision.
const fetchAndCacheCloudPlan = async (orgId: string): Promise<TFeatureSet> => {
const org = await requestMemoize(requestMemoKeys.orgFindRootOrgDetails(orgId), () =>
orgDAL.findRootOrgDetails(orgId)
@@ -232,51 +174,19 @@ export const licenseServiceFactory = ({
if (!org) throw new NotFoundError({ message: `Organization with ID '${orgId}' not found` });
const rootOrgId = org.id;
- let currentPlan: TFeatureSet;
- if (envConfig.LICENSE_SERVER_V2_MODE === "on") {
- // Serve from License Server v2, projected into the v1 plan shape so getPlan callers are unchanged.
- if (!licenseClient) {
- throw new BadRequestError({ message: "License Server v2 client is not configured" });
- }
- const entitlements = await licenseClient.getEntitlements({ id: rootOrgId, name: org.name, slug: org.slug });
- if (!entitlements) {
- throw new BadRequestError({ message: "License Server v2 entitlements are unavailable" });
- }
- currentPlan = projectV2ToFeatureSet(getDefaultOnPremFeatures(), entitlements);
- } else {
- const {
- data: { currentPlan: v1Plan }
- } = await licenseServerCloudApi.request.get<{ currentPlan: TFeatureSet }>(
- `/api/license-server/v1/customers/${org.customerId}/cloud-plan`
- );
- currentPlan = v1Plan;
+ // Serve from the License Server, projected into the legacy plan shape so getPlan callers are unchanged.
+ if (!licenseClient) {
+ throw new BadRequestError({ message: "License Server client is not configured" });
}
+ const entitlements = await licenseClient.getEntitlements({ id: rootOrgId, name: org.name, slug: org.slug });
+ if (!entitlements) {
+ throw new BadRequestError({ message: "License Server entitlements are unavailable" });
+ }
+ const currentPlan = projectV2ToFeatureSet(getDefaultOnPremFeatures(), entitlements);
currentPlan.workspacesUsed = await projectDAL.countOfBillableOrgProjects(rootOrgId);
-
- const membersUsed = await licenseDAL.countOfOrgMembers(rootOrgId);
- currentPlan.membersUsed = membersUsed;
- const identityUsed = await licenseDAL.countOrgUsersAndIdentities(rootOrgId);
-
- // Seat sync targets the v1 license server only; v2 derives usage from registered counters.
- if (
- envConfig.LICENSE_SERVER_V2_MODE !== "on" &&
- currentPlan?.identitiesUsed &&
- currentPlan.identitiesUsed !== identityUsed
- ) {
- try {
- await licenseServerCloudApi.request.patch(`/api/license-server/v1/customers/${org.customerId}/cloud-plan`, {
- quantity: membersUsed,
- quantityIdentities: identityUsed
- });
- } catch (error) {
- logger.error(
- error,
- `Update seats used: encountered an error when updating plan for customer [customerId=${org.customerId}]`
- );
- }
- }
- currentPlan.identitiesUsed = identityUsed;
+ currentPlan.membersUsed = await licenseDAL.countOfOrgMembers(rootOrgId);
+ currentPlan.identitiesUsed = await licenseDAL.countOrgUsersAndIdentities(rootOrgId);
await keyStore.setItemWithExpiry(
KeyStorePrefixes.LicenseCloudPlan(org.id),
@@ -375,24 +285,20 @@ export const licenseServiceFactory = ({
}
};
- const generateOrgCustomerId = async (orgName: string, email?: string | null) => {
- if (isV1CloudKey()) {
- const {
- data: { customerId }
- } = await licenseServerCloudApi.request.post<{ customerId: string }>(
- "/api/license-server/v1/customers",
- {
- email: email ?? "",
- name: orgName
- },
- { timeout: 5000, signal: AbortSignal.timeout(5000) }
- );
- return customerId;
+ // Called after an org is deleted so it stops billing. Cloud-only: a self-hosted license covers the
+ // whole instance and has no per-org subscription to cancel. Never fatal, since the org row is already
+ // gone by this point and a License Server failure must not fail the deletion.
+ const cancelOrgSubscription = async (orgId: string) => {
+ if (!envConfig.isCloud) {
+ return;
}
- };
- const removeOrgCustomer = async (customerId: string) => {
- await licenseServerCloudApi.request.delete(`/api/license-server/v1/customers/${customerId}`);
+ try {
+ await licenseClient?.cancelSubscription(orgId);
+ await licenseClient?.invalidateEntitlements(orgId);
+ } catch (error) {
+ logger.error(error, `cancelOrgSubscription: failed to cancel subscription [orgId=${orgId}]`);
+ }
};
const updateSubscriptionOrgMemberCount = async (orgId: string, tx?: Knex) => {
@@ -402,22 +308,12 @@ export const licenseServiceFactory = ({
const rootOrgId = org.id;
// This is the single "org member count changed" signal in the codebase (invite/signup, SSO/SCIM
- // provisioning, member removal all call it), so emit the v2 user-seat meter here. Fire-and-forget
- // and no-op when the v2 license server is off; extra fires on identity-only changes re-count and
+ // provisioning, member removal all call it), so emit the user-seat meter here. Fire-and-forget and
+ // no-op when no license server is configured; extra fires on identity-only changes re-count and
// report-only-if-changed, so they're harmless.
usageMeteringService?.emit(rootOrgId, UserIdentities.key);
- if (isV1CloudKey()) {
- const quantity = await licenseDAL.countOfOrgMembers(rootOrgId, tx);
- const quantityIdentities = await licenseDAL.countOrgUsersAndIdentities(rootOrgId, tx);
- if (org?.customerId) {
- await licenseServerCloudApi.request.patch(`/api/license-server/v1/customers/${org.customerId}/cloud-plan`, {
- quantity,
- quantityIdentities
- });
- }
- await keyStore.deleteItem(KeyStorePrefixes.LicenseCloudPlan(rootOrgId));
- } else if (instanceType === InstanceType.EnterpriseOnPrem) {
+ if (instanceType === InstanceType.EnterpriseOnPrem) {
// Self-hosted reports usage asynchronously via the usage-snapshot queue, not a synchronous seat
// patch; keep the in-memory counts current so limit checks are accurate until the next sync.
onPremFeatures.membersUsed = await licenseDAL.countOfOrgMembers(null, tx);
@@ -426,30 +322,6 @@ export const licenseServiceFactory = ({
await refreshPlan(rootOrgId);
};
- // below all are api calls
- const getOrgPlansTableByBillCycle = async ({
- orgId,
- actor,
- actorId,
- actorOrgId,
- actorAuthMethod,
- billingCycle
- }: TOrgPlansTableDTO) => {
- const { permission } = await permissionService.getOrgPermission({
- actorId,
- actor,
- orgId,
- actorOrgId,
- actorAuthMethod,
- scope: OrganizationActionScope.ParentOrganization
- });
- ForbiddenError.from(permission).throwUnlessCan(OrgPermissionBillingActions.Read, OrgPermissionSubjects.Billing);
- const { data } = await licenseServerCloudApi.request.get(
- `/api/license-server/v1/cloud-products?billing-cycle=${billingCycle}`
- );
- return data;
- };
-
const getOrgPlan = async ({
orgId,
actor,
@@ -475,565 +347,6 @@ export const licenseServiceFactory = ({
return plan;
};
- const startOrgTrial = async ({
- orgId,
- actorId,
- actor,
- actorOrgId,
- actorAuthMethod,
- success_url
- }: TStartOrgTrialDTO) => {
- if (envConfig.DISABLE_LICENSE_V1_CLOUD) {
- throw new BadRequestError({
- message: "We're currently updating our license system. Please check back again later."
- });
- }
-
- const { permission } = await permissionService.getOrgPermission({
- actorId,
- actor,
- orgId,
- actorOrgId,
- actorAuthMethod,
- scope: OrganizationActionScope.ParentOrganization
- });
- ForbiddenError.from(permission).throwUnlessCan(
- OrgPermissionBillingActions.ManageBilling,
- OrgPermissionSubjects.Billing
- );
-
- const organization = await requestMemoize(requestMemoKeys.orgFindById(orgId), () => orgDAL.findById(orgId));
- if (!organization) {
- throw new NotFoundError({
- message: `Organization with ID '${orgId}' not found`
- });
- }
-
- await updateSubscriptionOrgMemberCount(orgId);
-
- const {
- data: { url }
- } = await licenseServerCloudApi.request.post(
- `/api/license-server/v1/customers/${organization.customerId}/session/trial`,
- { success_url }
- );
- await keyStore.deleteItem(KeyStorePrefixes.LicenseCloudPlan(orgId));
- return { url };
- };
-
- const createOrganizationPortalSession = async ({
- orgId,
- actorId,
- actor,
- actorAuthMethod,
- actorOrgId
- }: TCreateOrgPortalSession) => {
- if (envConfig.DISABLE_LICENSE_V1_CLOUD) {
- throw new BadRequestError({
- message: "We're currently updating our license system. Please check back again later."
- });
- }
-
- const { permission } = await permissionService.getOrgPermission({
- actorId,
- actor,
- orgId,
- actorOrgId,
- actorAuthMethod,
- scope: OrganizationActionScope.ParentOrganization
- });
- ForbiddenError.from(permission).throwUnlessCan(
- OrgPermissionBillingActions.ManageBilling,
- OrgPermissionSubjects.Billing
- );
-
- const organization = await requestMemoize(requestMemoKeys.orgFindById(orgId), () => orgDAL.findById(orgId));
- if (!organization) {
- throw new NotFoundError({
- message: "Organization not found"
- });
- }
-
- const {
- data: { pmtMethods }
- } = await licenseServerCloudApi.request.get<{ pmtMethods: string[] }>(
- `/api/license-server/v1/customers/${organization.customerId}/billing-details/payment-methods`
- );
-
- if (pmtMethods.length < 1) {
- // case: organization has no payment method on file
- // -> redirect to add payment method portal
- const {
- data: { url }
- } = await licenseServerCloudApi.request.post(
- `/api/license-server/v1/customers/${organization.customerId}/billing-details/payment-methods`,
- {
- success_url: `${envConfig.SITE_URL}/organizations/${orgId}/billing`,
- cancel_url: `${envConfig.SITE_URL}/organizations/${orgId}/billing`
- }
- );
-
- return { url };
- }
- // case: organization has payment method on file
- // -> redirect to billing portal
- const {
- data: { url }
- } = await licenseServerCloudApi.request.post(
- `/api/license-server/v1/customers/${organization.customerId}/billing-details/billing-portal`,
- {
- return_url: `${envConfig.SITE_URL}/organizations/${orgId}/billing`
- }
- );
-
- return { url };
- };
-
- const getUsageMetrics = async (orgId: string) => {
- const [orgMembersUsed, identityUsed, projectCount] = await Promise.all([
- orgDAL.countAllOrgMembers(orgId),
- licenseDAL.countOfOrgIdentities(orgId),
- projectDAL.countOfBillableOrgProjects(orgId)
- ]);
-
- return {
- orgMembersUsed,
- identityUsed,
- projectCount,
- totalIdentities: identityUsed + orgMembersUsed
- };
- };
-
- const getOrgBillingInfo = async ({ orgId, actor, actorId, actorAuthMethod, actorOrgId }: TGetOrgBillInfoDTO) => {
- const { permission } = await permissionService.getOrgPermission({
- actorId,
- actor,
- orgId,
- actorOrgId,
- actorAuthMethod,
- scope: OrganizationActionScope.ParentOrganization
- });
- ForbiddenError.from(permission).throwUnlessCan(OrgPermissionBillingActions.Read, OrgPermissionSubjects.Billing);
-
- const organization = await requestMemoize(requestMemoKeys.orgFindById(orgId), () => orgDAL.findById(orgId));
- if (!organization) {
- throw new NotFoundError({
- message: `Organization with ID '${orgId}' not found`
- });
- }
- if (instanceType === InstanceType.Cloud) {
- const { data } = await licenseServerCloudApi.request.get<TPlanBillingInfo>(
- `/api/license-server/v1/customers/${organization.customerId}/cloud-plan/billing`
- );
- const { identityUsed, orgMembersUsed } = await getUsageMetrics(orgId);
-
- return {
- ...data,
- users: orgMembersUsed,
- identities: identityUsed
- };
- }
-
- return {
- currentPeriodStart: selfHostedLicense?.issuedAt ? Date.parse(selfHostedLicense?.issuedAt) / 1000 : undefined,
- currentPeriodEnd: selfHostedLicense?.expiresAt ? Date.parse(selfHostedLicense?.expiresAt) / 1000 : undefined,
- interval: "month",
- intervalCount: 1,
- amount: 0,
- quantity: 1,
- users: 0,
- identities: 0
- };
- };
-
- const calculateUsageValue = (
- rowName: string,
- field: string,
- projectCount: number,
- totalIdentities: number
- ): string => {
- if (rowName === BillingPlanRows.WorkspaceLimit.name || field === BillingPlanRows.WorkspaceLimit.field) {
- return projectCount.toString();
- }
- if (rowName === BillingPlanRows.IdentityLimit.name || field === BillingPlanRows.IdentityLimit.field) {
- return totalIdentities.toString();
- }
- return "-";
- };
-
- const fetchPlanTableFromServer = async (customerId: string | null | undefined) => {
- const baseUrl = `/api/license-server/v1/customers`;
-
- if (instanceType === InstanceType.Cloud) {
- if (!customerId) {
- throw new NotFoundError({ message: "Organization customer ID is required for plan table retrieval" });
- }
- const { data } = await licenseServerCloudApi.request.get<{
- head: { name: string }[];
- rows: { name: string; allowed: boolean }[];
- }>(`${baseUrl}/${customerId}/cloud-plan/table`);
- return data;
- }
-
- throw new Error(`Unsupported instance type for server-based plan table: ${instanceType}`);
- };
-
- // returns org current plan feature table
- const getOrgPlanTable = async ({ orgId, actor, actorId, actorAuthMethod, actorOrgId }: TGetOrgBillInfoDTO) => {
- const { permission } = await permissionService.getOrgPermission({
- actorId,
- actor,
- orgId,
- actorOrgId,
- actorAuthMethod,
- scope: OrganizationActionScope.ParentOrganization
- });
- ForbiddenError.from(permission).throwUnlessCan(OrgPermissionBillingActions.Read, OrgPermissionSubjects.Billing);
-
- const organization = await requestMemoize(requestMemoKeys.orgFindById(orgId), () => orgDAL.findById(orgId));
- if (!organization) {
- throw new NotFoundError({
- message: `Organization with ID '${orgId}' not found`
- });
- }
-
- const { projectCount, totalIdentities } = await getUsageMetrics(orgId);
-
- if (instanceType === InstanceType.Cloud) {
- const tableResponse = await fetchPlanTableFromServer(organization.customerId);
-
- return {
- head: tableResponse.head,
- rows: tableResponse.rows.map((row) => ({
- ...row,
- used: calculateUsageValue(row.name, "", projectCount, totalIdentities)
- }))
- };
- }
-
- const mappedRows = Object.values(BillingPlanRows).map(({ name, field }) => ({
- name,
- allowed: onPremFeatures[field as keyof TFeatureSet] as boolean | number | null,
- used: calculateUsageValue(name, field, projectCount, totalIdentities)
- }));
-
- return {
- head: Object.values(BillingPlanTableHead),
- rows: mappedRows
- };
- };
-
- const getOrgBillingDetails = async ({ orgId, actor, actorId, actorAuthMethod, actorOrgId }: TGetOrgBillInfoDTO) => {
- const { permission } = await permissionService.getOrgPermission({
- actorId,
- actor,
- orgId,
- actorOrgId,
- actorAuthMethod,
- scope: OrganizationActionScope.ParentOrganization
- });
- ForbiddenError.from(permission).throwUnlessCan(OrgPermissionBillingActions.Read, OrgPermissionSubjects.Billing);
-
- const organization = await requestMemoize(requestMemoKeys.orgFindById(orgId), () => orgDAL.findById(orgId));
- if (!organization) {
- throw new NotFoundError({
- message: `Organization with ID '${orgId}' not found`
- });
- }
-
- const { data } = await licenseServerCloudApi.request.get(
- `/api/license-server/v1/customers/${organization.customerId}/billing-details`
- );
- return data;
- };
-
- const updateOrgBillingDetails = async ({
- actorId,
- actor,
- actorOrgId,
- actorAuthMethod,
- orgId,
- name,
- email
- }: TUpdateOrgBillingDetailsDTO) => {
- const { permission } = await permissionService.getOrgPermission({
- actorId,
- actor,
- orgId,
- actorOrgId,
- actorAuthMethod,
- scope: OrganizationActionScope.ParentOrganization
- });
- ForbiddenError.from(permission).throwUnlessCan(
- OrgPermissionBillingActions.ManageBilling,
- OrgPermissionSubjects.Billing
- );
-
- const organization = await requestMemoize(requestMemoKeys.orgFindById(orgId), () => orgDAL.findById(orgId));
- if (!organization) {
- throw new NotFoundError({
- message: `Organization with ID '${orgId}' not found`
- });
- }
- const { data } = await licenseServerCloudApi.request.patch(
- `/api/license-server/v1/customers/${organization.customerId}/billing-details`,
- {
- name,
- email
- }
- );
- return data;
- };
-
- const getOrgPmtMethods = async ({ orgId, actor, actorId, actorAuthMethod, actorOrgId }: TOrgPmtMethodsDTO) => {
- const { permission } = await permissionService.getOrgPermission({
- actorId,
- actor,
- orgId,
- actorOrgId,
- actorAuthMethod,
- scope: OrganizationActionScope.ParentOrganization
- });
- ForbiddenError.from(permission).throwUnlessCan(OrgPermissionBillingActions.Read, OrgPermissionSubjects.Billing);
-
- const organization = await requestMemoize(requestMemoKeys.orgFindById(orgId), () => orgDAL.findById(orgId));
- if (!organization) {
- throw new NotFoundError({
- message: `Organization with ID '${orgId}' not found`
- });
- }
-
- const {
- data: { pmtMethods }
- } = await licenseServerCloudApi.request.get(
- `/api/license-server/v1/customers/${organization.customerId}/billing-details/payment-methods`
- );
- return pmtMethods;
- };
-
- const addOrgPmtMethods = async ({
- orgId,
- actor,
- actorId,
- actorAuthMethod,
- actorOrgId,
- success_url,
- cancel_url
- }: TAddOrgPmtMethodDTO) => {
- if (envConfig.DISABLE_LICENSE_V1_CLOUD) {
- throw new BadRequestError({
- message: "We're currently updating our license system. Please check back again later."
- });
- }
-
- const { permission } = await permissionService.getOrgPermission({
- actorId,
- actor,
- orgId,
- actorOrgId,
- actorAuthMethod,
- scope: OrganizationActionScope.ParentOrganization
- });
- ForbiddenError.from(permission).throwUnlessCan(
- OrgPermissionBillingActions.ManageBilling,
- OrgPermissionSubjects.Billing
- );
-
- const organization = await requestMemoize(requestMemoKeys.orgFindById(orgId), () => orgDAL.findById(orgId));
- if (!organization) {
- throw new NotFoundError({
- message: `Organization with ID '${orgId}' not found`
- });
- }
- const {
- data: { url }
- } = await licenseServerCloudApi.request.post(
- `/api/license-server/v1/customers/${organization.customerId}/billing-details/payment-methods`,
- {
- success_url,
- cancel_url
- }
- );
- return { url };
- };
-
- const delOrgPmtMethods = async ({
- actorId,
- actor,
- actorAuthMethod,
- actorOrgId,
- orgId,
- pmtMethodId
- }: TDelOrgPmtMethodDTO) => {
- const { permission } = await permissionService.getOrgPermission({
- actorId,
- actor,
- orgId,
- actorOrgId,
- actorAuthMethod,
- scope: OrganizationActionScope.ParentOrganization
- });
- ForbiddenError.from(permission).throwUnlessCan(
- OrgPermissionBillingActions.ManageBilling,
- OrgPermissionSubjects.Billing
- );
-
- const organization = await requestMemoize(requestMemoKeys.orgFindById(orgId), () => orgDAL.findById(orgId));
- if (!organization) {
- throw new NotFoundError({
- message: `Organization with ID '${orgId}' not found`
- });
- }
-
- try {
- const { data } = await licenseServerCloudApi.request.delete(
- `/api/license-server/v1/customers/${organization.customerId}/billing-details/payment-methods/${pmtMethodId}`
- );
- return data;
- } catch (error) {
- if (error instanceof AxiosError) {
- throw new BadRequestError({
- // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access
- message: `Failed to remove payment method: ${error.response?.data?.message}`
- });
- }
- throw new BadRequestError({
- message: "Unable to remove payment method"
- });
- }
- };
-
- const getOrgTaxIds = async ({ orgId, actor, actorId, actorAuthMethod, actorOrgId }: TGetOrgTaxIdDTO) => {
- const { permission } = await permissionService.getOrgPermission({
- actorId,
- actor,
- orgId,
- actorOrgId,
- actorAuthMethod,
- scope: OrganizationActionScope.ParentOrganization
- });
- ForbiddenError.from(permission).throwUnlessCan(OrgPermissionBillingActions.Read, OrgPermissionSubjects.Billing);
-
- const organization = await requestMemoize(requestMemoKeys.orgFindById(orgId), () => orgDAL.findById(orgId));
- if (!organization) {
- throw new NotFoundError({
- message: `Organization with ID '${orgId}' not found`
- });
- }
- const {
- data: { tax_ids: taxIds }
- } = await licenseServerCloudApi.request.get(
- `/api/license-server/v1/customers/${organization.customerId}/billing-details/tax-ids`
- );
- return taxIds;
- };
-
- const addOrgTaxId = async ({ actorId, actor, actorAuthMethod, actorOrgId, orgId, type, value }: TAddOrgTaxIdDTO) => {
- const { permission } = await permissionService.getOrgPermission({
- actorId,
- actor,
- orgId,
- actorOrgId,
- actorAuthMethod,
- scope: OrganizationActionScope.ParentOrganization
- });
- ForbiddenError.from(permission).throwUnlessCan(
- OrgPermissionBillingActions.ManageBilling,
- OrgPermissionSubjects.Billing
- );
-
- const organization = await requestMemoize(requestMemoKeys.orgFindById(orgId), () => orgDAL.findById(orgId));
- if (!organization) {
- throw new NotFoundError({
- message: `Organization with ID '${orgId}' not found`
- });
- }
-
- const { data } = await licenseServerCloudApi.request.post(
- `/api/license-server/v1/customers/${organization.customerId}/billing-details/tax-ids`,
- {
- type,
- value
- }
- );
- return data;
- };
-
- const delOrgTaxId = async ({ orgId, actor, actorId, actorAuthMethod, actorOrgId, taxId }: TDelOrgTaxIdDTO) => {
- const { permission } = await permissionService.getOrgPermission({
- actorId,
- actor,
- orgId,
- actorOrgId,
- actorAuthMethod,
- scope: OrganizationActionScope.ParentOrganization
- });
- ForbiddenError.from(permission).throwUnlessCan(
- OrgPermissionBillingActions.ManageBilling,
- OrgPermissionSubjects.Billing
- );
-
- const organization = await requestMemoize(requestMemoKeys.orgFindById(orgId), () => orgDAL.findById(orgId));
- if (!organization) {
- throw new NotFoundError({
- message: `Organization with ID '${orgId}' not found`
- });
- }
-
- const { data } = await licenseServerCloudApi.request.delete(
- `/api/license-server/v1/customers/${organization.customerId}/billing-details/tax-ids/${taxId}`
- );
- return data;
- };
-
- const getOrgTaxInvoices = async ({ actorId, actor, actorOrgId, actorAuthMethod, orgId }: TOrgInvoiceDTO) => {
- const { permission } = await permissionService.getOrgPermission({
- actorId,
- actor,
- orgId,
- actorOrgId,
- actorAuthMethod,
- scope: OrganizationActionScope.ParentOrganization
- });
- ForbiddenError.from(permission).throwUnlessCan(OrgPermissionBillingActions.Read, OrgPermissionSubjects.Billing);
-
- const organization = await requestMemoize(requestMemoKeys.orgFindById(orgId), () => orgDAL.findById(orgId));
- if (!organization) {
- throw new NotFoundError({
- message: `Organization with ID '${orgId}' not found`
- });
- }
-
- const {
- data: { invoices }
- } = await licenseServerCloudApi.request.get(`/api/license-server/v1/customers/${organization.customerId}/invoices`);
- return invoices;
- };
-
- const getOrgLicenses = async ({ orgId, actor, actorId, actorAuthMethod, actorOrgId }: TOrgLicensesDTO) => {
- const { permission } = await permissionService.getOrgPermission({
- actorId,
- actor,
- orgId,
- actorOrgId,
- actorAuthMethod,
- scope: OrganizationActionScope.ParentOrganization
- });
- ForbiddenError.from(permission).throwUnlessCan(OrgPermissionBillingActions.Read, OrgPermissionSubjects.Billing);
-
- const organization = await requestMemoize(requestMemoKeys.orgFindById(orgId), () => orgDAL.findById(orgId));
- if (!organization) {
- throw new NotFoundError({
- message: `Organization with ID '${orgId}' not found`
- });
- }
-
- const {
- data: { licenses }
- } = await licenseServerCloudApi.request.get(`/api/license-server/v1/customers/${organization.customerId}/licenses`);
- return licenses;
- };
-
const invalidateGetPlan = async (orgId: string) => {
await keyStore.deleteItem(KeyStorePrefixes.LicenseCloudPlan(orgId));
};
@@ -1049,12 +362,8 @@ export const licenseServiceFactory = ({
};
return {
- generateOrgCustomerId,
- removeOrgCustomer,
+ cancelOrgSubscription,
init,
- get isValidLicense() {
- return isValidLicense;
- },
getInstanceType() {
return instanceType;
},
@@ -1067,21 +376,6 @@ export const licenseServiceFactory = ({
invalidateGetPlan,
updateSubscriptionOrgMemberCount,
getOrgPlan,
- getOrgPlansTableByBillCycle,
- startOrgTrial,
- createOrganizationPortalSession,
- getOrgBillingInfo,
- getOrgPlanTable,
- getOrgBillingDetails,
- updateOrgBillingDetails,
- addOrgPmtMethods,
- delOrgPmtMethods,
- getOrgPmtMethods,
- getOrgLicenses,
- getOrgTaxInvoices,
- getOrgTaxIds,
- addOrgTaxId,
- delOrgTaxId,
initializeBackgroundSync
};
};
diff --git a/backend/src/ee/services/license/license-types.ts b/backend/src/ee/services/license/license-types.ts
index c00e9190ff..07dea6fc39 100644
--- a/backend/src/ee/services/license/license-types.ts
+++ b/backend/src/ee/services/license/license-types.ts
@@ -28,15 +28,6 @@ export type TOfflineLicense = {
entitlements?: TEntitlementsResponse;
};
-export type TPlanBillingInfo = {
- currentPeriodStart: number;
- currentPeriodEnd: number;
- interval: "month" | "year";
- intervalCount: number;
- amount: number;
- quantity: number;
-};
-
export type TFeatureSet = {
_id: null;
slug: string | null;
@@ -123,49 +114,12 @@ export type TFeatureSet = {
crossProjectSecretSharing: false;
};
-export type TOrgPlansTableDTO = {
- billingCycle: string;
-} & TOrgPermission;
-
export type TOrgPlanDTO = {
projectId?: string;
refreshCache?: boolean;
rootOrgId: string;
} & TOrgPermission;
-export type TStartOrgTrialDTO = {
- success_url: string;
-} & TOrgPermission;
-
-export type TCreateOrgPortalSession = TOrgPermission;
-
-export type TGetOrgBillInfoDTO = TOrgPermission;
-
-export type TOrgPlanTableDTO = TOrgPermission;
-
-export type TOrgBillingDetailsDTO = TOrgPermission;
-
-export type TUpdateOrgBillingDetailsDTO = TOrgPermission & {
- name?: string;
- email?: string;
-};
-
-export type TOrgPmtMethodsDTO = TOrgPermission;
-
-export type TAddOrgPmtMethodDTO = TOrgPermission & { success_url: string; cancel_url: string };
-
-export type TDelOrgPmtMethodDTO = TOrgPermission & { pmtMethodId: string };
-
-export type TGetOrgTaxIdDTO = TOrgPermission;
-
-export type TAddOrgTaxIdDTO = TOrgPermission & { type: string; value: string };
-
-export type TDelOrgTaxIdDTO = TOrgPermission & { taxId: string };
-
-export type TOrgInvoiceDTO = TOrgPermission;
-
-export type TOrgLicensesDTO = TOrgPermission;
-
export enum LicenseType {
Offline = "offline",
// Self-hosted online license key; resolves entitlements from License Server v2.
diff --git a/backend/src/lib/config/env.ts b/backend/src/lib/config/env.ts
index f63e723fa8..3055ba868b 100644
--- a/backend/src/lib/config/env.ts
+++ b/backend/src/lib/config/env.ts
@@ -395,16 +395,11 @@ const envSchema = z
"A scan left in the `scanning` state for longer than this is marked failed by the reaper. Must exceed clone + scan timeouts combined."
),
// LICENSE
+ // The License Server host. Serves both the self-hosted token endpoint and the entitlement API.
LICENSE_SERVER_URL: zpStr(z.string().optional().default("https://portal.infisical.com")),
- LICENSE_SERVER_KEY: zpStr(z.string().optional()),
LICENSE_KEY: zpStr(z.string().optional()),
LICENSE_KEY_OFFLINE: zpStr(z.string().optional()),
- LICENSE_SERVER_V2_MODE: z.enum(["off", "read-compare", "on"]).default("on"),
- LICENSE_SERVER_V2_URL: zpStr(z.string().optional()),
LICENSE_SERVER_V2_SERVICE_KEY: zpStr(z.string().optional()),
- // When true, new checkouts (adding a payment method) and trials on License Server v1 cloud are
- // disallowed, pushing orgs onto License Server v2.
- DISABLE_LICENSE_V1_CLOUD: zodStrBool.default("false"),
// GENERIC
STANDALONE_MODE: z
@@ -637,9 +632,8 @@ const envSchema = z
DB_READ_REPLICAS: data.DB_READ_REPLICAS
? databaseReadReplicaSchema.parse(JSON.parse(data.DB_READ_REPLICAS))
: undefined,
- // Inferred from the legacy license server key; needs a new signal once License Server v2 fully replaces it.
- isCloud: Boolean(data.LICENSE_SERVER_KEY || data.LICENSE_SERVER_V2_SERVICE_KEY),
- isLicenseDualReadEnabled: data.LICENSE_SERVER_V2_MODE === "read-compare",
+ // Only cloud holds the License Server service key; self-hosted authenticates with a license key.
+ isCloud: Boolean(data.LICENSE_SERVER_V2_SERVICE_KEY),
isSmtpConfigured: Boolean(data.SMTP_HOST),
isRedisConfigured: Boolean(data.REDIS_URL || data.REDIS_SENTINEL_HOSTS || data.REDIS_CLUSTER_HOSTS),
isClickHouseConfigured: Boolean(data.CLICKHOUSE_URL),
diff --git a/backend/src/lib/telemetry/metrics.ts b/backend/src/lib/telemetry/metrics.ts
index 7534913e54..f93b831dd6 100644
--- a/backend/src/lib/telemetry/metrics.ts
+++ b/backend/src/lib/telemetry/metrics.ts
@@ -382,33 +382,6 @@ export const rateLimitExceededCounter = infisicalCoreMeter.createCounter("infisi
unit: "{request}"
});
-// -- License Server v2 dual-read (InfisicalCore meter) ----------------------------------------------
-export const licenseDualReadDiffCounter = infisicalCoreMeter.createCounter("infisical.license.dual_read.diff.count", {
- description:
- "v1 vs License Server v2 entitlement comparison results, by feature and kind (mismatch/v2_missing/v1_absent/indeterminate). Match results are not counted.",
- unit: "{result}"
-});
-
-export const licenseDualReadErrorCounter = infisicalCoreMeter.createCounter("infisical.license.dual_read.error.count", {
- description: "Failures resolving the v2 entitlement set during dual-read comparison, by error type.",
- unit: "{error}"
-});
-
-export const recordLicenseDualReadDiff = (params: { feature: string; kind: string }) => {
- if (!isTelemetryEnabled()) return;
- licenseDualReadDiffCounter.add(1, {
- "license.feature": params.feature,
- "license.dual_read.kind": params.kind
- });
-};
-
-export const recordLicenseDualReadError = (params: { error?: unknown }) => {
- if (!isTelemetryEnabled()) return;
- const attributes: Record<string, string> = {};
- if (params.error !== undefined) attributes["error.type"] = classifyError(params.error);
- licenseDualReadErrorCounter.add(1, attributes);
-};
-
// -- Authentication latency (InfisicalCore meter) ---------------------------------------------------
export const authAttemptDurationHistogram = infisicalCoreMeter.createHistogram("infisical.auth.attempt.duration", {
description:
diff --git a/backend/src/lib/telemetry/telemetry-attributes.ts b/backend/src/lib/telemetry/telemetry-attributes.ts
index 806276dd71..b4698d31d4 100644
--- a/backend/src/lib/telemetry/telemetry-attributes.ts
+++ b/backend/src/lib/telemetry/telemetry-attributes.ts
@@ -33,9 +33,6 @@ export const INFISICAL_CORE_METER_ATTRIBUTES = [
"destination",
"type",
"operation",
- // License Server v2 dual-read comparison (bounded: feature key set + a small set of diff kinds)
- "license.feature",
- "license.dual_read.kind",
// Build info gauge labels — single-value per deploy, no cardinality concern
"service.version",
"git.commit.sha",
diff --git a/backend/src/server/routes/index.ts b/backend/src/server/routes/index.ts
index 228b8feae3..b6cec8444b 100644
--- a/backend/src/server/routes/index.ts
+++ b/backend/src/server/routes/index.ts
@@ -783,9 +783,9 @@ export const registerRoutes = async (
// is the single read primitive; falls back to feature defaults until the server is configured.
const licenseClient = licenseClientFactory({ envConfig, keyStore, isOffline: isOfflineLicense });
- // Created before licenseService so the latter can emit the v2 user-seat meter from its
+ // Created before licenseService so the latter can emit the user-seat meter from its
// updateSubscriptionOrgMemberCount chokepoint.
- const usageMeteringService = usageMeteringServiceFactory({ queueService, projectDAL, keyStore, envConfig });
+ const usageMeteringService = usageMeteringServiceFactory({ queueService, projectDAL, keyStore, licenseClient });
const licenseService = licenseServiceFactory({
permissionService,
@@ -798,8 +798,8 @@ export const registerRoutes = async (
usageMeteringService
});
- // Usage metering: counts the metered features and reports them to the License Server. Inert while
- // LICENSE_SERVER_V2_MODE is off; active in read-compare and on (emitter no-ops / worker no-ops without a reporter).
+ // Usage metering: counts the metered features and reports them to the License Server. Inert when no
+ // license server is configured (emitter no-ops / worker no-ops without a reporter).
const usageCounterDAL = usageCounterDALFactory(db);
const meteredFeatures = buildMeteredFeatures({ licenseDAL, usageCounterDAL, isCloud: envConfig.isCloud });
meteredFeatures.forEach(({ feature, count }) => licenseClient.registerCounter(feature, count));
@@ -821,8 +821,8 @@ export const registerRoutes = async (
source: usageSource
});
- // Flag-gated v2 billing surface. Drives the catalog, subscription, and entitlement reads off the
- // real license server via licenseClient; no new tables.
+ // Billing surface. Drives the catalog, subscription, and entitlement reads off the real license
+ // server via licenseClient; no new tables.
const licenseV2Service = licenseV2ServiceFactory({
envConfig,
orgDAL,
diff --git a/backend/src/server/routes/v1/admin-router.ts b/backend/src/server/routes/v1/admin-router.ts
index 4eb4c8cc4c..df13c84249 100644
--- a/backend/src/server/routes/v1/admin-router.ts
+++ b/backend/src/server/routes/v1/admin-router.ts
@@ -57,7 +57,6 @@ const SanitizedSuperAdminSchema = z.object({
isMigrationModeOn: z.boolean().optional(),
isSecretScanningDisabled: z.boolean().optional(),
isPublicSecretSharingDisabled: z.boolean().optional(),
- licenseServerV2Enabled: z.boolean().optional(),
kubernetesAutoFetchServiceAccountToken: z.boolean().optional(),
paramsFolderSecretDetectionEnabled: z.boolean().optional(),
isOfflineUsageReportsEnabled: z.boolean().optional(),
@@ -114,7 +113,6 @@ export const registerAdminRouter = async (server: FastifyZodProvider) => {
authConsentContent: config.authConsentContent,
pageFrameContent: config.pageFrameContent,
isPublicSecretSharingDisabled: serverEnvs.DISABLE_PUBLIC_SECRET_SHARING,
- licenseServerV2Enabled: serverEnvs.LICENSE_SERVER_V2_MODE === "on",
isCrossProjectSecretSharingEnabled: plan.crossProjectSecretSharing,
latestAvailableVersion
}
@@ -129,7 +127,6 @@ export const registerAdminRouter = async (server: FastifyZodProvider) => {
isMigrationModeOn: serverEnvs.MAINTENANCE_MODE,
isSecretScanningDisabled: serverEnvs.DISABLE_SECRET_SCANNING,
isPublicSecretSharingDisabled: serverEnvs.DISABLE_PUBLIC_SECRET_SHARING,
- licenseServerV2Enabled: serverEnvs.LICENSE_SERVER_V2_MODE === "on",
kubernetesAutoFetchServiceAccountToken: serverEnvs.KUBERNETES_AUTO_FETCH_SERVICE_ACCOUNT_TOKEN,
paramsFolderSecretDetectionEnabled: serverEnvs.PARAMS_FOLDER_SECRET_DETECTION_ENABLED,
isOfflineUsageReportsEnabled: hasOfflineLicense,
diff --git a/backend/src/server/routes/v2/organization-router.ts b/backend/src/server/routes/v2/organization-router.ts
index 5ae48281fc..0bf4d73775 100644
--- a/backend/src/server/routes/v2/organization-router.ts
+++ b/backend/src/server/routes/v2/organization-router.ts
@@ -433,7 +433,6 @@ export const registerOrgRouter = async (server: FastifyZodProvider) => {
const organization = await server.services.org.createOrganization({
userId: req.permission.id,
- userEmail: req.auth.user.email,
orgName: req.body.name
});
diff --git a/backend/src/services/auth/auth-signup-service.ts b/backend/src/services/auth/auth-signup-service.ts
index ec38527071..fb12601346 100644
--- a/backend/src/services/auth/auth-signup-service.ts
+++ b/backend/src/services/auth/auth-signup-service.ts
@@ -215,7 +215,6 @@ export const authSignupServiceFactory = ({
const org = await orgService.createOrganization(
{
userId: user.id,
- userEmail: user.email ?? user.username,
orgName: dto.organizationName
},
tx
diff --git a/backend/src/services/license-client/dual-read/dual-read-service.ts b/backend/src/services/license-client/dual-read/dual-read-service.ts
deleted file mode 100644
index 3d10436ef3..0000000000
--- a/backend/src/services/license-client/dual-read/dual-read-service.ts
+++ /dev/null
@@ -1,65 +0,0 @@
-import { TFeatureSet } from "@app/ee/services/license/license-types";
-import { TEnvConfig } from "@app/lib/config/env";
-import { logger } from "@app/lib/logger";
-import { recordLicenseDualReadDiff, recordLicenseDualReadError } from "@app/lib/telemetry/metrics";
-import { TLicenseClientFactory } from "@app/services/license-client/license-client";
-
-import { DualReadDiffKind } from "./dual-read-types";
-import { compareEntitlements } from "./entitlement-comparator";
-import { FEATURE_MAPPINGS } from "./feature-mapping";
-import { classifyUnlicensedCompare } from "./unlicensed";
-
-export type TDualReadServiceFactory = ReturnType<typeof dualReadServiceFactory>;
-
-type TDualReadServiceFactoryDep = {
- licenseClient: Pick<TLicenseClientFactory, "getEntitlements">;
- envConfig: Pick<TEnvConfig, "isLicenseDualReadEnabled">;
-};
-
-export const dualReadServiceFactory = ({ licenseClient, envConfig }: TDualReadServiceFactoryDep) => {
- // Fire-and-forget shadow compare against the already-resolved v1 plan. Never awaited, never throws into
- // the request path; inert unless mode is read-compare. Reads v2 through the real client SDK so the
- // production read path is exercised under real traffic ahead of the cutover.
- const compareInBackground = (orgId: string, planV1: TFeatureSet) => {
- if (!envConfig.isLicenseDualReadEnabled) {
- return;
- }
-
- void (async () => {
- const entitlements = await licenseClient.getEntitlements({ id: orgId });
- if (!entitlements) {
- recordLicenseDualReadError({ error: new Error("v2 entitlements unavailable") });
- logger.warn(`license-dual-read: v2 entitlements unavailable [orgId=${orgId}]`);
- return;
- }
-
- const { skip, warnPaid } = classifyUnlicensedCompare(entitlements, planV1);
- if (skip) {
- if (warnPaid) {
- logger.warn(`license-dual-read: paid v1 org unlicensed in v2 [orgId=${orgId}] [v1Slug=${planV1.slug}]`);
- }
- return;
- }
-
- const discrepancies = compareEntitlements(planV1, entitlements, FEATURE_MAPPINGS);
- const diffs = discrepancies.filter((d) => d.kind !== DualReadDiffKind.Match);
-
- for (const d of diffs) {
- recordLicenseDualReadDiff({ feature: d.v2Key, kind: d.kind });
- logger.info(
- { orgId, feature: d.v2Key, kind: d.kind, v1Value: d.v1Value, v2Value: d.v2Value },
- `license-dual-read discrepancy [orgId=${orgId}] [feature=${d.v2Key}] [kind=${d.kind}] [v1=${String(d.v1Value)}] [v2=${String(d.v2Value)}]`
- );
- }
-
- logger.info(
- `license-dual-read: compared entitlements [orgId=${orgId}] [diffs=${diffs.length}] [total=${discrepancies.length}]`
- );
- })().catch((error: unknown) => {
- recordLicenseDualReadError({ error });
- logger.error(error, `license-dual-read: compare failed [orgId=${orgId}]`);
- });
- };
-
- return { compareInBackground };
-};
diff --git a/backend/src/services/license-client/dual-read/dual-read-types.ts b/backend/src/services/license-client/dual-read/dual-read-types.ts
deleted file mode 100644
index a1a02bf359..0000000000
--- a/backend/src/services/license-client/dual-read/dual-read-types.ts
+++ /dev/null
@@ -1,44 +0,0 @@
-import { TFeatureSet } from "@app/ee/services/license/license-types";
-
-import { TFeatureValue } from "../feature";
-
-export enum DualReadDiffKind {
- Match = "match",
- Mismatch = "mismatch",
- V2Missing = "v2_missing",
- V1Absent = "v1_absent",
- Indeterminate = "indeterminate"
-}
-
-// Sentinel so a v1 null (unlimited cap) compares equal to a v2 unlimited representation. It is a
-// plain string value, so TNormalizedValue stays TFeatureValue | null.
-export const UNLIMITED = "unlimited" as const;
-
-export type TNormalizedValue = TFeatureValue | null;
-
-export type TFeatureMapping = {
- // Must match a License Server v2 feature registry key (a separate repo); a wrong key surfaces as a v2_missing diff.
- v2Key: string;
- // The TFeatureSet field name this maps to (drives the completeness test); dotted for nested
- // fields (e.g. "rateLimits.readLimit"). null when v2-only.
- v1Field: string | null;
- // Resolves the v1 value. null when there is no corresponding v1 field (v2-only descriptor).
- extractV1: ((plan: TFeatureSet) => TFeatureValue | null) | null;
- // Normalizes a value before comparison (e.g. null -> UNLIMITED). Applied to both sides.
- normalize?: (value: TFeatureValue | null) => TNormalizedValue;
-};
-
-export type TDiscrepancy = {
- v2Key: string;
- kind: DualReadDiffKind;
- v1Value: TNormalizedValue;
- v2Value: TNormalizedValue;
-};
-
-// Maps a possibly-null cap to UNLIMITED; reusable by mapping files for "null = unlimited" v1 caps.
-export const unlimitedWhenNull = (value: TFeatureValue | null): TNormalizedValue => {
- if (value === null || value === undefined) {
- return UNLIMITED;
- }
- return value;
-};
diff --git a/backend/src/services/license-client/dual-read/entitlement-comparator.test.ts b/backend/src/services/license-client/dual-read/entitlement-comparator.test.ts
deleted file mode 100644
index 6912704af2..0000000000
--- a/backend/src/services/license-client/dual-read/entitlement-comparator.test.ts
+++ /dev/null
@@ -1,144 +0,0 @@
-import { describe, expect, test } from "vitest";
-
-import { TFeatureSet } from "@app/ee/services/license/license-types";
-
-import { TEntitlementsResponse } from "../license-client-types";
-import { DualReadDiffKind, TFeatureMapping, UNLIMITED, unlimitedWhenNull } from "./dual-read-types";
-import { compareEntitlements } from "./entitlement-comparator";
-
-// TFeatureSet fields are literal-typed (e.g. auditLogsRetentionDays: 0), so fixtures use loose values.
-const makePlan = (overrides: Partial<Record<keyof TFeatureSet, unknown>>): TFeatureSet =>
- ({ ...overrides }) as TFeatureSet;
-
-const makeEntitlements = (features: TEntitlementsResponse["features"]): TEntitlementsResponse =>
- ({ features }) as TEntitlementsResponse;
-
-const findByKey = (result: ReturnType<typeof compareEntitlements>, v2Key: string): (typeof result)[number] => {
- const match = result.find((d) => d.v2Key === v2Key);
- if (!match) {
- throw new Error(`expected a discrepancy for [v2Key=${v2Key}]`);
- }
- return match;
-};
-
-describe("compareEntitlements", () => {
- test("boolean values that agree report a Match", () => {
- const mappings: TFeatureMapping[] = [
- { v2Key: "sso_enforcement", v1Field: "enforceGoogleSSO", extractV1: (p) => p.enforceGoogleSSO }
- ];
- const plan = makePlan({ enforceGoogleSSO: false });
- const entitlements = makeEntitlements({ sso_enforcement: { value: false } });
-
- const result = compareEntitlements(plan, entitlements, mappings);
- const diff = findByKey(result, "sso_enforcement");
- expect(diff.kind).toBe(DualReadDiffKind.Match);
- expect(diff.v1Value).toBe(false);
- expect(diff.v2Value).toBe(false);
- });
-
- test("boolean values that disagree report a Mismatch", () => {
- const mappings: TFeatureMapping[] = [
- { v2Key: "sso_enforcement", v1Field: "enforceGoogleSSO", extractV1: (p) => p.enforceGoogleSSO }
- ];
- const plan = makePlan({ enforceGoogleSSO: false });
- const entitlements = makeEntitlements({ sso_enforcement: { value: true } });
-
- const diff = findByKey(compareEntitlements(plan, entitlements, mappings), "sso_enforcement");
- expect(diff.kind).toBe(DualReadDiffKind.Mismatch);
- expect(diff.v1Value).toBe(false);
- expect(diff.v2Value).toBe(true);
- });
-
- test("v1 null cap normalized to UNLIMITED matches a v2 unlimited representation", () => {
- const mappings: TFeatureMapping[] = [
- {
- v2Key: "identities",
- v1Field: "identityLimit",
- extractV1: (p) => p.identityLimit,
- normalize: unlimitedWhenNull
- }
- ];
- const plan = makePlan({ identityLimit: null });
- const entitlements = makeEntitlements({ identities: { value: UNLIMITED } });
-
- const diff = findByKey(compareEntitlements(plan, entitlements, mappings), "identities");
- expect(diff.kind).toBe(DualReadDiffKind.Match);
- expect(diff.v1Value).toBe(UNLIMITED);
- expect(diff.v2Value).toBe(UNLIMITED);
- });
-
- test("a v2 key that is absent reports V2Missing", () => {
- const mappings: TFeatureMapping[] = [
- {
- v2Key: "audit_retention_days",
- v1Field: "auditLogsRetentionDays",
- extractV1: (p) => p.auditLogsRetentionDays
- }
- ];
- const plan = makePlan({ auditLogsRetentionDays: 30 });
- const entitlements = makeEntitlements({});
-
- const diff = findByKey(compareEntitlements(plan, entitlements, mappings), "audit_retention_days");
- expect(diff.kind).toBe(DualReadDiffKind.V2Missing);
- expect(diff.v1Value).toBe(30);
- expect(diff.v2Value).toBeNull();
- });
-
- test("a mapping with no v1 extractor reports V1Absent", () => {
- const mappings: TFeatureMapping[] = [{ v2Key: "internal_cas", v1Field: null, extractV1: null }];
- const plan = makePlan({});
- const entitlements = makeEntitlements({ internal_cas: { value: 5 } });
-
- const diff = findByKey(compareEntitlements(plan, entitlements, mappings), "internal_cas");
- expect(diff.kind).toBe(DualReadDiffKind.V1Absent);
- expect(diff.v1Value).toBeNull();
- expect(diff.v2Value).toBe(5);
- });
-
- test("v1 UNLIMITED versus a v2 finite number downgrades to Indeterminate", () => {
- const mappings: TFeatureMapping[] = [
- {
- v2Key: "identities",
- v1Field: "identityLimit",
- extractV1: (p) => p.identityLimit,
- normalize: unlimitedWhenNull
- }
- ];
- const plan = makePlan({ identityLimit: null });
- const entitlements = makeEntitlements({ identities: { value: 100 } });
-
- const diff = findByKey(compareEntitlements(plan, entitlements, mappings), "identities");
- expect(diff.kind).toBe(DualReadDiffKind.Indeterminate);
- expect(diff.v1Value).toBe(UNLIMITED);
- expect(diff.v2Value).toBe(100);
- });
-
- test("a v2 value present but null reports V2Missing, not a false Mismatch, for a non-normalized feature", () => {
- const mappings: TFeatureMapping[] = [{ v2Key: "rbac", v1Field: "rbac", extractV1: (p) => p.rbac }];
- const plan = makePlan({ rbac: false });
- const entitlements = makeEntitlements({ rbac: { value: null } });
-
- const diff = findByKey(compareEntitlements(plan, entitlements, mappings), "rbac");
- expect(diff.kind).toBe(DualReadDiffKind.V2Missing);
- expect(diff.v1Value).toBe(false);
- expect(diff.v2Value).toBeNull();
- });
-
- test("a v2 null normalized via unlimitedWhenNull matches a v1 unlimited cap", () => {
- const mappings: TFeatureMapping[] = [
- {
- v2Key: "workspace_limit",
- v1Field: "workspaceLimit",
- extractV1: (p) => p.workspaceLimit,
- normalize: unlimitedWhenNull
- }
- ];
- const plan = makePlan({ workspaceLimit: null });
- const entitlements = makeEntitlements({ workspace_limit: { value: null } });
-
- const diff = findByKey(compareEntitlements(plan, entitlements, mappings), "workspace_limit");
- expect(diff.kind).toBe(DualReadDiffKind.Match);
- expect(diff.v1Value).toBe(UNLIMITED);
- expect(diff.v2Value).toBe(UNLIMITED);
- });
-});
diff --git a/backend/src/services/license-client/dual-read/entitlement-comparator.ts b/backend/src/services/license-client/dual-read/entitlement-comparator.ts
deleted file mode 100644
index 58eb30ec10..0000000000
--- a/backend/src/services/license-client/dual-read/entitlement-comparator.ts
+++ /dev/null
@@ -1,44 +0,0 @@
-import { TFeatureSet } from "@app/ee/services/license/license-types";
-
-import { TEntitlementsResponse } from "../license-client-types";
-import { DualReadDiffKind, TDiscrepancy, TFeatureMapping, TNormalizedValue, UNLIMITED } from "./dual-read-types";
-
-const identity = (value: TNormalizedValue): TNormalizedValue => value;
-
-const compareOne = (plan: TFeatureSet, entitlements: TEntitlementsResponse, mapping: TFeatureMapping): TDiscrepancy => {
- const normalize = mapping.normalize ?? identity;
- const v2Raw = entitlements.features[mapping.v2Key];
-
- // Resolve the v2 side once. The entitlement schema allows a null value, and a normalize (e.g.
- // unlimitedWhenNull) may turn that into a real value; anything still null means v2 resolved nothing.
- let v2Value: TNormalizedValue = null;
- if (v2Raw) {
- v2Value = normalize(v2Raw.value);
- }
-
- if (mapping.extractV1 === null) {
- return { v2Key: mapping.v2Key, kind: DualReadDiffKind.V1Absent, v1Value: null, v2Value };
- }
-
- const v1Value = normalize(mapping.extractV1(plan));
-
- if (v2Value === null) {
- return { v2Key: mapping.v2Key, kind: DualReadDiffKind.V2Missing, v1Value, v2Value: null };
- }
-
- let kind = DualReadDiffKind.Mismatch;
- if (v1Value === v2Value) {
- kind = DualReadDiffKind.Match;
- } else if ((v1Value === UNLIMITED) !== (v2Value === UNLIMITED)) {
- // v2 has no pinned cross-repo "unlimited" representation, so this can't be confirmed a mismatch.
- kind = DualReadDiffKind.Indeterminate;
- }
-
- return { v2Key: mapping.v2Key, kind, v1Value, v2Value };
-};
-
-export const compareEntitlements = (
- plan: TFeatureSet,
- entitlements: TEntitlementsResponse,
- mappings: TFeatureMapping[]
-): TDiscrepancy[] => mappings.map((mapping) => compareOne(plan, entitlements, mapping));
diff --git a/backend/src/services/license-client/dual-read/feature-mapping/access.ts b/backend/src/services/license-client/dual-read/feature-mapping/access.ts
deleted file mode 100644
index 3578a39d0d..0000000000
--- a/backend/src/services/license-client/dual-read/feature-mapping/access.ts
+++ /dev/null
@@ -1,64 +0,0 @@
-import { TFeatureMapping } from "../dual-read-types";
-
-export const accessMappings: TFeatureMapping[] = [
- {
- v2Key: "rbac",
- v1Field: "rbac",
- extractV1: (p) => p.rbac
- },
- {
- v2Key: "groups",
- v1Field: "groups",
- extractV1: (p) => p.groups
- },
- {
- v2Key: "ip_allowlisting",
- v1Field: "ipAllowlisting",
- extractV1: (p) => p.ipAllowlisting
- },
- {
- v2Key: "saml_sso",
- v1Field: "samlSSO",
- extractV1: (p) => p.samlSSO
- },
- {
- v2Key: "oidc_sso",
- v1Field: "oidcSSO",
- extractV1: (p) => p.oidcSSO
- },
- {
- v2Key: "ldap",
- v1Field: "ldap",
- extractV1: (p) => p.ldap
- },
- {
- v2Key: "scim",
- v1Field: "scim",
- extractV1: (p) => p.scim
- },
- {
- v2Key: "enforce_google_sso",
- v1Field: "enforceGoogleSSO",
- extractV1: (p) => p.enforceGoogleSSO
- },
- {
- v2Key: "enforce_mfa",
- v1Field: "enforceMfa",
- extractV1: (p) => p.enforceMfa
- },
- {
- v2Key: "github_org_sync",
- v1Field: "githubOrgSync",
- extractV1: (p) => p.githubOrgSync
- },
- {
- v2Key: "audit_logs",
- v1Field: "auditLogs",
- extractV1: (p) => p.auditLogs
- },
- {
- v2Key: "audit_log_streams",
- v1Field: "auditLogStreams",
- extractV1: (p) => p.auditLogStreams
- }
-];
diff --git a/backend/src/services/license-client/dual-read/feature-mapping/core.ts b/backend/src/services/license-client/dual-read/feature-mapping/core.ts
deleted file mode 100644
index 952f1be87c..0000000000
--- a/backend/src/services/license-client/dual-read/feature-mapping/core.ts
+++ /dev/null
@@ -1,114 +0,0 @@
-import { TFeatureMapping } from "../dual-read-types";
-
-export const coreMappings: TFeatureMapping[] = [
- {
- v2Key: "secret_versioning",
- v1Field: "secretVersioning",
- extractV1: (p) => p.secretVersioning
- },
- {
- v2Key: "pit_recovery",
- v1Field: "pitRecovery",
- extractV1: (p) => p.pitRecovery
- },
- {
- v2Key: "dynamic_secret",
- v1Field: "dynamicSecret",
- extractV1: (p) => p.dynamicSecret
- },
- {
- v2Key: "sub_organization",
- v1Field: "subOrganization",
- extractV1: (p) => p.subOrganization
- },
- {
- v2Key: "secret_approval",
- v1Field: "secretApproval",
- extractV1: (p) => p.secretApproval
- },
- {
- v2Key: "secret_rotation",
- v1Field: "secretRotation",
- extractV1: (p) => p.secretRotation
- },
- {
- v2Key: "secret_access_insights",
- v1Field: "secretAccessInsights",
- extractV1: (p) => p.secretAccessInsights
- },
- {
- v2Key: "project_templates",
- v1Field: "projectTemplates",
- extractV1: (p) => p.projectTemplates
- },
- {
- v2Key: "event_subscriptions",
- v1Field: "eventSubscriptions",
- extractV1: (p) => p.eventSubscriptions
- },
- {
- v2Key: "pam_slack_notifications",
- v1Field: "pamSlackNotifications",
- extractV1: (p) => p.pamSlackNotifications
- },
- {
- v2Key: "machine_identity_auth_templates",
- v1Field: "machineIdentityAuthTemplates",
- extractV1: (p) => p.machineIdentityAuthTemplates
- },
- {
- v2Key: "secret_share_external_branding",
- v1Field: "secretShareExternalBranding",
- extractV1: (p) => p.secretShareExternalBranding
- },
- {
- v2Key: "instance_user_management",
- v1Field: "instanceUserManagement",
- extractV1: (p) => p.instanceUserManagement
- },
- {
- v2Key: "secret_scanning",
- v1Field: "secretScanning",
- extractV1: (p) => p.secretScanning
- },
- {
- v2Key: "enterprise_secret_syncs",
- v1Field: "enterpriseSecretSyncs",
- extractV1: (p) => p.enterpriseSecretSyncs
- },
- {
- v2Key: "enterprise_app_connections",
- v1Field: "enterpriseAppConnections",
- extractV1: (p) => p.enterpriseAppConnections
- },
- {
- v2Key: "enterprise_certificate_syncs",
- v1Field: "enterpriseCertificateSyncs",
- extractV1: (p) => p.enterpriseCertificateSyncs
- },
- {
- v2Key: "pam",
- v1Field: "pam",
- extractV1: (p) => p.pam
- },
- {
- v2Key: "cert_manager",
- v1Field: "certManager",
- extractV1: (p) => p.certManager
- },
- {
- v2Key: "secrets_temporary_access",
- v1Field: "secretsTemporaryAccess",
- extractV1: (p) => p.secretsTemporaryAccess
- },
- {
- v2Key: "enterprise_pam_account",
- v1Field: "enterprisePamAccount",
- extractV1: (p) => p.enterprisePamAccount
- },
- {
- v2Key: "cross_project_secret_sharing",
- v1Field: "crossProjectSecretSharing",
- extractV1: (p) => p.crossProjectSecretSharing
- }
-];
diff --git a/backend/src/services/license-client/dual-read/feature-mapping/existing.ts b/backend/src/services/license-client/dual-read/feature-mapping/existing.ts
deleted file mode 100644
index b2d0f0d3f0..0000000000
--- a/backend/src/services/license-client/dual-read/feature-mapping/existing.ts
+++ /dev/null
@@ -1,36 +0,0 @@
-import { ActiveCerts, AuditRetentionDays, IdentitiesMeter, InternalCas, SsoEnforcement } from "../../features";
-import { TFeatureMapping } from "../dual-read-types";
-
-export const existingDescriptorMappings: TFeatureMapping[] = [
- {
- // v2's `identities` is a usage meter (reported count); the identity cap is a separate v2 feature
- // (max_identity_limit) mapped in limits.ts, so the meter itself maps to no v1 field.
- v2Key: IdentitiesMeter.key,
- v1Field: null,
- extractV1: null
- },
- {
- v2Key: AuditRetentionDays.key,
- v1Field: "auditLogsRetentionDays",
- extractV1: (p) => p.auditLogsRetentionDays
- },
- {
- // v2's sso_enforcement is the general "can enforce SSO" entitlement; v1 has no single field for it
- // (SAML/OIDC enforcement rides on the samlSSO/oidcSSO capabilities, Google on enforceGoogleSSO).
- v2Key: SsoEnforcement.key,
- v1Field: null,
- extractV1: null
- },
- {
- // v2's `internal_cas` is a usage meter; the internal-CA cap is a separate v2 feature
- // (max_internal_cas) mapped in limits.ts, so the meter itself maps to no v1 field.
- v2Key: InternalCas.key,
- v1Field: null,
- extractV1: null
- },
- {
- v2Key: ActiveCerts.key,
- v1Field: null,
- extractV1: null
- }
-];
diff --git a/backend/src/services/license-client/dual-read/feature-mapping/index.ts b/backend/src/services/license-client/dual-read/feature-mapping/index.ts
deleted file mode 100644
index 7fa1648f20..0000000000
--- a/backend/src/services/license-client/dual-read/feature-mapping/index.ts
+++ /dev/null
@@ -1,32 +0,0 @@
-import { TFeatureMapping } from "../dual-read-types";
-import { accessMappings } from "./access";
-import { coreMappings } from "./core";
-import { existingDescriptorMappings } from "./existing";
-import { limitsMappings } from "./limits";
-import { pkiSecurityMappings } from "./pki-security";
-
-export const FEATURE_MAPPINGS: TFeatureMapping[] = [
- ...existingDescriptorMappings,
- ...coreMappings,
- ...accessMappings,
- ...pkiSecurityMappings,
- ...limitsMappings
-];
-
-// v1 TFeatureSet keys intentionally not compared: live usage counters, plan metadata, and v1 fields
-// with no License Server v2 feature (v2 never returns them, so a mapping would be permanently v2_missing).
-export const EXCLUDED_FIELDS: ReadonlySet<string> = new Set([
- "_id",
- "slug",
- "tier",
- "status",
- "trial_end",
- "has_used_trial",
- "workspacesUsed",
- "membersUsed",
- "identitiesUsed",
- "environmentsUsed",
- "workspaceLimit",
- "memberLimit",
- "pkiLegacyTemplates"
-]);
diff --git a/backend/src/services/license-client/dual-read/feature-mapping/limits.ts b/backend/src/services/license-client/dual-read/feature-mapping/limits.ts
deleted file mode 100644
index c14a25db9c..0000000000
--- a/backend/src/services/license-client/dual-read/feature-mapping/limits.ts
+++ /dev/null
@@ -1,63 +0,0 @@
-import { TFeatureMapping, unlimitedWhenNull } from "../dual-read-types";
-
-export const limitsMappings: TFeatureMapping[] = [
- {
- v2Key: "environment_limit",
- v1Field: "environmentLimit",
- extractV1: (p) => p.environmentLimit,
- normalize: unlimitedWhenNull
- },
- {
- // Max identities allowed. Dedicated cap feature, separate from the `identities` usage meter.
- v2Key: "max_identity_limit",
- v1Field: "identityLimit",
- extractV1: (p) => p.identityLimit,
- normalize: unlimitedWhenNull
- },
- {
- // Max internal CAs allowed. Dedicated cap feature, separate from the `internal_cas` usage meter.
- v2Key: "max_internal_cas",
- v1Field: "maxInternalCas",
- extractV1: (p) => p.maxInternalCas,
- normalize: unlimitedWhenNull
- },
- {
- // Max PAM accounts allowed. null (v1 default) means uncapped, so it normalizes to UNLIMITED.
- v2Key: "max_pam_accounts",
- v1Field: "maxPamAccounts",
- extractV1: (p) => p.maxPamAccounts,
- normalize: unlimitedWhenNull
- },
- {
- // null (v1 default) means uncapped, so it normalizes to UNLIMITED for the dual-read compare.
- v2Key: "secret_sync_limit",
- v1Field: "secretSyncLimit",
- extractV1: (p) => p.secretSyncLimit,
- normalize: unlimitedWhenNull
- },
- {
- v2Key: "audit_log_stream_limit",
- v1Field: "auditLogStreamLimit",
- extractV1: (p) => p.auditLogStreamLimit
- },
- {
- v2Key: "honey_token_limit",
- v1Field: "honeyTokenLimit",
- extractV1: (p) => p.honeyTokenLimit
- },
- {
- v2Key: "read_rate_limit",
- v1Field: "rateLimits.readLimit",
- extractV1: (p) => p.rateLimits?.readLimit ?? null
- },
- {
- v2Key: "write_rate_limit",
- v1Field: "rateLimits.writeLimit",
- extractV1: (p) => p.rateLimits?.writeLimit ?? null
- },
- {
- v2Key: "secrets_rate_limit",
- v1Field: "rateLimits.secretsLimit",
- extractV1: (p) => p.rateLimits?.secretsLimit ?? null
- }
-];
diff --git a/backend/src/services/license-client/dual-read/feature-mapping/pki-security.ts b/backend/src/services/license-client/dual-read/feature-mapping/pki-security.ts
deleted file mode 100644
index 0ccdb07244..0000000000
--- a/backend/src/services/license-client/dual-read/feature-mapping/pki-security.ts
+++ /dev/null
@@ -1,89 +0,0 @@
-import { TFeatureMapping } from "../dual-read-types";
-
-export const pkiSecurityMappings: TFeatureMapping[] = [
- {
- v2Key: "ca_crl",
- v1Field: "caCrl",
- extractV1: (p) => p.caCrl
- },
- {
- v2Key: "pki_est",
- v1Field: "pkiEst",
- extractV1: (p) => p.pkiEst
- },
- {
- v2Key: "pki_acme",
- v1Field: "pkiAcme",
- extractV1: (p) => p.pkiAcme
- },
- {
- v2Key: "pki_scep",
- v1Field: "pkiScep",
- extractV1: (p) => p.pkiScep
- },
- {
- v2Key: "pki_pqc",
- v1Field: "pkiPqc",
- extractV1: (p) => p.pkiPqc
- },
- {
- v2Key: "pki_code_signing",
- v1Field: "pkiCodeSigning",
- extractV1: (p) => p.pkiCodeSigning
- },
- {
- v2Key: "hsm",
- v1Field: "hsm",
- extractV1: (p) => p.hsm
- },
- {
- v2Key: "external_kms",
- v1Field: "externalKms",
- extractV1: (p) => p.externalKms
- },
- {
- v2Key: "kms_pqc",
- v1Field: "kmsPqc",
- extractV1: (p) => p.kmsPqc
- },
- {
- v2Key: "kmip",
- v1Field: "kmip",
- extractV1: (p) => p.kmip
- },
- {
- v2Key: "fips",
- v1Field: "fips",
- extractV1: (p) => p.fips
- },
- {
- v2Key: "gateway",
- v1Field: "gateway",
- extractV1: (p) => p.gateway
- },
- {
- v2Key: "gateway_pool",
- v1Field: "gatewayPool",
- extractV1: (p) => p.gatewayPool
- },
- {
- v2Key: "honey_tokens",
- v1Field: "honeyTokens",
- extractV1: (p) => p.honeyTokens
- },
- {
- v2Key: "secrets_brokering",
- v1Field: "secretsBrokering",
- extractV1: (p) => p.secretsBrokering
- },
- {
- v2Key: "custom_rate_limits",
- v1Field: "customRateLimits",
- extractV1: (p) => p.customRateLimits
- },
- {
- v2Key: "custom_alerts",
- v1Field: "customAlerts",
- extractV1: (p) => p.customAlerts
- }
-];
diff --git a/backend/src/services/license-client/dual-read/unlicensed.test.ts b/backend/src/services/license-client/dual-read/unlicensed.test.ts
deleted file mode 100644
index 9a495c10a9..0000000000
--- a/backend/src/services/license-client/dual-read/unlicensed.test.ts
+++ /dev/null
@@ -1,71 +0,0 @@
-import { describe, expect, test } from "vitest";
-
-import { TFeatureSet } from "@app/ee/services/license/license-types";
-
-import { TEntitlementsResponse } from "../license-client-types";
-import { classifyUnlicensedCompare } from "./unlicensed";
-
-const makePlan = (slug: string | null): TFeatureSet => ({ slug }) as TFeatureSet;
-const makeEntitlements = (features: TEntitlementsResponse["features"]): TEntitlementsResponse =>
- ({ features }) as TEntitlementsResponse;
-
-describe("classifyUnlicensedCompare", () => {
- const cases: {
- name: string;
- features: TEntitlementsResponse["features"];
- slug: string | null;
- wantSkip: boolean;
- wantWarn: boolean;
- }[] = [
- { name: "empty features + paid v1 skips and warns", features: {}, slug: "pro", wantSkip: true, wantWarn: true },
- {
- name: "empty features + free v1 skips without warning",
- features: {},
- slug: "starter",
- wantSkip: true,
- wantWarn: false
- },
- {
- name: "empty features + null slug skips without warning",
- features: {},
- slug: null,
- wantSkip: true,
- wantWarn: false
- },
- {
- name: "all-default features + paid v1 skips and warns",
- features: {
- environment_limit: { value: 3, source: "default" },
- identities: { value: 5, source: "default" }
- },
- slug: "enterprise",
- wantSkip: true,
- wantWarn: true
- },
- {
- name: "mixed sources runs the compare",
- features: {
- environment_limit: { value: 3, source: "default" },
- sso_enforcement: { value: true, source: "plan" }
- },
- slug: "pro",
- wantSkip: false,
- wantWarn: false
- },
- {
- name: "licensed features run the compare",
- features: { sso_enforcement: { value: true, source: "plan" } },
- slug: "enterprise",
- wantSkip: false,
- wantWarn: false
- }
- ];
-
- for (const tc of cases) {
- test(tc.name, () => {
- const result = classifyUnlicensedCompare(makeEntitlements(tc.features), makePlan(tc.slug));
- expect(result.skip).toBe(tc.wantSkip);
- expect(result.warnPaid).toBe(tc.wantWarn);
- });
- }
-});
diff --git a/backend/src/services/license-client/dual-read/unlicensed.ts b/backend/src/services/license-client/dual-read/unlicensed.ts
deleted file mode 100644
index 700ef01873..0000000000
--- a/backend/src/services/license-client/dual-read/unlicensed.ts
+++ /dev/null
@@ -1,14 +0,0 @@
-import { TFeatureSet } from "@app/ee/services/license/license-types";
-
-import { TEntitlementsResponse } from "../license-client-types";
-
-// An unlicensed org resolves to all-default features (vacuously true on the empty map v2 returns today),
-// so there is nothing to compare. Paid v1 orgs are still flagged since they get downgraded at cutover.
-export const classifyUnlicensedCompare = (
- entitlements: TEntitlementsResponse,
- planV1: TFeatureSet
-): { skip: boolean; warnPaid: boolean } => {
- const skip = Object.values(entitlements.features).every((f) => f.source === "default");
- const warnPaid = skip && Boolean(planV1.slug) && planV1.slug !== "starter";
- return { skip, warnPaid };
-};
diff --git a/backend/src/services/license-client/dual-read/entitlement-projection.test.ts b/backend/src/services/license-client/entitlement-projection.test.ts
similarity index 96%
rename from backend/src/services/license-client/dual-read/entitlement-projection.test.ts
rename to backend/src/services/license-client/entitlement-projection.test.ts
index 634dd5b45b..73e0c885f4 100644
--- a/backend/src/services/license-client/dual-read/entitlement-projection.test.ts
+++ b/backend/src/services/license-client/entitlement-projection.test.ts
@@ -2,8 +2,8 @@ import { describe, expect, test } from "vitest";
import { TFeatureSet } from "@app/ee/services/license/license-types";
-import { TEntitlementsResponse } from "../license-client-types";
import { projectV2ToFeatureSet } from "./entitlement-projection";
+import { TEntitlementsResponse } from "./license-client-types";
const makeBase = (overrides: Partial<Record<keyof TFeatureSet, unknown>>): TFeatureSet =>
({ rateLimits: { readLimit: 0, writeLimit: 0, secretsLimit: 0 }, ...overrides }) as TFeatureSet;
diff --git a/backend/src/services/license-client/dual-read/entitlement-projection.ts b/backend/src/services/license-client/entitlement-projection.ts
similarity index 87%
rename from backend/src/services/license-client/dual-read/entitlement-projection.ts
rename to backend/src/services/license-client/entitlement-projection.ts
index 064480ca94..55dd74806d 100644
--- a/backend/src/services/license-client/dual-read/entitlement-projection.ts
+++ b/backend/src/services/license-client/entitlement-projection.ts
@@ -1,9 +1,9 @@
import { TFeatureSet } from "@app/ee/services/license/license-types";
-import { TEntitlementsResponse } from "../license-client-types";
import { FEATURE_MAPPINGS } from "./feature-mapping";
+import { TEntitlementsResponse } from "./license-client-types";
-// Builds a v1-shaped TFeatureSet from the v2 entitlement set so getPlan can serve v2 in "on" mode
+// Builds a plan-shaped TFeatureSet from the License Server entitlement set so getPlan can serve it
// without changing its callers. Starts from the passed base (free-tier defaults) and overlays each
// mapped feature; a key v2 omits or returns null for keeps the base value. Base is passed in (not
// imported from license-fns) to avoid a license-service <-> license-fns import cycle.
diff --git a/backend/src/services/license-client/dual-read/feature-mapping/mapping-completeness.test.ts b/backend/src/services/license-client/feature-mapping.test.ts
similarity index 92%
rename from backend/src/services/license-client/dual-read/feature-mapping/mapping-completeness.test.ts
rename to backend/src/services/license-client/feature-mapping.test.ts
index cfd2910bb4..ed551d4b5b 100644
--- a/backend/src/services/license-client/dual-read/feature-mapping/mapping-completeness.test.ts
+++ b/backend/src/services/license-client/feature-mapping.test.ts
@@ -2,7 +2,7 @@ import { describe, expect, test } from "vitest";
import { getDefaultOnPremFeatures } from "@app/ee/services/license/license-fns";
-import { EXCLUDED_FIELDS, FEATURE_MAPPINGS } from "./index";
+import { EXCLUDED_FIELDS, FEATURE_MAPPINGS } from "./feature-mapping";
const topLevelV1Field = (v1Field: string): string => {
const dotIndex = v1Field.indexOf(".");
diff --git a/backend/src/services/license-client/feature-mapping.ts b/backend/src/services/license-client/feature-mapping.ts
new file mode 100644
index 0000000000..27077bfd31
--- /dev/null
+++ b/backend/src/services/license-client/feature-mapping.ts
@@ -0,0 +1,327 @@
+import { ActiveCerts, AuditRetentionDays, IdentitiesMeter, InternalCas, SsoEnforcement } from "./features";
+
+export type TFeatureMapping = {
+ // Must match a License Server feature registry key (a separate repo); a wrong key means the feature
+ // is never projected onto the plan.
+ v2Key: string;
+ // The TFeatureSet field this maps to (drives the completeness test); dotted for nested fields
+ // (e.g. "rateLimits.readLimit"). null when the feature has no plan field to write.
+ v1Field: string | null;
+};
+
+// Org-wide capabilities that are not tied to a single product: identity and access, audit, KMS/HSM,
+// gateways, instance controls, and the org-level caps and rate limits.
+const platformMappings: TFeatureMapping[] = [
+ {
+ // v2's `identities` is a usage meter (reported count); the identity cap is a separate v2 feature
+ // (max_identity_limit) mapped below, so the meter itself maps to no v1 field.
+ v2Key: IdentitiesMeter.key,
+ v1Field: null
+ },
+ {
+ v2Key: AuditRetentionDays.key,
+ v1Field: "auditLogsRetentionDays"
+ },
+ {
+ // v2's sso_enforcement is the general "can enforce SSO" entitlement; v1 has no single field for it
+ // (SAML/OIDC enforcement rides on the samlSSO/oidcSSO capabilities, Google on enforceGoogleSSO).
+ v2Key: SsoEnforcement.key,
+ v1Field: null
+ },
+ {
+ v2Key: "rbac",
+ v1Field: "rbac"
+ },
+ {
+ v2Key: "groups",
+ v1Field: "groups"
+ },
+ {
+ v2Key: "ip_allowlisting",
+ v1Field: "ipAllowlisting"
+ },
+ {
+ v2Key: "saml_sso",
+ v1Field: "samlSSO"
+ },
+ {
+ v2Key: "oidc_sso",
+ v1Field: "oidcSSO"
+ },
+ {
+ v2Key: "ldap",
+ v1Field: "ldap"
+ },
+ {
+ v2Key: "scim",
+ v1Field: "scim"
+ },
+ {
+ v2Key: "enforce_google_sso",
+ v1Field: "enforceGoogleSSO"
+ },
+ {
+ v2Key: "enforce_mfa",
+ v1Field: "enforceMfa"
+ },
+ {
+ v2Key: "github_org_sync",
+ v1Field: "githubOrgSync"
+ },
+ {
+ v2Key: "machine_identity_auth_templates",
+ v1Field: "machineIdentityAuthTemplates"
+ },
+ {
+ v2Key: "sub_organization",
+ v1Field: "subOrganization"
+ },
+ {
+ v2Key: "instance_user_management",
+ v1Field: "instanceUserManagement"
+ },
+ {
+ v2Key: "project_templates",
+ v1Field: "projectTemplates"
+ },
+ {
+ v2Key: "event_subscriptions",
+ v1Field: "eventSubscriptions"
+ },
+ {
+ // App connections back secret syncs, rotations, cert syncs and PAM, so they are platform-level.
+ v2Key: "enterprise_app_connections",
+ v1Field: "enterpriseAppConnections"
+ },
+ {
+ v2Key: "audit_logs",
+ v1Field: "auditLogs"
+ },
+ {
+ v2Key: "audit_log_streams",
+ v1Field: "auditLogStreams"
+ },
+ {
+ v2Key: "hsm",
+ v1Field: "hsm"
+ },
+ {
+ v2Key: "external_kms",
+ v1Field: "externalKms"
+ },
+ {
+ v2Key: "kms_pqc",
+ v1Field: "kmsPqc"
+ },
+ {
+ v2Key: "kmip",
+ v1Field: "kmip"
+ },
+ {
+ v2Key: "fips",
+ v1Field: "fips"
+ },
+ {
+ v2Key: "gateway",
+ v1Field: "gateway"
+ },
+ {
+ v2Key: "gateway_pool",
+ v1Field: "gatewayPool"
+ },
+ {
+ v2Key: "custom_rate_limits",
+ v1Field: "customRateLimits"
+ },
+ {
+ v2Key: "custom_alerts",
+ v1Field: "customAlerts"
+ },
+ {
+ v2Key: "environment_limit",
+ v1Field: "environmentLimit"
+ },
+ {
+ // Max identities allowed. Dedicated cap feature, separate from the `identities` usage meter.
+ v2Key: "max_identity_limit",
+ v1Field: "identityLimit"
+ },
+ {
+ v2Key: "audit_log_stream_limit",
+ v1Field: "auditLogStreamLimit"
+ },
+ {
+ v2Key: "read_rate_limit",
+ v1Field: "rateLimits.readLimit"
+ },
+ {
+ v2Key: "write_rate_limit",
+ v1Field: "rateLimits.writeLimit"
+ },
+ {
+ v2Key: "secrets_rate_limit",
+ v1Field: "rateLimits.secretsLimit"
+ }
+];
+
+// Secrets Management: secret storage capabilities, syncs, sharing, scanning, and their caps.
+const secretManagerMappings: TFeatureMapping[] = [
+ {
+ v2Key: "secret_versioning",
+ v1Field: "secretVersioning"
+ },
+ {
+ v2Key: "pit_recovery",
+ v1Field: "pitRecovery"
+ },
+ {
+ v2Key: "dynamic_secret",
+ v1Field: "dynamicSecret"
+ },
+ {
+ v2Key: "secret_approval",
+ v1Field: "secretApproval"
+ },
+ {
+ v2Key: "secret_rotation",
+ v1Field: "secretRotation"
+ },
+ {
+ v2Key: "secret_access_insights",
+ v1Field: "secretAccessInsights"
+ },
+ {
+ v2Key: "secrets_temporary_access",
+ v1Field: "secretsTemporaryAccess"
+ },
+ {
+ v2Key: "secret_scanning",
+ v1Field: "secretScanning"
+ },
+ {
+ v2Key: "secrets_brokering",
+ v1Field: "secretsBrokering"
+ },
+ {
+ v2Key: "enterprise_secret_syncs",
+ v1Field: "enterpriseSecretSyncs"
+ },
+ {
+ v2Key: "secret_share_external_branding",
+ v1Field: "secretShareExternalBranding"
+ },
+ {
+ v2Key: "cross_project_secret_sharing",
+ v1Field: "crossProjectSecretSharing"
+ },
+ {
+ v2Key: "honey_tokens",
+ v1Field: "honeyTokens"
+ },
+ {
+ // null (v1 default) means uncapped.
+ v2Key: "secret_sync_limit",
+ v1Field: "secretSyncLimit"
+ },
+ {
+ v2Key: "honey_token_limit",
+ v1Field: "honeyTokenLimit"
+ }
+];
+
+// Cert Manager / PKI: the product entitlement, enrollment protocols, cert syncs, and CA caps and meters.
+const certManagerMappings: TFeatureMapping[] = [
+ {
+ v2Key: "cert_manager",
+ v1Field: "certManager"
+ },
+ {
+ v2Key: "ca_crl",
+ v1Field: "caCrl"
+ },
+ {
+ v2Key: "pki_est",
+ v1Field: "pkiEst"
+ },
+ {
+ v2Key: "pki_acme",
+ v1Field: "pkiAcme"
+ },
+ {
+ v2Key: "pki_scep",
+ v1Field: "pkiScep"
+ },
+ {
+ v2Key: "pki_pqc",
+ v1Field: "pkiPqc"
+ },
+ {
+ v2Key: "pki_code_signing",
+ v1Field: "pkiCodeSigning"
+ },
+ {
+ v2Key: "enterprise_certificate_syncs",
+ v1Field: "enterpriseCertificateSyncs"
+ },
+ {
+ // v2's `internal_cas` is a usage meter; the internal-CA cap is a separate v2 feature
+ // (max_internal_cas) mapped below, so the meter itself maps to no v1 field.
+ v2Key: InternalCas.key,
+ v1Field: null
+ },
+ {
+ v2Key: ActiveCerts.key,
+ v1Field: null
+ },
+ {
+ // Max internal CAs allowed. Dedicated cap feature, separate from the `internal_cas` usage meter.
+ v2Key: "max_internal_cas",
+ v1Field: "maxInternalCas"
+ }
+];
+
+// PAM: the product entitlement, its add-ons, and the account cap.
+const pamMappings: TFeatureMapping[] = [
+ {
+ v2Key: "pam",
+ v1Field: "pam"
+ },
+ {
+ v2Key: "enterprise_pam_account",
+ v1Field: "enterprisePamAccount"
+ },
+ {
+ v2Key: "pam_slack_notifications",
+ v1Field: "pamSlackNotifications"
+ },
+ {
+ // Max PAM accounts allowed. null (v1 default) means uncapped.
+ v2Key: "max_pam_accounts",
+ v1Field: "maxPamAccounts"
+ }
+];
+
+export const FEATURE_MAPPINGS: TFeatureMapping[] = [
+ ...platformMappings,
+ ...secretManagerMappings,
+ ...certManagerMappings,
+ ...pamMappings
+];
+
+// v1 TFeatureSet keys intentionally not compared: live usage counters, plan metadata, and v1 fields
+// with no License Server v2 feature (v2 never returns them, so a mapping would be permanently v2_missing).
+export const EXCLUDED_FIELDS: ReadonlySet<string> = new Set([
+ "_id",
+ "slug",
+ "tier",
+ "status",
+ "trial_end",
+ "has_used_trial",
+ "workspacesUsed",
+ "membersUsed",
+ "identitiesUsed",
+ "environmentsUsed",
+ "workspaceLimit",
+ "memberLimit",
+ "pkiLegacyTemplates"
+]);
diff --git a/backend/src/services/license-client/license-client.test.ts b/backend/src/services/license-client/license-client.test.ts
index 3583091a47..23a66c7242 100644
--- a/backend/src/services/license-client/license-client.test.ts
+++ b/backend/src/services/license-client/license-client.test.ts
@@ -135,14 +135,13 @@ describe("featureReaderFactory", () => {
});
});
-// How a consumer uses the client. With the kill switch off, every feature resolves to its fallback.
+// How a consumer uses the client. With no credential configured, every feature resolves to its fallback.
describe("licenseClientFactory (usage example)", () => {
const licenseClient = licenseClientFactory({
envConfig: {
- LICENSE_SERVER_V2_MODE: "off",
- LICENSE_SERVER_V2_URL: undefined,
LICENSE_SERVER_V2_SERVICE_KEY: undefined,
LICENSE_SERVER_URL: "https://license.example.com",
+ LICENSE_KEY: undefined,
INTERNAL_REGION: undefined
},
keyStore: createFakeKeyStore()
diff --git a/backend/src/services/license-client/license-client.ts b/backend/src/services/license-client/license-client.ts
index 6a2b798221..06fb6c7743 100644
--- a/backend/src/services/license-client/license-client.ts
+++ b/backend/src/services/license-client/license-client.ts
@@ -20,12 +20,7 @@ import { createSelfHostedTokenProvider } from "./license-token-provider";
type TLicenseClientFactoryDep = {
envConfig: Pick<
TEnvConfig,
- | "LICENSE_SERVER_V2_MODE"
- | "LICENSE_SERVER_V2_URL"
- | "LICENSE_SERVER_V2_SERVICE_KEY"
- | "LICENSE_SERVER_URL"
- | "LICENSE_KEY"
- | "INTERNAL_REGION"
+ "LICENSE_SERVER_V2_SERVICE_KEY" | "LICENSE_SERVER_URL" | "LICENSE_KEY" | "INTERNAL_REGION"
>;
keyStore: Pick<TKeyStoreFactory, "getItem" | "setItemWithExpiry" | "deleteItem">;
// Offline (air-gapped) licenses must never contact the license server; the SDK stays dormant for them.
@@ -34,8 +29,8 @@ type TLicenseClientFactoryDep = {
export type TLicenseClientFactory = ReturnType<typeof licenseClientFactory>;
-// Returns null (SDK dormant -> getFeature serves fallbacks) unless the kill switch is on and either a
-// self-hosted license key or the cloud service key (plus server URL) is configured.
+// Returns null (SDK dormant -> getFeature serves fallbacks) unless either a self-hosted license key or
+// the cloud service key (plus the license server URL) is configured.
const buildBackend = (
envConfig: TLicenseClientFactoryDep["envConfig"],
isOffline: boolean
@@ -58,13 +53,10 @@ const buildBackend = (
return licenseServerSelfHostedBackend(envConfig.LICENSE_SERVER_URL, tokenProvider, envConfig.INTERNAL_REGION);
}
- // Self-hosted sets only LICENSE_SERVER_URL (that one host now serves both the token endpoint and the
- // v2 API after the DNS switch); cloud sets LICENSE_SERVER_V2_URL. Accept either as the v2 API base.
- const serverUrl = envConfig.LICENSE_SERVER_V2_URL || envConfig.LICENSE_SERVER_URL;
+ // One host serves both the self-hosted token endpoint and the entitlement API.
+ const serverUrl = envConfig.LICENSE_SERVER_URL;
if (!serverUrl) {
- logger.warn(
- "license-client: enabled but neither LICENSE_SERVER_V2_URL nor LICENSE_SERVER_URL is set; serving feature fallbacks"
- );
+ logger.warn("license-client: LICENSE_SERVER_URL is not set; serving feature fallbacks");
return null;
}
@@ -73,11 +65,11 @@ const buildBackend = (
try {
parsedUrl = new URL(serverUrl);
} catch {
- logger.warn("license-client: LICENSE_SERVER_V2_URL is not a valid URL; serving feature fallbacks");
+ logger.warn("license-client: LICENSE_SERVER_URL is not a valid URL; serving feature fallbacks");
return null;
}
if (parsedUrl.protocol !== "http:" && parsedUrl.protocol !== "https:") {
- logger.warn("license-client: LICENSE_SERVER_V2_URL must use http(s); serving feature fallbacks");
+ logger.warn("license-client: LICENSE_SERVER_URL must use http(s); serving feature fallbacks");
return null;
}
@@ -229,6 +221,9 @@ export const licenseClientFactory = ({ envConfig, keyStore, isOffline = false }:
return {
...featureReaderFactory({ getEntitlements }),
+ // False when no license server is reachable (unlicensed self-hosted, or an offline license), so
+ // callers can skip work that would only end in a dormant no-op.
+ isEnabled: () => backend !== null,
getEntitlements,
invalidateEntitlements,
markEntitlementsStale,
diff --git a/backend/src/services/license-client/usage/usage-metering-service.ts b/backend/src/services/license-client/usage/usage-metering-service.ts
index b61fa01a1b..06a800b604 100644
--- a/backend/src/services/license-client/usage/usage-metering-service.ts
+++ b/backend/src/services/license-client/usage/usage-metering-service.ts
@@ -1,10 +1,10 @@
import { KeyStorePrefixes, KeyStoreTtls, TKeyStoreFactory } from "@app/keystore/keystore";
-import { TEnvConfig } from "@app/lib/config/env";
import { applyJitter } from "@app/lib/dates";
import { logger } from "@app/lib/logger";
import { QueueJobs, QueueName, TQueueServiceFactory } from "@app/queue";
import { TProjectDALFactory } from "@app/services/project/project-dal";
+import { TLicenseClientFactory } from "../license-client";
import { METERED_DIMENSION_KEYS } from "./usage-counters";
export type TUsageMeteringServiceFactory = ReturnType<typeof usageMeteringServiceFactory>;
@@ -13,7 +13,7 @@ type TUsageMeteringServiceFactoryDep = {
queueService: Pick<TQueueServiceFactory, "queue">;
projectDAL: Pick<TProjectDALFactory, "findById">;
keyStore: Pick<TKeyStoreFactory, "setItemWithExpiryNX">;
- envConfig: Pick<TEnvConfig, "LICENSE_SERVER_V2_MODE">;
+ licenseClient: Pick<TLicenseClientFactory, "isEnabled">;
};
const DEBOUNCE_MS = 5000;
@@ -22,7 +22,7 @@ export const usageMeteringServiceFactory = ({
queueService,
projectDAL,
keyStore,
- envConfig
+ licenseClient
}: TUsageMeteringServiceFactoryDep) => {
const enqueue = async (orgId: string, dimensionKey: string) => {
await queueService.queue(
@@ -43,9 +43,9 @@ export const usageMeteringServiceFactory = ({
};
// Fire-and-forget signal from a metered create/delete on an org-scoped meter. Never awaited and
- // never throws into the request path; inert until the v2 license server is enabled.
+ // never throws into the request path; inert while no license server is configured.
const emit = (orgId: string, dimensionKey: string) => {
- if (envConfig.LICENSE_SERVER_V2_MODE === "off") {
+ if (!licenseClient.isEnabled()) {
return;
}
@@ -60,7 +60,7 @@ export const usageMeteringServiceFactory = ({
// Project-scoped meters sum across an org's projects, so the event is keyed by org. The org is
// resolved in the background to keep the request path free of an extra read.
const emitForProject = (projectId: string, dimensionKey: string) => {
- if (envConfig.LICENSE_SERVER_V2_MODE === "off") {
+ if (!licenseClient.isEnabled()) {
return;
}
@@ -84,7 +84,7 @@ export const usageMeteringServiceFactory = ({
// marker throttles it to once per org per interval (and coalesces concurrent callers). The emits reuse
// the normal pipeline, so the slug gate and lastReported dedup still apply downstream.
const reconcile = (orgId: string) => {
- if (envConfig.LICENSE_SERVER_V2_MODE === "off") {
+ if (!licenseClient.isEnabled()) {
return;
}
diff --git a/backend/src/services/license-client/usage/usage-metering.test.ts b/backend/src/services/license-client/usage/usage-metering.test.ts
index 8b6714fd6a..ca8537284b 100644
--- a/backend/src/services/license-client/usage/usage-metering.test.ts
+++ b/backend/src/services/license-client/usage/usage-metering.test.ts
@@ -57,13 +57,13 @@ const createFakeKeyStore = () => {
};
describe("usageMeteringService.emit (org-scoped)", () => {
- test("does nothing when the v2 license server is disabled", async () => {
+ test("does nothing when no license server is configured", async () => {
const queue = makeQueueMock();
const svc = usageMeteringServiceFactory({
queueService: { queue },
keyStore: createFakeKeyStore(),
projectDAL: { findById: vi.fn() },
- envConfig: { LICENSE_SERVER_V2_MODE: "off" }
+ licenseClient: { isEnabled: () => false }
});
svc.emit(ORG_ID, IdentitiesMeter.key);
@@ -78,7 +78,7 @@ describe("usageMeteringService.emit (org-scoped)", () => {
queueService: { queue },
keyStore: createFakeKeyStore(),
projectDAL: { findById: vi.fn() },
- envConfig: { LICENSE_SERVER_V2_MODE: "read-compare" }
+ licenseClient: { isEnabled: () => true }
});
svc.emit(ORG_ID, IdentitiesMeter.key);
@@ -101,7 +101,7 @@ describe("usageMeteringService.emit (org-scoped)", () => {
queueService: { queue },
keyStore: createFakeKeyStore(),
projectDAL: { findById: vi.fn() },
- envConfig: { LICENSE_SERVER_V2_MODE: "read-compare" }
+ licenseClient: { isEnabled: () => true }
});
expect(() => svc.emit(ORG_ID, IdentitiesMeter.key)).not.toThrow();
@@ -117,7 +117,7 @@ describe("usageMeteringService.emitForProject (project-scoped)", () => {
queueService: { queue },
keyStore: createFakeKeyStore(),
projectDAL: { findById } as never,
- envConfig: { LICENSE_SERVER_V2_MODE: "read-compare" }
+ licenseClient: { isEnabled: () => true }
});
svc.emitForProject(PROJECT_ID, PamIdentities.key);
@@ -136,7 +136,7 @@ describe("usageMeteringService.emitForProject (project-scoped)", () => {
queueService: { queue },
keyStore: createFakeKeyStore(),
projectDAL: { findById: vi.fn(async () => undefined) } as never,
- envConfig: { LICENSE_SERVER_V2_MODE: "read-compare" }
+ licenseClient: { isEnabled: () => true }
});
svc.emitForProject(PROJECT_ID, PamIdentities.key);
@@ -152,7 +152,7 @@ describe("usageMeteringService.emitForProject (project-scoped)", () => {
queueService: { queue },
keyStore: createFakeKeyStore(),
projectDAL: { findById },
- envConfig: { LICENSE_SERVER_V2_MODE: "off" }
+ licenseClient: { isEnabled: () => false }
});
svc.emitForProject(PROJECT_ID, PamIdentities.key);
@@ -164,13 +164,13 @@ describe("usageMeteringService.emitForProject (project-scoped)", () => {
});
describe("usageMeteringService.reconcile (demand-driven)", () => {
- test("does nothing when the v2 license server is disabled", async () => {
+ test("does nothing when no license server is configured", async () => {
const queue = makeQueueMock();
const svc = usageMeteringServiceFactory({
queueService: { queue },
keyStore: createFakeKeyStore(),
projectDAL: { findById: vi.fn() },
- envConfig: { LICENSE_SERVER_V2_MODE: "off" }
+ licenseClient: { isEnabled: () => false }
});
svc.reconcile(ORG_ID);
@@ -186,7 +186,7 @@ describe("usageMeteringService.reconcile (demand-driven)", () => {
queueService: { queue },
keyStore,
projectDAL: { findById: vi.fn() },
- envConfig: { LICENSE_SERVER_V2_MODE: "on" }
+ licenseClient: { isEnabled: () => true }
});
svc.reconcile(ORG_ID);
@@ -202,28 +202,30 @@ describe("usageMeteringService.reconcile (demand-driven)", () => {
});
describe("buildUsageReporter", () => {
- test("is null when disabled", () => {
- expect(
- buildUsageReporter({ LICENSE_SERVER_V2_MODE: "off", LICENSE_SERVER_URL: "https://license.example.com" })
- ).toBeNull();
+ test("is null without a license server URL", () => {
+ expect(buildUsageReporter({ LICENSE_SERVER_URL: "" })).toBeNull();
});
- test("is null when enabled but unconfigured", () => {
- expect(
- buildUsageReporter({ LICENSE_SERVER_V2_MODE: "read-compare", LICENSE_SERVER_URL: "https://license.example.com" })
- ).toBeNull();
+ test("is null when no credential is configured", () => {
+ expect(buildUsageReporter({ LICENSE_SERVER_URL: "https://license.example.com" })).toBeNull();
});
- test("is a reporter when enabled and configured", () => {
+ test("is a reporter with the cloud service key", () => {
const reporter = buildUsageReporter({
- LICENSE_SERVER_V2_MODE: "read-compare",
- LICENSE_SERVER_V2_URL: "https://license.example.com",
LICENSE_SERVER_V2_SERVICE_KEY: "svc-key",
LICENSE_SERVER_URL: "https://license.example.com"
});
expect(reporter).not.toBeNull();
expect(typeof reporter?.reportSnapshots).toBe("function");
});
+
+ test("is a reporter with a self-hosted license key", () => {
+ const reporter = buildUsageReporter({
+ LICENSE_KEY: "infisical_lk_test",
+ LICENSE_SERVER_URL: "https://license.example.com"
+ });
+ expect(reporter).not.toBeNull();
+ });
});
describe("buildMeteredFeatures", () => {
diff --git a/backend/src/services/license-client/usage/usage-reporter.ts b/backend/src/services/license-client/usage/usage-reporter.ts
index 7258f381e5..cf88940d75 100644
--- a/backend/src/services/license-client/usage/usage-reporter.ts
+++ b/backend/src/services/license-client/usage/usage-reporter.ts
@@ -60,32 +60,17 @@ export const usageReporterFactory = (serverUrl: string, getBearerToken: () => Pr
}
});
-// Returns null when the v2 license server is disabled or unconfigured, which keeps usage reporting
-// inert. A self-hosted v2 license exchanges its key for a short-lived JWT at the token endpoint (on
-// LICENSE_SERVER_URL) and reports with that bearer; cloud mints a short-lived RS256 service JWT signed
-// with the service key (the same scheme the rest of the v2 client uses). The raw key/signing key is
-// never sent as the bearer.
+// Returns null when the license server is unconfigured, which keeps usage reporting inert. A
+// self-hosted license exchanges its key for a short-lived JWT at the token endpoint and reports with
+// that bearer; cloud mints a short-lived RS256 service JWT signed with the service key (the same scheme
+// the rest of the license client uses). The raw key/signing key is never sent as the bearer.
export const buildUsageReporter = (
- envConfig: Pick<
- TEnvConfig,
- | "LICENSE_SERVER_V2_MODE"
- | "LICENSE_SERVER_V2_URL"
- | "LICENSE_SERVER_V2_SERVICE_KEY"
- | "LICENSE_SERVER_URL"
- | "LICENSE_KEY"
- >
+ envConfig: Pick<TEnvConfig, "LICENSE_SERVER_V2_SERVICE_KEY" | "LICENSE_SERVER_URL" | "LICENSE_KEY">
): TUsageReporter | null => {
- if (envConfig.LICENSE_SERVER_V2_MODE === "off") {
- return null;
- }
-
- // Self-hosted sets only LICENSE_SERVER_URL (that one host now serves both the token endpoint and the
- // v2 API after the DNS switch); cloud sets LICENSE_SERVER_V2_URL. Accept either as the v2 API base.
- const serverUrl = envConfig.LICENSE_SERVER_V2_URL || envConfig.LICENSE_SERVER_URL;
+ // One host serves both the self-hosted token endpoint and the usage API.
+ const serverUrl = envConfig.LICENSE_SERVER_URL;
if (!serverUrl) {
- logger.warn(
- "usage-reporter: enabled but neither LICENSE_SERVER_V2_URL nor LICENSE_SERVER_URL is set; usage reporting disabled"
- );
+ logger.warn("usage-reporter: LICENSE_SERVER_URL is not set; usage reporting disabled");
return null;
}
@@ -106,11 +91,7 @@ export const buildUsageReporter = (
// and use that. Cloud sets no LICENSE_KEY, so it falls through to the service-JWT path below.
const licenseKey = envConfig.LICENSE_KEY;
if (licenseKey) {
- if (!envConfig.LICENSE_SERVER_URL) {
- logger.warn("usage-reporter: self-hosted key set but LICENSE_SERVER_URL is missing; usage reporting disabled");
- return null;
- }
- const tokenProvider = createSelfHostedTokenProvider(licenseKey, { serverUrl: envConfig.LICENSE_SERVER_URL });
+ const tokenProvider = createSelfHostedTokenProvider(licenseKey, { serverUrl });
return usageReporterFactory(serverUrl, () => tokenProvider.getToken());
}
diff --git a/backend/src/services/org/org-service.ts b/backend/src/services/org/org-service.ts
index c778690760..90fbabb200 100644
--- a/backend/src/services/org/org-service.ts
+++ b/backend/src/services/org/org-service.ts
@@ -122,7 +122,7 @@ type TOrgServiceFactoryDep = {
permissionService: TPermissionServiceFactory;
licenseService: Pick<
TLicenseServiceFactory,
- "getPlan" | "updateSubscriptionOrgMemberCount" | "generateOrgCustomerId" | "removeOrgCustomer"
+ "getPlan" | "updateSubscriptionOrgMemberCount" | "cancelOrgSubscription"
>;
projectBotService: Pick<TProjectBotServiceFactory, "getBotKey">;
loginService: Pick<TAuthLoginFactory, "generateUserTokens">;
@@ -672,23 +672,16 @@ export const orgServiceFactory = ({
const createOrganization = async (
{
userId,
- userEmail,
orgName
}: {
userId?: string;
orgName: string;
- userEmail?: string | null;
},
trx?: Knex
) => {
- const customerId = await licenseService.generateOrgCustomerId(orgName, userEmail);
-
const createOrg = async (tx: Knex) => {
// akhilmhdh: for now this is auto created. in future we can input from user and for previous users just modifiy
- const org = await orgDAL.create(
- { name: orgName, customerId, slug: slugify(`${orgName}-${alphaNumericNanoId(4)}`) },
- tx
- );
+ const org = await orgDAL.create({ name: orgName, slug: slugify(`${orgName}-${alphaNumericNanoId(4)}`) }, tx);
if (userId) {
const membership = await orgDAL.createMembership(
{
@@ -804,10 +797,6 @@ export const orgServiceFactory = ({
const deletedOrg = await orgDAL.deleteById(orgId, tx);
- if (deletedOrg.customerId) {
- await licenseService.removeOrgCustomer(deletedOrg.customerId);
- }
-
// Generate new tokens without the organization ID present
const user = await userDAL.findById(userId, tx);
const { access: accessToken, refresh: refreshToken } = await loginService.generateUserTokens(
@@ -831,6 +820,10 @@ export const orgServiceFactory = ({
};
});
+ // After commit: the org is gone, so stop it billing. Never throws, so a License Server outage can't
+ // fail a deletion that already succeeded, and it stays out of the transaction.
+ await licenseService.cancelOrgSubscription(orgId);
+
return response;
};
/*
diff --git a/backend/src/services/super-admin/super-admin-service.ts b/backend/src/services/super-admin/super-admin-service.ts
index 89073c49cf..20023a4ddc 100644
--- a/backend/src/services/super-admin/super-admin-service.ts
+++ b/backend/src/services/super-admin/super-admin-service.ts
@@ -555,7 +555,6 @@ export const superAdminServiceFactory = ({
const organization = await orgService.createOrganization({
userId: userInfo.user.id,
- userEmail: userInfo.user.email,
orgName: initialOrganizationName
});
@@ -620,7 +619,6 @@ export const superAdminServiceFactory = ({
const organization = await orgService.createOrganization({
userId: userInfo.user.id,
- userEmail: userInfo.user.email,
orgName: initialOrganizationName
});
@@ -886,13 +884,7 @@ export const superAdminServiceFactory = ({
}
const { organization, users: usersToEmail } = await orgDAL.transaction(async (tx) => {
- const org = await orgService.createOrganization(
- {
- orgName: name,
- userEmail: serverAdmin?.email ?? serverAdmin?.username // identities can be server admins so we can't require this
- },
- tx
- );
+ const org = await orgService.createOrganization({ orgName: name }, tx);
const users: Pick<TUsers, "id" | "firstName" | "lastName" | "email" | "username" | "isAccepted">[] = [];
diff --git a/frontend/src/hooks/api/admin/types.ts b/frontend/src/hooks/api/admin/types.ts
index 311675e1f7..70e249aedd 100644
--- a/frontend/src/hooks/api/admin/types.ts
+++ b/frontend/src/hooks/api/admin/types.ts
@@ -85,7 +85,6 @@ export type TServerConfig = {
invalidatingCache: boolean;
envOverrides?: Record<string, string>;
isPublicSecretSharingDisabled?: boolean;
- licenseServerV2Enabled?: boolean;
isCrossProjectSecretSharingEnabled?: boolean;
// populated on self-hosted instances when a newer release than the running version exists
latestAvailableVersion?: string | null;
diff --git a/frontend/src/hooks/api/organization/index.ts b/frontend/src/hooks/api/organization/index.ts
index 80ae09881d..dec619bf51 100644
--- a/frontend/src/hooks/api/organization/index.ts
+++ b/frontend/src/hooks/api/organization/index.ts
@@ -3,31 +3,16 @@ export {
fetchOrganizations,
fetchOrganizationsWithSubOrgs,
organizationKeys,
- useAddOrgPmtMethod,
- useAddOrgTaxId,
- useCreateCustomerPortalSession,
useCreateOrg,
useDeleteOrgById,
- useDeleteOrgPmtMethod,
- useDeleteOrgTaxId,
useGetIdentityMembershipOrgs,
useGetOrganizationGroups,
useGetOrganizations,
useGetOrganizationsWithSubOrgs,
- useGetOrgBillingDetails,
useGetOrgIntegrationAuths,
- useGetOrgInvoices,
- useGetOrgLicenses,
- useGetOrgPlanBillingInfo,
- useGetOrgPlansTable,
- useGetOrgPlanTable,
- useGetOrgPmtMethods,
useGetOrgProductStats,
- useGetOrgTaxIds,
- useGetOrgTrialUrl,
useSearchOrganizationGroups,
useUpdateOrg,
- useUpdateOrgBillingDetails,
useUpgradePrivilegeSystem
} from "./queries";
export type { TOrgProductStats } from "./types";
diff --git a/frontend/src/hooks/api/organization/queries.tsx b/frontend/src/hooks/api/organization/queries.tsx
index 5cdda578fe..7666c910c0 100644
--- a/frontend/src/hooks/api/organization/queries.tsx
+++ b/frontend/src/hooks/api/organization/queries.tsx
@@ -8,16 +8,8 @@ import { getAuthToken } from "../reactQuery";
import { TOrgRole } from "../roles/types";
import { IntegrationAuth } from "../types";
import {
- BillingDetails,
- Invoice,
- License,
Organization,
OrgIdentityOrderBy,
- OrgPlanTable,
- PlanBillingInfo,
- PmtMethod,
- ProductsTable,
- TaxID,
TListOrgIdentitiesDTO,
TOrgIdentitiesList,
TOrgProductStats,
@@ -32,15 +24,6 @@ export type TOrgWithSubOrgs = Organization & {
export const organizationKeys = {
getUserOrganizations: ["organization"] as const,
getUserOrganizationsWithSubOrgs: ["organization", "with-sub-orgs"] as const,
- getOrgPlanBillingInfo: (orgId: string) => [{ orgId }, "organization-plan-billing"] as const,
- getOrgPlanTable: (orgId: string) => [{ orgId }, "organization-plan-table"] as const,
- getOrgPlansTable: (orgId: string, billingCycle: "monthly" | "yearly") =>
- [{ orgId, billingCycle }, "organization-plans-table"] as const,
- getOrgBillingDetails: (orgId: string) => [{ orgId }, "organization-billing-details"] as const,
- getOrgPmtMethods: (orgId: string) => [{ orgId }, "organization-pmt-methods"] as const,
- getOrgTaxIds: (orgId: string) => [{ orgId }, "organization-tax-ids"] as const,
- getOrgInvoices: (orgId: string) => [{ orgId }, "organization-invoices"] as const,
- getOrgLicenses: (orgId: string) => [{ orgId }, "organization-licenses"] as const,
getOrgIdentityMemberships: (orgId: string) =>
[{ orgId }, "organization-identity-memberships"] as const,
// allows invalidation using above key without knowing params
@@ -233,289 +216,6 @@ export const useUpgradePrivilegeSystem = () => {
});
};
-export const useGetOrgTrialUrl = () => {
- return useMutation({
- mutationFn: async ({ orgId, success_url }: { orgId: string; success_url: string }) => {
- const {
- data: { url }
- } = await apiRequest.post(`/api/v1/organizations/${orgId}/session/trial`, {
- success_url
- });
-
- return url;
- }
- });
-};
-
-export const useGetOrgPlanBillingInfo = (organizationId: string) => {
- return useQuery({
- queryKey: organizationKeys.getOrgPlanBillingInfo(organizationId),
- queryFn: async () => {
- const { data } = await apiRequest.get<PlanBillingInfo>(
- `/api/v1/organizations/${organizationId}/plan/billing`
- );
-
- return data;
- },
- enabled: true
- });
-};
-
-export const useGetOrgPlanTable = (organizationId: string) => {
- return useQuery({
- queryKey: organizationKeys.getOrgPlanTable(organizationId),
- queryFn: async () => {
- const { data } = await apiRequest.get<OrgPlanTable>(
- `/api/v1/organizations/${organizationId}/plan/table`
- );
-
- return data;
- },
- enabled: true
- });
-};
-
-export const useGetOrgPlansTable = ({
- organizationId,
- billingCycle
-}: {
- organizationId: string;
- billingCycle: "monthly" | "yearly";
-}) => {
- return useQuery({
- queryKey: organizationKeys.getOrgPlansTable(organizationId, billingCycle),
- queryFn: async () => {
- const { data } = await apiRequest.get<ProductsTable>(
- `/api/v1/organizations/${organizationId}/plans/table?billingCycle=${billingCycle}`
- );
-
- return data;
- },
- enabled: true
- });
-};
-
-export const useGetOrgBillingDetails = (organizationId: string) => {
- return useQuery({
- queryKey: organizationKeys.getOrgBillingDetails(organizationId),
- queryFn: async () => {
- const { data } = await apiRequest.get<BillingDetails>(
- `/api/v1/organizations/${organizationId}/billing-details`
- );
-
- return data;
- },
- enabled: true
- });
-};
-
-export const useUpdateOrgBillingDetails = () => {
- const queryClient = useQueryClient();
- return useMutation({
- mutationFn: async ({
- organizationId,
- name,
- email
- }: {
- organizationId: string;
- name?: string;
- email?: string;
- }) => {
- const { data } = await apiRequest.patch(
- `/api/v1/organizations/${organizationId}/billing-details`,
- {
- name,
- email
- }
- );
-
- return data;
- },
- onSuccess(_, dto) {
- queryClient.invalidateQueries({
- queryKey: organizationKeys.getOrgBillingDetails(dto.organizationId)
- });
- }
- });
-};
-
-export const useGetOrgPmtMethods = (organizationId: string) => {
- return useQuery({
- queryKey: organizationKeys.getOrgPmtMethods(organizationId),
- queryFn: async () => {
- const { data } = await apiRequest.get<PmtMethod[]>(
- `/api/v1/organizations/${organizationId}/billing-details/payment-methods`
- );
-
- return data;
- },
- enabled: true
- });
-};
-
-export const useAddOrgPmtMethod = () => {
- const queryClient = useQueryClient();
-
- return useMutation({
- mutationFn: async ({
- organizationId,
- success_url,
- cancel_url
- }: {
- organizationId: string;
- success_url: string;
- cancel_url: string;
- }) => {
- const {
- data: { url }
- } = await apiRequest.post(
- `/api/v1/organizations/${organizationId}/billing-details/payment-methods`,
- {
- success_url,
- cancel_url
- }
- );
-
- return url;
- },
- onSuccess(_, dto) {
- queryClient.invalidateQueries({
- queryKey: organizationKeys.getOrgPmtMethods(dto.organizationId)
- });
- }
- });
-};
-
-export const useDeleteOrgPmtMethod = () => {
- const queryClient = useQueryClient();
-
- return useMutation({
- mutationFn: async ({
- organizationId,
- pmtMethodId
- }: {
- organizationId: string;
- pmtMethodId: string;
- }) => {
- const { data } = await apiRequest.delete(
- `/api/v1/organizations/${organizationId}/billing-details/payment-methods/${pmtMethodId}`
- );
-
- return data;
- },
- onSuccess(_, dto) {
- queryClient.invalidateQueries({
- queryKey: organizationKeys.getOrgPmtMethods(dto.organizationId)
- });
- }
- });
-};
-
-export const useGetOrgTaxIds = (organizationId: string) => {
- return useQuery({
- queryKey: organizationKeys.getOrgTaxIds(organizationId),
- queryFn: async () => {
- const { data } = await apiRequest.get<TaxID[]>(
- `/api/v1/organizations/${organizationId}/billing-details/tax-ids`
- );
-
- return data;
- },
- enabled: true
- });
-};
-
-export const useAddOrgTaxId = () => {
- const queryClient = useQueryClient();
-
- return useMutation({
- mutationFn: async ({
- organizationId,
- type,
- value
- }: {
- organizationId: string;
- type: string;
- value: string;
- }) => {
- const { data } = await apiRequest.post(
- `/api/v1/organizations/${organizationId}/billing-details/tax-ids`,
- {
- type,
- value
- }
- );
-
- return data;
- },
- onSuccess(_, dto) {
- queryClient.invalidateQueries({
- queryKey: organizationKeys.getOrgTaxIds(dto.organizationId)
- });
- }
- });
-};
-
-export const useDeleteOrgTaxId = () => {
- const queryClient = useQueryClient();
-
- return useMutation({
- mutationFn: async ({ organizationId, taxId }: { organizationId: string; taxId: string }) => {
- const { data } = await apiRequest.delete(
- `/api/v1/organizations/${organizationId}/billing-details/tax-ids/${taxId}`
- );
-
- return data;
- },
- onSuccess(_, dto) {
- queryClient.invalidateQueries({
- queryKey: organizationKeys.getOrgTaxIds(dto.organizationId)
- });
- }
- });
-};
-
-export const useGetOrgInvoices = (organizationId: string) => {
- return useQuery({
- queryKey: organizationKeys.getOrgInvoices(organizationId),
- queryFn: async () => {
- const { data } = await apiRequest.get<Invoice[]>(
- `/api/v1/organizations/${organizationId}/invoices`
- );
-
- return data;
- },
- enabled: true
- });
-};
-
-export const useCreateCustomerPortalSession = () => {
- return useMutation({
- mutationFn: async (organizationId: string) => {
- const { data } = await apiRequest.post(
- `/api/v1/organizations/${organizationId}/customer-portal-session`
- );
- return data;
- }
- });
-};
-
-export const useGetOrgLicenses = (organizationId: string) => {
- return useQuery({
- queryKey: organizationKeys.getOrgLicenses(organizationId),
- queryFn: async () => {
- if (organizationId === "") return undefined;
-
- const { data } = await apiRequest.get<License[]>(
- `/api/v1/organizations/${organizationId}/licenses`
- );
-
- return data;
- },
- enabled: true
- });
-};
-
export const useGetIdentityMembershipOrgs = (
{
organizationId,
@@ -576,35 +276,8 @@ export const useDeleteOrgById = () => {
);
return organization;
},
- onSuccess(_, dto) {
+ onSuccess() {
queryClient.invalidateQueries({ queryKey: organizationKeys.getUserOrganizations });
- queryClient.invalidateQueries({
- queryKey: organizationKeys.getOrgPlanBillingInfo(dto.organizationId)
- });
- queryClient.invalidateQueries({
- queryKey: organizationKeys.getOrgPlanTable(dto.organizationId)
- });
- queryClient.invalidateQueries({
- queryKey: organizationKeys.getOrgPlansTable(dto.organizationId, "monthly")
- }); // You might need to invalidate for 'yearly' as well.
- queryClient.invalidateQueries({
- queryKey: organizationKeys.getOrgPlansTable(dto.organizationId, "yearly")
- });
- queryClient.invalidateQueries({
- queryKey: organizationKeys.getOrgBillingDetails(dto.organizationId)
- });
- queryClient.invalidateQueries({
- queryKey: organizationKeys.getOrgPmtMethods(dto.organizationId)
- });
- queryClient.invalidateQueries({
- queryKey: organizationKeys.getOrgTaxIds(dto.organizationId)
- });
- queryClient.invalidateQueries({
- queryKey: organizationKeys.getOrgInvoices(dto.organizationId)
- });
- queryClient.invalidateQueries({
- queryKey: organizationKeys.getOrgLicenses(dto.organizationId)
- });
}
});
};
diff --git a/frontend/src/hooks/api/organization/types.ts b/frontend/src/hooks/api/organization/types.ts
index 70affa2548..af9daf2110 100644
--- a/frontend/src/hooks/api/organization/types.ts
+++ b/frontend/src/hooks/api/organization/types.ts
@@ -67,95 +67,6 @@ export type UpdateOrgDTO = {
secretShareBrandConfig?: TSecretShareBrandConfig;
};
-export type BillingDetails = {
- name: string;
- email: string;
-};
-
-export type PlanBillingInfo = {
- amount: number;
- currentPeriodEnd: number;
- currentPeriodStart: number;
- interval: "month" | "year";
- intervalCount: number;
- quantity: number;
- users: number;
- identities: number;
-};
-
-export type Invoice = {
- id: string;
- created: number;
- invoice_pdf: string;
- number: string;
- paid: boolean;
- total: number;
-};
-
-export type PmtMethod = {
- _id: string;
- brand: string;
- exp_month: number;
- exp_year: number;
- funding: string;
- last4: string;
-};
-
-export type TaxID = {
- id: string;
- country: string;
- type: string;
- value: string;
-};
-
-export type License = {
- id: string;
- customerId: string;
- prefix: string;
- licenseKey: string;
- isActivated: boolean;
- expiresAt: string;
- createdAt: string;
- updatedAt: string;
-};
-
-export type OrgPlanTableHead = {
- name: string;
-};
-
-export type OrgPlanTableRow = {
- name: string;
- allowed: number | boolean | null;
- used: string;
-};
-
-export type OrgPlanTable = {
- head: OrgPlanTableHead[];
- rows: OrgPlanTableRow[];
-};
-
-export type ProductsTableHead = {
- name: string;
- price: number | null;
- priceLine: string;
- productId: string;
- slug: string;
- tier: number;
-};
-
-export type ProductsTableRow = {
- name: string;
- starter: number | boolean | null;
- team: number | boolean | null;
- pro: number | boolean | null;
- enterprise: number | boolean | null;
-};
-
-export type ProductsTable = {
- head: ProductsTableHead[];
- rows: ProductsTableRow[];
-};
-
export type TListOrgIdentitiesDTO = {
organizationId: string;
offset?: number;
diff --git a/frontend/src/layouts/OrganizationLayout/components/NavBar/Navbar.tsx b/frontend/src/layouts/OrganizationLayout/components/NavBar/Navbar.tsx
index 6362a8017f..4c96696af8 100644
--- a/frontend/src/layouts/OrganizationLayout/components/NavBar/Navbar.tsx
+++ b/frontend/src/layouts/OrganizationLayout/components/NavBar/Navbar.tsx
@@ -12,7 +12,6 @@ import {
Clipboard,
ExternalLink,
Github,
- Infinity,
Info,
LogOut,
Mail,
@@ -78,14 +77,12 @@ import {
projectKeys,
subOrganizationsQuery,
useGetOrganizations,
- useGetOrgTrialUrl,
useLogoutUser
} from "@app/hooks/api";
import { authKeys, selectOrganization } from "@app/hooks/api/auth/queries";
import { MfaMethod } from "@app/hooks/api/auth/types";
import { getAuthToken } from "@app/hooks/api/reactQuery";
import { getSubscriptionPlanLabel } from "@app/hooks/api/subscriptions";
-import { SubscriptionPlanTypes } from "@app/hooks/api/subscriptions/types";
import { Organization } from "@app/hooks/api/types";
import { AuthMethod } from "@app/hooks/api/users/types";
import {
@@ -269,8 +266,6 @@ export const Navbar = () => {
}
};
- const { mutateAsync } = useGetOrgTrialUrl();
-
const logout = useLogoutUser();
const logOutUser = async () => {
try {
@@ -600,35 +595,9 @@ export const Navbar = () => {
</div>
<VersionBadge />
- {subscription &&
- subscription.slug === SubscriptionPlanTypes.Starter &&
- !subscription.has_used_trial ? (
- <Tooltip>
- <TooltipTrigger asChild>
- <Button
- variant="info"
- size="xs"
- className="mt-px mr-2"
- onClick={async () => {
- if (!subscription || !rootOrg) return;
- const url = await mutateAsync({
- orgId: rootOrg.id,
- success_url: window.location.href
- });
- window.location.href = url;
- }}
- >
- <Infinity />
- Free Pro Trial
- </Button>
- </TooltipTrigger>
- <TooltipContent>Start Free Pro Trial</TooltipContent>
- </Tooltip>
- ) : (
- <Badge variant="info" className="mt-[3px] mr-3 hidden md:inline-flex">
- {getSubscriptionPlanLabel(subscription)}
- </Badge>
- )}
+ <Badge variant="info" className="mt-[3px] mr-3 hidden md:inline-flex">
+ {getSubscriptionPlanLabel(subscription)}
+ </Badge>
{!location.pathname.startsWith("/admin") && user.superAdmin && (
<Button variant="outline" size="xs" className="mt-px mr-2" asChild>
<Link to="/admin" onClick={handleNavigateToAdminConsole}>
diff --git a/frontend/src/pages/organization/BillingPage/BillingPage.tsx b/frontend/src/pages/organization/BillingPage/BillingPage.tsx
index d16656f8bc..276afc2269 100644
--- a/frontend/src/pages/organization/BillingPage/BillingPage.tsx
+++ b/frontend/src/pages/organization/BillingPage/BillingPage.tsx
@@ -1,58 +1,16 @@
-import { Helmet } from "react-helmet";
-import { useTranslation } from "react-i18next";
-
-import { OrgPermissionCan } from "@app/components/permissions";
-import { PageHeader } from "@app/components/v2";
-import {
- OrgPermissionBillingActions,
- OrgPermissionSubjects,
- useServerConfig,
- useSubscription
-} from "@app/context";
+import { useSubscription } from "@app/context";
import { BillingV2Page } from "../BillingV2Page";
-import { BillingTabGroup } from "./components";
import { OfflineBillingPage } from "./OfflineBillingPage";
export const BillingPage = () => {
- const { t } = useTranslation();
- const { config } = useServerConfig();
const { subscription } = useSubscription();
- // Offline (air-gapped) licenses can't reach the license server, so neither billing surface can load;
- // short-circuit to the offline page (no API calls) before mounting either.
+ // Offline (air-gapped) licenses can't reach the license server, so the billing surface can't load;
+ // short-circuit to the offline page (no API calls) before mounting it.
if (subscription?.isOffline) {
return <OfflineBillingPage />;
}
- if (config.licenseServerV2Enabled) {
- return <BillingV2Page />;
- }
-
- return (
- <div className="h-full bg-bunker-800">
- <Helmet>
- <title>{t("common.head-title", { title: t("billing.title") })}</title>
- <link rel="icon" href="/infisical.ico" />
- <meta property="og:image" content="/images/message.png" />
- </Helmet>
- <div className="flex h-full w-full justify-center bg-bunker-800 text-white">
- <div className="w-full max-w-8xl">
- <PageHeader
- scope="org"
- title={t("billing.title")}
- description="View your billing plan, next billing cycle."
- />
-
- <OrgPermissionCan
- passThrough={false}
- I={OrgPermissionBillingActions.Read}
- a={OrgPermissionSubjects.Billing}
- >
- <BillingTabGroup />
- </OrgPermissionCan>
- </div>
- </div>
- </div>
- );
+ return <BillingV2Page />;
};
diff --git a/frontend/src/pages/organization/BillingPage/components/BillingCloudTab/BillingCloudTab.tsx b/frontend/src/pages/organization/BillingPage/components/BillingCloudTab/BillingCloudTab.tsx
deleted file mode 100644
index 6085b90c64..0000000000
--- a/frontend/src/pages/organization/BillingPage/components/BillingCloudTab/BillingCloudTab.tsx
+++ /dev/null
@@ -1,11 +0,0 @@
-import { CurrentPlanSection } from "./CurrentPlanSection";
-import { PreviewSection } from "./PreviewSection";
-
-export const BillingCloudTab = () => {
- return (
- <div>
- <PreviewSection />
- <CurrentPlanSection />
- </div>
- );
-};
diff --git a/frontend/src/pages/organization/BillingPage/components/BillingCloudTab/CurrentPlanSection.tsx b/frontend/src/pages/organization/BillingPage/components/BillingCloudTab/CurrentPlanSection.tsx
deleted file mode 100644
index 0602bc58cb..0000000000
--- a/frontend/src/pages/organization/BillingPage/components/BillingCloudTab/CurrentPlanSection.tsx
+++ /dev/null
@@ -1,93 +0,0 @@
-import {
- faCircleCheck,
- faCircleXmark,
- faFileInvoice,
- faInfoCircle
-} from "@fortawesome/free-solid-svg-icons";
-import { FontAwesomeIcon } from "@fortawesome/react-fontawesome";
-
-import {
- EmptyState,
- Table,
- TableContainer,
- TableSkeleton,
- TBody,
- Td,
- Th,
- THead,
- Tooltip,
- Tr
-} from "@app/components/v2";
-import { useOrganization } from "@app/context";
-import { useGetOrgPlanTable } from "@app/hooks/api";
-
-export const CurrentPlanSection = () => {
- const { currentOrg } = useOrganization();
- const { data, isPending } = useGetOrgPlanTable(currentOrg?.id ?? "");
-
- const displayCell = (value: null | number | string | boolean) => {
- if (value === null) return "-";
-
- if (typeof value === "boolean") {
- if (value) return <FontAwesomeIcon icon={faCircleCheck} color="#2ecc71" />;
-
- return <FontAwesomeIcon icon={faCircleXmark} color="#e74c3c" />;
- }
-
- return value;
- };
-
- return (
- <div className="mb-6 rounded-lg border border-mineshaft-600 bg-mineshaft-900 p-4">
- <h2 className="mb-8 flex-1 text-xl font-medium text-white">Current usage</h2>
- <TableContainer className="mt-4">
- <Table>
- <THead>
- <Tr>
- <Th className="w-1/3">Feature</Th>
- <Th className="w-1/3">Allowed</Th>
- <Th className="w-1/3">Used</Th>
- </Tr>
- </THead>
- <TBody>
- {!isPending &&
- data &&
- data?.rows?.length > 0 &&
- data.rows.map(({ name, allowed, used }) => {
- let toolTipText = null;
- if (name === "Organization identity limit") {
- toolTipText =
- "Identity count is calculated by the total number of user identities and machine identities.";
- }
-
- return (
- <Tr key={`current-plan-row-${name}`} className="h-12">
- <Td>
- <div className="flex items-center">
- {name}
- {toolTipText && (
- <Tooltip content={toolTipText}>
- <FontAwesomeIcon icon={faInfoCircle} className="ml-2" size="xs" />
- </Tooltip>
- )}
- </div>
- </Td>
- <Td>{displayCell(allowed)}</Td>
- <Td>{used}</Td>
- </Tr>
- );
- })}
- {isPending && <TableSkeleton columns={5} innerKey="invoices" />}
- {!isPending && data && data?.rows?.length === 0 && (
- <Tr>
- <Td colSpan={3}>
- <EmptyState title="No plan details found" icon={faFileInvoice} />
- </Td>
- </Tr>
- )}
- </TBody>
- </Table>
- </TableContainer>
- </div>
- );
-};
diff --git a/frontend/src/pages/organization/BillingPage/components/BillingCloudTab/ManagePlansModal.tsx b/frontend/src/pages/organization/BillingPage/components/BillingCloudTab/ManagePlansModal.tsx
deleted file mode 100644
index a24e3ca319..0000000000
--- a/frontend/src/pages/organization/BillingPage/components/BillingCloudTab/ManagePlansModal.tsx
+++ /dev/null
@@ -1,62 +0,0 @@
-import { Fragment } from "react";
-import { Tab } from "@headlessui/react";
-
-import { Modal, ModalContent } from "@app/components/v2";
-import { UsePopUpState } from "@app/hooks/usePopUp";
-
-import { ManagePlansTable } from "./ManagePlansTable";
-
-type Props = {
- popUp: UsePopUpState<["managePlan"]>;
- handlePopUpToggle: (popUpName: keyof UsePopUpState<["managePlan"]>, state?: boolean) => void;
-};
-
-export const ManagePlansModal = ({ popUp, handlePopUpToggle }: Props) => {
- return (
- <Modal
- isOpen={popUp?.managePlan?.isOpen}
- onOpenChange={(isOpen) => {
- handlePopUpToggle("managePlan", isOpen);
- }}
- >
- <ModalContent className="max-w-(--breakpoint-lg)" title="Infisical Cloud Plans">
- <Tab.Group>
- <Tab.List className="max-w-(--breakpoint-lg) border-b-2 border-mineshaft-600">
- <Tab as={Fragment}>
- {({ selected }) => (
- <button
- type="button"
- className={`p-4 ${
- selected ? "border-b-2 border-white text-white" : "text-mineshaft-400"
- } w-30 font-medium whitespace-nowrap outline-hidden`}
- >
- Bill monthly
- </button>
- )}
- </Tab>
- <Tab as={Fragment}>
- {({ selected }) => (
- <button
- type="button"
- className={`p-4 ${
- selected ? "border-b-2 border-white text-white" : "text-mineshaft-400"
- } w-30 font-medium outline-hidden`}
- >
- Bill yearly
- </button>
- )}
- </Tab>
- </Tab.List>
- <Tab.Panels className="mt-4">
- <Tab.Panel>
- <ManagePlansTable billingCycle="monthly" />
- </Tab.Panel>
- <Tab.Panel>
- <ManagePlansTable billingCycle="yearly" />
- </Tab.Panel>
- </Tab.Panels>
- </Tab.Group>
- </ModalContent>
- </Modal>
- );
-};
diff --git a/frontend/src/pages/organization/BillingPage/components/BillingCloudTab/ManagePlansTable.tsx b/frontend/src/pages/organization/BillingPage/components/BillingCloudTab/ManagePlansTable.tsx
deleted file mode 100644
index 29b0326c4e..0000000000
--- a/frontend/src/pages/organization/BillingPage/components/BillingCloudTab/ManagePlansTable.tsx
+++ /dev/null
@@ -1,138 +0,0 @@
-import { faCircleCheck, faCircleXmark, faFileInvoice } from "@fortawesome/free-solid-svg-icons";
-import { FontAwesomeIcon } from "@fortawesome/react-fontawesome";
-
-import {
- Button,
- EmptyState,
- Table,
- TableContainer,
- TableSkeleton,
- TBody,
- Td,
- Th,
- THead,
- Tr
-} from "@app/components/v2";
-import { useOrganization, useSubscription } from "@app/context";
-import { useCreateCustomerPortalSession, useGetOrgPlansTable } from "@app/hooks/api";
-
-type Props = {
- billingCycle: "monthly" | "yearly";
-};
-
-export const ManagePlansTable = ({ billingCycle }: Props) => {
- const { currentOrg } = useOrganization();
- const { subscription } = useSubscription();
- const { data: tableData, isPending: isTableDataLoading } = useGetOrgPlansTable({
- organizationId: currentOrg?.id ?? "",
- billingCycle
- });
- const createCustomerPortalSession = useCreateCustomerPortalSession();
-
- const displayCell = (value: null | number | string | boolean) => {
- if (value === null) return "Unlimited";
-
- if (typeof value === "boolean") {
- if (value) return <FontAwesomeIcon icon={faCircleCheck} color="#2ecc71" />;
-
- return <FontAwesomeIcon icon={faCircleXmark} color="#e74c3c" />;
- }
-
- return value;
- };
-
- return (
- <TableContainer>
- <Table>
- <THead>
- {subscription && !isTableDataLoading && tableData && (
- <Tr>
- <Th className="">Feature / Limit</Th>
- {tableData.head.map(({ name, priceLine }) => {
- return (
- <Th
- key={`plans-feature-head-${billingCycle}-${name}`}
- className="flex-1 text-center"
- >
- <p>{name}</p>
- <p>{priceLine}</p>
- </Th>
- );
- })}
- </Tr>
- )}
- </THead>
- <TBody>
- {subscription &&
- !isTableDataLoading &&
- tableData &&
- tableData.rows.map(({ name, starter, pro, enterprise }) => {
- return (
- <Tr className="h-12" key={`plans-feature-row-${billingCycle}-${name}`}>
- <Td>{displayCell(name)}</Td>
- <Td className="text-center">{displayCell(starter)}</Td>
- <Td className="text-center">{displayCell(pro)}</Td>
- <Td className="text-center">{displayCell(enterprise)}</Td>
- </Tr>
- );
- })}
- {isTableDataLoading && <TableSkeleton columns={5} innerKey="cloud-products" />}
- {!isTableDataLoading && tableData?.rows.length === 0 && (
- <Tr>
- <Td colSpan={5}>
- <EmptyState title="No cloud product details found" icon={faFileInvoice} />
- </Td>
- </Tr>
- )}
- {subscription && !isTableDataLoading && tableData && (
- <Tr className="h-12">
- <Td />
- {tableData.head.map(({ slug, tier }) => {
- const isCurrentPlan = slug === subscription.slug;
- let subscriptionText = "Upgrade";
-
- if (subscription.tier > tier) {
- subscriptionText = "Downgrade";
- }
-
- if (tier === 3) {
- subscriptionText = "Contact sales";
- }
-
- return isCurrentPlan ? (
- <Td>
- <Button colorSchema="secondary" className="w-full" isDisabled>
- Current
- </Button>
- </Td>
- ) : (
- <Td>
- <Button
- onClick={async () => {
- if (!currentOrg?.id) return;
-
- if (tier !== 3) {
- const { url } = await createCustomerPortalSession.mutateAsync(
- currentOrg.id
- );
- window.location.href = url;
- return;
- }
-
- window.location.href = "https://infisical.com/scheduledemo";
- }}
- color="mineshaft"
- className="w-full"
- >
- {subscriptionText}
- </Button>
- </Td>
- );
- })}
- </Tr>
- )}
- </TBody>
- </Table>
- </TableContainer>
- );
-};
diff --git a/frontend/src/pages/organization/BillingPage/components/BillingCloudTab/PreviewSection.tsx b/frontend/src/pages/organization/BillingPage/components/BillingCloudTab/PreviewSection.tsx
deleted file mode 100644
index 6cc01abdd9..0000000000
--- a/frontend/src/pages/organization/BillingPage/components/BillingCloudTab/PreviewSection.tsx
+++ /dev/null
@@ -1,232 +0,0 @@
-import { useEffect } from "react";
-import { faArrowUpRightFromSquare, faInfoCircle } from "@fortawesome/free-solid-svg-icons";
-import { FontAwesomeIcon } from "@fortawesome/react-fontawesome";
-import { useQueryClient } from "@tanstack/react-query";
-
-import { OrgPermissionCan } from "@app/components/permissions";
-import { Button, Tooltip } from "@app/components/v2";
-import {
- OrgPermissionBillingActions,
- OrgPermissionSubjects,
- useOrganization,
- useSubscription
-} from "@app/context";
-import { isInfisicalCloud } from "@app/helpers/platform";
-import {
- useCreateCustomerPortalSession,
- useGetOrgPlanBillingInfo,
- useGetOrgTrialUrl
-} from "@app/hooks/api";
-import { subscriptionQueryKeys } from "@app/hooks/api/subscriptions/queries";
-import { SubscriptionPlanTypes } from "@app/hooks/api/subscriptions/types";
-import { usePopUp } from "@app/hooks/usePopUp";
-
-import { ManagePlansModal } from "./ManagePlansModal";
-
-export const PreviewSection = () => {
- const { currentOrg } = useOrganization();
- const { subscription } = useSubscription(true);
- const queryClient = useQueryClient();
- const { data, isPending } = useGetOrgPlanBillingInfo(currentOrg?.id ?? "");
-
- const totalAmount = data?.amount ? data.amount * (data.users + data.identities) : 0;
-
- const getOrgTrialUrl = useGetOrgTrialUrl();
- const createCustomerPortalSession = useCreateCustomerPortalSession();
-
- const { popUp, handlePopUpOpen, handlePopUpToggle } = usePopUp(["managePlan"] as const);
-
- const formatAmount = (amount: number) => {
- const formattedTotal = (Math.floor(amount) / 100).toLocaleString("en-US", {
- style: "currency",
- currency: "USD"
- });
-
- return formattedTotal;
- };
-
- useEffect(() => {
- queryClient.invalidateQueries({
- queryKey: subscriptionQueryKeys.getOrgSubsription(currentOrg?.id ?? "")
- });
- }, []);
-
- const formatDate = (date: number) => {
- const createdDate = new Date(date * 1000);
- const day: number = createdDate.getDate();
- const month: number = createdDate.getMonth() + 1;
- const year: number = createdDate.getFullYear();
- const formattedDate: string = `${day}/${month}/${year}`;
-
- return formattedDate;
- };
-
- function formatPlanSlug(slug: SubscriptionPlanTypes) {
- if (!slug) {
- return "-";
- }
- return slug.replace(/(\b[a-z])/g, (match) => match.toUpperCase()).replace(/-/g, " ");
- }
-
- const handleUpgradeBtnClick = async () => {
- try {
- if (!subscription || !currentOrg) return;
-
- if (!isInfisicalCloud()) {
- window.open("https://infisical.com/pricing", "_blank");
- return;
- }
-
- if (!subscription.has_used_trial) {
- // direct user to start pro trial
- const url = await getOrgTrialUrl.mutateAsync({
- orgId: currentOrg.id,
- success_url: window.location.href
- });
-
- window.location.href = url;
- } else {
- // open compare plans modal
- handlePopUpOpen("managePlan");
- }
- } catch (err) {
- console.error(err);
- }
- };
-
- const getUpgradePlanLabel = () => {
- if (!isInfisicalCloud()) {
- return (
- <div>
- Go to Pricing
- <FontAwesomeIcon icon={faArrowUpRightFromSquare} className="mb-[0.06rem] ml-1 text-xs" />
- </div>
- );
- }
-
- return !subscription.has_used_trial ? "Start Pro Free Trial" : "Upgrade Plan";
- };
-
- return (
- <div>
- {subscription &&
- subscription?.slug !== SubscriptionPlanTypes.Enterprise &&
- subscription?.slug !== SubscriptionPlanTypes.Advanced &&
- subscription?.slug !== SubscriptionPlanTypes.Pro &&
- subscription?.slug !== SubscriptionPlanTypes.ProAnnual && (
- <div className="flex flex-row space-x-6">
- <div className="mb-6 flex flex-1 items-center rounded-lg border border-primary/40 bg-primary/10 p-4">
- <div className="flex-1">
- <h2 className="text-xl font-medium text-mineshaft-100">
- Unleash the full power of{" "}
- <span className="bg-linear-to-r from-primary-500 to-yellow bg-clip-text font-medium text-transparent">
- Infisical
- </span>
- </h2>
- <p className="mt-4 text-gray-400">
- Get unlimited members, projects, RBAC, smart alerts, and so much more.
- </p>
- </div>
- <OrgPermissionCan
- I={OrgPermissionBillingActions.ManageBilling}
- a={OrgPermissionSubjects.Billing}
- >
- {(isAllowed) => (
- <Button
- onClick={() => handleUpgradeBtnClick()}
- color="mineshaft"
- isDisabled={!isAllowed}
- >
- {getUpgradePlanLabel()}
- </Button>
- )}
- </OrgPermissionCan>
- </div>
- <div className="mb-6 flex w-full max-w-48 flex-col items-center rounded-lg border border-mineshaft-600 bg-mineshaft-800 p-4">
- <div className="mb-4 flex w-full justify-center font-medium text-mineshaft-200">
- Want to learn more?{" "}
- </div>
- <div className="flex w-full justify-center">
- <a
- href="https://infisical.com/talk-to-us"
- target="_blank"
- rel="noopener noreferrer"
- >
- <span className="cursor-pointer rounded-full border border-mineshaft-500 bg-mineshaft-600 px-4 py-2 duration-200 hover:border-primary/40 hover:bg-primary/10">
- Book a demo{" "}
- <FontAwesomeIcon
- icon={faArrowUpRightFromSquare}
- className="mb-[0.06rem] ml-1 text-xs"
- />
- </span>
- </a>
- </div>
- </div>
- </div>
- )}
- {!isPending && subscription && data && (
- <div className="mb-6 flex">
- <div className="mr-4 flex-1 rounded-lg border border-mineshaft-600 bg-mineshaft-900 p-4">
- <p className="mb-2 text-gray-400">Current plan</p>
- <p className="mb-8 text-2xl font-medium text-mineshaft-50">
- {`${formatPlanSlug(subscription.slug)} ${
- subscription.status === "trialing" ? "(Trial)" : ""
- }`}
- </p>
- {isInfisicalCloud() && (
- <OrgPermissionCan
- I={OrgPermissionBillingActions.ManageBilling}
- a={OrgPermissionSubjects.Billing}
- >
- {(isAllowed) => (
- <button
- type="button"
- onClick={async () => {
- if (!currentOrg?.id) return;
- const { url } = await createCustomerPortalSession.mutateAsync(currentOrg.id);
- window.location.href = url;
- }}
- disabled={!isAllowed}
- className="text-primary"
- >
- Manage plan &rarr;
- </button>
- )}
- </OrgPermissionCan>
- )}
- </div>
- {subscription.slug !== SubscriptionPlanTypes.Enterprise ? (
- <div className="mr-4 flex-1 rounded-lg border border-mineshaft-600 bg-mineshaft-900 p-4">
- <p className="mb-2 text-gray-400">Price</p>
- <p className="mb-8 text-2xl font-medium text-mineshaft-50">
- {subscription.status === "trialing" ? (
- "$0.00 / month"
- ) : (
- <>
- {formatAmount(totalAmount)} / {data.interval}
- {(subscription.slug === SubscriptionPlanTypes.Pro ||
- subscription.slug === SubscriptionPlanTypes.ProAnnual) && (
- <Tooltip
- content={`Total price is based on the number of users and machine identities at ${formatAmount(data.amount)} each. You have ${data.users} ${data.users > 1 ? "users" : "user"} and ${data.identities} ${data.identities > 1 ? "machine identities" : "machine identity"}.`}
- className="max-w-lg"
- >
- <FontAwesomeIcon icon={faInfoCircle} className="ml-2" size="xs" />
- </Tooltip>
- )}
- </>
- )}
- </p>
- </div>
- ) : null}
- <div className="flex-1 rounded-lg border border-mineshaft-600 bg-mineshaft-900 p-4">
- <p className="mb-2 text-gray-400">Subscription renews on</p>
- <p className="mb-8 text-2xl font-medium text-mineshaft-50">
- {data.currentPeriodEnd ? formatDate(data.currentPeriodEnd) : "-"}
- </p>
- </div>
- </div>
- )}
- <ManagePlansModal popUp={popUp} handlePopUpToggle={handlePopUpToggle} />
- </div>
- );
-};
diff --git a/frontend/src/pages/organization/BillingPage/components/BillingCloudTab/index.tsx b/frontend/src/pages/organization/BillingPage/components/BillingCloudTab/index.tsx
deleted file mode 100644
index 341251e997..0000000000
--- a/frontend/src/pages/organization/BillingPage/components/BillingCloudTab/index.tsx
+++ /dev/null
@@ -1 +0,0 @@
-export { BillingCloudTab } from "./BillingCloudTab";
diff --git a/frontend/src/pages/organization/BillingPage/components/BillingDetailsTab/BillingDetailsTab.tsx b/frontend/src/pages/organization/BillingPage/components/BillingDetailsTab/BillingDetailsTab.tsx
deleted file mode 100644
index f422fe0465..0000000000
--- a/frontend/src/pages/organization/BillingPage/components/BillingDetailsTab/BillingDetailsTab.tsx
+++ /dev/null
@@ -1,15 +0,0 @@
-import { CompanyNameSection } from "./CompanyNameSection";
-import { InvoiceEmailSection } from "./InvoiceEmailSection";
-import { PmtMethodsSection } from "./PmtMethodsSection";
-import { TaxIDSection } from "./TaxIDSection";
-
-export const BillingDetailsTab = () => {
- return (
- <>
- <CompanyNameSection />
- <InvoiceEmailSection />
- <PmtMethodsSection />
- <TaxIDSection />
- </>
- );
-};
diff --git a/frontend/src/pages/organization/BillingPage/components/BillingDetailsTab/CompanyNameSection.tsx b/frontend/src/pages/organization/BillingPage/components/BillingDetailsTab/CompanyNameSection.tsx
deleted file mode 100644
index f63b5d6d13..0000000000
--- a/frontend/src/pages/organization/BillingPage/components/BillingDetailsTab/CompanyNameSection.tsx
+++ /dev/null
@@ -1,86 +0,0 @@
-import { useEffect } from "react";
-import { Controller, useForm } from "react-hook-form";
-import { zodResolver } from "@hookform/resolvers/zod";
-import { z } from "zod";
-
-import { createNotification } from "@app/components/notifications";
-import { OrgPermissionCan } from "@app/components/permissions";
-import { Button, FormControl, Input } from "@app/components/v2";
-import { OrgPermissionBillingActions, OrgPermissionSubjects, useOrganization } from "@app/context";
-import { useGetOrgBillingDetails, useUpdateOrgBillingDetails } from "@app/hooks/api";
-
-const schema = z
- .object({
- name: z.string()
- })
- .required();
-
-export const CompanyNameSection = () => {
- const { currentOrg } = useOrganization();
- const { reset, control, handleSubmit } = useForm({
- defaultValues: {
- name: ""
- },
- resolver: zodResolver(schema)
- });
- const { data } = useGetOrgBillingDetails(currentOrg?.id ?? "");
- const { mutateAsync, isPending } = useUpdateOrgBillingDetails();
-
- useEffect(() => {
- if (data) {
- reset({
- name: data?.name ?? ""
- });
- }
- }, [data]);
-
- const onFormSubmit = async ({ name }: { name: string }) => {
- if (!currentOrg?.id) return;
- if (name === "") return;
- await mutateAsync({
- name,
- organizationId: currentOrg.id
- });
-
- createNotification({
- text: "Successfully updated business name",
- type: "success"
- });
- };
-
- return (
- <form
- onSubmit={handleSubmit(onFormSubmit)}
- className="mb-6 rounded-lg border border-mineshaft-600 bg-mineshaft-900 p-4"
- >
- <h2 className="mb-8 flex-1 text-xl font-medium text-mineshaft-100">Business name</h2>
- <div className="max-w-md">
- <Controller
- defaultValue=""
- render={({ field, fieldState: { error } }) => (
- <FormControl isError={Boolean(error)} errorText={error?.message}>
- <Input placeholder="Acme Corp" {...field} className="bg-mineshaft-800" />
- </FormControl>
- )}
- control={control}
- name="name"
- />
- </div>
- <OrgPermissionCan
- I={OrgPermissionBillingActions.ManageBilling}
- a={OrgPermissionSubjects.Billing}
- >
- {(isAllowed) => (
- <Button
- type="submit"
- colorSchema="secondary"
- isLoading={isPending}
- isDisabled={isPending || !isAllowed}
- >
- Save
- </Button>
- )}
- </OrgPermissionCan>
- </form>
- );
-};
diff --git a/frontend/src/pages/organization/BillingPage/components/BillingDetailsTab/InvoiceEmailSection.tsx b/frontend/src/pages/organization/BillingPage/components/BillingDetailsTab/InvoiceEmailSection.tsx
deleted file mode 100644
index dc05a72086..0000000000
--- a/frontend/src/pages/organization/BillingPage/components/BillingDetailsTab/InvoiceEmailSection.tsx
+++ /dev/null
@@ -1,87 +0,0 @@
-import { useEffect } from "react";
-import { Controller, useForm } from "react-hook-form";
-import { zodResolver } from "@hookform/resolvers/zod";
-import { z } from "zod";
-
-import { createNotification } from "@app/components/notifications";
-import { OrgPermissionCan } from "@app/components/permissions";
-import { Button, FormControl, Input } from "@app/components/v2";
-import { OrgPermissionBillingActions, OrgPermissionSubjects, useOrganization } from "@app/context";
-import { useGetOrgBillingDetails, useUpdateOrgBillingDetails } from "@app/hooks/api";
-
-const schema = z
- .object({
- email: z.string()
- })
- .required();
-
-export const InvoiceEmailSection = () => {
- const { currentOrg } = useOrganization();
- const { reset, control, handleSubmit } = useForm({
- defaultValues: {
- email: ""
- },
- resolver: zodResolver(schema)
- });
- const { data } = useGetOrgBillingDetails(currentOrg?.id ?? "");
- const { mutateAsync, isPending } = useUpdateOrgBillingDetails();
-
- useEffect(() => {
- if (data) {
- reset({
- email: data?.email ?? ""
- });
- }
- }, [data]);
-
- const onFormSubmit = async ({ email }: { email: string }) => {
- if (!currentOrg?.id) return;
- if (email === "") return;
-
- await mutateAsync({
- email,
- organizationId: currentOrg.id
- });
-
- createNotification({
- text: "Successfully updated invoice email recipient",
- type: "success"
- });
- };
-
- return (
- <form
- onSubmit={handleSubmit(onFormSubmit)}
- className="mb-6 rounded-lg border border-mineshaft-600 bg-mineshaft-900 p-4"
- >
- <h2 className="mb-8 flex-1 text-xl font-medium text-white">Invoice email recipient</h2>
- <div className="max-w-md">
- <Controller
- defaultValue=""
- render={({ field, fieldState: { error } }) => (
- <FormControl isError={Boolean(error)} errorText={error?.message}>
- <Input placeholder="[email protected]" {...field} className="bg-mineshaft-800" />
- </FormControl>
- )}
- control={control}
- name="email"
- />
- </div>
- <OrgPermissionCan
- I={OrgPermissionBillingActions.ManageBilling}
- a={OrgPermissionSubjects.Billing}
- >
- {(isAllowed) => (
- <Button
- type="submit"
- colorSchema="secondary"
- isLoading={isPending}
- isDisabled={isPending || !isAllowed}
- >
- Save
- </Button>
- )}
- </OrgPermissionCan>
- </form>
- );
-};
diff --git a/frontend/src/pages/organization/BillingPage/components/BillingDetailsTab/PmtMethodsSection.tsx b/frontend/src/pages/organization/BillingPage/components/BillingDetailsTab/PmtMethodsSection.tsx
deleted file mode 100644
index 1008996dba..0000000000
--- a/frontend/src/pages/organization/BillingPage/components/BillingDetailsTab/PmtMethodsSection.tsx
+++ /dev/null
@@ -1,50 +0,0 @@
-import { faPlus } from "@fortawesome/free-solid-svg-icons";
-import { FontAwesomeIcon } from "@fortawesome/react-fontawesome";
-
-import { OrgPermissionCan } from "@app/components/permissions";
-import { Button } from "@app/components/v2";
-import { OrgPermissionBillingActions, OrgPermissionSubjects, useOrganization } from "@app/context";
-import { useAddOrgPmtMethod } from "@app/hooks/api";
-
-import { PmtMethodsTable } from "./PmtMethodsTable";
-
-export const PmtMethodsSection = () => {
- const { currentOrg } = useOrganization();
- const { mutateAsync, isPending } = useAddOrgPmtMethod();
-
- const handleAddPmtMethodBtnClick = async () => {
- if (!currentOrg?.id) return;
- const url = await mutateAsync({
- organizationId: currentOrg.id,
- success_url: window.location.href,
- cancel_url: window.location.href
- });
-
- window.location.href = url;
- };
-
- return (
- <div className="mb-6 rounded-lg border border-mineshaft-600 bg-mineshaft-900 p-4">
- <div className="mb-8 flex items-center">
- <h2 className="flex-1 text-xl font-medium text-white">Payment methods</h2>
- <OrgPermissionCan
- I={OrgPermissionBillingActions.ManageBilling}
- a={OrgPermissionSubjects.Billing}
- >
- {(isAllowed) => (
- <Button
- onClick={handleAddPmtMethodBtnClick}
- colorSchema="secondary"
- isLoading={isPending}
- leftIcon={<FontAwesomeIcon icon={faPlus} />}
- isDisabled={!isAllowed}
- >
- Add method
- </Button>
- )}
- </OrgPermissionCan>
- </div>
- <PmtMethodsTable />
- </div>
- );
-};
diff --git a/frontend/src/pages/organization/BillingPage/components/BillingDetailsTab/PmtMethodsTable.tsx b/frontend/src/pages/organization/BillingPage/components/BillingDetailsTab/PmtMethodsTable.tsx
deleted file mode 100644
index 15a6bc8e9d..0000000000
--- a/frontend/src/pages/organization/BillingPage/components/BillingDetailsTab/PmtMethodsTable.tsx
+++ /dev/null
@@ -1,117 +0,0 @@
-import { faCreditCard, faXmark } from "@fortawesome/free-solid-svg-icons";
-import { FontAwesomeIcon } from "@fortawesome/react-fontawesome";
-
-import { createNotification } from "@app/components/notifications";
-import { OrgPermissionCan } from "@app/components/permissions";
-import {
- DeleteActionModal,
- EmptyState,
- IconButton,
- Table,
- TableContainer,
- TableSkeleton,
- TBody,
- Td,
- Th,
- THead,
- Tr
-} from "@app/components/v2";
-import { OrgPermissionBillingActions, OrgPermissionSubjects, useOrganization } from "@app/context";
-import { usePopUp } from "@app/hooks";
-import { useDeleteOrgPmtMethod, useGetOrgPmtMethods } from "@app/hooks/api";
-
-export const PmtMethodsTable = () => {
- const { currentOrg } = useOrganization();
- const { data, isPending } = useGetOrgPmtMethods(currentOrg?.id ?? "");
- const deleteOrgPmtMethod = useDeleteOrgPmtMethod();
- const { handlePopUpOpen, handlePopUpClose, handlePopUpToggle, popUp } = usePopUp([
- "removeCard"
- ] as const);
-
- const pmtMethodToRemove = popUp.removeCard.data as { id: string; last4: string } | undefined;
-
- const handleDeletePmtMethodBtnClick = async () => {
- if (!currentOrg?.id || !pmtMethodToRemove) return;
- if (data?.length === 1) {
- createNotification({
- type: "error",
- text: "You must have at least one payment method"
- });
- return;
- }
- await deleteOrgPmtMethod.mutateAsync({
- organizationId: currentOrg.id,
- pmtMethodId: pmtMethodToRemove.id
- });
- createNotification({
- type: "success",
- text: "Successfully removed payment method"
- });
- handlePopUpClose("removeCard");
- };
-
- return (
- <>
- <TableContainer className="mt-4">
- <Table>
- <THead>
- <Tr>
- <Th className="flex-1">Brand</Th>
- <Th className="flex-1">Type</Th>
- <Th className="flex-1">Last 4 Digits</Th>
- <Th className="flex-1">Expiration</Th>
- <Th className="w-5" />
- </Tr>
- </THead>
- <TBody>
- {!isPending &&
- data &&
- data?.length > 0 &&
- data.map(({ _id: id, brand, exp_month, exp_year, funding, last4 }) => (
- <Tr key={`pmt-method-${id}`} className="h-10">
- <Td>{brand.charAt(0).toUpperCase() + brand.slice(1)}</Td>
- <Td>{funding.charAt(0).toUpperCase() + funding.slice(1)}</Td>
- <Td>{last4}</Td>
- <Td>{`${exp_month}/${exp_year}`}</Td>
- <Td>
- <OrgPermissionCan
- I={OrgPermissionBillingActions.ManageBilling}
- a={OrgPermissionSubjects.Billing}
- >
- {(isAllowed) => (
- <IconButton
- onClick={() => handlePopUpOpen("removeCard", { id, last4 })}
- size="lg"
- isDisabled={!isAllowed}
- colorSchema="danger"
- variant="plain"
- ariaLabel="update"
- >
- <FontAwesomeIcon icon={faXmark} />
- </IconButton>
- )}
- </OrgPermissionCan>
- </Td>
- </Tr>
- ))}
- {isPending && <TableSkeleton columns={5} innerKey="pmt-methods" />}
- {!isPending && data && data?.length === 0 && (
- <Tr>
- <Td colSpan={5}>
- <EmptyState title="No payment methods on file" icon={faCreditCard} />
- </Td>
- </Tr>
- )}
- </TBody>
- </Table>
- </TableContainer>
- <DeleteActionModal
- isOpen={popUp.removeCard.isOpen}
- deleteKey="confirm"
- onChange={(isOpen) => handlePopUpToggle("removeCard", isOpen)}
- title={`Remove payment method ending in *${pmtMethodToRemove?.last4}?`}
- onDeleteApproved={handleDeletePmtMethodBtnClick}
- />
- </>
- );
-};
diff --git a/frontend/src/pages/organization/BillingPage/components/BillingDetailsTab/TaxIDModal.tsx b/frontend/src/pages/organization/BillingPage/components/BillingDetailsTab/TaxIDModal.tsx
deleted file mode 100644
index 23542ac8d7..0000000000
--- a/frontend/src/pages/organization/BillingPage/components/BillingDetailsTab/TaxIDModal.tsx
+++ /dev/null
@@ -1,174 +0,0 @@
-import { Controller, useForm } from "react-hook-form";
-import { zodResolver } from "@hookform/resolvers/zod";
-import { z } from "zod";
-
-import { createNotification } from "@app/components/notifications";
-import {
- Button,
- FormControl,
- Input,
- Modal,
- ModalContent,
- Select,
- SelectItem
-} from "@app/components/v2";
-import { useOrganization } from "@app/context";
-import { useAddOrgTaxId } from "@app/hooks/api";
-import { UsePopUpState } from "@app/hooks/usePopUp";
-
-const taxIDTypes = [
- { label: "Australia ABN", value: "au_abn" },
- { label: "Australia ARN", value: "au_arn" },
- { label: "Brazil CNPJ", value: "br_cnpj" },
- { label: "Brazil CPF", value: "br_cpf" },
- { label: "Bulgaria UIC", value: "bg_uic" },
- { label: "Canada BN", value: "ca_bn" },
- { label: "Canada GST/HST", value: "ca_gst_hst" },
- { label: "Canada PST BC", value: "ca_pst_bc" },
- { label: "Canada PST MB", value: "ca_pst_mb" },
- { label: "Canada PST SK", value: "ca_pst_sk" },
- { label: "Canada QST", value: "ca_qst" },
- { label: "Chile TIN", value: "cl_tin" },
- { label: "Egypt TIN", value: "eg_tin" },
- { label: "EU OSS VAT", value: "eu_oss_vat" },
- { label: "EU VAT", value: "eu_vat" },
- { label: "GB VAT", value: "gb_vat" },
- { label: "Georgia VAT", value: "ge_vat" },
- { label: "Hong Kong BR", value: "hk_br" },
- { label: "Hungary TIN", value: "hu_tin" },
- { label: "Iceland VAT", value: "is_vat" },
- { label: "India GST", value: "in_gst" },
- { label: "Indonesia NPWP", value: "id_npwp" },
- { label: "Israel VAT", value: "il_vat" },
- { label: "Japan CN", value: "jp_cn" },
- { label: "Japan RN", value: "jp_rn" },
- { label: "Japan TRN", value: "jp_trn" },
- { label: "Kenya PIN", value: "ke_pin" },
- { label: "Liechtenstein UID", value: "li_uid" },
- { label: "Malaysia FRP", value: "my_frp" },
- { label: "Malaysia ITN", value: "my_itn" },
- { label: "Malaysia SST", value: "my_sst" },
- { label: "Mexico RFC", value: "mx_rfc" },
- { label: "New Zealand GST", value: "nz_gst" },
- { label: "Norway VAT", value: "no_vat" },
- { label: "Philippines TIN", value: "ph_tin" },
- { label: "Russia INN", value: "ru_inn" },
- { label: "Russia KPP", value: "ru_kpp" },
- { label: "Saudi Arabia VAT", value: "sa_vat" },
- { label: "Singapore GST", value: "sg_gst" },
- { label: "Singapore UEN", value: "sg_uen" },
- { label: "Slovenia TIN", value: "si_tin" },
- { label: "South Africa VAT", value: "za_vat" },
- { label: "South Korea BRN", value: "kr_brn" },
- { label: "Spain CIF", value: "es_cif" },
- { label: "Switzerland VAT", value: "ch_vat" },
- { label: "Taiwan VAT", value: "tw_vat" },
- { label: "Thailand VAT", value: "th_vat" },
- { label: "Turkey TIN", value: "tr_tin" },
- { label: "US EIN", value: "us_ein" },
- { label: "Ukraine VAT", value: "ua_vat" }
-];
-
-const schema = z
- .object({
- type: z.string(),
- value: z.string()
- })
- .required();
-
-export type AddTaxIDFormData = z.infer<typeof schema>;
-
-type Props = {
- popUp: UsePopUpState<["addTaxID"]>;
- handlePopUpClose: (popUpName: keyof UsePopUpState<["addTaxID"]>) => void;
- handlePopUpToggle: (popUpName: keyof UsePopUpState<["addTaxID"]>, state?: boolean) => void;
-};
-
-export const TaxIDModal = ({ popUp, handlePopUpClose, handlePopUpToggle }: Props) => {
- const { currentOrg } = useOrganization();
- const addOrgTaxId = useAddOrgTaxId();
-
- const {
- control,
- handleSubmit,
- reset,
- formState: { isSubmitting }
- } = useForm<AddTaxIDFormData>({
- resolver: zodResolver(schema)
- });
-
- const onTaxIDModalSubmit = async ({ type, value }: AddTaxIDFormData) => {
- if (!currentOrg?.id) return;
- await addOrgTaxId.mutateAsync({
- organizationId: currentOrg.id,
- type,
- value
- });
-
- createNotification({
- text: "Successfully added Tax ID",
- type: "success"
- });
- handlePopUpClose("addTaxID");
- };
-
- return (
- <Modal
- isOpen={popUp?.addTaxID?.isOpen}
- onOpenChange={(isOpen) => {
- handlePopUpToggle("addTaxID", isOpen);
- reset();
- }}
- >
- <ModalContent title="Add Tax ID">
- <form onSubmit={handleSubmit(onTaxIDModalSubmit)}>
- <Controller
- control={control}
- name="type"
- defaultValue="eu_vat"
- render={({ field: { onChange, ...field }, fieldState: { error } }) => (
- <FormControl label="Type" errorText={error?.message} isError={Boolean(error)}>
- <Select
- defaultValue={field.value}
- {...field}
- onValueChange={(e) => onChange(e)}
- className="w-full"
- >
- {taxIDTypes.map(({ label, value }) => (
- <SelectItem value={String(value || "")} key={label}>
- {label}
- </SelectItem>
- ))}
- </Select>
- </FormControl>
- )}
- />
- <Controller
- control={control}
- defaultValue=""
- name="value"
- render={({ field, fieldState: { error } }) => (
- <FormControl label="Value" isError={Boolean(error)} errorText={error?.message}>
- <Input {...field} placeholder="DE000000000" />
- </FormControl>
- )}
- />
- <div className="mt-8 flex items-center">
- <Button
- className="mr-4"
- size="sm"
- type="submit"
- isLoading={isSubmitting}
- isDisabled={isSubmitting}
- >
- Add
- </Button>
- <Button colorSchema="secondary" variant="plain">
- Cancel
- </Button>
- </div>
- </form>
- </ModalContent>
- </Modal>
- );
-};
diff --git a/frontend/src/pages/organization/BillingPage/components/BillingDetailsTab/TaxIDSection.tsx b/frontend/src/pages/organization/BillingPage/components/BillingDetailsTab/TaxIDSection.tsx
deleted file mode 100644
index bcad4be538..0000000000
--- a/frontend/src/pages/organization/BillingPage/components/BillingDetailsTab/TaxIDSection.tsx
+++ /dev/null
@@ -1,45 +0,0 @@
-import { faPlus } from "@fortawesome/free-solid-svg-icons";
-import { FontAwesomeIcon } from "@fortawesome/react-fontawesome";
-
-import { OrgPermissionCan } from "@app/components/permissions";
-import { Button } from "@app/components/v2";
-import { OrgPermissionBillingActions, OrgPermissionSubjects } from "@app/context";
-import { usePopUp } from "@app/hooks/usePopUp";
-
-import { TaxIDModal } from "./TaxIDModal";
-import { TaxIDTable } from "./TaxIDTable";
-
-export const TaxIDSection = () => {
- const { popUp, handlePopUpOpen, handlePopUpClose, handlePopUpToggle } = usePopUp([
- "addTaxID"
- ] as const);
-
- return (
- <div className="mb-6 rounded-lg border border-mineshaft-600 bg-mineshaft-900 p-4">
- <div className="mb-8 flex items-center">
- <h2 className="flex-1 text-xl font-medium text-white">Tax ID</h2>
- <OrgPermissionCan
- I={OrgPermissionBillingActions.ManageBilling}
- a={OrgPermissionSubjects.Billing}
- >
- {(isAllowed) => (
- <Button
- onClick={() => handlePopUpOpen("addTaxID")}
- colorSchema="secondary"
- isDisabled={!isAllowed}
- leftIcon={<FontAwesomeIcon icon={faPlus} />}
- >
- Add method
- </Button>
- )}
- </OrgPermissionCan>
- </div>
- <TaxIDTable />
- <TaxIDModal
- popUp={popUp}
- handlePopUpClose={handlePopUpClose}
- handlePopUpToggle={handlePopUpToggle}
- />
- </div>
- );
-};
diff --git a/frontend/src/pages/organization/BillingPage/components/BillingDetailsTab/TaxIDTable.tsx b/frontend/src/pages/organization/BillingPage/components/BillingDetailsTab/TaxIDTable.tsx
deleted file mode 100644
index 2364b03daa..0000000000
--- a/frontend/src/pages/organization/BillingPage/components/BillingDetailsTab/TaxIDTable.tsx
+++ /dev/null
@@ -1,139 +0,0 @@
-import { faFileInvoice, faXmark } from "@fortawesome/free-solid-svg-icons";
-import { FontAwesomeIcon } from "@fortawesome/react-fontawesome";
-
-import { OrgPermissionCan } from "@app/components/permissions";
-import {
- EmptyState,
- IconButton,
- Table,
- TableContainer,
- TableSkeleton,
- TBody,
- Td,
- Th,
- THead,
- Tr
-} from "@app/components/v2";
-import { OrgPermissionBillingActions, OrgPermissionSubjects, useOrganization } from "@app/context";
-import { useDeleteOrgTaxId, useGetOrgTaxIds } from "@app/hooks/api";
-
-const taxIDTypeLabelMap: { [key: string]: string } = {
- au_abn: "Australia ABN",
- au_arn: "Australia ARN",
- bg_uic: "Bulgaria UIC",
- br_cnpj: "Brazil CNPJ",
- br_cpf: "Brazil CPF",
- ca_bn: "Canada BN",
- ca_gst_hst: "Canada GST/HST",
- ca_pst_bc: "Canada PST BC",
- ca_pst_mb: "Canada PST MB",
- ca_pst_sk: "Canada PST SK",
- ca_qst: "Canada QST",
- ch_vat: "Switzerland VAT",
- cl_tin: "Chile TIN",
- eg_tin: "Egypt TIN",
- es_cif: "Spain CIF",
- eu_oss_vat: "EU OSS VAT",
- eu_vat: "EU VAT",
- gb_vat: "GB VAT",
- ge_vat: "Georgia VAT",
- hk_br: "Hong Kong BR",
- hu_tin: "Hungary TIN",
- id_npwp: "Indonesia NPWP",
- il_vat: "Israel VAT",
- in_gst: "India GST",
- is_vat: "Iceland VAT",
- jp_cn: "Japan CN",
- jp_rn: "Japan RN",
- jp_trn: "Japan TRN",
- ke_pin: "Kenya PIN",
- kr_brn: "South Korea BRN",
- li_uid: "Liechtenstein UID",
- mx_rfc: "Mexico RFC",
- my_frp: "Malaysia FRP",
- my_itn: "Malaysia ITN",
- my_sst: "Malaysia SST",
- no_vat: "Norway VAT",
- nz_gst: "New Zealand GST",
- ph_tin: "Philippines TIN",
- ru_inn: "Russia INN",
- ru_kpp: "Russia KPP",
- sa_vat: "Saudi Arabia VAT",
- sg_gst: "Singapore GST",
- sg_uen: "Singapore UEN",
- si_tin: "Slovenia TIN",
- th_vat: "Thailand VAT",
- tr_tin: "Turkey TIN",
- tw_vat: "Taiwan VAT",
- ua_vat: "Ukraine VAT",
- us_ein: "US EIN",
- za_vat: "South Africa VAT"
-};
-
-export const TaxIDTable = () => {
- const { currentOrg } = useOrganization();
- const { data, isPending } = useGetOrgTaxIds(currentOrg?.id ?? "");
- const deleteOrgTaxId = useDeleteOrgTaxId();
-
- const handleDeleteTaxIdBtnClick = async (taxId: string) => {
- if (!currentOrg?.id) return;
- await deleteOrgTaxId.mutateAsync({
- organizationId: currentOrg.id,
- taxId
- });
- };
-
- return (
- <TableContainer className="mt-4">
- <Table>
- <THead>
- <Tr>
- <Th className="flex-1">Type</Th>
- <Th className="flex-1">Value</Th>
- <Th className="w-5" />
- </Tr>
- </THead>
- <TBody>
- {!isPending &&
- data &&
- data?.length > 0 &&
- data.map(({ id, type, value }) => (
- <Tr key={`tax-id-${id}`} className="h-10">
- <Td>{taxIDTypeLabelMap[type]}</Td>
- <Td>{value}</Td>
- <Td>
- <OrgPermissionCan
- I={OrgPermissionBillingActions.ManageBilling}
- a={OrgPermissionSubjects.Billing}
- >
- {(isAllowed) => (
- <IconButton
- onClick={async () => {
- await handleDeleteTaxIdBtnClick(id);
- }}
- size="lg"
- colorSchema="danger"
- variant="plain"
- ariaLabel="update"
- isDisabled={!isAllowed}
- >
- <FontAwesomeIcon icon={faXmark} />
- </IconButton>
- )}
- </OrgPermissionCan>
- </Td>
- </Tr>
- ))}
- {isPending && <TableSkeleton columns={3} innerKey="tax-ids" />}
- {!isPending && data && data?.length === 0 && (
- <Tr>
- <Td colSpan={5}>
- <EmptyState title="No Tax IDs on file" icon={faFileInvoice} />
- </Td>
- </Tr>
- )}
- </TBody>
- </Table>
- </TableContainer>
- );
-};
diff --git a/frontend/src/pages/organization/BillingPage/components/BillingDetailsTab/index.tsx b/frontend/src/pages/organization/BillingPage/components/BillingDetailsTab/index.tsx
deleted file mode 100644
index 346c0f7d3d..0000000000
--- a/frontend/src/pages/organization/BillingPage/components/BillingDetailsTab/index.tsx
+++ /dev/null
@@ -1 +0,0 @@
-export { BillingDetailsTab } from "./BillingDetailsTab";
diff --git a/frontend/src/pages/organization/BillingPage/components/BillingReceiptsTab/BillingReceiptsTab.tsx b/frontend/src/pages/organization/BillingPage/components/BillingReceiptsTab/BillingReceiptsTab.tsx
deleted file mode 100644
index 2f0333c155..0000000000
--- a/frontend/src/pages/organization/BillingPage/components/BillingReceiptsTab/BillingReceiptsTab.tsx
+++ /dev/null
@@ -1,10 +0,0 @@
-import { InvoicesTable } from "./InvoicesTable";
-
-export const BillingReceiptsTab = () => {
- return (
- <div className="mb-6 rounded-lg border border-mineshaft-600 bg-mineshaft-900 p-4">
- <h2 className="flex-1 text-xl font-medium text-white">Invoices</h2>
- <InvoicesTable />
- </div>
- );
-};
diff --git a/frontend/src/pages/organization/BillingPage/components/BillingReceiptsTab/InvoicesTable.tsx b/frontend/src/pages/organization/BillingPage/components/BillingReceiptsTab/InvoicesTable.tsx
deleted file mode 100644
index cfca906e8a..0000000000
--- a/frontend/src/pages/organization/BillingPage/components/BillingReceiptsTab/InvoicesTable.tsx
+++ /dev/null
@@ -1,82 +0,0 @@
-import { faDownload, faFileInvoice } from "@fortawesome/free-solid-svg-icons";
-import { FontAwesomeIcon } from "@fortawesome/react-fontawesome";
-
-import {
- EmptyState,
- IconButton,
- Table,
- TableContainer,
- TableSkeleton,
- TBody,
- Td,
- Th,
- THead,
- Tr
-} from "@app/components/v2";
-import { useOrganization } from "@app/context";
-import { useGetOrgInvoices } from "@app/hooks/api";
-
-export const InvoicesTable = () => {
- const { currentOrg } = useOrganization();
- const { data, isPending } = useGetOrgInvoices(currentOrg?.id ?? "");
- return (
- <TableContainer className="mt-8">
- <Table>
- <THead>
- <Tr>
- <Th className="flex-1">Invoice #</Th>
- <Th className="flex-1">Date</Th>
- <Th className="flex-1">Status</Th>
- <Th className="flex-1">Amount</Th>
- <Th className="w-5" />
- </Tr>
- </THead>
- <TBody>
- {!isPending &&
- data &&
- data?.length > 0 &&
- data.map(({ id, created, paid, number, total, invoice_pdf }) => {
- const formattedTotal = (Math.floor(total) / 100).toLocaleString("en-US", {
- style: "currency",
- currency: "USD"
- });
- const createdDate = new Date(created * 1000);
- const day: number = createdDate.getDate();
- const month: number = createdDate.getMonth() + 1;
- const year: number = createdDate.getFullYear();
- const formattedDate: string = `${day}/${month}/${year}`;
-
- return (
- <Tr key={`invoice-${id}`} className="h-10">
- <Td>{number}</Td>
- <Td>{formattedDate}</Td>
- <Td>{paid ? "Paid" : "Not Paid"}</Td>
- <Td>{formattedTotal}</Td>
- <Td>
- {invoice_pdf && (
- <IconButton
- onClick={async () => window.open(invoice_pdf)}
- size="lg"
- variant="plain"
- ariaLabel="download invoice"
- >
- <FontAwesomeIcon icon={faDownload} />
- </IconButton>
- )}
- </Td>
- </Tr>
- );
- })}
- {isPending && <TableSkeleton columns={5} innerKey="invoices" />}
- {!isPending && data && data?.length === 0 && (
- <Tr>
- <Td colSpan={5}>
- <EmptyState title="No invoices on file" icon={faFileInvoice} />
- </Td>
- </Tr>
- )}
- </TBody>
- </Table>
- </TableContainer>
- );
-};
diff --git a/frontend/src/pages/organization/BillingPage/components/BillingReceiptsTab/index.tsx b/frontend/src/pages/organization/BillingPage/components/BillingReceiptsTab/index.tsx
deleted file mode 100644
index eec019952c..0000000000
--- a/frontend/src/pages/organization/BillingPage/components/BillingReceiptsTab/index.tsx
+++ /dev/null
@@ -1 +0,0 @@
-export { BillingReceiptsTab } from "./BillingReceiptsTab";
diff --git a/frontend/src/pages/organization/BillingPage/components/BillingSelfHostedTab/BillingSelfHostedTab.tsx b/frontend/src/pages/organization/BillingPage/components/BillingSelfHostedTab/BillingSelfHostedTab.tsx
deleted file mode 100644
index c5a8d8f94e..0000000000
--- a/frontend/src/pages/organization/BillingPage/components/BillingSelfHostedTab/BillingSelfHostedTab.tsx
+++ /dev/null
@@ -1,9 +0,0 @@
-import { LicensesSection } from "./LicensesSection";
-
-export const BillingSelfHostedTab = () => {
- return (
- <div>
- <LicensesSection />
- </div>
- );
-};
diff --git a/frontend/src/pages/organization/BillingPage/components/BillingSelfHostedTab/LicensesSection.tsx b/frontend/src/pages/organization/BillingPage/components/BillingSelfHostedTab/LicensesSection.tsx
deleted file mode 100644
index ab779ceeea..0000000000
--- a/frontend/src/pages/organization/BillingPage/components/BillingSelfHostedTab/LicensesSection.tsx
+++ /dev/null
@@ -1,63 +0,0 @@
-import { faFileContract } from "@fortawesome/free-solid-svg-icons";
-
-import {
- EmptyState,
- Table,
- TableContainer,
- TableSkeleton,
- TBody,
- Td,
- Th,
- THead,
- Tr
-} from "@app/components/v2";
-import { useOrganization } from "@app/context";
-import { useGetOrgLicenses } from "@app/hooks/api";
-
-export const LicensesSection = () => {
- const { currentOrg } = useOrganization();
- const { data, isPending } = useGetOrgLicenses(currentOrg?.id ?? "");
-
- return (
- <div className="mb-6 rounded-lg border border-mineshaft-600 bg-mineshaft-900 p-4">
- <h2 className="mb-8 flex-1 text-xl font-medium text-white">Enterprise licenses</h2>
- <TableContainer className="mt-4">
- <Table>
- <THead>
- <Tr>
- <Th>License Key</Th>
- <Th>Status</Th>
- <Th>Issued Date</Th>
- <Th>Expiry Date</Th>
- </Tr>
- </THead>
- <TBody>
- {!isPending &&
- data &&
- data?.length > 0 &&
- data.map(({ id, licenseKey, isActivated, createdAt, expiresAt }) => {
- const formattedCreatedAt = new Date(createdAt).toISOString().split("T")[0];
- const formattedExpiresAt = new Date(expiresAt).toISOString().split("T")[0];
- return (
- <Tr key={`license-${id}`} className="h-10">
- <Td>{licenseKey}</Td>
- <Td>{isActivated ? "Active" : "Inactive"}</Td>
- <Td>{formattedCreatedAt}</Td>
- <Td>{formattedExpiresAt}</Td>
- </Tr>
- );
- })}
- {isPending && <TableSkeleton columns={4} innerKey="licenses" />}
- {!isPending && data && data?.length === 0 && (
- <Tr>
- <Td colSpan={4}>
- <EmptyState title="No enterprise licenses on file" icon={faFileContract} />
- </Td>
- </Tr>
- )}
- </TBody>
- </Table>
- </TableContainer>
- </div>
- );
-};
diff --git a/frontend/src/pages/organization/BillingPage/components/BillingSelfHostedTab/index.tsx b/frontend/src/pages/organization/BillingPage/components/BillingSelfHostedTab/index.tsx
deleted file mode 100644
index da9282157a..0000000000
--- a/frontend/src/pages/organization/BillingPage/components/BillingSelfHostedTab/index.tsx
+++ /dev/null
@@ -1 +0,0 @@
-export * from "./BillingSelfHostedTab";
diff --git a/frontend/src/pages/organization/BillingPage/components/BillingTabGroup/BillingTabGroup.tsx b/frontend/src/pages/organization/BillingPage/components/BillingTabGroup/BillingTabGroup.tsx
deleted file mode 100644
index 237717bdbc..0000000000
--- a/frontend/src/pages/organization/BillingPage/components/BillingTabGroup/BillingTabGroup.tsx
+++ /dev/null
@@ -1,49 +0,0 @@
-import { Tab, TabList, TabPanel, Tabs } from "@app/components/v2";
-import { OrgPermissionBillingActions, OrgPermissionSubjects } from "@app/context";
-import { isInfisicalCloud } from "@app/helpers/platform";
-import { withPermission } from "@app/hoc";
-
-import { BillingCloudTab } from "../BillingCloudTab";
-import { BillingDetailsTab } from "../BillingDetailsTab";
-import { BillingReceiptsTab } from "../BillingReceiptsTab";
-import { BillingSelfHostedTab } from "../BillingSelfHostedTab";
-
-const tabs = [
- { name: "Infisical Cloud", key: "tab-infisical-cloud" },
- { name: "Infisical Self-Hosted", key: "tab-infisical-self-hosted" },
- { name: "Receipts", key: "tab-receipts" },
- { name: "Billing details", key: "tab-billing-details" }
-];
-
-export const BillingTabGroup = withPermission(
- () => {
- if (!isInfisicalCloud()) {
- return <BillingCloudTab />;
- }
-
- return (
- <Tabs orientation="vertical" defaultValue={tabs[0].key}>
- <TabList>
- {tabs.map((tab) => (
- <Tab variant="org" key={tab.key} value={tab.key}>
- {tab.name}
- </Tab>
- ))}
- </TabList>
- <TabPanel value={tabs[0].key}>
- <BillingCloudTab />
- </TabPanel>
- <TabPanel value={tabs[1].key}>
- <BillingSelfHostedTab />
- </TabPanel>
- <TabPanel value={tabs[2].key}>
- <BillingReceiptsTab />
- </TabPanel>
- <TabPanel value={tabs[3].key}>
- <BillingDetailsTab />
- </TabPanel>
- </Tabs>
- );
- },
- { action: OrgPermissionBillingActions.Read, subject: OrgPermissionSubjects.Billing }
-);
diff --git a/frontend/src/pages/organization/BillingPage/components/BillingTabGroup/index.tsx b/frontend/src/pages/organization/BillingPage/components/BillingTabGroup/index.tsx
deleted file mode 100644
index 8ad1fb5b87..0000000000
--- a/frontend/src/pages/organization/BillingPage/components/BillingTabGroup/index.tsx
+++ /dev/null
@@ -1 +0,0 @@
-export { BillingTabGroup } from "./BillingTabGroup";
diff --git a/frontend/src/pages/organization/BillingPage/components/index.tsx b/frontend/src/pages/organization/BillingPage/components/index.tsx
deleted file mode 100644
index 8ad1fb5b87..0000000000
--- a/frontend/src/pages/organization/BillingPage/components/index.tsx
+++ /dev/null
@@ -1 +0,0 @@
-export { BillingTabGroup } from "./BillingTabGroup";