protect routes and import function

This commit is contained in:
Alex Holliday committed 2025-11-29 19:24:08 +00:00
1 parent e600f293b0
commit f476a57748
12 files changed
+112 -28

No files matched your search

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