diff --git a/server/src/db/models/auth/Org.ts b/server/src/db/models/auth/Org.ts index 8e3ce7f81..698d4fd23 100644 --- a/server/src/db/models/auth/Org.ts +++ b/server/src/db/models/auth/Org.ts @@ -1,8 +1,39 @@ import mongoose, { Schema, Document, Types } from "mongoose"; +export type SubscriptionStatus = + | "active" + | "trialing" + | "past_due" + | "canceled" + | "incomplete"; + export interface IOrg extends Document { _id: Types.ObjectId; name: string; ownerId: Types.ObjectId; + + // Entitlements & plan + planKey: "free" | "pro" | "business" | "enterprise"; + + // Billing + billingCustomerId?: string; + subscriptionId?: string; + priceIds?: string[]; + subscriptionStatus?: SubscriptionStatus; + currentPeriodStart?: Date; + currentPeriodEnd?: Date; + trialEnd?: Date; + cancelAtPeriodEnd?: boolean; + + // Cached entitlements + entitlements?: { + monitorsMax: number; + notificationChannelsMax: number; + statusPageMax: number; + checksIntervalMsMin: number; + teamsMax: number; + notificationsEnabled: boolean; + retentionDays: number; + }; createdAt: Date; updatedAt: Date; } @@ -11,6 +42,34 @@ const orgSchema = new Schema( { name: { type: String, required: true }, ownerId: { type: Schema.Types.ObjectId, ref: "User", required: true }, + + // Subscription Info + planKey: { + type: String, + enum: ["free", "pro", "business", "enterprise"], + default: "free", + required: true, + }, + billingCustomerId: { type: String }, + subscriptionId: { type: String }, + priceIds: { type: [String], default: undefined }, + subscriptionStatus: { + type: String, + enum: ["active", "trialing", "past_due", "canceled", "incomplete"], + }, + currentPeriodStart: { type: Date }, + currentPeriodEnd: { type: Date }, + trialEnd: { type: Date }, + cancelAtPeriodEnd: { type: Boolean }, + entitlements: { + monitorsMax: { type: Number }, + notificationChannelsMax: { type: Number }, + statusPageMax: { type: Number }, + checksIntervalMsMin: { type: Number }, + teamsMax: { type: Number }, + notificationsEnabled: { type: Boolean }, + retentionDays: { type: Number }, + }, }, { timestamps: true } ); diff --git a/server/src/init/routes.ts b/server/src/init/routes.ts index ae245207b..a507b25e6 100644 --- a/server/src/init/routes.ts +++ b/server/src/init/routes.ts @@ -16,6 +16,7 @@ import { ProfileRoutes, IncidentsRoutes, SettingsRoutes, + MeRoutes, } from "@/routes/index.js"; import { errorHandler } from "@/middleware/ErrorHandler.js"; export const initRoutes = (controllers: any, app: Express) => { @@ -46,6 +47,7 @@ export const initRoutes = (controllers: any, app: Express) => { const profileRoutes = new ProfileRoutes(controllers.profileController); const incidentsRoutes = new IncidentsRoutes(controllers.incidentsController); const settingsRoutes = new SettingsRoutes(controllers.settingsController); + const meRoutes = new MeRoutes(); app.use("/api/v1/auth", authRoutes.getRouter()); app.use("/api/v1/invite", inviteRoutes.getRouter()); @@ -66,5 +68,6 @@ export const initRoutes = (controllers: any, app: Express) => { app.use("/api/v1/profile", profileRoutes.getRouter()); app.use("/api/v1/incidents", incidentsRoutes.getRouter()); app.use("/api/v1/settings", settingsRoutes.getRouter()); + app.use("/api/v1/me", meRoutes.getRouter()); app.use(errorHandler); }; diff --git a/server/src/middleware/AddUserContext.ts b/server/src/middleware/AddUserContext.ts index 9ea842677..bbd3c7db9 100644 --- a/server/src/middleware/AddUserContext.ts +++ b/server/src/middleware/AddUserContext.ts @@ -1,7 +1,10 @@ import { Request, Response, NextFunction } from "express"; import { OrgMembership, TeamMembership, IRole } from "@/db/models/index.js"; import ApiError from "@/utils/ApiError.js"; - +import { EntitlementsFactory } from "@/services/system/EntitlementsService.js"; +import type { Entitlements } from "@/types/entitlements.js"; +import { getChildLogger } from "@/logger/Logger.js"; +const logger = getChildLogger("AddUserContext"); interface IRolesObj { orgRole?: IRole; teamRole: IRole; @@ -145,6 +148,11 @@ export const addUserContext = async ( }; req.user.currentTeamId = currentTeamId; + // Attach entitlements for the org + const provider = EntitlementsFactory.create(); + const entitlements: Entitlements = await provider.getForOrg(orgId); + req.entitlements = entitlements; + return next(); } catch (error) { next(error); diff --git a/server/src/middleware/VerifyEntitlements.ts b/server/src/middleware/VerifyEntitlements.ts new file mode 100644 index 000000000..7662b79fb --- /dev/null +++ b/server/src/middleware/VerifyEntitlements.ts @@ -0,0 +1,85 @@ +import type { Request, Response, NextFunction } from "express"; +import ApiError from "@/utils/ApiError.js"; +import type { Entitlements } from "@/types/entitlements.js"; + +type BooleanKeys = { + [K in keyof T]-?: T[K] extends boolean ? K : never; +}[keyof T]; + +type NumberKeys = { + [K in keyof T]-?: T[K] extends number ? K : never; +}[keyof T]; + +const getEntitlements = (req: Request): Entitlements | undefined => { + return (req as any).entitlements as Entitlements | undefined; +}; + +export const requireFeature = (flag: BooleanKeys) => { + return (req: Request, _res: Response, next: NextFunction) => { + const ent = getEntitlements(req); + if (!ent) return next(new ApiError("Entitlements unavailable", 500)); + if (!ent[flag]) + return next(new ApiError("Feature not available on plan", 403)); + return next(); + }; +}; + +export const enforceMax = ( + key: NumberKeys, + countFn: (req: Request) => Promise +) => { + return async (req: Request, _res: Response, next: NextFunction) => { + try { + const ent = getEntitlements(req); + if (!ent) return next(new ApiError("Entitlements unavailable", 500)); + const max = ent[key] as unknown as number; + const used = await countFn(req); + if (typeof max === "number" && used >= max) { + return next(new ApiError("Plan limit reached", 403)); + } + return next(); + } catch (err) { + return next(err); + } + }; +}; + +export const enforceMinInterval = ( + key: NumberKeys, + readInterval: (req: Request) => number +) => { + return (req: Request, _res: Response, next: NextFunction) => { + const ent = getEntitlements(req); + if (!ent) return next(new ApiError("Entitlements unavailable", 500)); + const min = ent[key] as unknown as number; + const value = readInterval(req); + if (typeof min === "number" && (typeof value !== "number" || value < min)) { + return next( + new ApiError( + `Minimum interval for your plan is ${min / 1000} seconds`, + 400 + ) + ); + } + return next(); + }; +}; + +export const enforceRetentionBounds = ( + key: NumberKeys, + readDays: (req: Request) => number +) => { + return (req: Request, _res: Response, next: NextFunction) => { + const ent = getEntitlements(req); + if (!ent) return next(new ApiError("Entitlements unavailable", 500)); + const maxDays = ent[key] as unknown as number; + const requested = readDays(req); + if ( + typeof maxDays === "number" && + (typeof requested !== "number" || requested > maxDays) + ) { + return next(new ApiError(`Maximum retention is ${maxDays} days`, 403)); + } + return next(); + }; +}; diff --git a/server/src/routes/index.ts b/server/src/routes/index.ts index d1fe3a4e1..50f944c3f 100644 --- a/server/src/routes/index.ts +++ b/server/src/routes/index.ts @@ -14,3 +14,4 @@ export { default as RecoveryRoutes } from "./recovery.js"; export { default as ProfileRoutes } from "./profile.js"; export { default as IncidentsRoutes } from "./incidents.js"; export { default as SettingsRoutes } from "./settings.js"; +export { default as MeRoutes } from "./me.js"; diff --git a/server/src/routes/me.ts b/server/src/routes/me.ts new file mode 100644 index 000000000..ff7e41bcf --- /dev/null +++ b/server/src/routes/me.ts @@ -0,0 +1,29 @@ +import { Router } from "express"; +import { verifyToken } from "@/middleware/VerifyToken.js"; +import { addUserContext } from "@/middleware/AddUserContext.js"; + +class MeRoutes { + private router; + constructor() { + this.router = Router(); + this.initRoutes(); + } + + initRoutes = () => { + this.router.get( + "/entitlements", + verifyToken, + addUserContext, + (req, res) => { + const entitlements = req.entitlements || {}; + return res.json({ entitlements }); + } + ); + }; + + getRouter() { + return this.router; + } +} + +export default MeRoutes; diff --git a/server/src/routes/monitors.ts b/server/src/routes/monitors.ts index c5eb0500e..df1c9fd9c 100644 --- a/server/src/routes/monitors.ts +++ b/server/src/routes/monitors.ts @@ -8,6 +8,11 @@ import { import { addUserContext } from "@/middleware/AddUserContext.js"; import { PERMISSIONS } from "@/services/business/AuthService.js"; import { validateBody, validateQuery } from "@/middleware/validation.js"; +import { + enforceMax, + enforceMinInterval, +} from "@/middleware/VerifyEntitlements.js"; +import { Monitor } from "@/db/models/index.js"; import { monitorSchema, monitorIdChecksQuerySchema, @@ -31,7 +36,11 @@ class MonitorRoutes { verifyToken, addUserContext, verifyTeamPermission([PERMISSIONS.monitors.write]), + enforceMax("monitorsMax", async (req) => + Monitor.countDocuments({ orgId: req?.user?.orgId }) + ), validateBody(monitorSchema), + enforceMinInterval("checksIntervalMsMin", (req) => req.body.interval), this.controller.create ); diff --git a/server/src/routes/notificationChannels.ts b/server/src/routes/notificationChannels.ts index 6c7784ea3..f3df037bb 100644 --- a/server/src/routes/notificationChannels.ts +++ b/server/src/routes/notificationChannels.ts @@ -1,15 +1,17 @@ +import { NotificationChannel } from "@/db/models/index.js"; import { Router } from "express"; import { NotificationChannelController } from "@/controllers/index.js"; import { verifyToken } from "@/middleware/VerifyToken.js"; import { verifyTeamPermission } from "@/middleware/VerifyPermission.js"; import { addUserContext } from "@/middleware/AddUserContext.js"; import { PERMISSIONS } from "@/services/business/AuthService.js"; -import { validateBody, validateQuery } from "@/middleware/validation.js"; +import { validateBody } from "@/middleware/validation.js"; +import { enforceMax } from "@/middleware/VerifyEntitlements.js"; import { notificationChannelSchema, notificationPatchSchema, } from "@/validation/index.js"; - +import type { Request } from "express"; class NotificationChannelRoutes { private router; private controller; @@ -25,6 +27,9 @@ class NotificationChannelRoutes { verifyToken, addUserContext, verifyTeamPermission([PERMISSIONS.notifications.write]), + enforceMax("notificationChannelsMax", async (req: Request) => + NotificationChannel.countDocuments({ orgId: req?.user?.orgId }) + ), validateBody(notificationChannelSchema), this.controller.create ); diff --git a/server/src/routes/statusPages.ts b/server/src/routes/statusPages.ts index dcfb016a7..4b7f8a990 100644 --- a/server/src/routes/statusPages.ts +++ b/server/src/routes/statusPages.ts @@ -1,4 +1,5 @@ import { Router } from "express"; +import { StatusPage } from "@/db/models/index.js"; import { StatusPageController } from "@/controllers/index.js"; import { verifyToken } from "@/middleware/VerifyToken.js"; import { verifyTeamPermission } from "@/middleware/VerifyPermission.js"; @@ -6,6 +7,7 @@ import { addUserContext } from "@/middleware/AddUserContext.js"; import { PERMISSIONS } from "@/services/business/AuthService.js"; import { validateBody } from "@/middleware/validation.js"; import { statusPageSchema } from "@/validation/index.js"; +import { enforceMax } from "@/middleware/VerifyEntitlements.js"; class StatusPageRoutes { private router; @@ -22,7 +24,11 @@ class StatusPageRoutes { verifyToken, addUserContext, verifyTeamPermission([PERMISSIONS.statusPages.write]), + enforceMax("statusPageMax", async (req) => + StatusPage.countDocuments({ orgId: req?.user?.orgId }) + ), validateBody(statusPageSchema), + this.controller.create ); diff --git a/server/src/routes/team.ts b/server/src/routes/team.ts index 83c9281ca..444e27893 100644 --- a/server/src/routes/team.ts +++ b/server/src/routes/team.ts @@ -1,9 +1,11 @@ +import { Team } from "@/db/models/index.js"; import { Router } from "express"; import { TeamController } from "@/controllers/index.js"; import { verifyToken } from "@/middleware/VerifyToken.js"; import { addUserContext } from "@/middleware/AddUserContext.js"; import { verifyOrgPermission } from "@/middleware/VerifyPermission.js"; +import { enforceMax } from "@/middleware/VerifyEntitlements.js"; import { PERMISSIONS } from "@/services/business/AuthService.js"; class TeamRoutes { @@ -21,6 +23,9 @@ class TeamRoutes { verifyToken, addUserContext, verifyOrgPermission([PERMISSIONS.teams.write]), + enforceMax("teamsMax", async (req) => + Team.countDocuments({ orgId: req?.user?.orgId }) + ), this.controller.create ); diff --git a/server/src/services/system/EntitlementsService.ts b/server/src/services/system/EntitlementsService.ts new file mode 100644 index 000000000..70c7628f8 --- /dev/null +++ b/server/src/services/system/EntitlementsService.ts @@ -0,0 +1,38 @@ +import { Entitlements, Plans } from "@/types/entitlements.js"; +import { Org } from "@/db/models/index.js"; + +export interface IEntitlementsProvider { + getForOrg(orgId: string): Promise; +} + +export class SaaSEntitlementsProvider implements IEntitlementsProvider { + async getForOrg(orgId: string): Promise { + const org = await Org.findById(orgId).lean(); + + const plan = org?.planKey ?? "free"; + switch (plan) { + case "pro": + return Plans.pro; + case "business": + return Plans.business; + case "enterprise": + return Plans.enterprise; + default: + return Plans.free; + } + } +} + +export class SelfHostedEntitlementsProvider implements IEntitlementsProvider { + async getForOrg(_orgId: string): Promise { + return Plans.unlimited; + } +} + +export class EntitlementsFactory { + static create(): IEntitlementsProvider { + const mode = (process.env.DEPLOYMENT_MODE || "saas").toLowerCase(); + if (mode === "self") return new SelfHostedEntitlementsProvider(); + return new SaaSEntitlementsProvider(); + } +} diff --git a/server/src/types/entitlements.ts b/server/src/types/entitlements.ts new file mode 100644 index 000000000..d8f7c114f --- /dev/null +++ b/server/src/types/entitlements.ts @@ -0,0 +1,65 @@ +export type PlanKey = "free" | "pro" | "business" | "enterprise" | "unlimited"; + +export interface Entitlements { + plan: PlanKey; + monitorsMax: number; + notificationChannelsMax: number; + statusPageMax: number; + checksIntervalMsMin: number; + teamsMax: number; + notificationsEnabled: boolean; + retentionDays: number; +} + +export const Plans: Record = { + free: { + plan: "free", + monitorsMax: 5, + notificationChannelsMax: 2, + statusPageMax: 2, + checksIntervalMsMin: 60_000, + teamsMax: 2, + notificationsEnabled: true, + retentionDays: 30, + }, + pro: { + plan: "pro", + monitorsMax: 50, + notificationChannelsMax: 5, + statusPageMax: 5, + checksIntervalMsMin: 30_000, + teamsMax: 5, + notificationsEnabled: true, + retentionDays: 90, + }, + business: { + plan: "business", + monitorsMax: 200, + notificationChannelsMax: 20, + statusPageMax: 20, + checksIntervalMsMin: 15_000, + teamsMax: 10, + notificationsEnabled: true, + retentionDays: 180, + }, + enterprise: { + plan: "enterprise", + monitorsMax: 5000, + notificationChannelsMax: 100, + statusPageMax: 100, + checksIntervalMsMin: 10_000, + teamsMax: 20, + notificationsEnabled: true, + retentionDays: 365, + }, + unlimited: { + plan: "unlimited", + monitorsMax: Number.MAX_SAFE_INTEGER, + notificationChannelsMax: Number.MAX_SAFE_INTEGER, + statusPageMax: Number.MAX_SAFE_INTEGER, + checksIntervalMsMin: 1000, + teamsMax: Number.MAX_SAFE_INTEGER, + notificationsEnabled: true, + retentionDays: 365, + }, +}; diff --git a/server/src/types/express.d.ts b/server/src/types/express.d.ts index 42b616791..b53b5e35a 100644 --- a/server/src/types/express.d.ts +++ b/server/src/types/express.d.ts @@ -1,11 +1,12 @@ -import { IUserContext } from "../db/models/index.ts"; - +import { IUserContext } from "@/db/models/index.ts"; +import type { Entitlements } from "@/types/entitlements.ts"; declare global { namespace Express { interface Request { user?: IUserContext; resource?: any; validatedQuery: Record; + entitlements?: Entitlements; } } }