From 4da6ff7516c8530a54ade9ddc7fbe17b6e0ef61a Mon Sep 17 00:00:00 2001 From: li4nee Date: Mon, 13 Jul 2026 10:41:35 +0545 Subject: [PATCH] feat(auth): add email verification and password reset functionality - Introduced VerifyEmailDTO for email verification requests. - Updated user repository to exclude sensitive fields from queries. - Enhanced auth routes to include signup, resend verification email, and verify email endpoints. - Implemented email verification logic in AuthService, including token generation and sending verification emails. - Added password reset functionality with token generation and email notifications. - Created utility functions for building email templates and sending emails via Resend API. - Implemented caching for API keys to improve performance and reduce database load. - Updated client service to handle user signup and client creation with email verification. - Added error handling for unverified email during login attempts. - Introduced new error types for better error management. --- server/docker-compose.yml | 16 +++ server/package-lock.json | 20 --- server/package.json | 5 +- .../services/channels/email.channel.ts | 110 +++++++++++++---- .../auth/contracts/IAuthService.contract.ts | 8 ++ .../auth/controllers/auth.controller.ts | 40 ++++++ server/src/modules/auth/dtos/emailOnly.dto.ts | 7 ++ .../modules/auth/dtos/resetPassword.dto.ts | 20 +++ .../src/modules/auth/dtos/userResponse.dto.ts | 2 + .../src/modules/auth/dtos/verifyEmail.dto.ts | 7 ++ server/src/modules/auth/repos/user.repo.ts | 4 +- server/src/modules/auth/routes/auth.route.ts | 33 +++++ .../src/modules/auth/services/auth.service.ts | 100 ++++++++++++++- .../contracts/IApiKeyService.contract.ts | 7 +- .../contracts/IClientService.contract.ts | 2 + .../client/controllers/client.controller.ts | 16 ++- .../client/dependencies/client.dependency.ts | 2 +- server/src/modules/client/dtos/signup.dto.ts | 26 ++++ .../modules/client/repos/apiKeyBase.repo.ts | 4 + .../src/modules/client/repos/apikey.repo.ts | 20 +++ .../modules/client/services/apiKey.service.ts | 43 +++++-- .../modules/client/services/client.service.ts | 115 ++++++++++++++++-- server/src/shared/config/global.config.ts | 24 ++-- server/src/shared/infra/cache/apiKeyCache.ts | 51 ++++++++ .../src/shared/infra/cache/authTokenCache.ts | 28 +++++ .../infra/db/mongo/models/user.model.ts | 5 + .../middleware/validateApiKey.middleware.ts | 15 +-- server/src/shared/typings/error.typings.ts | 11 ++ .../shared/utils/authEmailTemplates.utils.ts | 66 ++++++++++ .../shared/utils/emailVerification.utils.ts | 48 ++++++++ server/src/shared/utils/html.utils.ts | 8 ++ server/src/shared/utils/resendMailer.utils.ts | 52 ++++++++ 32 files changed, 815 insertions(+), 100 deletions(-) create mode 100644 server/src/modules/auth/dtos/emailOnly.dto.ts create mode 100644 server/src/modules/auth/dtos/resetPassword.dto.ts create mode 100644 server/src/modules/auth/dtos/verifyEmail.dto.ts create mode 100644 server/src/modules/client/dtos/signup.dto.ts create mode 100644 server/src/shared/infra/cache/apiKeyCache.ts create mode 100644 server/src/shared/infra/cache/authTokenCache.ts create mode 100644 server/src/shared/utils/authEmailTemplates.utils.ts create mode 100644 server/src/shared/utils/emailVerification.utils.ts create mode 100644 server/src/shared/utils/html.utils.ts create mode 100644 server/src/shared/utils/resendMailer.utils.ts diff --git a/server/docker-compose.yml b/server/docker-compose.yml index 2420087..77f1145 100644 --- a/server/docker-compose.yml +++ b/server/docker-compose.yml @@ -141,6 +141,22 @@ services: redis: condition: service_healthy + alerting-worker: + container_name: server-monitoring-alerting-worker + build: + context: . + dockerfile: Dockerfile.consumer + command: ["node", "dist/modules/alerting/worker/alertingWorkerStartup.js"] + env_file: .env + networks: + - website-monitoring-network + restart: unless-stopped + depends_on: + postgres: + condition: service_healthy + mongo: + condition: service_healthy + volumes: postgres_data: driver: local diff --git a/server/package-lock.json b/server/package-lock.json index 98bf006..a070c75 100644 --- a/server/package-lock.json +++ b/server/package-lock.json @@ -23,7 +23,6 @@ "kysely": "^0.28.17", "mongoose": "^9.2.1", "ms": "^2.1.3", - "nodemailer": "^8.0.7", "pg": "^8.18.0", "rate-limit-redis": "^5.0.0", "uuid": "^13.0.0", @@ -39,7 +38,6 @@ "@types/express": "^5.0.6", "@types/jsonwebtoken": "^9.0.10", "@types/node": "^25.3.0", - "@types/nodemailer": "^8.0.0", "@types/pg": "^8.16.0", "eslint": "^10.6.0", "eslint-config-prettier": "^10.1.8", @@ -1314,15 +1312,6 @@ "undici-types": "~7.18.0" } }, - "node_modules/@types/nodemailer": { - "version": "8.0.0", - "resolved": "https://registry.npmjs.org/@types/nodemailer/-/nodemailer-8.0.0.tgz", - "integrity": "sha512-fyf8jWULsCo0d0BuoQ75i6IeoHs47qcqxWc7yUdUcV0pOZGjUTTOvwdG1PRXUDqN/8A64yQdQdnA2pZgcdi+cA==", - "dev": true, - "dependencies": { - "@types/node": "*" - } - }, "node_modules/@types/pg": { "version": "8.16.0", "resolved": "https://registry.npmjs.org/@types/pg/-/pg-8.16.0.tgz", @@ -3578,15 +3567,6 @@ "node-gyp-build-test": "build-test.js" } }, - "node_modules/nodemailer": { - "version": "8.0.11", - "resolved": "https://registry.npmjs.org/nodemailer/-/nodemailer-8.0.11.tgz", - "integrity": "sha512-nrO/pDAUKl+wXX+lx16tDLbnm0fW6sK/x8mgohaCpg+CdCEl482bD4tCuAZk2DyliruiNTIZxRCoWkDqJEnAiA==", - "license": "MIT-0", - "engines": { - "node": ">=6.0.0" - } - }, "node_modules/nodemon": { "version": "3.1.14", "resolved": "https://registry.npmjs.org/nodemon/-/nodemon-3.1.14.tgz", diff --git a/server/package.json b/server/package.json index 5ef257a..cff0627 100644 --- a/server/package.json +++ b/server/package.json @@ -19,8 +19,7 @@ "dev:dlq": "nodemon --watch src --ext ts --exec ts-node src/modules/processor/dlqConsumerStartup.ts", "migrate": "ts-node scripts/migrate.ts up", "migrate:down": "ts-node scripts/migrate.ts down", - "sync-indexes": "ts-node scripts/syncMongoIndexes.ts", - "backfill-api-hit-expiry": "ts-node scripts/backfillApiHitExpiry.ts" + "sync-indexes": "ts-node scripts/syncMongoIndexes.ts" }, "keywords": [], "author": "", @@ -41,7 +40,6 @@ "kysely": "^0.28.17", "mongoose": "^9.2.1", "ms": "^2.1.3", - "nodemailer": "^8.0.7", "pg": "^8.18.0", "rate-limit-redis": "^5.0.0", "uuid": "^13.0.0", @@ -57,7 +55,6 @@ "@types/express": "^5.0.6", "@types/jsonwebtoken": "^9.0.10", "@types/node": "^25.3.0", - "@types/nodemailer": "^8.0.0", "@types/pg": "^8.16.0", "eslint": "^10.6.0", "eslint-config-prettier": "^10.1.8", diff --git a/server/src/modules/alerting/services/channels/email.channel.ts b/server/src/modules/alerting/services/channels/email.channel.ts index 86d024f..72b3a5d 100644 --- a/server/src/modules/alerting/services/channels/email.channel.ts +++ b/server/src/modules/alerting/services/channels/email.channel.ts @@ -1,34 +1,91 @@ -import nodemailer from "nodemailer"; import logger from "../../../../shared/config/logger.config"; import { globalConfig } from "../../../../shared/config/global.config"; +import { escapeHtml } from "../../../../shared/utils/html.utils"; +import { sendViaResend } from "../../../../shared/utils/resendMailer.utils"; import { IAlertChannel, DispatchPayload } from "./channel.interface"; export class EmailChannel implements IAlertChannel { readonly type = "email"; - private transport = nodemailer.createTransport({ - host: globalConfig.email.host, - port: globalConfig.email.port, - secure: globalConfig.email.secure, - auth: globalConfig.email.user ? { user: globalConfig.email.user, pass: globalConfig.email.pass } : undefined, - }); + private formatFiredAt(iso: string): string { + return new Date(iso).toLocaleString("en-US", { + dateStyle: "medium", + timeStyle: "short", + }); + } private buildHtml(payload: DispatchPayload): string { - const statsLine = `Hits: ${payload.stats.total_hits} | Errors: ${payload.stats.total_errors} | Error Rate: ${payload.stats.error_rate}% | Avg Latency: ${payload.stats.avg_latency}ms`; - const reasonsList = payload.reasons.map((r) => `
  • ${r}
  • `).join(""); + const esc = (v: string) => escapeHtml(v); + const alertTypeLabel = payload.alert.alertType.replace(/_/g, " "); + + const stat = (label: string, value: string) => ` + +
    ${label}
    +
    ${value}
    + `; + + const reasonsList = payload.reasons.map((r) => `
  • ${esc(r)}
  • `).join(""); return ` -

    Alert Fired: ${payload.alert.name}

    - - - - - - -
    Alert ID${payload.alert.id}
    Alert Type${payload.alert.alertType}
    Client ID${payload.alert.clientId}
    Fired At${payload.firedAt}
    Stats${statsLine}
    -

    Reasons

    - - `; + + + + + + + + + + + + + + + + + + + + + + + +
     
    +
    + ⚠ Alert Fired +
    +

    ${esc(payload.alert.name)}

    +

    + ${esc(alertTypeLabel)} · fired ${esc(this.formatFiredAt(payload.firedAt))} +

    +
    + + + ${stat("Total Hits", String(payload.stats.total_hits))} + + ${stat("Errors", String(payload.stats.total_errors))} + + + + ${stat("Error Rate", `${payload.stats.error_rate}%`)} + + ${stat("Avg Latency", `${payload.stats.avg_latency}ms`)} + +
     
     
     
    +
    +
    +
    Why this fired
    +
      ${reasonsList}
    +
    +
    +

    + Alert ID ${esc(payload.alert.id)} +  ·  Client ${esc(payload.alert.clientId)}
    + Sent by ServerStats alerting +

    +
    + +`; } async dispatch(config: Record, payload: DispatchPayload): Promise { @@ -38,16 +95,23 @@ export class EmailChannel implements IAlertChannel { return; } + if (!globalConfig.email.resendApiKey) { + logger.warn("[EmailChannel] RESEND_API_KEY is not configured. Skipping."); + return; + } + + const toList = Array.isArray(to) ? to : [to]; const from = (config.from as string) || globalConfig.email.defaultFrom; const subject = (config.subject as string) || `Alert Fired: ${payload.alert.name}`; - await this.transport.sendMail({ + await sendViaResend({ + apiKey: globalConfig.email.resendApiKey, from, - to: Array.isArray(to) ? to.join(", ") : to, + to: toList, subject, html: this.buildHtml(payload), }); - logger.info(`[EmailChannel] Email dispatched to ${Array.isArray(to) ? to.join(", ") : to} for alert ${payload.alert.id}`); + logger.info(`[EmailChannel] Email dispatched via Resend to ${toList.join(", ")} for alert ${payload.alert.id}`); } } diff --git a/server/src/modules/auth/contracts/IAuthService.contract.ts b/server/src/modules/auth/contracts/IAuthService.contract.ts index f9aa7af..ec0391a 100644 --- a/server/src/modules/auth/contracts/IAuthService.contract.ts +++ b/server/src/modules/auth/contracts/IAuthService.contract.ts @@ -15,4 +15,12 @@ export interface IAuthService { isSuperAdmin(id: string): Promise; changePassword(userId: string, data: ChangePasswordDTOType): Promise; + + resendVerificationEmail(email: string): Promise; + + verifyEmail(token: string): Promise; + + forgotPassword(email: string): Promise; + + resetPassword(token: string, newPassword: string): Promise; } diff --git a/server/src/modules/auth/controllers/auth.controller.ts b/server/src/modules/auth/controllers/auth.controller.ts index ce878d6..e2036f3 100644 --- a/server/src/modules/auth/controllers/auth.controller.ts +++ b/server/src/modules/auth/controllers/auth.controller.ts @@ -78,4 +78,44 @@ export class AuthController { next(error); } } + + async resendVerificationEmail(req: Request, res: Response, next: NextFunction) { + try { + await this.authService.resendVerificationEmail(req.body.email); + return res + .status(200) + .json(ResponseFormatter.success("If that email exists and isn't verified yet, a new link has been sent.", 200, null)); + } catch (error) { + next(error); + } + } + + async verifyEmail(req: Request, res: Response, next: NextFunction) { + try { + await this.authService.verifyEmail(req.body.token); + return res.status(200).json(ResponseFormatter.success("Email verified successfully.", 200, null)); + } catch (error) { + next(error); + } + } + + async forgotPassword(req: Request, res: Response, next: NextFunction) { + try { + await this.authService.forgotPassword(req.body.email); + return res + .status(200) + .json(ResponseFormatter.success("If that email exists, a password reset link has been sent.", 200, null)); + } catch (error) { + next(error); + } + } + + async resetPassword(req: Request, res: Response, next: NextFunction) { + try { + await this.authService.resetPassword(req.body.token, req.body.newPassword); + return res.status(200).json(ResponseFormatter.success("Password reset successfully.", 200, null)); + } catch (error) { + next(error); + } + } } diff --git a/server/src/modules/auth/dtos/emailOnly.dto.ts b/server/src/modules/auth/dtos/emailOnly.dto.ts new file mode 100644 index 0000000..4c2ec5c --- /dev/null +++ b/server/src/modules/auth/dtos/emailOnly.dto.ts @@ -0,0 +1,7 @@ +import { z } from "zod"; + +export const EmailOnlyDTO = z.object({ + email: z.string().email("Please enter a valid email address"), +}); + +export type EmailOnlyDTOType = z.infer; diff --git a/server/src/modules/auth/dtos/resetPassword.dto.ts b/server/src/modules/auth/dtos/resetPassword.dto.ts new file mode 100644 index 0000000..0a03b0a --- /dev/null +++ b/server/src/modules/auth/dtos/resetPassword.dto.ts @@ -0,0 +1,20 @@ +import { z } from "zod"; + +export const ResetPasswordDTO = z + .object({ + token: z.string().min(1, "Token is required"), + newPassword: z + .string() + .min(8, "Password must be at least 8 characters") + .regex( + /^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)(?=.*[@$!%*?&])/, + "Password must contain uppercase, lowercase, number, and special character", + ), + confirmNewPassword: z.string().min(1, "Confirm password is required"), + }) + .refine((data) => data.newPassword === data.confirmNewPassword, { + message: "Passwords do not match", + path: ["confirmNewPassword"], + }); + +export type ResetPasswordDTOType = z.infer; diff --git a/server/src/modules/auth/dtos/userResponse.dto.ts b/server/src/modules/auth/dtos/userResponse.dto.ts index f4567fd..d49919e 100644 --- a/server/src/modules/auth/dtos/userResponse.dto.ts +++ b/server/src/modules/auth/dtos/userResponse.dto.ts @@ -7,12 +7,14 @@ export class UserResponseDto { username?: string; role: string; clientId?: string; + isEmailVerified: boolean; constructor(user: UserWithId) { this.id = user._id.toString(); this.email = user.email; this.username = user.username; this.role = user.role; + this.isEmailVerified = user.isEmailVerified ?? false; if (user.clientId) { this.clientId = user.clientId.toString(); } diff --git a/server/src/modules/auth/dtos/verifyEmail.dto.ts b/server/src/modules/auth/dtos/verifyEmail.dto.ts new file mode 100644 index 0000000..fdbaba8 --- /dev/null +++ b/server/src/modules/auth/dtos/verifyEmail.dto.ts @@ -0,0 +1,7 @@ +import { z } from "zod"; + +export const VerifyEmailDTO = z.object({ + token: z.string().min(1, "Token is required"), +}); + +export type VerifyEmailDTOType = z.infer; diff --git a/server/src/modules/auth/repos/user.repo.ts b/server/src/modules/auth/repos/user.repo.ts index 5527043..e55b2e9 100644 --- a/server/src/modules/auth/repos/user.repo.ts +++ b/server/src/modules/auth/repos/user.repo.ts @@ -86,7 +86,9 @@ export class MongoUserRepo extends UserBaseRepo { .find(filter) .sort({ _id: -1 }) .limit(safeLimit + 1) - .select("-password -__v"); + .select( + "-password -__v -emailVerificationTokenHash -emailVerificationTokenExpiresAt -passwordResetTokenHash -passwordResetTokenExpiresAt", + ); let nextCursor: string | undefined; let data: UserWithId[]; diff --git a/server/src/modules/auth/routes/auth.route.ts b/server/src/modules/auth/routes/auth.route.ts index 1e079f7..657d3ba 100644 --- a/server/src/modules/auth/routes/auth.route.ts +++ b/server/src/modules/auth/routes/auth.route.ts @@ -1,5 +1,6 @@ import { NextFunction, Router } from "express"; import AuthDependenciesContainer from "../dependencies/auth.dependecy"; +import ClientDependeniesContainer from "../../client/dependencies/client.dependency"; import { validateBody } from "../../../shared/middleware/zodValidators.middleware"; import { RegistrationDTO, SuperAdminOnboardingDto } from "../dtos/onboarding.dto"; import { Response } from "express"; @@ -11,9 +12,14 @@ import { USER_ROLE } from "../../../shared/typings/auth.typings"; import { LoginDTO } from "../dtos/sessionManagement.dto"; import { authRateLimiter } from "../../../shared/infra/resilience/rateLimit.infra"; import { ChangePasswordDTO } from "../dtos/changePassword.dto"; +import { EmailOnlyDTO } from "../dtos/emailOnly.dto"; +import { VerifyEmailDTO } from "../dtos/verifyEmail.dto"; +import { ResetPasswordDTO } from "../dtos/resetPassword.dto"; +import { SignupDTO } from "../../client/dtos/signup.dto"; const router = Router(); const { authController } = AuthDependenciesContainer.init().controllers; +const { clientController } = ClientDependeniesContainer.init().controllers; router.post( "/onboard-super-admin", @@ -22,6 +28,14 @@ router.post( (req: Request, res: Response, next: NextFunction) => authController.onboardSuperAdmin(req, res, next), ); +/** + * Public signup for new companies. + * Creates the tenant and its first admin user. + */ +router.post("/signup", authRateLimiter, validateBody(SignupDTO), (req: Request, res: Response, next: NextFunction) => + clientController.signup(req, res, next), +); + router.post( "/register", authenticate, @@ -45,4 +59,23 @@ router.patch( (req: Request, res: Response, next: NextFunction) => authController.changePassword(req, res, next), ); +router.post( + "/resend-verification-email", + authRateLimiter, + validateBody(EmailOnlyDTO), + (req: Request, res: Response, next: NextFunction) => authController.resendVerificationEmail(req, res, next), +); + +router.post("/verify-email", authRateLimiter, validateBody(VerifyEmailDTO), (req: Request, res: Response, next: NextFunction) => + authController.verifyEmail(req, res, next), +); + +router.post("/forgot-password", authRateLimiter, validateBody(EmailOnlyDTO), (req: Request, res: Response, next: NextFunction) => + authController.forgotPassword(req, res, next), +); + +router.post("/reset-password", authRateLimiter, validateBody(ResetPasswordDTO), (req: Request, res: Response, next: NextFunction) => + authController.resetPassword(req, res, next), +); + export default router; diff --git a/server/src/modules/auth/services/auth.service.ts b/server/src/modules/auth/services/auth.service.ts index 9907958..94a4223 100644 --- a/server/src/modules/auth/services/auth.service.ts +++ b/server/src/modules/auth/services/auth.service.ts @@ -1,6 +1,8 @@ +import crypto from "crypto"; import { globalConfig } from "../../../shared/config/global.config"; import { User, UserDocument, UserWithId } from "../../../shared/infra/db/mongo/models/user.model"; import { + EmailNotVerifiedError, InvalidInputError, PermissionNotGranted, ResourceNotFoundError, @@ -14,6 +16,12 @@ import { ChangePasswordDTOType } from "../dtos/changePassword.dto"; import { PasswordUtils } from "../../../shared/utils/password.utils"; import { IPasswordUtils, JwtConfig, USER_ROLE } from "../../../shared/typings/auth.typings"; import { UserResponseDto } from "../dtos/userResponse.dto"; +import { issueAndSendVerificationEmail, hashVerificationOrResetToken } from "../../../shared/utils/emailVerification.utils"; +import { sendViaResend } from "../../../shared/utils/resendMailer.utils"; +import { buildPasswordResetEmailHtml } from "../../../shared/utils/authEmailTemplates.utils"; +import { AuthTokenCache, EMAIL_VERIFICATION_TOKEN_PREFIX, PASSWORD_RESET_TOKEN_PREFIX } from "../../../shared/infra/cache/authTokenCache"; + +const PASSWORD_RESET_TOKEN_TTL_SECONDS = 60 * 60; // 1 hour type UniqueCheck = "email" | "username" | "both"; @@ -104,10 +112,13 @@ export class AuthService { async onboardSuperAdmin(superAdminData: Partial): Promise<{ user: UserResponseDto; token: string }> { try { - const user = await this.createUser(superAdminData, { - uniqueBy: "email", - isSuperAdmin: true, - }); + const user = await this.createUser( + { ...superAdminData, isEmailVerified: true }, + { + uniqueBy: "email", + isSuperAdmin: true, + }, + ); const token = this.generateToken(user); @@ -134,6 +145,8 @@ export class AuthService { uniqueBy: "both", }); + void issueAndSendVerificationEmail(user); + return new UserResponseDto(user); } catch (error) { logger.error("User registration failed", { error }); @@ -162,6 +175,11 @@ export class AuthService { throw new PermissionNotGranted("Invalid email or password."); } + if (!user.isEmailVerified) { + logger.warn(`Unverified login attempt: ${loginData.email}`); + throw new EmailNotVerifiedError(); + } + const token = this.generateToken(user as UserWithId); logger.info(`User logged in: ${user.email}`); @@ -211,4 +229,78 @@ export class AuthService { throw error; } } + + async resendVerificationEmail(email: string): Promise { + const user = await this.userRepo.findByEmail(email, true); + if (!user) return; + + const full = await this.userRepo.findById(user._id.toString()); + if (!full || full.isEmailVerified) return; + + await issueAndSendVerificationEmail(full); + } + + async verifyEmail(token: string): Promise { + const tokenHash = hashVerificationOrResetToken(token); + const userId = await AuthTokenCache.consume(EMAIL_VERIFICATION_TOKEN_PREFIX, tokenHash); + + if (!userId) { + throw new InvalidInputError("This verification link is invalid or has expired."); + } + + await this.userRepo.update(userId, { isEmailVerified: true }); + + logger.info(`[AuthService] Email verified for user: ${userId}`); + } + + /** + * Always resolves without revealing whether the email exists, to avoid account enumeration. + */ + async forgotPassword(email: string): Promise { + const user = await this.userRepo.findByEmail(email, true); + if (!user) return; + + try { + const rawToken = crypto.randomBytes(32).toString("hex"); + const tokenHash = hashVerificationOrResetToken(rawToken); + + await AuthTokenCache.store(PASSWORD_RESET_TOKEN_PREFIX, tokenHash, user._id.toString(), PASSWORD_RESET_TOKEN_TTL_SECONDS); + + if (!globalConfig.email.resendApiKey) { + logger.warn("[AuthService] RESEND_API_KEY is not configured. Skipping password reset email."); + return; + } + + const full = await this.userRepo.findById(user._id.toString()); + if (!full) return; + + const resetUrl = `${globalConfig.frontendUrl}/reset-password?token=${rawToken}`; + + await sendViaResend({ + apiKey: globalConfig.email.resendApiKey, + from: globalConfig.email.defaultFrom, + to: full.email, + subject: "Reset your ServerStats password", + html: buildPasswordResetEmailHtml(resetUrl), + }); + + logger.info(`[AuthService] Password reset email sent to ${full.email}`); + } catch (error) { + logger.error("[AuthService] Failed to send password reset email", { error, userId: user._id.toString() }); + } + } + + async resetPassword(token: string, newPassword: string): Promise { + const tokenHash = hashVerificationOrResetToken(token); + const userId = await AuthTokenCache.consume(PASSWORD_RESET_TOKEN_PREFIX, tokenHash); + + if (!userId) { + throw new InvalidInputError("This password reset link is invalid or has expired."); + } + + const hashed = await PasswordUtils.hashPassword(newPassword); + await this.userRepo.update(userId, { password: hashed }); + + logger.info(`[AuthService] Password reset for user: ${userId}`); + } } diff --git a/server/src/modules/client/contracts/IApiKeyService.contract.ts b/server/src/modules/client/contracts/IApiKeyService.contract.ts index 08c200b..41e2763 100644 --- a/server/src/modules/client/contracts/IApiKeyService.contract.ts +++ b/server/src/modules/client/contracts/IApiKeyService.contract.ts @@ -1,8 +1,8 @@ -import { Types } from "mongoose"; import { ApiKeyWithId } from "../../../shared/infra/db/mongo/models/apiKeys.model"; import { CreateApiKeyDtoType } from "../dtos/createApiKey.dto"; import { CreateApiKeyResponseDto } from "../dtos/createApiKeyResponse.dto"; import { UserInsideAuthorizedRequest } from "../../../shared/typings/auth.typings"; +import { ApiKeyLookupResult } from "../../../shared/infra/cache/apiKeyCache"; export interface IApiKeyService { createApiKeysForClient( @@ -19,10 +19,7 @@ export interface IApiKeyService { requestedBy: UserInsideAuthorizedRequest, ): Promise>; - getClientFromApiKey(apiKeyValue: string): Promise<{ - client: { _id: Types.ObjectId; name: string; slug: string; isActive: boolean }; - apiKeyDoc: ApiKeyWithId; - }>; + getClientFromApiKey(apiKeyValue: string): Promise; revokeApiKey(clientId: string, apiKeyId: string, requestedBy: UserInsideAuthorizedRequest): Promise; } diff --git a/server/src/modules/client/contracts/IClientService.contract.ts b/server/src/modules/client/contracts/IClientService.contract.ts index eaef007..f7c28c8 100644 --- a/server/src/modules/client/contracts/IClientService.contract.ts +++ b/server/src/modules/client/contracts/IClientService.contract.ts @@ -5,9 +5,11 @@ import { CreateClientDTOType } from "../dtos/createClient.dto"; import { CreateClientUserDTOType } from "../dtos/createClientUser.dto"; import { UpdateClientDTOType } from "../dtos/updateClient.dto"; import { UpdateUserPermissionsDTOType } from "../dtos/updateUser.dto"; +import { SignupDTOType } from "../dtos/signup.dto"; export interface IClientService { createClient(clientData: CreateClientDTOType, createdBy: string): Promise; + signup(data: SignupDTOType): Promise<{ client: Client; user: Omit }>; getClient(clientId: string, requestedBy: UserInsideAuthorizedRequest): Promise; listClients( requestedBy: UserInsideAuthorizedRequest, diff --git a/server/src/modules/client/controllers/client.controller.ts b/server/src/modules/client/controllers/client.controller.ts index 8e6f570..a3317a2 100644 --- a/server/src/modules/client/controllers/client.controller.ts +++ b/server/src/modules/client/controllers/client.controller.ts @@ -1,5 +1,5 @@ import { AuthorizedRequest } from "../../../shared/typings/auth.typings"; -import type { Response, NextFunction } from "express"; +import type { Request, Response, NextFunction } from "express"; import { InvalidInputError, ResourceNotInitializedError } from "../../../shared/typings/error.typings"; import { ResponseFormatter } from "../../../shared/utils/responseFormatter.utils"; import { IClientService } from "../contracts/IClientService.contract"; @@ -40,6 +40,20 @@ export class ClientController { } } + /** + * Public self-service signup — no auth required. + */ + async signup(req: Request, res: Response, next: NextFunction) { + try { + const result = await this.clientService.signup(req.body); + return res + .status(201) + .json(ResponseFormatter.success("Account created. Check your email to verify before signing in.", 201, result)); + } catch (error) { + next(error); + } + } + /** * Create a new user for a specific client */ diff --git a/server/src/modules/client/dependencies/client.dependency.ts b/server/src/modules/client/dependencies/client.dependency.ts index 031a6cc..565b32a 100644 --- a/server/src/modules/client/dependencies/client.dependency.ts +++ b/server/src/modules/client/dependencies/client.dependency.ts @@ -35,7 +35,7 @@ class ClientDependeniesContainer { userRepo: new MongoUserRepo(), }; const services = { - clientService: new ClientService(repositories.clientRepo, repositories.userRepo), + clientService: new ClientService(repositories.clientRepo, repositories.userRepo, repositories.apiKeyRepo), apiKeyService: new ApiKeyService(repositories.apiKeyRepo, repositories.clientRepo), }; const controllers = { diff --git a/server/src/modules/client/dtos/signup.dto.ts b/server/src/modules/client/dtos/signup.dto.ts new file mode 100644 index 0000000..8d7c546 --- /dev/null +++ b/server/src/modules/client/dtos/signup.dto.ts @@ -0,0 +1,26 @@ +import { z } from "zod"; + +export const SignupDTO = z + .object({ + companyName: z.string().min(3, "Company name must be at least 3 characters"), + companyWebsite: z.string().url("Please enter a valid URL").optional().or(z.literal("")), + username: z + .string() + .min(3, "Username must be at least 3 characters") + .regex(/^[a-zA-Z0-9_]+$/, "Username can only contain letters, numbers, and underscores"), + email: z.string().email("Please enter a valid email address"), + password: z + .string() + .min(8, "Password must be at least 8 characters") + .regex( + /^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)(?=.*[@$!%*?&])/, + "Password must contain uppercase, lowercase, number, and special character", + ), + confirmPassword: z.string().min(8, "Confirm password must be at least 8 characters"), + }) + .refine((data) => data.password === data.confirmPassword, { + message: "Passwords do not match", + path: ["confirmPassword"], + }); + +export type SignupDTOType = z.infer; diff --git a/server/src/modules/client/repos/apiKeyBase.repo.ts b/server/src/modules/client/repos/apiKeyBase.repo.ts index 09ba896..094581a 100644 --- a/server/src/modules/client/repos/apiKeyBase.repo.ts +++ b/server/src/modules/client/repos/apiKeyBase.repo.ts @@ -6,4 +6,8 @@ export abstract class ApiKeyBaseRepo { abstract findByKeyValue(keyValue: string, isActive: boolean, checkExpiry: boolean): Promise; abstract findByClientId(clientId: string, isActive: boolean, checkExpiry: boolean): Promise; abstract findAll(_filter?: any, _options?: any): Promise<{ data: T[]; nextCursor?: string }>; + /** Only for cache invalidation — findById() deliberately excludes keyValue everywhere else. */ + abstract findKeyValueById(id: string): Promise; + /** Only for cache invalidation — findByClientId() deliberately excludes keyValue everywhere else. */ + abstract findKeyValuesByClientId(clientId: string, isActive: boolean): Promise; } diff --git a/server/src/modules/client/repos/apikey.repo.ts b/server/src/modules/client/repos/apikey.repo.ts index 8446eca..15bb47b 100644 --- a/server/src/modules/client/repos/apikey.repo.ts +++ b/server/src/modules/client/repos/apikey.repo.ts @@ -54,6 +54,16 @@ export class MongoApiKeyRepo extends ApiKeyBaseRepo { } } + async findKeyValueById(id: string): Promise { + try { + const apiKey = await this.model.findById(id).select("keyValue"); + return apiKey?.keyValue ?? null; + } catch (error) { + logger.error(`Error finding API key hash by id: ${id}`, { error }); + throw error; + } + } + async findByKeyValue(keyValue: string, isActive: boolean, checkExpiry: boolean): Promise { try { const now = new Date(); @@ -88,6 +98,16 @@ export class MongoApiKeyRepo extends ApiKeyBaseRepo { } } + async findKeyValuesByClientId(clientId: string, isActive: boolean): Promise { + try { + const apiKeys = await this.model.find({ clientId: new Types.ObjectId(clientId), isActive }).select("keyValue"); + return apiKeys.map((k) => k.keyValue); + } catch (error) { + logger.error(`Error finding API key hashes by client ID: ${clientId}`, { error }); + throw error; + } + } + async findAll( filter: any = {}, options: { limit?: number; cursor?: string; sort?: any } = {}, diff --git a/server/src/modules/client/services/apiKey.service.ts b/server/src/modules/client/services/apiKey.service.ts index e8ee15b..1aab573 100644 --- a/server/src/modules/client/services/apiKey.service.ts +++ b/server/src/modules/client/services/apiKey.service.ts @@ -17,6 +17,7 @@ import { ApiKeyWithId } from "../../../shared/infra/db/mongo/models/apiKeys.mode import { ClientWithId } from "../../../shared/infra/db/mongo/models/client.model"; import { globalConfig } from "../../../shared/config/global.config"; import { AuditLogger } from "../../../shared/utils/auditLogger.utils"; +import { ApiKeyCache, ApiKeyLookupResult } from "../../../shared/infra/cache/apiKeyCache"; export class ApiKeyService { protected apiKeyRepo: ApiKeyBaseRepo; @@ -168,7 +169,13 @@ export class ApiKeyService { if (apiKey.clientId.toString() !== clientId) throw new PermissionNotGranted("This API key does not belong to this client."); + // Fetched before delete so we have the hash to evict from cache — revoke + // must not leave a cached copy of the key working until TTL expiry. + const keyValueHash = await this.apiKeyRepo.findKeyValueById(apiKeyId); + await this.apiKeyRepo.delete(apiKeyId); + if (keyValueHash) void ApiKeyCache.invalidate(keyValueHash); + logger.info(`API key revoked: ${apiKeyId} for clientId: ${clientId} by user: ${requestedBy.id}`); AuditLogger.log({ action: "api_key.revoked", @@ -185,12 +192,12 @@ export class ApiKeyService { } } - async getClientFromApiKey(apiKeyValue: string): Promise<{ - client: { _id: Types.ObjectId; name: string; slug: string; isActive: boolean }; - apiKeyDoc: ApiKeyWithId; - }> { + async getClientFromApiKey(apiKeyValue: string): Promise { + const hashedKeyValue = this.hashApiKey(apiKeyValue); + try { - const hashedKeyValue = this.hashApiKey(apiKeyValue); + const cached = await ApiKeyCache.get(hashedKeyValue); + if (cached) return cached; const apiKeyDoc = await this.apiKeyRepo.findByKeyValue(hashedKeyValue, true, true); @@ -208,14 +215,28 @@ export class ApiKeyService { throw new ResourceNotFoundError("Client not found"); } - const safeClient: { _id: Types.ObjectId; name: string; slug: string; isActive: boolean } = { - _id: client._id, - name: client.name, - slug: client.slug, - isActive: client.isActive, + const result: ApiKeyLookupResult = { + client: { + id: client._id.toString(), + name: client.name, + slug: client.slug, + isActive: client.isActive, + }, + apiKey: { + id: apiKeyDoc._id.toString(), + keyId: apiKeyDoc.keyId, + name: apiKeyDoc.name, + permissions: { + writeAccess: apiKeyDoc.permissions?.writeAccess ?? false, + readAccess: apiKeyDoc.permissions?.readAccess ?? false, + }, + }, }; - return { client: safeClient, apiKeyDoc }; + // Only successful lookups are cached — see ApiKeyCache's doc comment on why. + void ApiKeyCache.set(hashedKeyValue, result); + + return result; } catch (error) { logger.error("Error retrieving client from API key", { error }); throw error; diff --git a/server/src/modules/client/services/client.service.ts b/server/src/modules/client/services/client.service.ts index 2e58d97..5e48fd9 100644 --- a/server/src/modules/client/services/client.service.ts +++ b/server/src/modules/client/services/client.service.ts @@ -14,26 +14,31 @@ import { ClientBaseRepo } from "../repos/clientBase.repo"; import { USER_ROLE, UserInsideAuthorizedRequest } from "../../../shared/typings/auth.typings"; import { AuthorizationUtils } from "../../../shared/utils/authorization.utils"; import { CreateClientUserDTOType } from "../dtos/createClientUser.dto"; -import { Client } from "../../../shared/infra/db/mongo/models/client.model"; +import { Client, ClientWithId } from "../../../shared/infra/db/mongo/models/client.model"; import { User, UserWithId } from "../../../shared/infra/db/mongo/models/user.model"; import { AuditLogger } from "../../../shared/utils/auditLogger.utils"; +import { issueAndSendVerificationEmail } from "../../../shared/utils/emailVerification.utils"; +import { ApiKeyBaseRepo } from "../repos/apiKeyBase.repo"; +import { ApiKeyWithId } from "../../../shared/infra/db/mongo/models/apiKeys.model"; +import { ApiKeyCache } from "../../../shared/infra/cache/apiKeyCache"; +import { SignupDTOType } from "../dtos/signup.dto"; export class ClientService { protected clientRepo: ClientBaseRepo; - // protected apiKeyRepo: ApiKeyBaseRepo; + protected apiKeyRepo: ApiKeyBaseRepo; protected userRepo: UserBaseRepo; - constructor(clientRepo: ClientBaseRepo, userRepo: UserBaseRepo) { + constructor(clientRepo: ClientBaseRepo, userRepo: UserBaseRepo, apiKeyRepo: ApiKeyBaseRepo) { if (!clientRepo) { throw new ResourceNotInitializedError("Client repository must be provided to ClientService"); } - // if (!apiKeyRepo) { - // throw new ResourceNotInitializedError("API Key repository must be provided to ClientService"); - // } + if (!apiKeyRepo) { + throw new ResourceNotInitializedError("API Key repository must be provided to ClientService"); + } if (!userRepo) { throw new ResourceNotInitializedError("User repository must be provided to ClientService"); } this.clientRepo = clientRepo; - // this.apiKeyRepo = apiKeyRepo; + this.apiKeyRepo = apiKeyRepo; this.userRepo = userRepo; } @@ -93,10 +98,9 @@ export class ClientService { createdBy: new Types.ObjectId(createdBy), }); logger.info(`Client created successfully with slug : ${newClient.slug} by user: ${createdBy}`); - // createClient is only ever reachable via a super_admin-only route (see clientAdmin.route.ts). - // `Client` (the repo's declared generic here) doesn't expose `_id` even - // though the underlying document has one — slug is a stable, unique, - // type-safe identifier to correlate this entry with instead. + // This method is only reached through a super_admin-only route (see clientAdmin.route.ts). + // The repo's `Client` type does not expose `_id`, even though the underlying + // document has one, so we use the slug here as a stable, unique, type-safe identifier. AuditLogger.log({ action: "client.created", actorId: createdBy, @@ -112,6 +116,76 @@ export class ClientService { } } + /** + * Public signup that creates a new client and its first user. + */ + async signup(data: SignupDTOType): Promise<{ client: Client; user: Omit }> { + try { + const slug = this.generateSlug(data.companyName); + + const existingClient = await this.clientRepo.findBySlug(slug, true); + if (existingClient) { + throw new InvalidInputError("A company with this name is already registered. Please choose a different name."); + } + + await this.checkIfClientUserExistsAndThrowError(data.username, data.email); + + const newUserId = new Types.ObjectId(); + + const newClient = await this.clientRepo.create({ + name: data.companyName, + email: data.email, + website: data.companyWebsite || "", + slug, + createdBy: newUserId, + }); + + const clientId = (newClient as unknown as ClientWithId)._id; + + try { + const newUser = await this.userRepo.create({ + _id: newUserId, + username: data.username, + email: data.email, + password: data.password, + role: USER_ROLE.CLIENT_ADMIN, + clientId, + permissions: { + canCreateApiKeys: true, + canManageUsers: true, + canViewRawLogs: true, + canViewAnalytics: true, + canManageSettings: true, + canExportData: true, + }, + } as Partial & { _id: Types.ObjectId }); + + void issueAndSendVerificationEmail(newUser); + + logger.info(`New company signed up: ${newClient.slug}, admin: ${newUser.username}`); + AuditLogger.log({ + action: "client.signup", + actorId: newUserId.toString(), + actorRole: USER_ROLE.CLIENT_ADMIN, + clientId: clientId.toString(), + targetType: "client", + targetId: newClient.slug, + metadata: { name: newClient.name, slug: newClient.slug }, + }); + + return { client: newClient, user: this.formatUserResponseWithoutPassword(newUser) }; + } catch (userCreateError) { + // Roll back the orphaned client if the admin user couldn't be created + // (e.g. an email/username collision that slipped past the check above). + await this.clientRepo.delete(clientId.toString()); + throw userCreateError; + } + } catch (error) { + logger.error("Error during company signup", { error, companyName: data.companyName, email: data.email }); + throw error; + } + } + async createClientUser( clientId: string, userData: CreateClientUserDTOType, @@ -158,6 +232,8 @@ export class ClientService { logger.info( `Client user created successfully with username : ${newUser.username} for clientId: ${clientId} by user: ${createdBy.id}`, ); + + void issueAndSendVerificationEmail(newUser); AuditLogger.log({ action: "user.created", actorId: createdBy.id, @@ -334,6 +410,14 @@ export class ClientService { this.requireSuperAdmin(requestedBy); const updated = await this.clientRepo.update(clientId, { isActive } as any); if (!updated) throw new ResourceNotFoundError("Client not found."); + + if (!isActive) { + // Cached API-key lookups embed client.isActive — without this, a + // deactivated client's keys would keep validating until the cache + // TTL naturally expires instead of stopping immediately. + void this.invalidateApiKeyCacheForClient(clientId); + } + logger.info(`Client ${isActive ? "activated" : "deactivated"}: ${clientId} by user: ${requestedBy.id}`); AuditLogger.log({ action: isActive ? "client.activated" : "client.deactivated", @@ -349,4 +433,13 @@ export class ClientService { throw error; } } + + private async invalidateApiKeyCacheForClient(clientId: string): Promise { + try { + const keyValueHashes = await this.apiKeyRepo.findKeyValuesByClientId(clientId, true); + await Promise.all(keyValueHashes.map((hash) => ApiKeyCache.invalidate(hash))); + } catch (error) { + logger.error("Error invalidating API key cache for client", { error, clientId }); + } + } } diff --git a/server/src/shared/config/global.config.ts b/server/src/shared/config/global.config.ts index fc776d4..3e0daea 100644 --- a/server/src/shared/config/global.config.ts +++ b/server/src/shared/config/global.config.ts @@ -87,13 +87,12 @@ const envSchema = z.object({ CORS_ALLOWED_ORIGINS: z.string().optional(), API_KEY_HMAC_SECRET: z.string().optional(), + API_KEY_CACHE_TTL_SECONDS: numeric, - SMTP_HOST: z.string().optional(), - SMTP_PORT: numeric, - SMTP_SECURE: booleanish, - SMTP_USER: z.string().optional(), - SMTP_PASS: z.string().optional(), - SMTP_DEFAULT_FROM: z.string().optional(), + RESEND_API_KEY: z.string().optional(), + RESEND_DEFAULT_FROM: z.string().optional(), + + FRONTEND_URL: z.string().optional(), }); const envSchemaWithProdChecks = envSchema.superRefine((data, ctx) => { @@ -239,14 +238,15 @@ export const globalConfig = { apiKey: { hmacSecret: env.API_KEY_HMAC_SECRET || (isProduction ? "" : "dev-only-insecure-apikey-hmac-secret"), + // Kept deliberately short: bounds how long a revoked/deactivated key can + // keep working through the cache, and keeps memory use tiny on small hosts. + cacheTtlSeconds: parseInt(env.API_KEY_CACHE_TTL_SECONDS || "30", 10), }, email: { - host: env.SMTP_HOST || "smtp.gmail.com", - port: parseInt(env.SMTP_PORT || "587", 10), - secure: env.SMTP_SECURE === "true", - user: env.SMTP_USER || "", - pass: env.SMTP_PASS || "", - defaultFrom: env.SMTP_DEFAULT_FROM || "alerts@servermonitoring.local", + resendApiKey: env.RESEND_API_KEY || "", + defaultFrom: env.RESEND_DEFAULT_FROM || "alerts@servermonitoring.local", }, + + frontendUrl: env.FRONTEND_URL || "http://localhost:3000", }; diff --git a/server/src/shared/infra/cache/apiKeyCache.ts b/server/src/shared/infra/cache/apiKeyCache.ts new file mode 100644 index 0000000..218817b --- /dev/null +++ b/server/src/shared/infra/cache/apiKeyCache.ts @@ -0,0 +1,51 @@ +import redisConnection from "../redisConnection"; +import logger from "../../config/logger.config"; +import { globalConfig } from "../../config/global.config"; + +const KEY_PREFIX = "cache:apikey:"; + +export interface ApiKeyLookupResult { + client: { id: string; name: string; slug: string; isActive: boolean }; + apiKey: { + id: string; + keyId: string; + name: string; + permissions: { writeAccess: boolean; readAccess: boolean }; + }; +} + +/** + * Caches resolved API keys so ingest requests don't keep hitting the DB. + * Keeps a short TTL so revoked keys expire quickly. + */ +export class ApiKeyCache { + static async get(hashedKeyValue: string): Promise { + try { + const raw = await redisConnection.getClient().get(`${KEY_PREFIX}${hashedKeyValue}`); + return raw ? (JSON.parse(raw) as ApiKeyLookupResult) : null; + } catch (error) { + logger.error("[ApiKeyCache] Redis read failed, falling back to DB", { + error: error instanceof Error ? error.message : error, + }); + return null; + } + } + + static async set(hashedKeyValue: string, result: ApiKeyLookupResult): Promise { + try { + await redisConnection + .getClient() + .set(`${KEY_PREFIX}${hashedKeyValue}`, JSON.stringify(result), "EX", globalConfig.apiKey.cacheTtlSeconds); + } catch (error) { + logger.error("[ApiKeyCache] Redis write failed", { error: error instanceof Error ? error.message : error }); + } + } + + static async invalidate(hashedKeyValue: string): Promise { + try { + await redisConnection.getClient().del(`${KEY_PREFIX}${hashedKeyValue}`); + } catch (error) { + logger.error("[ApiKeyCache] Redis invalidation failed", { error: error instanceof Error ? error.message : error }); + } + } +} diff --git a/server/src/shared/infra/cache/authTokenCache.ts b/server/src/shared/infra/cache/authTokenCache.ts new file mode 100644 index 0000000..6545299 --- /dev/null +++ b/server/src/shared/infra/cache/authTokenCache.ts @@ -0,0 +1,28 @@ +import redisConnection from "../redisConnection"; +import logger from "../../config/logger.config"; + +export const EMAIL_VERIFICATION_TOKEN_PREFIX = "auth:email-verify:"; +export const PASSWORD_RESET_TOKEN_PREFIX = "auth:password-reset:"; + +export class AuthTokenCache { + static async store(prefix: string, tokenHash: string, userId: string, ttlSeconds: number): Promise { + await redisConnection.getClient().set(`${prefix}${tokenHash}`, userId, "EX", ttlSeconds); + } + + /** Looks up and atomically deletes the token so it can't be replayed. Returns the userId, or null if missing/expired. */ + static async consume(prefix: string, tokenHash: string): Promise { + const key = `${prefix}${tokenHash}`; + const client = redisConnection.getClient(); + + try { + const userId = await client.get(key); + if (userId === null) return null; + + await client.del(key); + return userId; + } catch (error) { + logger.error("[AuthTokenCache] Redis lookup failed", { error: error instanceof Error ? error.message : error, prefix }); + return null; + } + } +} diff --git a/server/src/shared/infra/db/mongo/models/user.model.ts b/server/src/shared/infra/db/mongo/models/user.model.ts index 7fddf76..c4676ab 100644 --- a/server/src/shared/infra/db/mongo/models/user.model.ts +++ b/server/src/shared/infra/db/mongo/models/user.model.ts @@ -108,6 +108,11 @@ const userSchema = new mongoose.Schema( type: Boolean, default: false, }, + + isEmailVerified: { + type: Boolean, + default: false, + }, }, { timestamps: true, diff --git a/server/src/shared/middleware/validateApiKey.middleware.ts b/server/src/shared/middleware/validateApiKey.middleware.ts index 62871c0..7f1c35c 100644 --- a/server/src/shared/middleware/validateApiKey.middleware.ts +++ b/server/src/shared/middleware/validateApiKey.middleware.ts @@ -8,7 +8,8 @@ const { apiKeyService } = ClientDependeniesContainer.init().services; /** * Middleware to validate API key from the request header. - * TODO: instead of database use REDIS . + * Backed by ApiKeyCache (Redis, short TTL) — see apiKey.service.ts's + * getClientFromApiKey — since this runs on every single /ingest request. */ const validateApiKey = async (req: ClientAuthorizedRequest, _res: Response, next: NextFunction) => { try { @@ -25,7 +26,7 @@ const validateApiKey = async (req: ClientAuthorizedRequest, _res: Response, next const result = await apiKeyService.getClientFromApiKey(apiKey); const client = result?.client; - const apiKeyDoc = result?.apiKeyDoc; + const apiKeyDoc = result?.apiKey; if (!apiKeyDoc) { logger.warn("[ValidateApiKey] Invalid API key provided", { @@ -55,7 +56,7 @@ const validateApiKey = async (req: ClientAuthorizedRequest, _res: Response, next throw new PermissionNotGranted("API key belongs to an inactive client"); } - if (!apiKeyDoc?.permissions?.writeAccess) { + if (!apiKeyDoc.permissions.writeAccess) { logger.warn("[ValidateApiKey] API key does not have write access", { endpoint: req.originalUrl, method: req.method, @@ -66,7 +67,7 @@ const validateApiKey = async (req: ClientAuthorizedRequest, _res: Response, next } req.client = { - id: client._id.toString(), + id: client.id, name: client.name, slug: client.slug, ip: req.ip, @@ -74,12 +75,12 @@ const validateApiKey = async (req: ClientAuthorizedRequest, _res: Response, next }; req.apiKey = { - id: apiKeyDoc._id.toString(), + id: apiKeyDoc.id, apiKeyId: apiKeyDoc.keyId, name: apiKeyDoc.name, permissions: { - writeAccess: apiKeyDoc.permissions?.writeAccess ?? false, - readAccess: apiKeyDoc.permissions?.readAccess ?? false, + writeAccess: apiKeyDoc.permissions.writeAccess, + readAccess: apiKeyDoc.permissions.readAccess, }, }; diff --git a/server/src/shared/typings/error.typings.ts b/server/src/shared/typings/error.typings.ts index c539595..b6939fb 100644 --- a/server/src/shared/typings/error.typings.ts +++ b/server/src/shared/typings/error.typings.ts @@ -21,6 +21,7 @@ export enum ErrorCode { CORS_ERROR = "CORS_ERROR", ENVIRONMENT_VARIABLE_ERROR = "ENVIRONMENT_VARIABLE_ERROR", ALERT_EVALUATION_FAILED = "ALERT_EVALUATION_FAILED", + EMAIL_NOT_VERIFIED = "EMAIL_NOT_VERIFIED", } export enum ErrorHttpStatusCode { @@ -158,3 +159,13 @@ export class AlertEvaluationError extends CustomError { this.alertId = alertId; } } + +/** + * Error caused by attempting to log in before verifying the account's email address. + * @extends CustomError + */ +export class EmailNotVerifiedError extends CustomError { + constructor(message = "Please verify your email address before logging in.") { + super(message, ErrorHttpStatusCode.PERMISSION_NOT_GRANTED, ErrorCode.EMAIL_NOT_VERIFIED); + } +} diff --git a/server/src/shared/utils/authEmailTemplates.utils.ts b/server/src/shared/utils/authEmailTemplates.utils.ts new file mode 100644 index 0000000..522b51c --- /dev/null +++ b/server/src/shared/utils/authEmailTemplates.utils.ts @@ -0,0 +1,66 @@ +import { escapeHtml } from "./html.utils"; + +function wrapper(badgeColor: string, badgeText: string, heading: string, bodyHtml: string, buttonLabel: string, buttonUrl: string): string { + return ` + + + + + + + + + + + + + + + + + + + + +
     
    +
    + ${badgeText} +
    +

    ${heading}

    +
    ${bodyHtml}
    +
    + ${buttonLabel} +

    + Or paste this link into your browser:
    + ${buttonUrl} +

    +
    +

    + Sent by ServerStats. If you didn't expect this email, you can safely ignore it. +

    +
    + +`; +} + +export function buildVerificationEmailHtml(verifyUrl: string): string { + return wrapper( + "#2563eb", + "Verify your email", + "Confirm your email address", + "Click the button below to verify your email and activate your ServerStats account. This link expires in 24 hours.", + "Verify email", + escapeHtml(verifyUrl), + ); +} + +export function buildPasswordResetEmailHtml(resetUrl: string): string { + return wrapper( + "#e5484d", + "Password reset", + "Reset your password", + "We received a request to reset your ServerStats password. Click the button below to choose a new one. This link expires in 1 hour and can only be used once.", + "Reset password", + escapeHtml(resetUrl), + ); +} diff --git a/server/src/shared/utils/emailVerification.utils.ts b/server/src/shared/utils/emailVerification.utils.ts new file mode 100644 index 0000000..1fe8958 --- /dev/null +++ b/server/src/shared/utils/emailVerification.utils.ts @@ -0,0 +1,48 @@ +import crypto from "crypto"; +import { globalConfig } from "../config/global.config"; +import logger from "../config/logger.config"; +import { sendViaResend } from "./resendMailer.utils"; +import { buildVerificationEmailHtml } from "./authEmailTemplates.utils"; +import { UserWithId } from "../infra/db/mongo/models/user.model"; +import { AuthTokenCache, EMAIL_VERIFICATION_TOKEN_PREFIX } from "../infra/cache/authTokenCache"; + +const VERIFICATION_TOKEN_TTL_SECONDS = 24 * 60 * 60; // 24 hours + +function hashToken(rawToken: string): string { + return crypto.createHmac("sha256", globalConfig.jwt.secret).update(rawToken).digest("hex"); +} + + +export async function issueAndSendVerificationEmail(user: UserWithId): Promise { + try { + const rawToken = crypto.randomBytes(32).toString("hex"); + const tokenHash = hashToken(rawToken); + + await AuthTokenCache.store(EMAIL_VERIFICATION_TOKEN_PREFIX, tokenHash, user._id.toString(), VERIFICATION_TOKEN_TTL_SECONDS); + + if (!globalConfig.email.resendApiKey) { + logger.warn("[EmailVerification] RESEND_API_KEY is not configured. Skipping verification email.", { + userId: user._id.toString(), + }); + return; + } + + const verifyUrl = `${globalConfig.frontendUrl}/verify-email?token=${rawToken}`; + + await sendViaResend({ + apiKey: globalConfig.email.resendApiKey, + from: globalConfig.email.defaultFrom, + to: user.email, + subject: "Verify your ServerStats email address", + html: buildVerificationEmailHtml(verifyUrl), + }); + + logger.info(`[EmailVerification] Verification email sent to ${user.email}`); + } catch (error) { + logger.error("[EmailVerification] Failed to send verification email", { error, userId: user._id.toString() }); + } +} + +export function hashVerificationOrResetToken(rawToken: string): string { + return hashToken(rawToken); +} diff --git a/server/src/shared/utils/html.utils.ts b/server/src/shared/utils/html.utils.ts new file mode 100644 index 0000000..60be801 --- /dev/null +++ b/server/src/shared/utils/html.utils.ts @@ -0,0 +1,8 @@ +export function escapeHtml(value: string): string { + return value + .replace(/&/g, "&") + .replace(//g, ">") + .replace(/"/g, """) + .replace(/'/g, "'"); +} diff --git a/server/src/shared/utils/resendMailer.utils.ts b/server/src/shared/utils/resendMailer.utils.ts new file mode 100644 index 0000000..cd33796 --- /dev/null +++ b/server/src/shared/utils/resendMailer.utils.ts @@ -0,0 +1,52 @@ +import https from "https"; + +export interface ResendEmailParams { + apiKey: string; + from: string; + to: string | string[]; + subject: string; + html: string; +} + +/** Sends an email via the Resend HTTP API (https://resend.com/docs/api-reference/emails/send-email). */ +export function sendViaResend(params: ResendEmailParams): Promise { + return new Promise((resolve, reject) => { + const data = JSON.stringify({ + from: params.from, + to: params.to, + subject: params.subject, + html: params.html, + }); + + const req = https.request( + { + hostname: "api.resend.com", + path: "/emails", + method: "POST", + headers: { + Authorization: `Bearer ${params.apiKey}`, + "Content-Type": "application/json", + "Content-Length": Buffer.byteLength(data), + }, + }, + (res) => { + let body = ""; + res.on("data", (chunk) => (body += chunk)); + res.on("end", () => { + if (res.statusCode && res.statusCode >= 200 && res.statusCode < 300) { + resolve(); + } else { + reject(new Error(`Resend API responded ${res.statusCode}: ${body}`)); + } + }); + }, + ); + + req.on("error", reject); + req.setTimeout(10000, () => { + req.destroy(new Error("Resend API request timed out")); + }); + req.write(data); + req.end(); + }); +}