diff --git a/server/src/controllers/AuthController.ts b/server/src/controllers/AuthController.ts index 536c981e2..ba614380d 100644 --- a/server/src/controllers/AuthController.ts +++ b/server/src/controllers/AuthController.ts @@ -3,7 +3,6 @@ import { encode, decode } from "@/utils/JWTUtils.js"; import AuthService from "@/services/business/AuthService.js"; import ApiError from "@/utils/ApiError.js"; import InviteService from "@/services/business/InviteService.js"; -import { registerSchema } from "@/validation/index.js"; class AuthController { private authService: AuthService; private inviteService: InviteService; diff --git a/server/src/controllers/MonitorController.ts b/server/src/controllers/MonitorController.ts index 0fb203a50..f158d78c6 100644 --- a/server/src/controllers/MonitorController.ts +++ b/server/src/controllers/MonitorController.ts @@ -395,17 +395,27 @@ class MonitorController { throw new ApiError("No organization ID", 400); } - const result = await this.monitorService.import( + const entitlements = req.entitlements; + if (!entitlements) { + throw new ApiError("Entitlements not found", 500); + } + + const result: any = await this.monitorService.import( orgId, teamId, userContext.sub, + entitlements, req.body ); + const defaultMessageMap: Record = { + OK: `Imported ${result.imported} monitors`, + PARTIAL: `Imported ${result.imported} monitors, ${result.errors} skipped`, + NO_CAPACITY: `No capacity available. ${result.attempted} skipped`, + UNEXPECTED: `Import failed unexpectedly`, + }; - res.status(200).json({ - message: `Import request received. ${result.imported} successfully inserted, ${result.errors} failed`, - data: result, - }); + const message = result?.message || defaultMessageMap[result?.code] || "Import completed"; + res.status(result?.status ?? 200).json({ message, data: result }); try { } catch (error) { diff --git a/server/src/db/models/auth/Org.ts b/server/src/db/models/auth/Org.ts index 698d4fd23..c5ad73290 100644 --- a/server/src/db/models/auth/Org.ts +++ b/server/src/db/models/auth/Org.ts @@ -1,3 +1,4 @@ +import { PlanKey } from "@/types/entitlements.js"; import mongoose, { Schema, Document, Types } from "mongoose"; export type SubscriptionStatus = | "active" @@ -25,10 +26,11 @@ export interface IOrg extends Document { cancelAtPeriodEnd?: boolean; // Cached entitlements - entitlements?: { + entitlements: { + plan: PlanKey; monitorsMax: number; notificationChannelsMax: number; - statusPageMax: number; + statusPagesMax: number; checksIntervalMsMin: number; teamsMax: number; notificationsEnabled: boolean; @@ -62,9 +64,10 @@ const orgSchema = new Schema( trialEnd: { type: Date }, cancelAtPeriodEnd: { type: Boolean }, entitlements: { + plan: { type: String }, monitorsMax: { type: Number }, notificationChannelsMax: { type: Number }, - statusPageMax: { type: Number }, + statusPagesMax: { type: Number }, checksIntervalMsMin: { type: Number }, teamsMax: { type: Number }, notificationsEnabled: { type: Boolean }, diff --git a/server/src/db/models/auth/User.ts b/server/src/db/models/auth/User.ts index 1fea4930c..9e924cccf 100644 --- a/server/src/db/models/auth/User.ts +++ b/server/src/db/models/auth/User.ts @@ -1,5 +1,6 @@ import mongoose, { Schema, Document, Types } from "mongoose"; import { IRole, ITeam } from "@/db/models/index.js"; +import { Entitlements } from "@/types/entitlements.js"; export interface ITokenizedUser { sub: string; @@ -17,6 +18,7 @@ export interface IUserContext { orgRole?: IRole; teamRole: IRole; }; + entitlements: Entitlements; } export interface IUserReturnable { @@ -33,6 +35,7 @@ export interface IUserReturnable { name: string; permissions: string[]; }[]; + entitlements: Entitlements; } export interface IUser extends Document { diff --git a/server/src/middleware/AddUserContext.ts b/server/src/middleware/AddUserContext.ts index bbd3c7db9..7a6dda115 100644 --- a/server/src/middleware/AddUserContext.ts +++ b/server/src/middleware/AddUserContext.ts @@ -152,7 +152,6 @@ export const addUserContext = async ( 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 index 7662b79fb..21a856b60 100644 --- a/server/src/middleware/VerifyEntitlements.ts +++ b/server/src/middleware/VerifyEntitlements.ts @@ -11,7 +11,7 @@ type NumberKeys = { }[keyof T]; const getEntitlements = (req: Request): Entitlements | undefined => { - return (req as any).entitlements as Entitlements | undefined; + return req.entitlements; }; export const requireFeature = (flag: BooleanKeys) => { diff --git a/server/src/routes/monitors.ts b/server/src/routes/monitors.ts index df1c9fd9c..394e3a4db 100644 --- a/server/src/routes/monitors.ts +++ b/server/src/routes/monitors.ts @@ -11,6 +11,7 @@ import { validateBody, validateQuery } from "@/middleware/validation.js"; import { enforceMax, enforceMinInterval, + requireFeature, } from "@/middleware/VerifyEntitlements.js"; import { Monitor } from "@/db/models/index.js"; import { @@ -86,6 +87,7 @@ class MonitorRoutes { PERMISSIONS.monitors.read, PERMISSIONS.notifications.read, ]), + requireFeature("notificationsEnabled"), this.controller.testNotifications ); @@ -111,6 +113,8 @@ class MonitorRoutes { addUserContext, verifyTeamPermission([PERMISSIONS.monitors.write]), validateBody(monitorPatchSchema), + enforceMinInterval("checksIntervalMsMin", (req) => req.body.interval), + this.controller.update ); diff --git a/server/src/routes/notificationChannels.ts b/server/src/routes/notificationChannels.ts index f3df037bb..f8e26809b 100644 --- a/server/src/routes/notificationChannels.ts +++ b/server/src/routes/notificationChannels.ts @@ -6,7 +6,7 @@ import { verifyTeamPermission } from "@/middleware/VerifyPermission.js"; import { addUserContext } from "@/middleware/AddUserContext.js"; import { PERMISSIONS } from "@/services/business/AuthService.js"; import { validateBody } from "@/middleware/validation.js"; -import { enforceMax } from "@/middleware/VerifyEntitlements.js"; +import { enforceMax, requireFeature } from "@/middleware/VerifyEntitlements.js"; import { notificationChannelSchema, notificationPatchSchema, @@ -27,6 +27,7 @@ class NotificationChannelRoutes { verifyToken, addUserContext, verifyTeamPermission([PERMISSIONS.notifications.write]), + requireFeature("notificationsEnabled"), enforceMax("notificationChannelsMax", async (req: Request) => NotificationChannel.countDocuments({ orgId: req?.user?.orgId }) ), @@ -47,6 +48,7 @@ class NotificationChannelRoutes { verifyToken, addUserContext, verifyTeamPermission([PERMISSIONS.notifications.write]), + requireFeature("notificationsEnabled"), this.controller.toggleActive ); @@ -55,6 +57,7 @@ class NotificationChannelRoutes { verifyToken, addUserContext, verifyTeamPermission([PERMISSIONS.notifications.update]), + requireFeature("notificationsEnabled"), validateBody(notificationPatchSchema), this.controller.update ); @@ -79,6 +82,7 @@ class NotificationChannelRoutes { verifyToken, addUserContext, verifyTeamPermission([PERMISSIONS.notifications.write]), + requireFeature("notificationsEnabled"), validateBody(notificationChannelSchema), this.controller.test ); diff --git a/server/src/routes/statusPages.ts b/server/src/routes/statusPages.ts index 4b7f8a990..98501ea63 100644 --- a/server/src/routes/statusPages.ts +++ b/server/src/routes/statusPages.ts @@ -24,7 +24,7 @@ class StatusPageRoutes { verifyToken, addUserContext, verifyTeamPermission([PERMISSIONS.statusPages.write]), - enforceMax("statusPageMax", async (req) => + enforceMax("statusPagesMax", async (req) => StatusPage.countDocuments({ orgId: req?.user?.orgId }) ), validateBody(statusPageSchema), diff --git a/server/src/services/business/AuthService.ts b/server/src/services/business/AuthService.ts index 34f9b614a..706cb3ce0 100644 --- a/server/src/services/business/AuthService.ts +++ b/server/src/services/business/AuthService.ts @@ -20,6 +20,7 @@ import { Types } from "mongoose"; import ApiError from "@/utils/ApiError.js"; import { IJobQueue } from "../infrastructure/JobQueue.js"; import { hashPassword } from "@/utils/JWTUtils.js"; +import { Plans } from "@/types/entitlements.js"; const SERVICE_NAME = "AuthService"; @@ -206,6 +207,7 @@ class AuthService implements IAuthService { permissions: orgRoles?.permissions || [], }, teams: returnableTeams, + entitlements: org.entitlements, }; return returnableUser; @@ -237,6 +239,8 @@ class AuthService implements IAuthService { const org = await Org.create({ name: `${user.firstName}'s Org`, ownerId: user._id, + planKey: "free", + entitlements: Plans["free"], }); created.org = org._id; @@ -339,6 +343,7 @@ class AuthService implements IAuthService { permissions: roles[0]?.permissions || [], }, teams: [returnableTeam], + entitlements: org.entitlements, }; return { tokenizedUser, returnableUser }; @@ -474,6 +479,7 @@ class AuthService implements IAuthService { permissions: orgPermissions, }, teams: returnableTeams, + entitlements: org.entitlements, }; return { @@ -522,12 +528,24 @@ class AuthService implements IAuthService { } // Find org and roles - const org = await Org.findById(orgMembership.orgId).lean(); + let org = await Org.findById(orgMembership.orgId).lean(); if (!org) { throw new ApiError("Organization not found"); } + // Update org entitlements + const planKey = org.entitlements.plan; + org = await Org.findOneAndUpdate( + { _id: org._id }, + { $set: { entitlements: Plans[planKey] } }, + { new: true } + ); + + if (!org) { + throw new ApiError("Organization entitlement error"); + } + const orgRoles = await Role.findById(orgMembership.roleId).lean(); // Get teams @@ -567,6 +585,7 @@ class AuthService implements IAuthService { permissions: orgRoles?.permissions || [], }, teams: returnableTeams, + entitlements: org.entitlements, }; return { diff --git a/server/src/services/business/MonitorService.ts b/server/src/services/business/MonitorService.ts index a961c4a02..2c3f05b6c 100644 --- a/server/src/services/business/MonitorService.ts +++ b/server/src/services/business/MonitorService.ts @@ -5,6 +5,7 @@ import ApiError from "@/utils/ApiError.js"; import { IJobQueue } from "@/services/infrastructure/JobQueue.js"; import { MonitorWithChecksResponse } from "@/types/index.js"; import { MonitorStatus, MonitorType } from "@/db/models/monitors/Monitor.js"; +import { Entitlements } from "@/types/entitlements.js"; export interface IImportedMonitor { name: string; @@ -65,6 +66,7 @@ export interface IMonitorService { orgId: string, teamId: string, userId: string, + entitlements: Entitlements, data: { monitors: Array } ) => Promise<{ imported: number; errors: number }>; } @@ -686,12 +688,35 @@ class MonitorService implements IMonitorService { orgId: string, teamId: string, userId: string, + entitlements: Entitlements, data: { monitors: Array } ) => { - let result = []; + const attempted = Array.isArray(data?.monitors) ? data.monitors.length : 0; + let result: IMonitor[] = []; + let canImport = 0; try { + // Get current count + const monitorCount = await Monitor.countDocuments({ orgId }); + + // Check limits, return NO_CAPACITY if at limit + if (monitorCount >= entitlements.monitorsMax) { + return { + ok: true, + status: 200, + code: "NO_CAPACITY", + attempted, + eligible: 0, + imported: 0, + errors: attempted, + } as any; + } + + // Proceed with import + canImport = entitlements.monitorsMax - monitorCount; + const importableMonitors = data?.monitors.slice(0, canImport); + result = await Monitor.insertMany( - data?.monitors.map((monitor) => ({ + importableMonitors.map((monitor) => ({ ...monitor, orgId: new mongoose.Types.ObjectId(orgId), teamId: new mongoose.Types.ObjectId(teamId), @@ -703,14 +728,32 @@ class MonitorService implements IMonitorService { for (const monitor of result) { await this.jobQueue.addJob(monitor); } - } catch (error) { - console.error("Import error:", error); + } catch (error: any) { + return { + ok: false, + status: 500, + code: "UNEXPECTED", + attempted, + eligible: canImport, + imported: result.length, + errors: Math.max(0, attempted - result.length), + message: error.message, + } as any; } + const imported = result.length; + const errors = Math.max(0, attempted - imported); + const code = imported === attempted ? "OK" : "PARTIAL"; + const status = imported === attempted ? 200 : 207; return { - imported: result.length, - errors: data?.monitors?.length - result.length, - }; + ok: true, + status, + code, + attempted, + eligible: canImport, + imported, + errors, + } as any; }; } diff --git a/server/src/types/entitlements.ts b/server/src/types/entitlements.ts index d8f7c114f..f69b489a8 100644 --- a/server/src/types/entitlements.ts +++ b/server/src/types/entitlements.ts @@ -4,7 +4,7 @@ export interface Entitlements { plan: PlanKey; monitorsMax: number; notificationChannelsMax: number; - statusPageMax: number; + statusPagesMax: number; checksIntervalMsMin: number; teamsMax: number; notificationsEnabled: boolean; @@ -14,9 +14,9 @@ export interface Entitlements { export const Plans: Record = { free: { plan: "free", - monitorsMax: 5, + monitorsMax: 3, notificationChannelsMax: 2, - statusPageMax: 2, + statusPagesMax: 2, checksIntervalMsMin: 60_000, teamsMax: 2, notificationsEnabled: true, @@ -26,7 +26,7 @@ export const Plans: Record = { plan: "pro", monitorsMax: 50, notificationChannelsMax: 5, - statusPageMax: 5, + statusPagesMax: 5, checksIntervalMsMin: 30_000, teamsMax: 5, notificationsEnabled: true, @@ -36,7 +36,7 @@ export const Plans: Record = { plan: "business", monitorsMax: 200, notificationChannelsMax: 20, - statusPageMax: 20, + statusPagesMax: 20, checksIntervalMsMin: 15_000, teamsMax: 10, notificationsEnabled: true, @@ -46,7 +46,7 @@ export const Plans: Record = { plan: "enterprise", monitorsMax: 5000, notificationChannelsMax: 100, - statusPageMax: 100, + statusPagesMax: 100, checksIntervalMsMin: 10_000, teamsMax: 20, notificationsEnabled: true, @@ -56,7 +56,7 @@ export const Plans: Record = { plan: "unlimited", monitorsMax: Number.MAX_SAFE_INTEGER, notificationChannelsMax: Number.MAX_SAFE_INTEGER, - statusPageMax: Number.MAX_SAFE_INTEGER, + statusPagesMax: Number.MAX_SAFE_INTEGER, checksIntervalMsMin: 1000, teamsMax: Number.MAX_SAFE_INTEGER, notificationsEnabled: true,