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
29 changes: 28 additions & 1 deletion .env.example
Original file line number Diff line number Diff line change
Expand Up @@ -2,4 +2,31 @@
# Keep this file free of real credentials and secrets.

# Port on which the backend server listens inside its container.
PORT=4000
PORT=4000
RATE_LIMIT_BLACKLIST=30
RATE_LIMIT_SCORE=15
RATE_LIMIT_TLS=20
RATE_LIMIT_SHARE=60
SHARE_TTL_DAYS=1

## Optional Variables for Share
SHARE_PER_IP_DAILY=30
SHARE_MAX_TOTAL_MB=512
SHARE_MAX_FILES=5000

## Optional Variables for Score
SCORE_CACHE_TTL_SECONDS=300
SCORE_TARGET_TTL_SECONDS=900
SCORE_MAX_DNS_QUERIES=80
SCORE_DEADLINE_SECONDS=25
SCORE_MAX_CONCURRENT=8
SCORE_MAX_QUEUE=16
SCORE_DNSBL_IPS_PER_HOUR=300
SCORE_TLS_PROBES_PER_HOUR=120

# NOTE FOR CLOUD / VPS DEPLOYMENTS:
# 1. Port 25 Outbound: Cloud providers (AWS, GCP, DigitalOcean, Linode, Hetzner) block outbound
# 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.
16 changes: 14 additions & 2 deletions .github/CODEOWNERS
Original file line number Diff line number Diff line change
@@ -1,2 +1,14 @@
# Require the designated maintainer to review all project changes.
* @kaushikparui
# Default repository owner
* @kaushikparui

# Critical CI/CD workflows and repository automation
/.github/ @kaushikparui
/.github/workflows/ @kaushikparui

# Backend dependencies and source logic
/backend/package.json @kaushikparui
/backend/package-lock.json @kaushikparui
/backend/src/ @kaushikparui

# Frontend source logic
/frontend/src/ @kaushikparui
2 changes: 1 addition & 1 deletion .github/workflows/ci.yml
Original file line number Diff line number Diff line change
Expand Up @@ -35,7 +35,7 @@ jobs:

- name: Install backend dependencies
working-directory: backend
run: npm ci
run: npm ci --ignore-scripts

- name: Check backend JavaScript syntax
shell: bash
Expand Down
2 changes: 1 addition & 1 deletion .github/workflows/release.yml
Original file line number Diff line number Diff line change
Expand Up @@ -53,7 +53,7 @@ jobs:

- name: Install backend dependencies
working-directory: backend
run: npm ci
run: npm ci --ignore-scripts

- name: Audit backend dependencies
working-directory: backend
Expand Down
148 changes: 142 additions & 6 deletions README.md

Large diffs are not rendered by default.

2 changes: 2 additions & 0 deletions backend/Dockerfile
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,8 @@ RUN npm ci --omit=dev --ignore-scripts && npm cache clean --force

COPY --chown=node:node src ./src

RUN mkdir -p /app/data/shares && chown -R node:node /app/data

# Drop root: the "node" user (uid 1000) ships with the official image.
USER node

