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
9 changes: 8 additions & 1 deletion .env.example
Original file line number Diff line number Diff line change
Expand Up @@ -29,4 +29,11 @@ SCORE_TLS_PROBES_PER_HOUR=120
# port 25 by default. Contact your provider to unblock port 25 if live mail server TLS checks fail.
# 2. DNSBL / Blacklist checks: Public DNS resolvers (8.8.8.8, 1.1.1.1) are blocked by Spamhaus
# and Barracuda. For accurate blacklist checks, configure your VPS host to use a local
# recursive resolver (e.g. Unbound / Bind) instead of public open resolvers.
# recursive resolver (e.g. Unbound / Bind) instead of public open resolvers.

## Update notifications (checks GitHub for a newer release)
## Set this to your GitHub "owner/repo". Leave it empty or set DISABLE_UPDATE_CHECK=true to turn the feature off.
UPDATE_CHECK_REPO=devindevops/mailmetrix
# DISABLE_UPDATE_CHECK=true
# UPDATE_CHECK_INTERVAL_HOURS=6
# RATE_LIMIT_VERSION=60
183 changes: 146 additions & 37 deletions README.md

Large diffs are not rendered by default.

4 changes: 2 additions & 2 deletions backend/package-lock.json

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

2 changes: 1 addition & 1 deletion backend/package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "MailMetrix-backend",
"version": "1.2.0",
"version": "1.2.1",
"description": "MailMetrix SMTP and email infrastructure diagnostics backend",
"main": "src/server.js",
"scripts": {
Expand Down
18 changes: 18 additions & 0 deletions backend/src/routes/version.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
"use strict";

const express = require("express");
const { getLatestRelease } = require("../services/version");

const router = express.Router();

// GET /version/check (also reachable as /api/version/check, see server.js)
router.get("/check", async (_req, res, next) => {
try {
res.set("Cache-Control", "no-store");
res.json(await getLatestRelease());
} catch (err) {
next(err);
}
});

module.exports = router;
45 changes: 42 additions & 3 deletions backend/src/server.js
Original file line number Diff line number Diff line change
Expand Up @@ -12,8 +12,9 @@ const blacklistRoutes = require("./routes/blacklist");
const scoreRoutes = require("./routes/score");
const tlsRoutes = require("./routes/tls");
const shareRoutes = require("./routes/share");
const versionRoutes = require("./routes/version");

const app = express();
const app = express();
app.disable("x-powered-by"); // don't advertise "X-Powered-By: Express" on every response
const PORT = Number(process.env.PORT || 4000);

Expand Down Expand Up @@ -105,6 +106,13 @@ const shareLimiter = createLimiter(
"Share limit reached. Please try again later."
);

// Update check: answered from an in-memory cache (GitHub is contacted at most every
// few hours), so this is cheap, but it is public and runs on every page load.
const versionLimiter = createLimiter(
positiveInt(process.env.RATE_LIMIT_VERSION, 60),
"Too many requests, please try again later."
);

// HTTP request logging (registered first so 429 responses are logged too).
app.use((req, res, next) => {
const startTime = Date.now();
Expand All @@ -130,6 +138,8 @@ app.use("/blacklist", blacklistLimiter);
app.use("/score", scoreLimiter);
app.use("/tls", tlsLimiter);
app.use("/share", shareLimiter);
app.use("/version", versionLimiter);
app.use("/api/version", versionLimiter);

// Share allows larger payloads (up to 300kb) and parses its own body, so it
// must be mounted BEFORE the global 100kb parser below.
Expand Down Expand Up @@ -160,14 +170,22 @@ app.get("/", (_req, res) => {
// ("backend" is kept only so a UI that checks it for a status badge keeps
// working; it carries no sensitive information.)
function healthHandler(_req, res) {
res.set("Cache-Control", "no-store");

res.status(200).json({
status: "healthy",
backend: "connected"
backend: "connected",
uptimeSeconds: Math.round(process.uptime()),
cpuPercent: sampleCpuPercent(),
memory: {
rssMb: toMb(process.memoryUsage().rss),
heapUsedMb: toMb(process.memoryUsage().heapUsed),
heapTotalMb: toMb(process.memoryUsage().heapTotal)
}
});
}

app.get("/health", healthHandler);
// Also map /api/health to the same handler if your frontend polls /api/health
app.get("/api/health", healthHandler);

// INTERNAL telemetry: for monitoring from inside the Docker network only.
Expand Down Expand Up @@ -240,6 +258,22 @@ app.get("/internal/health", (req, res, next) => {
});
});

app.get("/api/telemetry", (req, res) => {
if (!isInternalRequest(req)) {
return res.status(404).end();
}

res.set("Cache-Control", "no-store");

res.json({
status: "healthy",
cpuPercent: sampleCpuPercent(),
memory: {
rssMb: toMb(process.memoryUsage().rss)
}
});
});

// Application routes.
app.use("/smtp", smtpRoutes);
app.use("/dns", dnsRoutes);
Expand All @@ -249,6 +283,11 @@ app.use("/blacklist", blacklistRoutes);
app.use("/score", scoreRoutes);
app.use("/tls", tlsRoutes);

// Update check. Mounted at both paths because the frontend calls /api/version/check and
// nginx may or may not strip the /api prefix (same reason /api/health exists above).
app.use("/version", versionRoutes);
app.use("/api/version", versionRoutes);

// Handle unmatched routes.
app.use((req, res) => {
res.status(404).json({
Expand Down
111 changes: 111 additions & 0 deletions backend/src/services/version.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,111 @@
"use strict";

/* ------------------------------------------------------------------ */
/* Update check */
/* */
/* Asks GitHub for the latest published release of this project and */
/* caches the answer, so the browser never talks to GitHub itself and */
/* GitHub's unauthenticated rate limit (60 req/h per IP) is never hit. */
/* */
/* The backend only reports what the latest release is. The frontend */
/* compares it against the version it was built with (version.json). */
/* */
/* Config (all optional except the repo): */
/* UPDATE_CHECK_REPO "owner/repo" on GitHub */
/* DISABLE_UPDATE_CHECK "true" to turn the feature off */
/* UPDATE_CHECK_INTERVAL_HOURS cache lifetime, default 6 */
/* GITHUB_TOKEN only needed for a private repo */
/* ------------------------------------------------------------------ */

const REPO = (process.env.UPDATE_CHECK_REPO || "").trim();
const DISABLED =
String(process.env.DISABLE_UPDATE_CHECK || "").trim().toLowerCase() === "true";
const REPO_RE = /^[A-Za-z0-9_.-]+\/[A-Za-z0-9_.-]+$/;
const ENABLED = !DISABLED && REPO_RE.test(REPO);

if (!DISABLED && !ENABLED) {
console.warn(
"Update check is off: set UPDATE_CHECK_REPO to \"owner/repo\" (or DISABLE_UPDATE_CHECK=true to silence this)."
);
}

const intervalHours = Number(process.env.UPDATE_CHECK_INTERVAL_HOURS);
const TTL_OK_MS =
(Number.isFinite(intervalHours) && intervalHours > 0 ? intervalHours : 6) *
60 * 60 * 1000;
const TTL_FAIL_MS = 15 * 60 * 1000; // after a failure, retry sooner but not on every page load
const TIMEOUT_MS = 5000;

// Plain releases only (1.1.0 or v1.1.0). GitHub's /releases/latest already skips
// drafts and pre-releases; this also ignores odd tags such as "1.1.0-rc1".
const SEMVER_RE = /^v?(\d+)\.(\d+)\.(\d+)$/;

let cache = { at: 0, ttl: 0, data: null };
let inflight = null;

async function fetchLatest() {
const headers = {
"User-Agent": "mailmetrix-update-check",
Accept: "application/vnd.github+json"
};
if (process.env.GITHUB_TOKEN) {
headers.Authorization = `Bearer ${process.env.GITHUB_TOKEN}`;
}

const res = await fetch(`https://api.github.com/repos/${REPO}/releases/latest`, {
headers,
signal: AbortSignal.timeout(TIMEOUT_MS)
});

if (res.status === 404) return null; // no published release yet
if (!res.ok) throw new Error(`GitHub API responded ${res.status}`);

const json = await res.json();
const m = SEMVER_RE.exec(String(json.tag_name || "").trim());
if (!m) return null;

const url = typeof json.html_url === "string" ? json.html_url : "";
return {
latest: `${m[1]}.${m[2]}.${m[3]}`,
releaseUrl: url.startsWith("https://github.com/") ? url : null,
publishedAt: typeof json.published_at === "string" ? json.published_at : null
};
}

async function getLatestRelease() {
const base = {
enabled: ENABLED,
latest: null,
releaseUrl: null,
publishedAt: null,
checkedAt: null
};
if (!ENABLED) return base;

if (Date.now() - cache.at >= cache.ttl) {
// One shared request even if many browsers load the page at the same moment.
if (!inflight) {
inflight = fetchLatest()
.then((data) => {
cache = { at: Date.now(), ttl: TTL_OK_MS, data };
})
.catch((err) => {
// Keep serving the last good answer; an update check must never break the app.
console.warn("Update check failed:", err.message);
cache = { at: Date.now(), ttl: TTL_FAIL_MS, data: cache.data };
})
.finally(() => {
inflight = null;
});
}
await inflight;
}

return {
...base,
...(cache.data || {}),
checkedAt: cache.at ? new Date(cache.at).toISOString() : null
};
}

module.exports = { getLatestRelease };
Binary file added docs/assets/screenshots/blacklist-check.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Binary file modified docs/assets/screenshots/dkim-dmarc-generator.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Binary file modified docs/assets/screenshots/dns-checker.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Binary file modified docs/assets/screenshots/header-analyzer.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Binary file modified docs/assets/screenshots/smtp-tester.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Binary file added docs/assets/screenshots/tls-inspector.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Loading
Loading