entitlementsBE

This commit is contained in:
Alex Holliday committed 2025-11-28 21:31:44 +00:00
1 parent 86ce30b5f4
commit c43241eb52
13 files changed
+319 -5

No files matched your search

+59
View File
@@ -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<IOrg>(
{
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 }
);
+3
View File
@@ -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);
};
+9 -1
View File
@@ -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);
@@ -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<T> = {
[K in keyof T]-?: T[K] extends boolean ? K : never;
}[keyof T];
type NumberKeys<T> = {
[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<Entitlements>) => {
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<Entitlements>,
countFn: (req: Request) => Promise<number>
) => {
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<Entitlements>,
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<Entitlements>,
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();
};
};
+1
View File
@@ -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";
+29
View File
@@ -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;
+9
View File
@@ -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
);
+7 -2
View File
@@ -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
);
+6
View File
@@ -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
);
+5
View File
@@ -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
);
@@ -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<Entitlements>;
}
export class SaaSEntitlementsProvider implements IEntitlementsProvider {
async getForOrg(orgId: string): Promise<Entitlements> {
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<Entitlements> {
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();
}
}
+65
View File
@@ -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<PlanKey, Entitlements> = {
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,
},
};
+3 -2
View File
@@ -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<string, any>;
entitlements?: Entitlements;
}
}
}