Expand Down
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.1.2",
"version": "1.2.0",
"description": "MailMetrix SMTP and email infrastructure diagnostics backend",
"main": "src/server.js",
"scripts": {
Expand Down
16 changes: 16 additions & 0 deletions backend/src/routes/_util.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
'use strict';
// Maps service errors to HTTP responses.
const CLIENT = new Set(['BAD_INPUT', 'BLOCKED', 'ENOTFOUND']);
module.exports = function sendError(res, e) {
if (CLIENT.has(e.code)) return res.status(400).json({ error: e.message });
if (e.code === 'TOO_LARGE') return res.status(413).json({ error: e.message });
if (e.code === 'RATE_LIMITED') return res.status(429).json({ error: e.message });
if (e.code === 'BUSY') return res.status(503).set('Retry-After', '5').json({ error: e.message });
if (e.code === 'TOO_COMPLEX') return res.status(422).json({ error: e.message });
if (e.code === 'FULL') return res.status(507).json({ error: e.message });
if (['TIMEOUT', 'ECONNREFUSED', 'ECONNRESET', 'EHOSTUNREACH', 'NO_STARTTLS', 'STARTTLS_REJECTED', 'BAD_GREETING', 'NO_CERT'].includes(e.code)) {
return res.status(502).json({ error: e.message });
}
console.error(e);
return res.status(500).json({ error: 'Internal error' });
};
15 changes: 15 additions & 0 deletions backend/src/routes/blacklist.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
'use strict';
const express = require('express');
const service = require('../services/blacklist');
const sendError = require('./_util');

const router = express.Router();
router.use(express.json({ limit: '10kb' }));

router.post('/', async (req, res) => {
try {
res.json(await service.check(req.body?.target));
} catch (e) { sendError(res, e); }
});

module.exports = router;
15 changes: 15 additions & 0 deletions backend/src/routes/score.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
'use strict';
const express = require('express');
const service = require('../services/score');
const sendError = require('./_util');

const router = express.Router();
router.use(express.json({ limit: '10kb' }));

router.post('/', async (req, res) => {
try {
res.json(await service.score(req.body?.domain, { selector: req.body?.selector }));
} catch (e) { sendError(res, e); }
});

module.exports = router;
49 changes: 49 additions & 0 deletions backend/src/routes/share.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,49 @@
'use strict';
const express = require('express');
const path = require('path');
const service = require('../services/share');
const sendError = require('./_util');

const router = express.Router();
router.use(express.json({ limit: '300kb' }));

const ID_RE = /^[A-Za-z0-9_-]{8,16}$/;

router.post('/', async (req, res) => {
try {
res.status(201).json(await service.create(req.body?.type, req.body?.data, req.ip));
} catch (e) { sendError(res, e); }
});

router.get('/:id', async (req, res) => {
try {
const id = path.basename(String(req.params.id || ''));
if (!ID_RE.test(id)) return res.status(404).json({ error: 'Share not found or expired' });
const rec = await service.get(id);
if (!rec) return res.status(404).json({ error: 'Share not found or expired' });
res.json({ type: rec.type, data: rec.data, createdAt: rec.createdAt, expiresAt: rec.expiresAt });
} catch (e) { sendError(res, e); }
});

router.get('/:id/export', async (req, res) => {
try {
const id = path.basename(String(req.params.id || ''));
if (!ID_RE.test(id)) return res.status(404).json({ error: 'Share not found or expired' });
const rec = await service.get(id);
if (!rec) return res.status(404).json({ error: 'Share not found or expired' });
const fmt = String(req.query.format || 'json');
const name = `mailmetrix-${rec.type}-${id}`;
if (fmt === 'csv') {
res.type('text/csv').set('Content-Disposition', `attachment; filename="${name}.csv"`);
return res.send(service.toCsv(rec.data));
}
if (fmt === 'html') {
res.set('Content-Security-Policy', "default-src 'none'; style-src 'unsafe-inline'");
return res.type('html').send(service.toHtml(rec, id));
}
res.type('application/json').set('Content-Disposition', `attachment; filename="${name}.json"`);
return res.send(JSON.stringify(rec.data, null, 2));
} catch (e) { sendError(res, e); }
});

module.exports = router;
113 changes: 113 additions & 0 deletions backend/src/routes/tls.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,113 @@
'use strict';

const express = require('express');
const net = require('net');

const service = require('../services/tls');
const { isValidHostname, isPrivateIp } = require('../services/netguard');
const sendError = require('./_util');

const router = express.Router();

router.use(express.json({
limit: '10kb',
}));

router.post('/', async (req, res) => {
try {
const {
host,
port = 25,
mode,
versions,
} = req.body || {};

// ----------------------------------------------
// Validate & sanitize hostname / IP address
// ----------------------------------------------

if (
typeof host !== 'string' ||
!host.trim() ||
host.length > 253
) {
return res.status(400).json({
error: 'A valid hostname or IP address is required',
});
}

const sanitizedHost = host.trim().toLowerCase();

const isIp = net.isIP(sanitizedHost);

// Host must be either a valid public hostname or a valid IP literal
if (!isIp && !isValidHostname(sanitizedHost)) {
return res.status(400).json({
error: 'A valid public hostname or IP address is required',
});
}

// Direct check: reject private, loopback, or reserved IP addresses immediately
if (isIp && isPrivateIp(sanitizedHost)) {
return res.status(400).json({
error: 'Private or reserved IP addresses are not permitted',
});
}

// ----------------------------------------------
// Validate port
// ----------------------------------------------

const parsedPort = Number(port ?? 25);
if (!Number.isInteger(parsedPort) || !service.ALLOWED_PORTS.has(parsedPort)) {
return res.status(400).json({
error: `Port must be one of: ${[...service.ALLOWED_PORTS].join(', ')}`,
});
}

// ----------------------------------------------
// Validate mode
// ----------------------------------------------

if (
mode !== undefined &&
!['implicit', 'starttls'].includes(mode)
) {
return res.status(400).json({
error: 'mode must be implicit or starttls',
});
}

// ----------------------------------------------
// Validate versions
// ----------------------------------------------

if (
versions !== undefined &&
typeof versions !== 'boolean'
) {
return res.status(400).json({
error: 'versions must be a boolean',
});
}

// ----------------------------------------------
// TLS inspection
// ----------------------------------------------
// The service performs DNS resolution, validates every returned IP,
// and connects only to a validated IP (never to this hostname directly).

const result = await service.inspect({
host: sanitizedHost,
port: parsedPort,
mode,
versions: versions === true,
});

return res.json(result);
} catch (error) {
return sendError(res, error);
}
});

module.exports = router;
48 changes: 47 additions & 1 deletion backend/src/server.js
Original file line number Diff line number Diff line change
Expand Up @@ -8,8 +8,13 @@ const smtpRoutes = require("./routes/smtp");
const dnsRoutes = require("./routes/dns");
const headerRoutes = require("./routes/headers");
const generatorRoutes = require("./routes/generator");
const blacklistRoutes = require("./routes/blacklist");
const scoreRoutes = require("./routes/score");
const tlsRoutes = require("./routes/tls");
const shareRoutes = require("./routes/share");

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 @@ -76,6 +81,30 @@ const headersLimiter = createLimiter(
"Too many requests, please try again later."
);

// Each blacklist check sends 9-12 DNS queries per IP.
const blacklistLimiter = createLimiter(
positiveInt(process.env.RATE_LIMIT_BLACKLIST, 30),
"Blacklist check limit reached. Please try again later."
);

// One score run = ~40 DNS queries + outbound TLS connection.
const scoreLimiter = createLimiter(
positiveInt(process.env.RATE_LIMIT_SCORE, 15),
"Deliverability score limit reached. Please try again later."
);

// Opens outbound sockets to user-chosen hosts (SSRF-guarded in services/netguard.js).
const tlsLimiter = createLimiter(
positiveInt(process.env.RATE_LIMIT_TLS, 20),
"TLS inspection limit reached. Please try again later."
);

// Creating shares writes to disk; viewing them is cheap.
const shareLimiter = createLimiter(
positiveInt(process.env.RATE_LIMIT_SHARE, 60),
"Share limit reached. 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 @@ -97,6 +126,20 @@ app.use("/smtp", smtpLimiter);
app.use("/generator", generatorLimiter);
app.use("/dns", dnsLimiter);
app.use("/headers", headersLimiter);
app.use("/blacklist", blacklistLimiter);
app.use("/score", scoreLimiter);
app.use("/tls", tlsLimiter);
app.use("/share", shareLimiter);

// Share allows larger payloads (up to 300kb) and parses its own body, so it
// must be mounted BEFORE the global 100kb parser below.
app.use("/share", shareRoutes);

// Raw email headers can be large (long ARC/DKIM chains, or a whole message pasted by mistake),
// so /headers gets a higher body limit than the global 100kb. Mounted BEFORE the global parser,
// which skips requests that are already parsed.
const HEADERS_BODY_LIMIT = process.env.HEADERS_BODY_LIMIT || "512kb";
app.use("/headers", express.json({ limit: HEADERS_BODY_LIMIT }));

// Parse JSON request bodies with a size limit.
app.use(express.json({ limit: "100kb" }));
Expand Down Expand Up @@ -202,6 +245,9 @@ app.use("/smtp", smtpRoutes);
app.use("/dns", dnsRoutes);
app.use("/headers", headerRoutes);
app.use("/generator", generatorRoutes);
app.use("/blacklist", blacklistRoutes);
app.use("/score", scoreRoutes);
app.use("/tls", tlsRoutes);

// Handle unmatched routes.
app.use((req, res) => {
Expand Down
Loading
Loading