Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
16 changes: 16 additions & 0 deletions server/docker-compose.yml
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
20 changes: 0 additions & 20 deletions server/package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

5 changes: 1 addition & 4 deletions server/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -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": "",
Expand All @@ -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",
Expand All @@ -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",
Expand Down
110 changes: 87 additions & 23 deletions server/src/modules/alerting/services/channels/email.channel.ts
Original file line number Diff line number Diff line change
@@ -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) => `<li>${r}</li>`).join("");
const esc = (v: string) => escapeHtml(v);
const alertTypeLabel = payload.alert.alertType.replace(/_/g, " ");

const stat = (label: string, value: string) => `
<td style="padding:16px 12px;text-align:center;background:#f9fafb;border:1px solid #eceef1;border-radius:8px;">
<div style="font-size:11px;font-weight:600;letter-spacing:0.04em;text-transform:uppercase;color:#8a8f98;margin:0 0 6px;">${label}</div>
<div style="font-size:20px;font-weight:700;color:#111318;line-height:1.2;">${value}</div>
</td>`;

const reasonsList = payload.reasons.map((r) => `<li style="margin:0 0 6px;color:#7a1f1f;">${esc(r)}</li>`).join("");

return `
<h2>Alert Fired: ${payload.alert.name}</h2>
<table>
<tr><td><strong>Alert ID</strong></td><td>${payload.alert.id}</td></tr>
<tr><td><strong>Alert Type</strong></td><td>${payload.alert.alertType}</td></tr>
<tr><td><strong>Client ID</strong></td><td>${payload.alert.clientId}</td></tr>
<tr><td><strong>Fired At</strong></td><td>${payload.firedAt}</td></tr>
<tr><td><strong>Stats</strong></td><td>${statsLine}</td></tr>
</table>
<h3>Reasons</h3>
<ul>${reasonsList}</ul>
`;
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
</head>
<body style="margin:0;padding:24px;background:#f4f5f7;font-family:-apple-system,BlinkMacSystemFont,'Segoe UI',Roboto,Helvetica,Arial,sans-serif;">
<table role="presentation" width="100%" cellpadding="0" cellspacing="0" style="max-width:560px;margin:0 auto;background:#ffffff;border-radius:12px;overflow:hidden;border:1px solid #eceef1;">
<tr>
<td style="height:4px;background:#e5484d;line-height:0;font-size:0;">&nbsp;</td>
</tr>
<tr>
<td style="padding:28px 32px 20px;">
<div style="display:inline-block;padding:4px 10px;background:#fdecec;color:#e5484d;font-size:12px;font-weight:700;letter-spacing:0.03em;text-transform:uppercase;border-radius:999px;margin-bottom:14px;">
&#9888; Alert Fired
</div>
<h1 style="margin:0 0 6px;font-size:20px;line-height:1.35;color:#111318;">${esc(payload.alert.name)}</h1>
<p style="margin:0;font-size:13px;color:#6b7280;">
${esc(alertTypeLabel)} &middot; fired ${esc(this.formatFiredAt(payload.firedAt))}
</p>
</td>
</tr>
<tr>
<td style="padding:0 32px 24px;">
<table role="presentation" width="100%" cellpadding="0" cellspacing="0">
<tr>
${stat("Total Hits", String(payload.stats.total_hits))}
<td style="width:8px;">&nbsp;</td>
${stat("Errors", String(payload.stats.total_errors))}
</tr>
<tr><td colspan="3" style="height:8px;">&nbsp;</td></tr>
<tr>
${stat("Error Rate", `${payload.stats.error_rate}%`)}
<td style="width:8px;">&nbsp;</td>
${stat("Avg Latency", `${payload.stats.avg_latency}ms`)}
</tr>
</table>
</td>
</tr>
<tr>
<td style="padding:0 32px 28px;">
<div style="background:#fdecec;border:1px solid #f6cfcf;border-radius:8px;padding:16px 18px;">
<div style="font-size:12px;font-weight:700;letter-spacing:0.03em;text-transform:uppercase;color:#e5484d;margin:0 0 8px;">Why this fired</div>
<ul style="margin:0;padding-left:18px;font-size:14px;line-height:1.5;">${reasonsList}</ul>
</div>
</td>
</tr>
<tr>
<td style="padding:18px 32px;background:#fafafa;border-top:1px solid #eceef1;">
<p style="margin:0;font-size:12px;color:#9aa0a6;line-height:1.6;">
Alert ID <span style="font-family:ui-monospace,SFMono-Regular,Menlo,monospace;">${esc(payload.alert.id)}</span>
&nbsp;&middot;&nbsp; Client <span style="font-family:ui-monospace,SFMono-Regular,Menlo,monospace;">${esc(payload.alert.clientId)}</span><br />
Sent by ServerStats alerting
</p>
</td>
</tr>
</table>
</body>
</html>`;
}

async dispatch(config: Record<string, unknown>, payload: DispatchPayload): Promise<void> {
Expand All @@ -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}`);
}
}
8 changes: 8 additions & 0 deletions server/src/modules/auth/contracts/IAuthService.contract.ts
Original file line number Diff line number Diff line change
Expand Up @@ -15,4 +15,12 @@ export interface IAuthService {
isSuperAdmin(id: string): Promise<boolean>;

changePassword(userId: string, data: ChangePasswordDTOType): Promise<void>;

resendVerificationEmail(email: string): Promise<void>;

verifyEmail(token: string): Promise<void>;

forgotPassword(email: string): Promise<void>;

resetPassword(token: string, newPassword: string): Promise<void>;
}
40 changes: 40 additions & 0 deletions server/src/modules/auth/controllers/auth.controller.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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);
}
}
}
7 changes: 7 additions & 0 deletions server/src/modules/auth/dtos/emailOnly.dto.ts
Original file line number Diff line number Diff line change
@@ -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<typeof EmailOnlyDTO>;
20 changes: 20 additions & 0 deletions server/src/modules/auth/dtos/resetPassword.dto.ts
Original file line number Diff line number Diff line change
@@ -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<typeof ResetPasswordDTO>;
2 changes: 2 additions & 0 deletions server/src/modules/auth/dtos/userResponse.dto.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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();
}
Expand Down
7 changes: 7 additions & 0 deletions server/src/modules/auth/dtos/verifyEmail.dto.ts
Original file line number Diff line number Diff line change
@@ -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<typeof VerifyEmailDTO>;
4 changes: 3 additions & 1 deletion server/src/modules/auth/repos/user.repo.ts
Original file line number Diff line number Diff line change
Expand Up @@ -86,7 +86,9 @@ export class MongoUserRepo extends UserBaseRepo<UserWithId> {
.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[];
Expand Down
Loading
Loading