From f343ac58ebafeb229f5ade88b1bd7f86e5de5425 Mon Sep 17 00:00:00 2001 From: devopsgithub1234 Date: Wed, 11 Nov 2026 18:58:17 +0530 Subject: [PATCH 01/12] adding new features. - Blacklist Check - Deliveribility Score - Mail server TLS Inspector - Shareable link, CSV, pdf report --- .github/CODEOWNERS | 16 ++- README.md | 148 +++++++++++++++++++++++- backend/Dockerfile | 2 + backend/src/routes/_util.js | 13 +++ backend/src/routes/blacklist.js | 15 +++ backend/src/routes/score.js | 15 +++ backend/src/routes/share.js | 38 ++++++ backend/src/routes/tls.js | 16 +++ backend/src/server.js | 45 ++++++++ backend/src/services/blacklist.js | 93 +++++++++++++++ backend/src/services/netguard.js | 67 +++++++++++ backend/src/services/score.js | 177 ++++++++++++++++++++++++++++ backend/src/services/share.js | 95 +++++++++++++++ backend/src/services/tls.js | 180 +++++++++++++++++++++++++++++ docker-compose.yml | 12 +- frontend/src/app.js | 17 +++ frontend/src/features.css | 14 +++ frontend/src/features/blacklist.js | 42 +++++++ frontend/src/features/dns.js | 10 ++ frontend/src/features/flow.js | 47 ++++++++ frontend/src/features/generator.js | 13 +++ frontend/src/features/headers.js | 113 +++++++++++++++--- frontend/src/features/renderers.js | 134 +++++++++++++++++++++ frontend/src/features/score.js | 43 +++++++ frontend/src/features/share.js | 166 ++++++++++++++++++++++++++ frontend/src/features/smtp.js | 64 +++++----- frontend/src/features/tabs.js | 32 ++++- frontend/src/features/tls.js | 57 +++++++++ frontend/src/features/ui.js | 50 ++++++++ frontend/src/index-snippets.html | 42 +++++++ frontend/src/index.html | 162 +++++++++++++++++++++++++- frontend/src/style.css | 67 ++++++++++- 32 files changed, 1948 insertions(+), 57 deletions(-) create mode 100644 backend/src/routes/_util.js create mode 100644 backend/src/routes/blacklist.js create mode 100644 backend/src/routes/score.js create mode 100644 backend/src/routes/share.js create mode 100644 backend/src/routes/tls.js create mode 100644 backend/src/services/blacklist.js create mode 100644 backend/src/services/netguard.js create mode 100644 backend/src/services/score.js create mode 100644 backend/src/services/share.js create mode 100644 backend/src/services/tls.js create mode 100644 frontend/src/features.css create mode 100644 frontend/src/features/blacklist.js create mode 100644 frontend/src/features/renderers.js create mode 100644 frontend/src/features/score.js create mode 100644 frontend/src/features/share.js create mode 100644 frontend/src/features/tls.js create mode 100644 frontend/src/features/ui.js create mode 100644 frontend/src/index-snippets.html diff --git a/.github/CODEOWNERS b/.github/CODEOWNERS index be4fa8b..08012cb 100644 --- a/.github/CODEOWNERS +++ b/.github/CODEOWNERS @@ -1,2 +1,14 @@ -# Require the designated maintainer to review all project changes. -* @kaushikparui \ No newline at end of file +# 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 \ No newline at end of file diff --git a/README.md b/README.md index 9cac4e1..0051b2b 100644 --- a/README.md +++ b/README.md @@ -2,7 +2,7 @@ **Self-hosted email infrastructure diagnostics.** -MailMetrix is an email diagnostics toolkit for developers, system administrators, and DevOps engineers. It brings SMTP testing, DNS email authentication checks, email header analysis, and DKIM/DMARC generation together in one web application. +MailMetrix is an email diagnostics toolkit for developers, system administrators, and DevOps engineers. It brings SMTP testing, DNS email authentication checks, email header analysis, and DKIM/DMARC generation together in one web application. It also includes blacklist checking, a domain deliverability score, a TLS certificate inspector, and shareable, exportable results. Run MailMetrix in your own environment and maintain control over how you deploy and access your email diagnostic tools. @@ -88,6 +88,96 @@ RSA key generation is CPU-intensive, so it runs off the main thread with a concu **Note:** A generated record is not proof that your email authentication configuration is correct. Validate the published configuration after deployment. +### 5. Blacklist Checker + +Check whether a sending IP address or domain is listed on common DNS blacklists (DNSBLs). + +- **IPv4 addresses** are checked against 9 lists: Spamhaus ZEN, Barracuda, SpamCop, Passive Spam Block List, UCEPROTECT Level 1, DroneBL, Mailspike, Manitu (NiX Spam), and s5h.net. +- **Domains** are checked against 3 domain lists (Spamhaus DBL, SURBL, URIBL). The domain's first three A-record IPs are also checked against the IP lists. +- Each list reports `listed`, `clean`, or `unknown`, with the return code and the list's reason text where available. +- IPv6 addresses are not supported for IP blacklists. + +```http +POST /api/blacklist +Content-Type: application/json + +{ "target": "203.0.113.10" } +``` + +**Note:** Several blacklists (Spamhaus in particular) refuse queries that arrive through large public resolvers such as `8.8.8.8` or `1.1.1.1`. These answers are shown as `unknown`, not `clean`. If you see many `unknown` results, point the backend container at your host's or provider's resolver using the commented `dns:` option in `docker-compose.yml`. + +### 6. Deliverability Score + +Grade a domain's overall email health from **A to F** (0-100) by combining several checks into one report, with fixes ordered by impact. + +| Check | Weight | What is evaluated | +|---|---|---| +| MX records | 10 | Presence and redundancy of MX records | +| SPF | 20 | Single record, enforcement mechanism (`-all`, `~all`, `+all`), and the 10 DNS-lookup limit | +| DKIM | 15 | Public key found on a supplied selector or on common selectors | +| DMARC | 20 | Policy strength (`none`, `quarantine`, `reject`) and reporting address | +| Reverse DNS (FCrDNS) | 10 | Forward-confirmed PTR records for the MX IP addresses | +| Blacklists | 10 | MX IP addresses on the IP blacklists listed above | +| MTA-STS | 5 | Presence of the `_mta-sts` TXT record | +| Mail server TLS | 10 | Certificate and protocol of the primary MX on port 25 | + +Checks that cannot be evaluated (for example, the TLS check when outbound port 25 is blocked, or blacklist servers refusing the resolver) are skipped and excluded from the total rather than counted as failures. + +```http +POST /api/score +Content-Type: application/json + +{ "domain": "example.com", "selector": "default" } +``` + +`selector` is optional. When omitted, a list of common DKIM selectors is probed; a domain using a custom selector may therefore show a partial DKIM result until its selector is supplied. + +**Note:** A score is a diagnostic aid, not a guarantee of inbox placement. Receiving providers apply their own reputation and content rules. + +### 7. TLS Certificate Inspector + +Negotiate TLS with a mail (or other TLS) server and review its certificate and connection details. + +- Supported ports: `25`, `587`, `2525` (SMTP with STARTTLS), and `465`, `993`, `995`, `443` (implicit TLS). +- Reports the negotiated protocol and cipher, whether the certificate chain is trusted, the certificate subject, issuer, validity dates, days remaining, key type and size, subject alternative names, SHA-256 fingerprint, and the certificate chain. +- Produces severity-rated findings for expired or soon-to-expire certificates, hostname mismatch, untrusted or self-signed certificates, deprecated TLS versions, weak ciphers, and weak RSA keys. +- Optionally probes which TLS versions (1.0-1.3) the server accepts. This opens several extra connections and is slower. +- Untrusted certificates on port 25 are reported as warnings rather than failures, because opportunistic TLS between mail servers commonly tolerates them. Strict senders and MTA-STS do not. + +```http +POST /api/tls +Content-Type: application/json + +{ "host": "mail.example.com", "port": 25, "versions": false } +``` + +Because this tool makes outbound connections to a host you specify, it is guarded by the same address restrictions as the SMTP tester (see [Built-in protections](#built-in-protections)). + +### 8. Shareable Links & Export + +The results of every tool (SMTP Tester, DNS Email Checker, Email Header Analyzer, DKIM & DMARC Generator, Blacklist Checker, Deliverability Score, and TLS Inspector) include a bar with: + +- **Share link:** stores the result on the server and returns a link of the form `/?share=`. Links expire automatically (7 days by default; see `SHARE_TTL_DAYS`). +- **JSON** and **CSV:** download the result from the browser. CSV values are protected against spreadsheet formula injection. +- **PDF:** prints only the result using the browser's print dialog, where you can choose "Save as PDF". + +```http +POST /api/share +GET /api/share/ +GET /api/share//export?format=json|csv|html +``` + +Notes: + +- SMTP Tester, DNS Checker, Header Analyzer, DKIM & DMARC Generator, Blacklist, Deliverability Score, and TLS results can be shared. +- A Header Analyzer share contains only the parsed analysis (sender and return-path addresses, message ID, authentication results, delivery path, and findings). The raw header text you pasted is never sent to the share endpoint. Header analyses can still contain third-party email addresses and mail server IP addresses, so by default the subject, display names, and the username part of every email address are hidden in shared and exported results. You can turn this off with the checkbox shown under the result. The PDF option prints the result exactly as displayed on screen. +- An SMTP share contains only the diagnostic output: status, message ID, accepted and rejected recipients, error stage and code, plus the SMTP host, port, and security mode. It never contains the username, password, From address, or message body. +- A DNS share contains the MX, SPF, and DMARC results, plus the DKIM result if a selector was checked. +- DKIM private keys are never included in shared results, JSON/CSV downloads, or printed output, even though the generator displays them on screen. The server also removes private-key blocks and any field named like a password, secret, token, or private key before anything is stored. +- Anyone who has a share link can view the result until it expires. Link IDs are random and unguessable, but links are not otherwise authenticated. +- If you protect your deployment with authentication, people opening a share link need access to the deployment too. +- Shared results are written to the `mailmetrix-data` Docker volume so they survive container restarts and rebuilds. Each result is limited to 256 KB, and storage is capped at 5,000 results. + ## Architecture MailMetrix separates the backend API from the frontend application. @@ -104,16 +194,26 @@ backend/ ├── package-lock.json └── src ├── routes + │ ├── _util.js + │ ├── blacklist.js │ ├── dns.js │ ├── generator.js │ ├── headers.js - │ └── smtp.js + │ ├── score.js + │ ├── share.js + │ ├── smtp.js + │ └── tls.js ├── server.js └── services + ├── blacklist.js ├── dns.js ├── generator.js ├── headers.js - └── smtp.js + ├── netguard.js + ├── score.js + ├── share.js + ├── smtp.js + └── tls.js ``` ### Frontend @@ -125,12 +225,18 @@ frontend/ └── src ├── app.js ├── features + │ ├── blacklist.js │ ├── dns.js │ ├── flow.js │ ├── generator.js │ ├── headers.js + │ ├── renderers.js + │ ├── score.js + │ ├── share.js │ ├── smtp.js │ ├── tabs.js + │ ├── tls.js + │ ├── ui.js │ └── utils.js ├── icons │ ├── android-chrome-192x192.png @@ -152,6 +258,11 @@ Backend routes and services separate API handling from feature logic. Frontend f The frontend intentionally uses a single-page HTML shell, avoiding unnecessary template and loading complexity. +Shared building blocks: + +- `backend/src/services/netguard.js` is the common outbound-connection guard (public-address validation and hostname checks) used by the blacklist, score, and TLS services. +- `frontend/src/features/flow.js` drives the Workflow card for every tool, and `frontend/src/features/share.js` wires the Blacklist, Score, and TLS tools (request, rendering, and the share/export bar) and provides the same share/export bar to the SMTP, DNS, and Generator tabs. `renderers.js` renders shared SMTP, DNS, and Generator results when a share link is opened. `ui.js` provides DOM helpers that build results with text nodes rather than `innerHTML`. + ## Version Management MailMetrix includes a version synchronization script at `scripts/sync-version.js` to keep version information consistent across the project. @@ -315,6 +426,8 @@ Stop the application: docker compose down ``` +Shared results are kept in the `mailmetrix-data` volume. `docker compose down` keeps the volume; `docker compose down -v` deletes it, along with all stored share links. + ### Development with Docker Compose Watch If your Docker Compose configuration defines file-watch actions, you can use: @@ -339,6 +452,12 @@ The following endpoints are currently documented by the project. | `GET` | `/api/dns/dkim?domain=example.com&selector=google` | Check a DKIM selector | | `POST` | `/api/headers/analyze` | Analyze submitted email headers | | `POST` | `/api/generator` | Generate SPF, DKIM, and DMARC records | +| `POST` | `/api/blacklist` | Check an IPv4 address or domain against DNS blacklists | +| `POST` | `/api/score` | Calculate a domain's deliverability score | +| `POST` | `/api/tls` | Inspect a server's TLS certificate and connection | +| `POST` | `/api/share` | Store a shareable result (SMTP, DNS, Header, Generator, Blacklist, Score, or TLS) and return a share ID | +| `GET` | `/api/share/` | Retrieve a shared result | +| `GET` | `/api/share//export?format=json\|csv\|html` | Download a shared result | Request bodies, response schemas, and error formats depend on the current API implementation. @@ -379,6 +498,8 @@ MailMetrix is designed to support self-hosted email diagnostics. Deploy it with | **HTTP hardening** | Nginx sends `Content-Security-Policy`, `X-Frame-Options`, `X-Content-Type-Options`, `Referrer-Policy`, and `Permissions-Policy` headers, hides its version, and strips the backend's `X-Powered-By` header. | | **Information exposure** | The public health probe returns no process internals. Detailed telemetry is limited to the internal network. | | **Container privileges** | Both containers run as non-root users (`node` for the backend, uid `101` for Nginx). All Linux capabilities are dropped and `no-new-privileges` is set. Base images are pinned to supported versions rather than floating tags. | +| **TLS inspector and score connections** | The TLS inspector (and the TLS check inside the deliverability score) validates the hostname, resolves it once, rejects loopback, private, link-local, and reserved addresses, and connects only to the validated IP. Ports are limited to a fixed allow-list (`25`, `465`, `587`, `2525`, `443`, `993`, `995`). | +| **Shared results** | Only SMTP, DNS, Header, Generator, Blacklist, Score, and TLS results can be stored, and header shares never include the raw header text. Private keys and secret-named fields are removed before storage. Share IDs are random, entries expire automatically, payload size and total count are capped, shared output is rendered with escaped text, and the HTML export is served with a restrictive Content-Security-Policy. | These controls reduce risk but do **not** replace authentication. Please read the limitations below. @@ -451,6 +572,8 @@ Then: - The Content Security Policy is strict (`script-src 'self'`). If you add inline scripts, third-party scripts, or web fonts to the frontend, update the policy in `frontend/nginx.conf`. - Internationalized (non-ASCII) email domains must be supplied in punycode form. - Network-level controls still matter. If you run on a cloud host, also block container access to the metadata address (`169.254.169.254`) or require IMDSv2 with a hop limit of 1. +- Shared result links are protected only by an unguessable ID. Anyone with a link can view the result until it expires, and anyone who can reach the deployment can create links. Share results only if their contents (hostnames, IP addresses, certificate details, and domain configuration) are fine to disclose to the recipients. For SMTP results this includes the SMTP host and the accepted and rejected recipient addresses; for header analyses it includes mail server hostnames and IP addresses from the delivery path. +- Shared results are stored as files in the `mailmetrix-data` volume and are removed after `SHARE_TTL_DAYS`. Back up or delete that volume according to your own retention needs. ### Understand external connections @@ -462,6 +585,8 @@ For example: - DNS checks query DNS infrastructure. - Header analysis processes the supplied header data. - DKIM/DMARC generation operates according to the implementation of the generator. +- Blacklist checks send DNS queries containing the IP address or domain being checked to the operators of the blacklists, through the resolver available to the backend container. +- The TLS inspector connects to the host and port you specify, and the deliverability score connects to the domain's primary MX on port 25 and queries DNS for its records and blacklists. Review the source code to understand which services receive requests or data during each operation. @@ -502,6 +627,12 @@ All of the following are optional. Add them to `.env` (or the backend `environme | `RATE_LIMIT_GENERATOR` | `30` | Max generator requests per client per window. | | `RATE_LIMIT_DNS` | `60` | Max DNS requests per client per window. | | `RATE_LIMIT_HEADERS` | `100` | Max header-analysis requests per client per window. | +| `RATE_LIMIT_BLACKLIST` | `30` | Max blacklist-check requests per client per window. | +| `RATE_LIMIT_SCORE` | `15` | Max deliverability-score requests per client per window. | +| `RATE_LIMIT_TLS` | `20` | Max TLS-inspection requests per client per window. | +| `RATE_LIMIT_SHARE` | `60` | Max share and share-export requests per client per window. | +| `SHARE_DIR` | `/app/data/shares` in `docker-compose.yml` | Directory where shared results are stored. Keep it on the `mailmetrix-data` volume so links survive restarts. | +| `SHARE_TTL_DAYS` | `7` | Days before a shared result link expires and is deleted. | | `SMTP_ALLOWED_PORTS` | `25,465,587,2525` | SMTP ports the tester may connect to. | | `SMTP_ALLOWED_HOSTS` | *(empty)* | Comma-separated hostnames of trusted internal relays that bypass the private-address block. Only list names you control. | | `ALLOWED_RECIPIENT_DOMAINS` | *(empty)* | Restrict test-email recipients to these domains, for example `example.com,*.corp.example.com`. `*.` matches subdomains. Empty means no domain restriction. | @@ -535,13 +666,14 @@ These checks reduce risk but do not guarantee that the software is free of vulne ## Privacy Policy -*Last updated: 4 November 2026* +*Last updated: 11 November 2026* ### In short - MailMetrix is **self-hosted software**. The maintainers do not operate a hosted service and **do not receive any data** from your instance. - MailMetrix has **no analytics, advertising, tracking, or telemetry**, and does not send data to the maintainers. - The backend does not store SMTP credentials, email headers, or generated keys. They are processed for the request and discarded. +- The only results the backend stores are SMTP, DNS, Header Analysis, Generator, Blacklist, Deliverability Score, and TLS results that a user explicitly chooses to share. Passwords, DKIM private keys, and raw header text are never stored. Header analyses hide the subject, display names, and email usernames by default. Shared results are kept on your instance's disk until they expire. - Data leaves your instance only to destinations **you** specify, such as the SMTP server you test and DNS resolvers. ### Scope and responsibility @@ -554,21 +686,24 @@ This policy applies to the MailMetrix software and to the project's GitHub Pages |---|---|---| | SMTP host, port, username, password, sender, recipient, subject, and message | To authenticate to and send a test email through the SMTP server you specify. | Used in memory for the request and not stored by MailMetrix. The password is not included in API responses. The data is sent to the SMTP server you specify, which handles it under its own policies. | | Domain names and DKIM selectors | To perform DNS lookups. | Not stored. They appear in request logs because they are part of the request URL. | -| Email headers | To analyze message routing and authentication results. | Processed in memory and not stored. | +| Email headers | To analyze message routing and authentication results. | Processed in memory and not stored. Only the parsed analysis (never the raw header text) is stored, and only if the user selects "Share link". | | Generated DKIM private keys | To give you key material to publish and keep. | Not stored on the server. The key is delivered to your browser, so protect it and transmit it only over HTTPS. | +| IP addresses, domains, hostnames, and ports submitted to the Blacklist, Score, and TLS tools | To perform blacklist lookups, score checks, and TLS handshakes. | Sent in the request body and processed in memory; not stored unless the user shares the result. The queried IP or domain is sent to blacklist operators via DNS, and the TLS and score tools connect to the host specified. | +| Shared results (SMTP, DNS, Header Analysis, Generator, Blacklist, Score, and TLS results) | To let a user send a result to someone else through a link. Shared SMTP results contain diagnostic output and the SMTP host and port, not credentials or message content; shared generator results exclude private keys; shared header analyses exclude the raw headers and, by default, hide the subject, display names, and email usernames. | Stored as a file on the instance's `mailmetrix-data` volume only when the user selects "Share link", and deleted automatically after `SHARE_TTL_DAYS` (7 days by default). Anyone with the link can view it until then. | | Client IP addresses | To apply rate limits. | Held temporarily in memory as counters, which expire after the rate-limit window and reset on restart. They also appear in Nginx access logs. | | Logs | To operate and troubleshoot the instance. | See below. | ### Logs - **Backend:** logs a timestamp, request method, URL (including the query string), status code, and duration. It does not intentionally log request bodies, so SMTP credentials sent in a request body are not written to these logs. Error messages may also be logged. -- **Nginx:** logs client IP addresses, request lines, status codes, and user agents in its standard access-log format. +- **Nginx:** logs client IP addresses, request lines, status codes, and user agents in its standard access-log format. Opening a share link (`/?share=`) records the share ID in these logs. - **Retention:** Docker keeps container logs on the host. The default Compose file rotates them (10 MB per file, up to 3 files per service). Removing the containers, for example with `docker compose down`, deletes their logs. Adjust log settings if you need shorter retention. ### Third parties and external connections - MailMetrix does not include third-party analytics, advertising, or tracking services. - SMTP tests connect to the mail server you specify, and DNS checks query DNS resolvers available to your environment. Those services receive the data needed for the lookup or message and handle it under their own policies. +- Blacklist checks and the blacklist portion of the deliverability score send DNS queries containing the IP address or domain being checked to the blacklist operators (for example Spamhaus, Barracuda, or SpamCop) through your resolver. Those operators handle query data under their own policies. - Your hosting provider, network, or reverse proxy can observe traffic to your instance. Use HTTPS for remote access. ### Cookies and browser storage @@ -585,6 +720,7 @@ The MailMetrix GitHub Pages site is a static page. It does not use analytics, co - Protect your instance with authentication and HTTPS. - Be careful before pasting real email headers, which can contain addresses, IP addresses, and message identifiers of third parties. - Configure log retention to suit your needs. +- Share results only when their contents are fine for the recipients to see, and lower `SHARE_TTL_DAYS` if you want links to expire sooner. - Do not post credentials, private keys, or personal data in public issues. ### Changes to this policy diff --git a/backend/Dockerfile b/backend/Dockerfile index 617d4fb..166eb7a 100644 --- a/backend/Dockerfile +++ b/backend/Dockerfile @@ -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 diff --git a/backend/src/routes/_util.js b/backend/src/routes/_util.js new file mode 100644 index 0000000..065c304 --- /dev/null +++ b/backend/src/routes/_util.js @@ -0,0 +1,13 @@ +'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 === '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' }); +}; diff --git a/backend/src/routes/blacklist.js b/backend/src/routes/blacklist.js new file mode 100644 index 0000000..9686815 --- /dev/null +++ b/backend/src/routes/blacklist.js @@ -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; diff --git a/backend/src/routes/score.js b/backend/src/routes/score.js new file mode 100644 index 0000000..9107ebf --- /dev/null +++ b/backend/src/routes/score.js @@ -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; diff --git a/backend/src/routes/share.js b/backend/src/routes/share.js new file mode 100644 index 0000000..028897d --- /dev/null +++ b/backend/src/routes/share.js @@ -0,0 +1,38 @@ +'use strict'; +const express = require('express'); +const service = require('../services/share'); +const sendError = require('./_util'); + +const router = express.Router(); +router.use(express.json({ limit: '300kb' })); + +router.post('/', (req, res) => { + try { + res.status(201).json(service.create(req.body?.type, req.body?.data)); + } catch (e) { sendError(res, e); } +}); + +router.get('/:id', (req, res) => { + const rec = service.get(req.params.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 }); +}); + +router.get('/:id/export', (req, res) => { + const rec = service.get(req.params.id); + if (!rec) return res.status(404).json({ error: 'Share not found or expired' }); + const fmt = String(req.query.format || 'json'); + const name = `mailprobe-${rec.type}-${req.params.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, req.params.id)); + } + res.type('application/json').set('Content-Disposition', `attachment; filename="${name}.json"`); + return res.send(JSON.stringify(rec.data, null, 2)); +}); + +module.exports = router; diff --git a/backend/src/routes/tls.js b/backend/src/routes/tls.js new file mode 100644 index 0000000..35eac34 --- /dev/null +++ b/backend/src/routes/tls.js @@ -0,0 +1,16 @@ +'use strict'; +const express = require('express'); +const service = require('../services/tls'); +const sendError = require('./_util'); + +const router = express.Router(); +router.use(express.json({ limit: '10kb' })); + +router.post('/', async (req, res) => { + try { + const { host, port, mode, versions } = req.body || {}; + res.json(await service.inspect({ host, port: port ?? 25, mode, versions: versions === true })); + } catch (e) { sendError(res, e); } +}); + +module.exports = router; diff --git a/backend/src/server.js b/backend/src/server.js index b3d2b4c..48ce2bb 100644 --- a/backend/src/server.js +++ b/backend/src/server.js @@ -8,6 +8,10 @@ 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 PORT = Number(process.env.PORT || 4000); @@ -76,6 +80,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(); @@ -97,6 +125,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" })); @@ -202,6 +244,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) => { diff --git a/backend/src/services/blacklist.js b/backend/src/services/blacklist.js new file mode 100644 index 0000000..ec4040d --- /dev/null +++ b/backend/src/services/blacklist.js @@ -0,0 +1,93 @@ +'use strict'; +const dns = require('dns'); +const net = require('net'); +const { resolvePublic, isValidHostname } = require('./netguard'); + +const resolver = new dns.promises.Resolver({ timeout: 4000, tries: 1 }); + +const IP_LISTS = [ + { zone: 'zen.spamhaus.org', name: 'Spamhaus ZEN' }, + { zone: 'b.barracudacentral.org', name: 'Barracuda' }, + { zone: 'bl.spamcop.net', name: 'SpamCop' }, + { zone: 'psbl.surriel.com', name: 'Passive Spam Block List' }, + { zone: 'dnsbl-1.uceprotect.net', name: 'UCEPROTECT L1' }, + { zone: 'dnsbl.dronebl.org', name: 'DroneBL' }, + { zone: 'bl.mailspike.net', name: 'Mailspike' }, + { zone: 'ix.dnsbl.manitu.net', name: 'Manitu (NiX Spam)' }, + { zone: 'all.s5h.net', name: 's5h.net' }, +]; + +const DOMAIN_LISTS = [ + { zone: 'dbl.spamhaus.org', name: 'Spamhaus DBL' }, + { zone: 'multi.surbl.org', name: 'SURBL' }, + { zone: 'multi.uribl.com', name: 'URIBL' }, +]; + +function reverseIPv4(ip) { + return ip.split('.').reverse().join('.'); +} + +async function queryZone(query, list) { + const base = { zone: list.zone, name: list.name }; + try { + const answers = await resolver.resolve4(`${query}.${list.zone}`); + const code = answers[0]; + // Spamhaus & others return 127.255.255.x when the resolver is blocked/over quota. + if (code.startsWith('127.255.255.')) { + return { ...base, status: 'unknown', returnCode: code, reason: 'Query refused (public resolver blocked or quota exceeded)' }; + } + let reason; + try { + reason = (await resolver.resolveTxt(`${query}.${list.zone}`)).map((c) => c.join('')).join(' ').slice(0, 300); + } catch { /* TXT is optional */ } + return { ...base, status: 'listed', returnCode: code, reason }; + } catch (e) { + if (e.code === 'ENOTFOUND' || e.code === 'ENODATA') return { ...base, status: 'clean' }; + return { ...base, status: 'unknown', reason: e.code || 'Lookup failed' }; + } +} + +async function checkIp(ip) { + if (!net.isIPv4(ip)) { + const e = new Error('Only IPv4 addresses are supported for IP blacklists'); + e.code = 'BAD_INPUT'; + throw e; + } + const q = reverseIPv4(ip); + const results = await Promise.all(IP_LISTS.map((l) => queryZone(q, l))); + return { type: 'ip', target: ip, results }; +} + +async function checkDomain(domain) { + const results = await Promise.all(DOMAIN_LISTS.map((l) => queryZone(domain, l))); + return { type: 'domain', target: domain, results }; +} + +function summarize(entries) { + const all = entries.flatMap((e) => e.results); + const listed = all.filter((r) => r.status === 'listed').length; + const unknown = all.filter((r) => r.status === 'unknown').length; + return { checked: all.length, listed, clean: all.length - listed - unknown, unknown }; +} + +// target may be an IPv4 address or a domain (domain: checks domain lists + its A records). +async function check(target) { + target = String(target || '').trim().toLowerCase(); + const entries = []; + if (net.isIPv4(target)) { + await resolvePublic(target); + entries.push(await checkIp(target)); + } else if (isValidHostname(target)) { + entries.push(await checkDomain(target)); + let ips = []; + try { ips = await resolver.resolve4(target); } catch { /* no A record */ } + for (const ip of ips.slice(0, 3)) entries.push(await checkIp(ip)); + } else { + const e = new Error('Enter a valid IPv4 address or domain name'); + e.code = 'BAD_INPUT'; + throw e; + } + return { target, checkedAt: new Date().toISOString(), summary: summarize(entries), entries }; +} + +module.exports = { check, checkIp, checkDomain }; diff --git a/backend/src/services/netguard.js b/backend/src/services/netguard.js new file mode 100644 index 0000000..eed2b78 --- /dev/null +++ b/backend/src/services/netguard.js @@ -0,0 +1,67 @@ +'use strict'; +// SSRF protection: only allow connections to public IPs. +const dns = require('dns').promises; +const net = require('net'); + +const HOST_RE = /^(?=.{1,253}$)([a-z0-9_]([a-z0-9_-]{0,61}[a-z0-9_])?\.)+[a-z]{2,63}$/i; + +function blocked(msg) { + const e = new Error(msg); + e.code = 'BLOCKED'; + return e; +} + +function isPrivateIPv4(ip) { + const [a, b] = ip.split('.').map(Number); + return ( + a === 0 || a === 10 || a === 127 || a >= 224 || + (a === 169 && b === 254) || + (a === 172 && b >= 16 && b <= 31) || + (a === 192 && b === 168) || + (a === 100 && b >= 64 && b <= 127) || + (a === 198 && (b === 18 || b === 19)) + ); +} + +function isPrivateIPv6(ip) { + const l = ip.toLowerCase(); + if (l === '::' || l === '::1') return true; + if (l.startsWith('::ffff:')) { + const v4 = l.slice(7); + return net.isIPv4(v4) ? isPrivateIPv4(v4) : true; + } + return /^(fc|fd|fe[89ab])/.test(l); +} + +function isPrivateIp(ip) { + if (net.isIPv4(ip)) return isPrivateIPv4(ip); + if (net.isIPv6(ip)) return isPrivateIPv6(ip); + return true; +} + +function isValidHostname(h) { + return typeof h === 'string' && HOST_RE.test(h); +} + +// Resolve a host and return public IPs only. Throws BLOCKED otherwise. +// Connect to the returned IP (not the hostname) to avoid DNS rebinding. +async function resolvePublic(host) { + if (net.isIP(host)) { + if (isPrivateIp(host)) throw blocked('Private or reserved IP addresses are not allowed'); + return [host]; + } + if (!isValidHostname(host)) throw blocked('Invalid hostname'); + let addrs; + try { + addrs = await dns.lookup(host, { all: true }); + } catch { + const e = new Error(`Could not resolve ${host}`); + e.code = 'ENOTFOUND'; + throw e; + } + if (!addrs.length) throw new Error(`No addresses for ${host}`); + if (addrs.some((a) => isPrivateIp(a.address))) throw blocked('Host resolves to a private or reserved address'); + return addrs.map((a) => a.address); +} + +module.exports = { isPrivateIp, isValidHostname, resolvePublic, HOST_RE }; diff --git a/backend/src/services/score.js b/backend/src/services/score.js new file mode 100644 index 0000000..5488804 --- /dev/null +++ b/backend/src/services/score.js @@ -0,0 +1,177 @@ +'use strict'; +// Deliverability score. Self-contained: swap the DNS helpers for your services/dns.js if you prefer. +const dns = require('dns'); +const { isValidHostname } = require('./netguard'); +const blacklist = require('./blacklist'); +const tlsService = require('./tls'); + +const resolver = new dns.promises.Resolver({ timeout: 4000, tries: 2 }); +const DKIM_SELECTORS = ['default', 'google', 'selector1', 'selector2', 'k1', 'k2', 'k3', 's1', 's2', 'mail', 'dkim', 'smtp', 'mandrill', 'mailjet', 'amazonses', 'zoho', 'sendgrid', 'em', 'protonmail']; + +const txt = async (name) => { + try { return (await resolver.resolveTxt(name)).map((c) => c.join('')); } catch { return []; } +}; +const safe = async (fn, fallback) => { try { return await fn(); } catch { return fallback; } }; + +const mk = (id, label, max, points, status, detail, fix) => ({ id, label, max, points: Math.round(points * 10) / 10, status, detail, fix: fix || null }); + +async function getMx(domain) { + const mx = await safe(() => resolver.resolveMx(domain), []); + return mx.filter((m) => m.exchange && m.exchange !== '.').sort((a, b) => a.priority - b.priority); +} + +async function mxIps(mx) { + const out = []; + for (const m of mx.slice(0, 3)) { + const ips = await safe(() => resolver.resolve4(m.exchange), []); + for (const ip of ips.slice(0, 2)) out.push({ host: m.exchange, ip }); + } + return out; +} + +async function spfLookups(domain, depth = 0, seen = new Set()) { + if (depth > 10 || seen.has(domain)) return 0; + seen.add(domain); + const rec = (await txt(domain)).find((t) => /^v=spf1\b/i.test(t)); + if (!rec) return 0; + let n = 0; + for (const term of rec.split(/\s+/).slice(1)) { + const m = term.replace(/^[+\-~?]/, ''); + if (/^include:/i.test(m)) n += 1 + (await spfLookups(m.slice(8), depth + 1, seen)); + else if (/^redirect=/i.test(m)) n += 1 + (await spfLookups(m.slice(9), depth + 1, seen)); + else if (/^(a|mx)(:|\/|$)/i.test(m) || /^(ptr|exists:)/i.test(m)) n += 1; + } + return n; +} + +async function checkMx(domain, mx) { + if (!mx.length) return mk('mx', 'MX records', 10, 0, 'fail', 'No MX records found.', 'Add MX records pointing at your mail servers.'); + if (mx.length === 1) return mk('mx', 'MX records', 10, 8, 'warn', `1 MX record (${mx[0].exchange}).`, 'Add a secondary MX for redundancy.'); + return mk('mx', 'MX records', 10, 10, 'pass', `${mx.length} MX records, primary ${mx[0].exchange}.`); +} + +async function checkSpf(domain) { + const recs = (await txt(domain)).filter((t) => /^v=spf1\b/i.test(t)); + if (!recs.length) return mk('spf', 'SPF', 20, 0, 'fail', 'No SPF record found.', 'Publish a TXT record such as "v=spf1 include: -all".'); + if (recs.length > 1) return mk('spf', 'SPF', 20, 4, 'fail', `${recs.length} SPF records found; receivers will return PermError.`, 'Merge into a single SPF record.'); + const rec = recs[0]; + const lookups = await spfLookups(domain); + let pts = 20; + const notes = []; + let status = 'pass'; + let fix = null; + if (/\s\+all\b/i.test(rec) || /\sall\b/i.test(rec) && !/[-~?]all/i.test(rec)) { pts = 2; status = 'fail'; notes.push('Allows any sender (+all).'); fix = 'Replace with -all or ~all.'; } + else if (/\s\?all\b/i.test(rec)) { pts -= 10; status = 'warn'; notes.push('Neutral policy (?all).'); fix = 'Use ~all or -all.'; } + else if (/\s~all\b/i.test(rec)) { pts -= 3; notes.push('Soft fail (~all).'); } + else if (/\s-all\b/i.test(rec)) notes.push('Hard fail (-all).'); + else if (!/redirect=/i.test(rec)) { pts -= 8; status = 'warn'; notes.push('No "all" mechanism.'); fix = 'End the record with -all or ~all.'; } + if (lookups > 10) { pts = Math.min(pts, 6); status = 'fail'; notes.push(`${lookups} DNS lookups (limit is 10).`); fix = 'Flatten includes to stay at 10 lookups or fewer.'; } + else if (lookups >= 8) { pts -= 2; if (status === 'pass') status = 'warn'; notes.push(`${lookups}/10 DNS lookups.`); } + else notes.push(`${lookups}/10 DNS lookups.`); + return mk('spf', 'SPF', 20, Math.max(pts, 0), status, notes.join(' '), fix); +} + +async function checkDkim(domain, selector) { + const selectors = selector ? [selector] : DKIM_SELECTORS; + const found = []; + await Promise.all(selectors.map(async (s) => { + const r = await txt(`${s}._domainkey.${domain}`); + if (r.some((t) => /v=DKIM1|p=/i.test(t))) found.push(s); + })); + if (found.length) return mk('dkim', 'DKIM', 15, 15, 'pass', `Key found for selector(s): ${found.join(', ')}.`); + return selector + ? mk('dkim', 'DKIM', 15, 0, 'fail', `No DKIM key at ${selector}._domainkey.${domain}.`, 'Publish your DKIM public key or check the selector name.') + : mk('dkim', 'DKIM', 15, 7, 'warn', 'No key found on common selectors (yours may use a custom one).', 'Re-run with your DKIM selector to verify.'); +} + +async function checkDmarc(domain) { + const rec = (await txt(`_dmarc.${domain}`)).find((t) => /^v=DMARC1/i.test(t)); + if (!rec) return mk('dmarc', 'DMARC', 20, 0, 'fail', 'No DMARC record found.', 'Add _dmarc TXT: "v=DMARC1; p=none; rua=mailto:dmarc@' + domain + '".'); + const p = (rec.match(/\bp=(\w+)/i) || [])[1]?.toLowerCase(); + const hasRua = /\brua=/i.test(rec); + let pts = { reject: 20, quarantine: 17, none: 9 }[p] ?? 5; + if (!hasRua) pts -= 2; + const status = p === 'reject' || p === 'quarantine' ? 'pass' : 'warn'; + const fix = p === 'none' ? 'Move to p=quarantine, then p=reject once reports look clean.' : !hasRua ? 'Add an rua= address to receive aggregate reports.' : null; + return mk('dmarc', 'DMARC', 20, Math.max(pts, 0), status, `Policy p=${p || 'unknown'}${hasRua ? ', reporting enabled' : ', no reporting address'}.`, fix); +} + +async function checkRdns(ips) { + if (!ips.length) return mk('rdns', 'Reverse DNS (FCrDNS)', 10, 0, 'skip', 'No MX IPs to test.'); + let ok = 0; + const bad = []; + for (const { ip } of ips) { + const names = await safe(() => resolver.reverse(ip), []); + let good = false; + for (const n of names) { + const fwd = await safe(() => resolver.resolve4(n), []); + if (fwd.includes(ip)) { good = true; break; } + } + if (good) ok += 1; else bad.push(ip); + } + const pts = (ok / ips.length) * 10; + if (!bad.length) return mk('rdns', 'Reverse DNS (FCrDNS)', 10, 10, 'pass', `All ${ips.length} MX IP(s) have matching PTR and A records.`); + return mk('rdns', 'Reverse DNS (FCrDNS)', 10, pts, ok ? 'warn' : 'fail', `No forward-confirmed PTR for: ${bad.join(', ')}.`, 'Ask your host to set a PTR that resolves back to the same IP.'); +} + +async function checkBlacklist(ips) { + if (!ips.length) return mk('blacklist', 'Blacklists', 10, 0, 'skip', 'No MX IPs to test.'); + const unique = [...new Set(ips.map((i) => i.ip))].slice(0, 3); + const results = await Promise.all(unique.map((ip) => safe(() => blacklist.checkIp(ip), null))); + const flat = results.filter(Boolean).flatMap((r) => r.results.filter((x) => x.status === 'listed').map((x) => `${r.target} on ${x.name}`)); + const known = results.filter(Boolean).flatMap((r) => r.results).filter((x) => x.status !== 'unknown').length; + if (!known) return mk('blacklist', 'Blacklists', 10, 0, 'skip', 'Blacklist servers did not answer (resolver may be blocked).'); + if (!flat.length) return mk('blacklist', 'Blacklists', 10, 10, 'pass', `MX IPs are clean on ${known} lookups.`); + return mk('blacklist', 'Blacklists', 10, Math.max(0, 10 - flat.length * 5), 'fail', `Listed: ${flat.join('; ')}.`, 'Request delisting and fix the cause (compromised account, open relay, bad reputation).'); +} + +async function checkMtaSts(domain) { + const rec = (await txt(`_mta-sts.${domain}`)).find((t) => /^v=STSv1/i.test(t)); + return rec + ? mk('mtasts', 'MTA-STS', 5, 5, 'pass', 'MTA-STS record published.') + : mk('mtasts', 'MTA-STS', 5, 0, 'warn', 'No MTA-STS record.', 'Publish _mta-sts TXT and a policy file to enforce TLS for inbound mail.'); +} + +async function checkTls(mx) { + if (!mx.length) return mk('tls', 'Mail server TLS', 10, 0, 'skip', 'No MX to test.'); + const host = mx[0].exchange; + try { + const r = await tlsService.inspect({ host, port: 25 }); + const crit = r.findings.filter((f) => f.severity === 'critical'); + const warn = r.findings.filter((f) => f.severity === 'warning'); + if (crit.length) return mk('tls', 'Mail server TLS', 10, 3, 'fail', `${host}: ${crit.map((f) => f.title).join(', ')}.`, 'Fix the certificate and use TLS 1.2 or newer.'); + if (warn.length) return mk('tls', 'Mail server TLS', 10, 7, 'warn', `${host}: ${warn.map((f) => f.title).join(', ')}.`, 'Install a publicly trusted certificate.'); + return mk('tls', 'Mail server TLS', 10, 10, 'pass', `${host}: ${r.connection.protocol}, trusted certificate.`); + } catch (e) { + if (e.code === 'NO_STARTTLS') return mk('tls', 'Mail server TLS', 10, 0, 'fail', `${host} does not offer STARTTLS.`, 'Enable STARTTLS on your MX.'); + return mk('tls', 'Mail server TLS', 10, 0, 'skip', `Could not test ${host}:25 (${e.message}).`); + } +} + +function grade(pct) { + return pct >= 90 ? 'A' : pct >= 80 ? 'B' : pct >= 70 ? 'C' : pct >= 60 ? 'D' : 'F'; +} + +async function score(rawDomain, { selector } = {}) { + const domain = String(rawDomain || '').trim().toLowerCase().replace(/^.*@/, ''); + if (!isValidHostname(domain)) throw Object.assign(new Error('Enter a valid domain name'), { code: 'BAD_INPUT' }); + if (selector && !/^[a-z0-9._-]{1,63}$/i.test(selector)) throw Object.assign(new Error('Invalid DKIM selector'), { code: 'BAD_INPUT' }); + + const mx = await getMx(domain); + const ips = await mxIps(mx); + + const checks = await Promise.all([ + checkMx(domain, mx), checkSpf(domain), checkDkim(domain, selector), checkDmarc(domain), + checkRdns(ips), checkBlacklist(ips), checkMtaSts(domain), checkTls(mx), + ]); + + const scored = checks.filter((c) => c.status !== 'skip'); + const max = scored.reduce((s, c) => s + c.max, 0) || 1; + const pts = scored.reduce((s, c) => s + c.points, 0); + const pct = Math.round((pts / max) * 100); + const fixes = checks.filter((c) => c.fix && c.points < c.max).sort((a, b) => (b.max - b.points) - (a.max - a.points)).map((c) => ({ check: c.label, fix: c.fix })); + + return { domain, checkedAt: new Date().toISOString(), score: pct, grade: grade(pct), skipped: checks.filter((c) => c.status === 'skip').map((c) => c.label), checks, fixes }; +} + +module.exports = { score }; diff --git a/backend/src/services/share.js b/backend/src/services/share.js new file mode 100644 index 0000000..18aa86c --- /dev/null +++ b/backend/src/services/share.js @@ -0,0 +1,95 @@ +'use strict'; +// File-backed share store with TTL. Mount DATA_DIR as a Docker volume to persist. +const fs = require('fs'); +const path = require('path'); +const crypto = require('crypto'); + +const DIR = process.env.SHARE_DIR || path.join(__dirname, '..', '..', 'data', 'shares'); +const TTL_MS = (Number(process.env.SHARE_TTL_DAYS) || 7) * 86400000; +const MAX_BYTES = 256 * 1024; +const MAX_FILES = 5000; +// Header shares contain only the parsed analysis (the client never sends raw header text). +const TYPES = new Set(['blacklist', 'score', 'tls', 'smtp', 'dns', 'generator', 'headers']); + +// Defence in depth: whatever the client sends, private keys and secrets are removed before storage. +const PEM_RE = /-----BEGIN [A-Z0-9 ]*PRIVATE KEY-----[\s\S]*?(?:-----END [A-Z0-9 ]*PRIVATE KEY-----|$)/g; +const SECRET_KEY_RE = /(priv(ate)?[_-]?key|passw(or)?d|secret|token|api[_-]?key)/i; + +function sanitize(value, depth = 0) { + if (depth > 12) return undefined; + if (typeof value === 'string') return value.replace(PEM_RE, '[private key removed]'); + if (Array.isArray(value)) return value.map((v) => sanitize(v, depth + 1)); + if (value && typeof value === 'object') { + const out = {}; + for (const [k, v] of Object.entries(value)) { + out[k] = SECRET_KEY_RE.test(k) ? '[removed]' : sanitize(v, depth + 1); + } + return out; + } + return value; +} +const ID_RE = /^[A-Za-z0-9_-]{8,16}$/; + +fs.mkdirSync(DIR, { recursive: true }); + +const fail = (msg, code) => Object.assign(new Error(msg), { code }); +const file = (id) => path.join(DIR, `${id}.json`); + +function create(type, data) { + if (!TYPES.has(type)) throw fail('Unknown result type', 'BAD_INPUT'); + if (!data || typeof data !== 'object') throw fail('Result data must be an object', 'BAD_INPUT'); + const body = JSON.stringify({ type, data: sanitize(data), createdAt: Date.now(), expiresAt: Date.now() + TTL_MS }); + if (Buffer.byteLength(body) > MAX_BYTES) throw fail('Result too large to share', 'TOO_LARGE'); + if (fs.readdirSync(DIR).length >= MAX_FILES) throw fail('Share storage is full, try again later', 'FULL'); + const id = crypto.randomBytes(9).toString('base64url'); + fs.writeFileSync(file(id), body, { mode: 0o600 }); + return { id, expiresAt: new Date(Date.now() + TTL_MS).toISOString() }; +} + +function get(id) { + if (!ID_RE.test(id)) return null; + let raw; + try { raw = fs.readFileSync(file(id), 'utf8'); } catch { return null; } + const rec = JSON.parse(raw); + if (rec.expiresAt < Date.now()) { fs.rm(file(id), () => {}); return null; } + return rec; +} + +function cleanup() { + for (const f of fs.readdirSync(DIR)) { + try { + const rec = JSON.parse(fs.readFileSync(path.join(DIR, f), 'utf8')); + if (rec.expiresAt < Date.now()) fs.rmSync(path.join(DIR, f)); + } catch { fs.rmSync(path.join(DIR, f), { force: true }); } + } +} +setInterval(cleanup, 3600000).unref(); + +// --- export helpers --- +const esc = (s) => String(s).replace(/[&<>"']/g, (c) => ({ '&': '&', '<': '<', '>': '>', '"': '"', "'": ''' }[c])); + +function flatten(obj, prefix = '', out = []) { + if (Array.isArray(obj)) obj.forEach((v, i) => flatten(v, `${prefix}[${i}]`, out)); + else if (obj && typeof obj === 'object') Object.entries(obj).forEach(([k, v]) => flatten(v, prefix ? `${prefix}.${k}` : k, out)); + else out.push([prefix, obj ?? '']); + return out; +} + +function toCsv(data) { + const cell = (v) => { + let s = String(v); + if (/^[=+\-@\t\r]/.test(s)) s = `'${s}`; // CSV injection guard + return `"${s.replace(/"/g, '""')}"`; + }; + return ['field,value', ...flatten(data).map(([k, v]) => `${cell(k)},${cell(v)}`)].join('\r\n'); +} + +function toHtml(rec, id) { + const rows = flatten(rec.data).map(([k, v]) => `${esc(k)}${esc(v)}`).join(''); + return `MailProbe ${esc(rec.type)} report + +

MailProbe ${esc(rec.type)} report

ID ${esc(id)} · created ${esc(new Date(rec.createdAt).toISOString())}

${rows}
`; +} + +module.exports = { create, get, toCsv, toHtml }; \ No newline at end of file diff --git a/backend/src/services/tls.js b/backend/src/services/tls.js new file mode 100644 index 0000000..564d9d0 --- /dev/null +++ b/backend/src/services/tls.js @@ -0,0 +1,180 @@ +'use strict'; +const net = require('net'); +const tls = require('tls'); +const { resolvePublic } = require('./netguard'); + +const ALLOWED_PORTS = new Set([25, 465, 587, 2525, 443, 993, 995]); +const IMPLICIT_PORTS = new Set([465, 443, 993, 995]); +const TIMEOUT = 10000; + +const err = (msg, code) => Object.assign(new Error(msg), { code }); + +function openSocket(ip, port) { + return new Promise((resolve, reject) => { + const s = net.connect({ host: ip, port }); + s.setTimeout(TIMEOUT); + s.once('connect', () => { s.setTimeout(0); resolve(s); }); + s.once('timeout', () => { s.destroy(); reject(err('Connection timed out', 'TIMEOUT')); }); + s.once('error', reject); + }); +} + +function readReply(sock) { + return new Promise((resolve, reject) => { + let buf = ''; + const t = setTimeout(() => { cleanup(); reject(err('SMTP server did not respond in time', 'TIMEOUT')); }, TIMEOUT); + const onData = (d) => { + buf += d.toString(); + if (buf.length > 8192) { cleanup(); return reject(err('Reply too large', 'BAD_REPLY')); } + if (buf.endsWith('\r\n') && buf.split('\r\n').some((l) => /^\d{3} /.test(l))) { cleanup(); resolve(buf); } + }; + const onErr = (e) => { cleanup(); reject(e); }; + const cleanup = () => { clearTimeout(t); sock.off('data', onData); sock.off('error', onErr); }; + sock.on('data', onData); + sock.on('error', onErr); + }); +} + +async function secureConnect({ ip, host, port, mode, tlsOpts = {} }) { + let plain; + if (mode === 'starttls') { + plain = await openSocket(ip, port); + try { + const greet = await readReply(plain); + if (!/^220/.test(greet)) throw err(`Unexpected SMTP greeting: ${greet.trim().slice(0, 120)}`, 'BAD_GREETING'); + plain.write('EHLO mailprobe.local\r\n'); + const ehlo = await readReply(plain); + if (!/^250[ -]STARTTLS/im.test(ehlo)) throw err('Server does not advertise STARTTLS', 'NO_STARTTLS'); + plain.write('STARTTLS\r\n'); + const ok = await readReply(plain); + if (!/^220/.test(ok)) throw err(`STARTTLS rejected: ${ok.trim().slice(0, 120)}`, 'STARTTLS_REJECTED'); + } catch (e) { + plain.destroy(); + throw e; + } + } + return new Promise((resolve, reject) => { + const sock = tls.connect({ + ...(plain ? { socket: plain } : { host: ip, port }), + servername: net.isIP(host) ? undefined : host, + rejectUnauthorized: false, // we inspect, then report trust problems ourselves + ...tlsOpts, + }); + sock.setTimeout(TIMEOUT, () => { sock.destroy(); reject(err('TLS handshake timed out', 'TIMEOUT')); }); + sock.once('secureConnect', () => { sock.setTimeout(0); resolve(sock); }); + sock.once('error', (e) => { if (plain) plain.destroy(); reject(e); }); + }); +} + +function summarizeCert(c) { + return { + subject: c.subject, + issuer: c.issuer, + validFrom: c.valid_from, + validTo: c.valid_to, + serialNumber: c.serialNumber, + fingerprint256: c.fingerprint256, + bits: c.bits, + curve: c.asn1Curve || null, + altNames: c.subjectaltname ? c.subjectaltname.split(', ').slice(0, 50) : [], + }; +} + +function buildChain(leaf) { + const out = []; + const seen = new Set(); + let c = leaf; + while (c && c.fingerprint256 && !seen.has(c.fingerprint256)) { + seen.add(c.fingerprint256); + out.push(summarizeCert(c)); + c = c.issuerCertificate; + } + return out; +} + +async function probeVersions(base) { + const out = {}; + for (const v of ['TLSv1', 'TLSv1.1', 'TLSv1.2', 'TLSv1.3']) { + try { + const s = await secureConnect({ ...base, tlsOpts: { minVersion: v, maxVersion: v, ciphers: 'ALL:@SECLEVEL=0' } }); + s.destroy(); + out[v] = true; + } catch { out[v] = false; } + } + return out; +} + +async function inspect({ host, port = 25, mode, versions = false }) { + host = String(host || '').trim().toLowerCase(); + port = Number(port); + if (!ALLOWED_PORTS.has(port)) throw err(`Port must be one of: ${[...ALLOWED_PORTS].join(', ')}`, 'BAD_INPUT'); + mode = mode || (IMPLICIT_PORTS.has(port) ? 'implicit' : 'starttls'); + if (!['implicit', 'starttls'].includes(mode)) throw err('mode must be implicit or starttls', 'BAD_INPUT'); + + const [ip] = await resolvePublic(host); + const base = { ip, host, port, mode }; + const sock = await secureConnect(base); + + try { + const leaf = sock.getPeerCertificate(true); + if (!leaf || !leaf.fingerprint256) throw err('Server presented no certificate', 'NO_CERT'); + + const chain = buildChain(leaf); + const protocol = sock.getProtocol(); + const cipher = sock.getCipher(); + const validTo = new Date(leaf.valid_to); + const daysRemaining = Math.floor((validTo - Date.now()) / 86400000); + const idErr = net.isIP(host) ? null : tls.checkServerIdentity(host, leaf); + const selfSigned = chain.length === 1 || leaf.issuerCertificate === leaf; + + const findings = []; + const add = (severity, title, detail) => findings.push({ severity, title, detail }); + + if (daysRemaining < 0) add('critical', 'Certificate expired', `Expired ${-daysRemaining} day(s) ago.`); + else if (daysRemaining < 14) add('critical', 'Certificate expires very soon', `${daysRemaining} day(s) left.`); + else if (daysRemaining < 30) add('warning', 'Certificate expires soon', `${daysRemaining} day(s) left.`); + else add('ok', 'Certificate validity', `${daysRemaining} day(s) remaining.`); + + if (idErr) add('critical', 'Hostname mismatch', idErr.reason || idErr.message); + else if (!net.isIP(host)) add('ok', 'Hostname matches certificate', host); + + if (!sock.authorized) { + add(mode === 'starttls' && port === 25 ? 'warning' : 'critical', 'Certificate not trusted', + `${sock.authorizationError || 'Unknown trust error'}${selfSigned ? ' (self-signed)' : ''}. ` + + 'Opportunistic TLS on port 25 tolerates this, but strict senders and MTA-STS will not.'); + } else add('ok', 'Certificate chain trusted', `${chain.length} certificate(s) in chain.`); + + if (['TLSv1', 'TLSv1.1', 'SSLv3'].includes(protocol)) add('critical', 'Deprecated TLS version negotiated', protocol); + else if (protocol === 'TLSv1.3') add('ok', 'Modern TLS', 'TLS 1.3 negotiated.'); + else add('ok', 'TLS version', `${protocol} negotiated.`); + + if (/RC4|3DES|NULL|EXPORT|MD5|DES-CBC/i.test(cipher.name)) add('critical', 'Weak cipher suite', cipher.name); + if (!leaf.asn1Curve && leaf.bits && leaf.bits < 2048) add('warning', 'Weak RSA key', `${leaf.bits}-bit key (2048+ recommended).`); + + const result = { + host, ip, port, mode, + checkedAt: new Date().toISOString(), + connection: { + protocol, + cipher: cipher.name, + authorized: sock.authorized, + authorizationError: sock.authorizationError ? String(sock.authorizationError) : null, + }, + certificate: { ...summarizeCert(leaf), daysRemaining, selfSigned, hostnameMatch: !idErr }, + chain, + findings, + }; + sock.destroy(); + + if (versions) { + result.supportedVersions = await probeVersions(base); + const legacy = ['TLSv1', 'TLSv1.1'].filter((v) => result.supportedVersions[v]); + if (legacy.length) result.findings.push({ severity: 'warning', title: 'Legacy protocols enabled', detail: legacy.join(', ') }); + } + return result; + } finally { + sock.destroy(); + } +} + +module.exports = { inspect, ALLOWED_PORTS }; diff --git a/docker-compose.yml b/docker-compose.yml index 7d056ae..854e6f1 100644 --- a/docker-compose.yml +++ b/docker-compose.yml @@ -11,7 +11,12 @@ services: environment: PORT: ${PORT:-4000} NODE_ENV: production - TRUST_PROXY: 1 + TRUST_PROXY: 1 # set to 2 if another proxy sits in front of port 50000 + SHARE_DIR: /app/data/shares + SHARE_TTL_DAYS: ${SHARE_TTL_DAYS:-7} + + volumes: + - mailmetrix-data:/app/data expose: - "${PORT:-4000}" @@ -114,4 +119,7 @@ services: networks: network: - driver: bridge \ No newline at end of file + driver: bridge + +volumes: + mailmetrix-data: diff --git a/frontend/src/app.js b/frontend/src/app.js index 5a995c5..958e532 100644 --- a/frontend/src/app.js +++ b/frontend/src/app.js @@ -3,12 +3,29 @@ import { initSMTP } from "./features/smtp.js"; import { initDNS } from "./features/dns.js"; import { initHeaders } from "./features/headers.js"; import { initGenerator } from "./features/generator.js"; +import { initBlacklist, renderBlacklist } from "./features/blacklist.js"; +import { initScore, renderScore } from "./features/score.js"; +import { initTls, renderTls } from "./features/tls.js"; +import { loadSharedFromUrl } from "./features/share.js"; +import { renderSmtp, renderDns, renderGenerator, renderHeaders } from "./features/renderers.js"; initTabs(); initSMTP(); initDNS(); initHeaders(); initGenerator(); +initBlacklist(); +initScore(); +initTls(); +loadSharedFromUrl({ + blacklist: renderBlacklist, + score: renderScore, + tls: renderTls, + smtp: renderSmtp, + dns: renderDns, + generator: renderGenerator, + headers: renderHeaders +}); /* ---------------- Theme toggle ---------------- */ (function initTheme() { diff --git a/frontend/src/features.css b/frontend/src/features.css new file mode 100644 index 0000000..0566192 --- /dev/null +++ b/frontend/src/features.css @@ -0,0 +1,14 @@ +/* Append to style.css. Adjust colours to your theme variables. */ +.mp-badge{display:inline-block;padding:1px 8px;border-radius:999px;font-size:.8em;font-weight:600} +.mp-good{background:#d9f5e3;color:#14532d}.mp-warn{background:#fdf0c8;color:#713f12} +.mp-bad{background:#fddcdc;color:#7f1d1d}.mp-muted{background:#e7e7ea;color:#444} +p.mp-muted{background:none;color:#777;font-size:.9em}.mp-error{color:#b91c1c} +.mp-table{border-collapse:collapse;width:100%;margin:.5rem 0} +.mp-table th,.mp-table td{border:1px solid #ddd;padding:4px 8px;text-align:left;vertical-align:top;word-break:break-word} +.mp-actions{display:flex;flex-wrap:wrap;gap:.5rem;align-items:center;margin-top:1rem} +.mp-findings{list-style:none;padding:0}.mp-findings li{margin:.35rem 0} +.mp-score{display:flex;gap:1.25rem;align-items:center} +.mp-grade{width:84px;height:84px;border-radius:50%;display:grid;place-items:center;font-size:2.6rem;font-weight:700;color:#fff;background:#6b7280} +.mp-grade-A{background:#16a34a}.mp-grade-B{background:#65a30d}.mp-grade-C{background:#ca8a04}.mp-grade-D{background:#ea580c}.mp-grade-F{background:#dc2626} +@media print{body *{visibility:hidden}.mp-print-target,.mp-print-target *{visibility:visible} +.mp-print-target{position:absolute;left:0;top:0;width:100%}} diff --git a/frontend/src/features/blacklist.js b/frontend/src/features/blacklist.js new file mode 100644 index 0000000..17e0ffc --- /dev/null +++ b/frontend/src/features/blacklist.js @@ -0,0 +1,42 @@ +import { el, post, badge } from "./ui.js"; +import { bindTool } from "./share.js"; + +export function renderBlacklist(root, data) { + const s = data.summary; + root.replaceChildren( + el("h3", {}, `Results for ${data.target}`), + el("p", {}, + badge(s.listed ? "listed" : "clean", s.listed ? `Listed on ${s.listed}` : "Not listed"), + ` ${s.checked} checks: ${s.clean} clean, ${s.listed} listed, ${s.unknown} unknown`), + ...data.entries.map((entry) => el("div", {}, + el("h4", {}, `${entry.type === "ip" ? "IP" : "Domain"}: ${entry.target}`), + el("table", {}, + el("thead", {}, el("tr", {}, el("th", {}, "List"), el("th", {}, "Status"), el("th", {}, "Details"))), + el("tbody", {}, entry.results.map((r) => el("tr", {}, + el("td", {}, r.name), + el("td", {}, badge(r.status)), + el("td", {}, [r.returnCode, r.reason].filter(Boolean).join(" · ") || "—"))))) + )), + s.unknown + ? el("p", { class: "mm-note" }, "“Unknown” usually means the list refused the DNS resolver (common with public resolvers like 8.8.8.8).") + : null + ); +} + +export function initBlacklist() { + const input = document.getElementById("blTarget"); + bindTool({ + button: document.getElementById("blButton"), + enterOn: [input], + out: document.getElementById("blResult"), + actions: document.getElementById("blActions"), + type: "blacklist", + busyMsg: "Querying blacklists…", + request: async () => { + const target = input.value.trim(); + if (!target) throw new Error("Enter an IPv4 address or domain name."); + return post("/blacklist", { target }); + }, + render: renderBlacklist + }); +} diff --git a/frontend/src/features/dns.js b/frontend/src/features/dns.js index 5a4d733..48b1575 100644 --- a/frontend/src/features/dns.js +++ b/frontend/src/features/dns.js @@ -1,5 +1,6 @@ import { $, escapeHtml } from "./utils.js"; import { startFlow, flowActive, flowSuccess, flowError } from "./flow.js"; +import { attachActions, clearActions } from "./share.js"; export function initDNS() { const button = $("dnsButton"); @@ -9,6 +10,7 @@ export function initDNS() { button.addEventListener("click", async () => { const value = domain.value.trim(); + clearActions("dnsActions"); if (!value) { output.className = "result error"; @@ -65,6 +67,9 @@ export function initDNS() { `; + // Share / export bar (updated again below if a DKIM selector is checked). + attachActions("dns", data, "dnsActions", "dnsResult"); + $("dkimButton").addEventListener("click", async () => { const selector = $("dkimSelector").value.trim(); const dkimButton = $("dkimButton"); @@ -87,6 +92,11 @@ export function initDNS() { } dkimOutput.innerHTML = `
${escapeHtml(dkim.hostname)}${escapeHtml(dkim.status)}
${dkim.record ? `
${escapeHtml(dkim.record)}
` : "
No DKIM record found for this selector.
"}
`; + + attachActions("dns", { + ...data, + dkim: { selector, hostname: dkim.hostname, status: dkim.status, record: dkim.record || null } + }, "dnsActions", "dnsResult"); } catch (error) { dkimOutput.innerHTML = `
${escapeHtml(error.message)}
`; } finally { diff --git a/frontend/src/features/flow.js b/frontend/src/features/flow.js index f9dde88..ba38dca 100644 --- a/frontend/src/features/flow.js +++ b/frontend/src/features/flow.js @@ -1,7 +1,12 @@ +// Shared workflow-card controller used by every tool tab. +// Steps: flowFrontend -> flowBackend -> flowSMTP (tool step 3) -> flowEmail (tool step 4). +// tabs.js relabels the steps per tool; this module only drives their state. import { $ } from "./utils.js"; const FLOW_IDS = ["flowFrontend", "flowBackend", "flowSMTP", "flowEmail"]; +/* ---------- low-level helpers (used by dns.js, headers.js, generator.js) ---------- */ + export function resetFlow() { FLOW_IDS.forEach((id) => { const element = $(id); @@ -33,3 +38,45 @@ export function flowSuccess(id) { export function flowActive(id) { setFlowStep(id, "active"); } + +/* ---------- backend reachability (shared by every tool) ---------- */ + +export async function checkBackend() { + try { + const response = await fetch("/api/health"); + return response.ok; + } catch { + return false; + } +} + +/* ---------- high-level controller for the standard tool lifecycle ---------- + const flow = createFlow(document.getElementById("blacklistTool")); + flow.start(); // Frontend ✓, Backend … + flow.backendOk(); // Backend ✓, step 3 … + flow.done(); // all ✓ flow.fail("flowSMTP") // mark a step ✗ + Every method is a no-op while `panel` is hidden, so a slow request can't repaint + the card after the user has switched to another tool. */ +export function createFlow(panel) { + const live = () => !panel || !panel.classList.contains("hidden"); + const run = (fn) => { if (live()) fn(); }; + + return { + start() { + run(() => { + resetFlow(); + flowSuccess("flowFrontend"); + flowActive("flowBackend"); + }); + }, + backendOk() { + run(() => { + flowSuccess("flowBackend"); + flowActive("flowSMTP"); + }); + }, + done() { run(() => FLOW_IDS.forEach(flowSuccess)); }, + fail(id) { run(() => flowError(id)); }, + set(id, state) { run(() => setFlowStep(id, state)); } + }; +} \ No newline at end of file diff --git a/frontend/src/features/generator.js b/frontend/src/features/generator.js index a070dec..09b4f9d 100644 --- a/frontend/src/features/generator.js +++ b/frontend/src/features/generator.js @@ -1,16 +1,26 @@ import { $, escapeHtml } from "./utils.js"; import { startFlow, flowActive, flowSuccess, flowError } from "./flow.js"; +import { attachActions, clearActions } from "./share.js"; function field(id) { return $(id)?.value.trim() || ""; } +// Copy of the response that is safe to share/export: the DKIM private key is never included. +function shareable(data) { + const copy = JSON.parse(JSON.stringify(data)); + if (copy.dkim) delete copy.dkim.privateKey; + delete copy.warning; + return copy; +} + export function initGenerator() { const button = $("generateAuthButton"); const output = $("generatorResult"); if (!button || !output) return; button.addEventListener("click", async () => { + clearActions("generatorActions"); const domain = field("generatorDomain"); if (!domain) { output.className = "result error"; @@ -104,6 +114,9 @@ export function initGenerator() { } }); }); + + // Share / export bar. The private key is excluded from everything that leaves this page. + attachActions("generator", shareable(data), "generatorActions", "generatorResult"); } catch (error) { flowError("flowBackend"); output.className = "result error"; diff --git a/frontend/src/features/headers.js b/frontend/src/features/headers.js index 8541fce..ba54fda 100644 --- a/frontend/src/features/headers.js +++ b/frontend/src/features/headers.js @@ -1,5 +1,6 @@ import { $, escapeHtml } from "./utils.js"; import { startFlow, flowActive, flowSuccess, flowError } from "./flow.js"; +import { attachActions, clearActions } from "./share.js"; const badge = (status) => { const value = String(status || "not_found").toLowerCase(); @@ -8,6 +9,86 @@ const badge = (status) => { return `${escapeHtml(value)}`; }; +/* ---------- sharing: parsed analysis only, never the raw header text ---------- */ + +const EMAIL_RE = /[A-Z0-9._%+-]+@([A-Z0-9.-]+\.[A-Z]{2,})/gi; + +const maskEmails = (value) => { + if (typeof value === "string") return value.replace(EMAIL_RE, "***@$1"); + if (Array.isArray(value)) return value.map(maskEmails); + if (value && typeof value === "object") { + return Object.fromEntries(Object.entries(value).map(([k, v]) => [k, maskEmails(v)])); + } + return value; +}; + +// Only these three fields are ever shared/exported. `redact` hides the subject, display names +// and the username part of every email address (the domain is kept because it is what you debug with). +function shareable(data, redact) { + const copy = JSON.parse(JSON.stringify({ + headerCount: data.headerCount, + analysis: data.analysis, + findings: data.findings + })); + if (!redact) return copy; + + const a = copy.analysis; + if (a) { + if (a.subject) a.subject = "[hidden]"; + ["from", "returnPath", "replyTo"].forEach((key) => { + if (a[key] && typeof a[key] === "object" && a[key].name) a[key].name = "[hidden]"; + }); + } + return maskEmails(copy); +} + +function setupShare(data) { + const bar = $("headerActions"); + if (!bar) return; + + let option = $("headerRedactOption"); + if (!option) { + option = document.createElement("label"); + option.id = "headerRedactOption"; + option.className = "custom-checkbox"; + option.style.marginTop = "14px"; + + const box = document.createElement("input"); + box.type = "checkbox"; + box.id = "headerRedact"; + box.checked = true; + + const text = document.createElement("span"); + text.textContent = "Hide subject, display names and email usernames in shared / exported results (PDF prints the result as displayed)"; + + option.append(box, text); + bar.before(option); + } + option.style.display = "inline-flex"; + + const box = $("headerRedact"); + const attach = () => attachActions("headers", shareable(data, box.checked), "headerActions", "headerResult"); + box.onchange = attach; + attach(); +} + +function clearShare() { + clearActions("headerActions"); + const option = $("headerRedactOption"); + if (option) option.style.display = "none"; +} + +// Header fields end at the first blank line; everything after it is the message body. +// Only when the paste is large do we cut at that blank line (a whole message was probably pasted), +// so smaller pastes with stray blank lines are still analysed in full. +const LARGE_PASTE_BYTES = 90 * 1024; + +function headerBlock(text) { + if (new Blob([text]).size <= LARGE_PASTE_BYTES) return { headers: text, trimmed: false }; + const cut = text.search(/\r?\n[ \t]*\r?\n/); + return cut > 0 ? { headers: text.slice(0, cut), trimmed: true } : { headers: text, trimmed: false }; +} + export function initHeaders() { const button = $("analyzeHeadersButton"); const input = $("emailHeaders"); @@ -15,7 +96,8 @@ export function initHeaders() { if (!button || !input || !result) return; button.addEventListener("click", async () => { - const headers = input.value.trim(); + const { headers, trimmed } = headerBlock(input.value.trim()); + clearShare(); if (!headers) { result.className = "result error"; @@ -46,7 +128,10 @@ export function initHeaders() { if (!response.ok) { flowError("flowSMTP"); result.className = "result error"; - result.innerHTML = `
Header Analysis Failed
${escapeHtml(data.error || "Unable to analyze the supplied headers.")}
`; + const message = response.status === 413 + ? "The pasted text is too large. Paste only the email headers (everything above the first blank line), not the whole message." + : data.error || "Unable to analyze the supplied headers."; + result.innerHTML = `
Header Analysis Failed
${escapeHtml(message)}
`; return; } @@ -68,12 +153,12 @@ export function initHeaders() { result.className = "result success"; result.innerHTML = `
Header Analysis Complete
-
Parsed ${escapeHtml(data.headerCount)} headers.
+
Parsed ${escapeHtml(data.headerCount)} headers.${trimmed ? " The message body was ignored." : ""}
-
From${escapeHtml(a.from.address || "Not found")}
-
Return-Path${escapeHtml(a.returnPath.address || "Not found")}
-
Message-ID${escapeHtml(a.messageId || "Not found")}
-
Received Hops${escapeHtml(a.deliveryPath.hopCount)}
+
From ${escapeHtml(a.from.address || "Not found")}
+
Return-Path ${escapeHtml(a.returnPath.address || "Not found")}
+
Message-ID ${escapeHtml(a.messageId || "Not found")}
+
Received Hops ${escapeHtml(a.deliveryPath.hopCount)}

Authentication

SPF${badge(auth.spf)}
DKIM${badge(auth.dkim)}
DMARC${badge(auth.dmarc)}
@@ -81,15 +166,17 @@ export function initHeaders() {

Message Metadata

-
Subject${escapeHtml(a.subject || "Not found")}
-
Date${escapeHtml(a.date || "Not found")}
-
Reply-To${escapeHtml(a.replyTo.address || "Not found")}
-
Content-Type${escapeHtml(a.contentType || "Not found")}
-
MIME-Version${escapeHtml(a.mimeVersion || "Not found")}
+
Subject ${escapeHtml(a.subject || "Not found")}
+
Date ${escapeHtml(a.date || "Not found")}
+
Reply-To ${escapeHtml(a.replyTo.address || "Not found")}
+
Content-Type ${escapeHtml(a.contentType || "Not found")}
+
MIME-Version ${escapeHtml(a.mimeVersion || "Not found")}

Delivery Path

${hops}

Findings

${findings}
`; + + setupShare(data); } catch (error) { flowError("flowBackend"); result.className = "result error"; @@ -99,4 +186,4 @@ export function initHeaders() { button.textContent = "Analyze Email Headers"; } }); -} +} \ No newline at end of file diff --git a/frontend/src/features/renderers.js b/frontend/src/features/renderers.js new file mode 100644 index 0000000..a43eb8b --- /dev/null +++ b/frontend/src/features/renderers.js @@ -0,0 +1,134 @@ +// Read-only views used when opening a shared link (?share=ID). Built with text nodes only. +import { el } from "./ui.js"; + +const label = (key) => key.replace(/([a-z])([A-Z])/g, "$1 $2").replace(/[_-]+/g, " ").replace(/^./, (c) => c.toUpperCase()); +const badge = (status) => el("span", { class: `dns-badge ${String(status ?? "").replace(/[^a-z0-9_-]/gi, "")}` }, status ?? "unknown"); +const pre = (text) => el("pre", {}, String(text)); + +/* ---------- SMTP ---------- */ +export function renderSmtp(root, d) { + const ok = d.status === "success"; + const row = (k, v) => (v === undefined || v === null || v === "" ? null : el("tr", {}, el("th", {}, k), el("td", {}, typeof v === "string" ? v : JSON.stringify(v)))); + root.replaceChildren( + el("h3", {}, d.title || (ok ? "SMTP Test Successful" : "SMTP Test Failed")), + d.message ? el("p", {}, d.message) : null, + d.error ? el("p", {}, d.error) : null, + el("table", {}, el("tbody", {}, + row("Result", ok ? "Success" : "Failed"), + row("Host", d.host), row("Port", d.port), row("Security", d.security), + row("Stage", d.stage), row("Code", d.code), + row("Message ID", d.messageId), row("Accepted", d.accepted), row("Rejected", d.rejected))) + ); +} + +/* ---------- DNS ---------- */ +export function renderDns(root, d) { + const mxRows = d.mx?.records?.length + ? d.mx.records.map((r) => el("div", { class: "dns-mx-row" }, el("span", { class: "dns-mx-priority" }, r.priority), " ", el("span", { class: "dns-mx-host" }, r.exchange))) + : [el("div", {}, "No MX records found.")]; + const record = (title, rec, missing) => el("div", { class: "dns-record" }, + el("div", { class: "dns-record-header" }, el("span", { class: "dns-record-title" }, title), badge(rec?.status)), + rec?.record ? pre(rec.record) : el("div", {}, missing)); + + root.replaceChildren( + el("h3", {}, "DNS Check"), + el("p", {}, "Email DNS records for ", el("strong", {}, d.domain), "."), + el("div", { class: "dns-result-grid" }, + el("div", { class: "dns-record" }, + el("div", { class: "dns-record-header" }, el("span", { class: "dns-record-title" }, "MX Records"), badge(d.mx?.status)), + el("div", { class: "dns-record-list" }, mxRows)), + record("SPF", d.spf, "No SPF TXT record found."), + record("DMARC", d.dmarc, "No DMARC record found."), + d.dkim + ? el("div", { class: "dns-record" }, + el("div", { class: "dns-record-header" }, el("span", { class: "dns-record-title" }, d.dkim.hostname || `DKIM (${d.dkim.selector})`), badge(d.dkim.status)), + d.dkim.record ? pre(d.dkim.record) : el("div", {}, "No DKIM record found for this selector.")) + : null) + ); +} + +/* ---------- Generator (same layout as the live result; the private key is never part of a share) ---------- */ +export function renderGenerator(root, d) { + const block = (title, value) => (value + ? el("div", { class: "generator-output" }, + el("div", { class: "generator-output-header" }, + el("strong", {}, title), + el("button", { + type: "button", + onclick: async (e) => { + const btn = e.currentTarget; + try { await navigator.clipboard.writeText(value); btn.textContent = "Copied"; } catch { btn.textContent = "Copy failed"; } + setTimeout(() => { btn.textContent = "Copy"; }, 1400); + } + }, "Copy")), + pre(value)) + : null); + const meta = (k, v) => (v === undefined || v === null || v === "" ? null : el("div", {}, el("span", {}, `${k} `), el("strong", {}, String(v)))); + + root.replaceChildren( + el("div", { class: "result-title" }, "SPF, DKIM & DMARC Generated"), + el("div", { class: "result-message" }, "Records generated for ", el("strong", {}, d.dkim?.domain || ""), "."), + el("div", { class: "generator-grid" }, + block("SPF DNS Record", d.spf?.dnsRecord), + block("DKIM DNS Record", d.dkim?.dnsRecord), + block("DMARC DNS Record", d.dmarc?.dnsRecord), + block("DKIM Public Key", d.dkim?.publicKey)), + el("div", { class: "generator-meta" }, + meta("SPF Hostname", d.spf?.hostname), + meta("DKIM Hostname", d.dkim?.hostname), + meta("Key Size", d.dkim?.keySize ? `${d.dkim.keySize}-bit RSA` : ""), + meta("DMARC Hostname", d.dmarc?.hostname)), + el("div", { class: "generator-warning" }, "The DKIM private key is never included in shared or exported results. Generate your own key pair to get one.") + ); +} + +/* ---------- Header analysis (same layout as the live result) ---------- */ +export function renderHeaders(root, d) { + const a = d.analysis || {}; + const auth = a.authentication || {}; + const hops = a.deliveryPath?.hops || []; + const findings = d.findings || []; + + const authBadge = (status) => { + const value = String(status || "not_found").toLowerCase(); + const cls = value === "pass" ? "ok" : ["fail", "softfail", "permerror", "temperror"].includes(value) ? "missing" : "info"; + return el("span", { class: `dns-badge ${cls}` }, value); + }; + const stat = (k, v) => el("div", { class: "header-stat" }, el("span", {}, k), el("strong", {}, v || "Not found")); + const meta = (k, v) => el("div", {}, el("span", {}, k), el("strong", {}, v || "Not found")); + const sev = (s) => String(s || "info").toLowerCase().replace(/[^a-z]/g, ""); + + root.replaceChildren( + el("div", { class: "result-title" }, "Header Analysis"), + el("div", { class: "result-message" }, "Parsed ", el("strong", {}, String(d.headerCount ?? "")), " headers. Raw header text is never included in shared results."), + el("div", { class: "header-summary" }, + stat("From", a.from?.address), stat("Return-Path", a.returnPath?.address), + stat("Message-ID", a.messageId), stat("Received Hops", String(a.deliveryPath?.hopCount ?? ""))), + el("div", { class: "header-section" }, + el("h3", {}, "Authentication"), + el("div", { class: "header-auth-grid" }, + el("div", {}, el("span", {}, "SPF"), authBadge(auth.spf)), + el("div", {}, el("span", {}, "DKIM"), authBadge(auth.dkim)), + el("div", {}, el("span", {}, "DMARC"), authBadge(auth.dmarc))), + auth.authenticationResults ? pre(auth.authenticationResults) : el("p", {}, "No Authentication-Results header found.")), + el("div", { class: "header-section" }, + el("h3", {}, "Message Metadata"), + el("div", { class: "header-meta" }, + meta("Subject", a.subject), meta("Date", a.date), meta("Reply-To", a.replyTo?.address), + meta("Content-Type", a.contentType), meta("MIME-Version", a.mimeVersion))), + el("div", { class: "header-section" }, + el("h3", {}, "Delivery Path"), + el("div", { class: "header-hops" }, hops.length + ? hops.map((hop) => el("div", { class: "header-hop" }, + el("div", { class: "header-hop-number" }, String(hop.hop)), + el("div", {}, + el("strong", {}, `${hop.from || "Unknown"}${hop.by ? ` → ${hop.by}` : ""}`), + el("small", {}, `${hop.protocol || "Protocol not specified"}${hop.timestamp ? ` · ${hop.timestamp}` : ""}`)))) + : [el("div", {}, "No Received headers found.")])), + el("div", { class: "header-section" }, + el("h3", {}, "Findings"), + el("div", { class: "header-findings" }, findings.length + ? findings.map((f) => el("div", { class: `header-finding ${sev(f.severity)}` }, el("strong", {}, String(f.severity || "").toUpperCase()), el("span", {}, f.message))) + : [el("div", { class: "header-finding success" }, el("strong", {}, "OK"), el("span", {}, "No basic header issues were detected."))])) + ); +} \ No newline at end of file diff --git a/frontend/src/features/score.js b/frontend/src/features/score.js new file mode 100644 index 0000000..bb95898 --- /dev/null +++ b/frontend/src/features/score.js @@ -0,0 +1,43 @@ +import { el, post, badge } from "./ui.js"; +import { bindTool } from "./share.js"; + +export function renderScore(root, d) { + root.replaceChildren( + el("div", { class: "mm-score" }, + el("div", { class: `mm-grade mm-grade-${d.grade}` }, d.grade), + el("div", {}, + el("h3", {}, d.domain), + el("p", {}, `Score ${d.score}/100`), + d.skipped.length ? el("p", { class: "mm-note" }, `Not scored: ${d.skipped.join(", ")}`) : null)), + el("table", {}, + el("thead", {}, el("tr", {}, ["Check", "Result", "Points", "Details"].map((h) => el("th", {}, h)))), + el("tbody", {}, d.checks.map((c) => el("tr", {}, + el("td", {}, c.label), + el("td", {}, badge(c.status)), + el("td", {}, c.status === "skip" ? "—" : `${c.points}/${c.max}`), + el("td", {}, c.detail))))), + d.fixes.length + ? el("div", {}, el("h4", {}, "What to fix first"), + el("ol", {}, d.fixes.map((f) => el("li", {}, el("strong", {}, `${f.check}: `), f.fix)))) + : el("p", {}, "Nothing to fix. Nice work.") + ); +} + +export function initScore() { + const domain = document.getElementById("scoreDomain"); + const selector = document.getElementById("scoreSelector"); + bindTool({ + button: document.getElementById("scoreButton"), + enterOn: [domain, selector], + out: document.getElementById("scoreResult"), + actions: document.getElementById("scoreActions"), + type: "score", + busyMsg: "Running checks (can take up to ~15 seconds)…", + request: async () => { + const d = domain.value.trim(); + if (!d) throw new Error("Enter a domain name."); + return post("/score", { domain: d, selector: selector.value.trim() || undefined }); + }, + render: renderScore + }); +} diff --git a/frontend/src/features/share.js b/frontend/src/features/share.js new file mode 100644 index 0000000..2d521d4 --- /dev/null +++ b/frontend/src/features/share.js @@ -0,0 +1,166 @@ +import { el, api, post, setBusy, setResult } from "./ui.js"; +import { createFlow, checkBackend } from "./flow.js"; + +// Never export or share private keys / secrets, even though the generator shows them on screen. +const PEM_RE = /-----BEGIN [A-Z0-9 ]*PRIVATE KEY-----[\s\S]*?(?:-----END [A-Z0-9 ]*PRIVATE KEY-----|$)/g; +const SECRET_KEY_RE = /(priv(ate)?[_-]?key|passw(or)?d|secret|token|api[_-]?key)/i; + +export function sanitize(value, depth = 0) { + if (depth > 12) return undefined; + if (typeof value === "string") return value.replace(PEM_RE, "[private key removed]"); + if (Array.isArray(value)) return value.map((v) => sanitize(v, depth + 1)); + if (value && typeof value === "object") { + return Object.fromEntries(Object.entries(value).map(([k, v]) => [k, SECRET_KEY_RE.test(k) ? "[removed]" : sanitize(v, depth + 1)])); + } + return value; +} + +function download(name, mime, content) { + const url = URL.createObjectURL(new Blob([content], { type: mime })); + const a = el("a", { href: url, download: name }); + document.body.append(a); + a.click(); + a.remove(); + setTimeout(() => URL.revokeObjectURL(url), 1000); +} + +function flatten(obj, prefix = "", out = []) { + if (Array.isArray(obj)) obj.forEach((v, i) => flatten(v, `${prefix}[${i}]`, out)); + else if (obj && typeof obj === "object") Object.entries(obj).forEach(([k, v]) => flatten(v, prefix ? `${prefix}.${k}` : k, out)); + else out.push([prefix, obj ?? ""]); + return out; +} + +function toCsv(data) { + const cell = (v) => { + let s = String(v); + if (/^[=+\-@\t\r]/.test(s)) s = `'${s}`; // spreadsheet formula-injection guard + return `"${s.replace(/"/g, '""')}"`; + }; + return ["field,value", ...flatten(data).map(([k, v]) => `${cell(k)},${cell(v)}`)].join("\r\n"); +} + +// Share link / JSON / CSV / PDF buttons. printTarget = the .result element to print. +export function resultActions(type, data, printTarget) { + data = sanitize(data); + const status = el("span", { class: "mm-note", role: "status" }); + const base = `mailmetrix-${type}-${new Date().toISOString().slice(0, 10)}`; + + const shareBtn = el("button", { + type: "button", + onclick: async () => { + shareBtn.disabled = true; + status.textContent = "Creating link…"; + try { + const { id, expiresAt } = await post("/share", { type, data }); + const url = `${location.origin}/?share=${id}`; + let copied = false; + try { await navigator.clipboard.writeText(url); copied = true; } catch { /* clipboard blocked */ } + status.replaceChildren( + copied ? "Link copied · " : "", + el("a", { href: url, target: "_blank", rel: "noopener" }, url), + ` · expires ${new Date(expiresAt).toLocaleDateString()}` + ); + } catch (e) { + status.textContent = e.message; + } finally { shareBtn.disabled = false; } + } + }, "Share link"); + + return el("div", { class: "action-bar-inner" }, + shareBtn, + el("button", { type: "button", onclick: () => download(`${base}.json`, "application/json", JSON.stringify(data, null, 2)) }, "JSON"), + el("button", { type: "button", onclick: () => download(`${base}.csv`, "text/csv", toCsv(data)) }, "CSV"), + el("button", { + type: "button", + onclick: () => { + printTarget.classList.add("mm-print-target"); + window.print(); + printTarget.classList.remove("mm-print-target"); + } + }, "PDF"), + status + ); +} + +// For tools that render their own result (SMTP, DNS, Generator): +// attachActions("dns", data, "dnsActions", "dnsResult") -> shows Share/JSON/CSV/PDF under the result +// clearActions("dnsActions") -> hides the bar (new run, error, validation failure) +export function attachActions(type, data, actionsId, printTargetId) { + const bar = document.getElementById(actionsId); + const target = document.getElementById(printTargetId); + if (!bar || !target) return; + bar.replaceChildren(resultActions(type, data, target)); +} + +export function clearActions(actionsId) { + document.getElementById(actionsId)?.replaceChildren(); +} + +// Wires a tool: button click / Enter -> validate -> backend check -> request -> render -> action bar. +// prepare(): validates inputs and returns the payload (throw Error for invalid input; no network call is made) +// request(payload): performs the API call +export function bindTool({ button, enterOn = [], out, actions, type, busyMsg, prepare, request, render }) { + if (!button || !out) return; + const flow = createFlow(out.closest(".tool-panel")); + + const run = async () => { + if (button.disabled) return; + + let payload; + try { + payload = prepare ? prepare() : undefined; + } catch (e) { + setResult(out, "error", e.message); // validation error: nothing was sent + actions?.replaceChildren(); + return; + } + + setBusy(button, true); + actions?.replaceChildren(); + setResult(out, "waiting", busyMsg); + flow.start(); + + let backendReached = false; + try { + if (!(await checkBackend())) throw new Error("Unable to connect to the Node.js backend."); + backendReached = true; + flow.backendOk(); + const data = await request(payload); + setResult(out, ""); + render(out, data); + actions?.replaceChildren(resultActions(type, data, out)); + flow.done(); + } catch (e) { + flow.fail(backendReached ? "flowSMTP" : "flowBackend"); // backend unreachable vs. check failed + setResult(out, "error", e.message); + } finally { setBusy(button, false); } + }; + button.addEventListener("click", run); + enterOn.forEach((i) => i?.addEventListener("keydown", (e) => { + if (e.key === "Enter") { e.preventDefault(); run(); } + })); +} + +// Renders ?share=ID into #sharedTool / #sharedResult. renderers = { blacklist, score, tls } +export async function loadSharedFromUrl(renderers) { + const id = new URLSearchParams(location.search).get("share"); + const card = document.getElementById("sharedTool"); + const out = document.getElementById("sharedResult"); + const meta = document.getElementById("sharedMeta"); + if (!id || !card || !out) return; + + card.classList.remove("hidden"); + setResult(out, "waiting", "Loading shared result…"); + try { + const rec = await api(`/share/${encodeURIComponent(id)}`); + meta.textContent = `${rec.type} result · expires ${new Date(rec.expiresAt).toLocaleString()}`; + setResult(out, ""); + const render = renderers[rec.type]; + if (render) render(out, rec.data); + else out.append(el("pre", {}, JSON.stringify(rec.data, null, 2))); + card.scrollIntoView({ block: "start" }); + } catch (e) { + setResult(out, "error", e.message); + } +} diff --git a/frontend/src/features/smtp.js b/frontend/src/features/smtp.js index 3c83b78..9101263 100644 --- a/frontend/src/features/smtp.js +++ b/frontend/src/features/smtp.js @@ -1,4 +1,6 @@ import { $, escapeHtml } from "./utils.js"; +import { startFlow, flowActive, flowSuccess, flowError, checkBackend } from "./flow.js"; +import { attachActions, clearActions } from "./share.js"; const setState = (id, state, text) => { const el = $(id); @@ -7,12 +9,16 @@ const setState = (id, state, text) => { if (text) el.querySelector("p")?.replaceChildren(document.createTextNode(text)); }; -const setFlow = (id, state) => { - const el = $(id); - if (!el) return; - el.classList.remove("active", "success", "error"); - el.classList.add(state); -}; +// Share/export the diagnostic OUTPUT only: never the username, password, sender, recipient list input or message body. +const shareResult = (status, title, data) => + attachActions("smtp", { + status, + title, + host: $("smtpHost").value.trim(), + port: Number($("smtpPort").value), + security: $("smtpSecurity").value, + ...data + }, "smtpActions", "result"); const showResult = (type, title, data = {}) => { const el = $("result"); @@ -34,19 +40,12 @@ const showResult = (type, title, data = {}) => { `; }; +// Reachability check (shared) + sidebar status badge update (SMTP-specific UI). async function backendHealth() { - try { - const response = await fetch("/api/health"); - if (!response.ok) throw new Error(); - await response.json(); - $("backendStatus").textContent = "Connected"; - $("backendDot").className = "status-dot online"; - return true; - } catch { - $("backendStatus").textContent = "Unavailable"; - $("backendDot").className = "status-dot offline"; - return false; - } + const ok = await checkBackend(); + $("backendStatus").textContent = ok ? "Connected" : "Unavailable"; + $("backendDot").className = `status-dot ${ok ? "online" : "offline"}`; + return ok; } export function initSMTP() { @@ -68,6 +67,7 @@ export function initSMTP() { }); button.addEventListener("click", async () => { + clearActions("smtpActions"); const fields = [ [$("smtpHost"), "SMTP host is required"], [port, "SMTP port is required"], @@ -88,15 +88,14 @@ export function initSMTP() { button.disabled = true; button.textContent = "Testing SMTP..."; - ["flowFrontend", "flowBackend", "flowSMTP", "flowEmail"].forEach((id) => - $(id)?.classList.remove("active", "success", "error") - ); - setFlow("flowFrontend", "success"); + startFlow(); + flowSuccess("flowFrontend"); + flowActive("flowBackend"); setState("stageBackend", "active", "Checking backend..."); if (!(await backendHealth())) { - setFlow("flowBackend", "error"); + flowError("flowBackend"); setState("stageBackend", "error", "Backend is not reachable."); showResult("error", "Backend Connection Failed", { stage: "backend_connection", @@ -107,9 +106,9 @@ export function initSMTP() { return; } - setFlow("flowBackend", "success"); + flowSuccess("flowBackend"); setState("stageBackend", "success", "Request reached Node.js backend."); - setFlow("flowSMTP", "active"); + flowActive("flowSMTP"); setState("stageSMTP", "active", "Connecting to SMTP server and verifying credentials..."); try { @@ -133,29 +132,32 @@ export function initSMTP() { const data = await response.json(); if (!response.ok && data.stage === "smtp_authentication") { - setFlow("flowSMTP", "error"); + flowError("flowSMTP"); setState("stageSMTP", "error", "SMTP connection or authentication failed."); showResult("error", "SMTP Authentication Failed", data); + shareResult("error", "SMTP Authentication Failed", data); return; } - setFlow("flowSMTP", "success"); + flowSuccess("flowSMTP"); setState("stageSMTP", "success", "SMTP credentials verified successfully."); - setFlow("flowEmail", "active"); + flowActive("flowEmail"); setState("stageEmail", "active", "Sending test email..."); if (!response.ok) { - setFlow("flowEmail", "error"); + flowError("flowEmail"); setState("stageEmail", "error", "Email sending failed."); showResult("error", "Email Sending Failed", data); + shareResult("error", "Email Sending Failed", data); return; } - setFlow("flowEmail", "success"); + flowSuccess("flowEmail"); setState("stageEmail", "success", "Test email was accepted by the SMTP server."); showResult("success", "SMTP Test Successful", data); + shareResult("success", "SMTP Test Successful", data); } catch (error) { - setFlow("flowEmail", "error"); + flowError("flowEmail"); setState("stageEmail", "error", "Could not communicate with the backend."); showResult("error", "Request Failed", { stage: "frontend_request", error: error.message }); } finally { diff --git a/frontend/src/features/tabs.js b/frontend/src/features/tabs.js index 9535e17..fe973d5 100644 --- a/frontend/src/features/tabs.js +++ b/frontend/src/features/tabs.js @@ -2,7 +2,10 @@ const PANELS = { smtp: "smtpTool", dns: "dnsTool", headers: "headersTool", - generator: "generatorTool" + generator: "generatorTool", + blacklist: "blacklistTool", + score: "scoreTool", + tls: "tlsTool" }; const FLOW_COPY = { @@ -41,6 +44,33 @@ const FLOW_COPY = { ["Generator", "Cryptography"], ["DNS", "Records"] ] + }, + blacklist: { + title: "Blacklist lookup path", + labels: [ + ["Frontend", "Browser"], + ["Backend", "Node.js"], + ["DNSBL", "Lookups"], + ["Verdict", "Listings"] + ] + }, + score: { + title: "Deliverability scoring path", + labels: [ + ["Frontend", "Browser"], + ["Backend", "Node.js"], + ["Checks", "DNS · TLS"], + ["Score", "Grade & fixes"] + ] + }, + tls: { + title: "TLS inspection path", + labels: [ + ["Frontend", "Browser"], + ["Backend", "Node.js"], + ["Server", "Handshake"], + ["Certificate", "Analysis"] + ] } }; diff --git a/frontend/src/features/tls.js b/frontend/src/features/tls.js new file mode 100644 index 0000000..582dd5b --- /dev/null +++ b/frontend/src/features/tls.js @@ -0,0 +1,57 @@ +import { el, post, badge } from "./ui.js"; +import { bindTool } from "./share.js"; + +const row = (k, v) => el("tr", {}, el("th", {}, k), el("td", {}, v ?? "—")); +const name = (o) => (o ? o.CN || o.O || Object.values(o).join(", ") : "—"); + +export function renderTls(root, d) { + const c = d.certificate; + const v = d.supportedVersions; + root.replaceChildren( + el("h3", {}, `${d.host}:${d.port}`), + el("ul", { class: "mm-findings" }, d.findings.map((f) => + el("li", {}, badge(f.severity, f.severity), " ", el("strong", {}, f.title), f.detail ? ` — ${f.detail}` : ""))), + el("h4", {}, "Connection"), + el("table", {}, el("tbody", {}, + row("IP", d.ip), + row("Mode", d.mode), + row("Protocol", d.connection.protocol), + row("Cipher", d.connection.cipher), + row("Trusted", d.connection.authorized ? "Yes" : `No (${d.connection.authorizationError})`), + v ? row("Versions", Object.entries(v).map(([k, ok]) => `${k}: ${ok ? "yes" : "no"}`).join(" · ")) : null)), + el("h4", {}, "Certificate"), + el("table", {}, el("tbody", {}, + row("Subject", name(c.subject)), + row("Issuer", name(c.issuer)), + row("Valid from", c.validFrom), + row("Valid to", `${c.validTo} (${c.daysRemaining} days)`), + row("Key", c.curve ? `EC ${c.curve}` : `RSA ${c.bits} bits`), + row("SANs", c.altNames.join(", ") || "—"), + row("SHA-256", c.fingerprint256), + row("Serial", c.serialNumber))), + el("h4", {}, "Chain"), + el("ol", {}, d.chain.map((x) => el("li", {}, `${name(x.subject)} (issued by ${name(x.issuer)})`))) + ); +} + +export function initTls() { + const host = document.getElementById("tlsHost"); + bindTool({ + button: document.getElementById("tlsButton"), + enterOn: [host], + out: document.getElementById("tlsResult"), + actions: document.getElementById("tlsActions"), + type: "tls", + busyMsg: "Connecting and negotiating TLS…", + request: async () => { + const h = host.value.trim(); + if (!h) throw new Error("Enter a mail server hostname."); + return post("/tls", { + host: h, + port: Number(document.getElementById("tlsPort").value), + versions: document.getElementById("tlsVersions").checked + }); + }, + render: renderTls + }); +} diff --git a/frontend/src/features/ui.js b/frontend/src/features/ui.js new file mode 100644 index 0000000..6f3fcba --- /dev/null +++ b/frontend/src/features/ui.js @@ -0,0 +1,50 @@ +// Small DOM helpers. Everything is built with textContent/text nodes, never innerHTML, +// so API data cannot inject markup. +export function el(tag, attrs = {}, ...kids) { + const n = document.createElement(tag); + for (const [k, v] of Object.entries(attrs || {})) { + if (k === "class") n.className = v; + else if (k.startsWith("on") && typeof v === "function") n.addEventListener(k.slice(2), v); + else if (v !== false && v != null) n.setAttribute(k, v); + } + for (const kid of kids.flat()) { + if (kid != null && kid !== false) n.append(kid.nodeType ? kid : document.createTextNode(String(kid))); + } + return n; +} + +export async function api(path, opts = {}) { + const res = await fetch(`/api${path}`, { headers: { "Content-Type": "application/json" }, ...opts }); + const body = await res.json().catch(() => ({})); + if (!res.ok) throw new Error(body.error || `Request failed (${res.status})`); + return body; +} + +export const post = (path, payload) => api(path, { method: "POST", body: JSON.stringify(payload) }); + +const TONES = { + pass: "good", ok: "good", clean: "good", + warn: "warn", warning: "warn", unknown: "warn", + fail: "bad", critical: "bad", listed: "bad", + skip: "muted" +}; + +export function badge(status, text) { + return el("span", { class: `mm-badge mm-${TONES[status] || "muted"}` }, text ?? status); +} + +// Works with the existing .test-button markup: +export function setBusy(btn, busy) { + const label = btn.querySelector("span"); + if (label) { + if (!btn.dataset.label) btn.dataset.label = label.textContent; + label.textContent = busy ? "Working…" : btn.dataset.label; + } + btn.disabled = busy; +} + +// state: "" (normal) | "waiting" | "error" +export function setResult(out, state, ...kids) { + out.className = state ? `result ${state}` : "result"; + out.replaceChildren(...kids); +} diff --git a/frontend/src/index-snippets.html b/frontend/src/index-snippets.html new file mode 100644 index 0000000..d5914c8 --- /dev/null +++ b/frontend/src/index-snippets.html @@ -0,0 +1,42 @@ + + +
+

Blacklist checker

+
+ + +
+
+
+ +
+

Deliverability score

+
+ + + +
+
+
+ +
+

TLS certificate inspector

+
+ + + + +
+
+
+ + +
diff --git a/frontend/src/index.html b/frontend/src/index.html index a617c59..d51dfb2 100644 --- a/frontend/src/index.html +++ b/frontend/src/index.html @@ -72,6 +72,24 @@ SPF, DKIM & DMARCCreate DNS records + + + @@ -163,6 +181,15 @@

SMTP delivery path

+ + +
@@ -287,6 +314,7 @@

Diagnostic output

Enter your SMTP credentials and click Test connection & send email to start.
+
@@ -325,6 +353,7 @@

DNS records

MX · SPF · DMARC · DKIM
Enter a domain name above to inspect its email records.
+
@@ -360,6 +389,7 @@

Parsed results

Findings
Paste raw email headers and run the analysis.
+
@@ -509,11 +539,142 @@

Generated records

DNS TXT
Configure the options and generate your DNS records and DKIM keypair.
+
+ + + + + + + + +
@@ -521,7 +682,6 @@

Generated records

MailMetrix - SMTP · DNS · Security
diff --git a/frontend/src/style.css b/frontend/src/style.css index 2edadc8..5a6ef6a 100644 --- a/frontend/src/style.css +++ b/frontend/src/style.css @@ -927,4 +927,69 @@ html { line-height: 1.5; cursor: default; } -.version-badge[hidden] { display: none; } \ No newline at end of file +.version-badge[hidden] { display: none; } + +.mm-badge { + display: inline-block; + padding: 2px 9px; + border: 1px solid var(--border); + border-radius: 999px; + font-size: 11.5px; font-weight: 650; line-height: 1.5; + white-space: nowrap; +} +.mm-good { color: var(--success-text); background: var(--success-bg); border-color: var(--success-border); } +.mm-warn { color: var(--warning-text); background: var(--warning-bg); border-color: var(--warning-border); } +.mm-bad { color: var(--danger-text); background: var(--danger-bg); border-color: var(--danger-border); } +.mm-muted { color: var(--text-soft); background: var(--surface-sunken); } + +.mm-note { color: var(--text-faint); font-size: 12.5px; } +.result .mm-note { margin: 6px 0; } + +.mm-findings { list-style: none; padding-left: 0 !important; } +.mm-findings li { margin: 7px 0; } + +/* Deliverability grade */ +.mm-score { display: flex; align-items: center; gap: 18px; margin-bottom: 8px; } +.mm-score h3 { margin: 0 0 2px; } +.mm-grade { + display: grid; place-items: center; + width: 76px; height: 76px; flex: 0 0 76px; + border-radius: 50%; + color: #fff; background: #6b7280; + font-size: 2.4rem; font-weight: 800; +} +.mm-grade-A { background: #16a34a; } +.mm-grade-B { background: #65a30d; } +.mm-grade-C { background: #ca8a04; } +.mm-grade-D { background: #ea580c; } +.mm-grade-F { background: #dc2626; } + +/* Share / export bar (sits OUTSIDE .result so it doesn't inherit the copy-button styling) */ +.action-bar:empty { display: none; } +.action-bar { margin-top: 14px; } +.action-bar-inner { display: flex; flex-wrap: wrap; align-items: center; gap: 8px; } +.action-bar button { + padding: 6px 14px; + border: 1px solid var(--border-strong); + border-radius: 999px; + color: var(--text-soft); + background: var(--surface); + box-shadow: var(--shadow-sm); + font-size: 12px; font-weight: 600; + cursor: pointer; + transition: color 0.15s ease, background 0.15s ease, border-color 0.15s ease; +} +.action-bar button:hover:not(:disabled) { color: var(--primary); border-color: var(--primary-ring); background: var(--primary-soft); } +.action-bar button:disabled { opacity: 0.55; cursor: wait; } +.action-bar a { color: var(--primary); word-break: break-all; } + +/* Print / "PDF" export: only the result is printed */ +@media print { + body * { visibility: hidden; } + .mm-print-target, .mm-print-target * { visibility: visible; } + .mm-print-target { + position: absolute; left: 0; top: 0; width: 100%; + color: #000 !important; background: #fff !important; border: 0 !important; + } + .bg-grid-overlay { display: none; } +} From 073eb4536ceaf77bc6a9ba6c5cc343e733b6ab64 Mon Sep 17 00:00:00 2001 From: devopsgithub1234 Date: Sat, 14 Nov 2026 09:38:54 +0530 Subject: [PATCH 02/12] update env example --- .env.example | 7 ++++++- 1 file changed, 6 insertions(+), 1 deletion(-) diff --git a/.env.example b/.env.example index b3ea698..881ac07 100644 --- a/.env.example +++ b/.env.example @@ -2,4 +2,9 @@ # Keep this file free of real credentials and secrets. # Port on which the backend server listens inside its container. -PORT=4000 \ No newline at end of file +PORT=4000 +SHARE_TTL_DAYS=7 +RATE_LIMIT_BLACKLIST=30 +RATE_LIMIT_SCORE=15 +RATE_LIMIT_TLS=20 +RATE_LIMIT_SHARE=60 \ No newline at end of file From a799cb3aafdcceef2a114f815c9cd285e57d54a3 Mon Sep 17 00:00:00 2001 From: Kaushik Parui Date: Sat, 14 Nov 2026 12:33:27 +0530 Subject: [PATCH 03/12] security & bug fixes --- .env.example | 18 ++- backend/src/routes/_util.js | 3 + backend/src/routes/share.js | 2 +- backend/src/services/netguard.js | 73 ++++++--- backend/src/services/score.js | 252 +++++++++++++++++++++++-------- backend/src/services/share.js | 137 ++++++++++++++--- backend/src/services/smtp.js | 98 +++++------- frontend/src/index-snippets.html | 42 ------ 8 files changed, 416 insertions(+), 209 deletions(-) delete mode 100644 frontend/src/index-snippets.html diff --git a/.env.example b/.env.example index 881ac07..2652cfd 100644 --- a/.env.example +++ b/.env.example @@ -3,8 +3,22 @@ # Port on which the backend server listens inside its container. PORT=4000 -SHARE_TTL_DAYS=7 RATE_LIMIT_BLACKLIST=30 RATE_LIMIT_SCORE=15 RATE_LIMIT_TLS=20 -RATE_LIMIT_SHARE=60 \ No newline at end of file +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_DNSBL_IPS_PER_HOUR=300 +SCORE_TLS_PROBES_PER_HOUR=120 \ No newline at end of file diff --git a/backend/src/routes/_util.js b/backend/src/routes/_util.js index 065c304..bc808a1 100644 --- a/backend/src/routes/_util.js +++ b/backend/src/routes/_util.js @@ -4,6 +4,9 @@ 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 }); diff --git a/backend/src/routes/share.js b/backend/src/routes/share.js index 028897d..d9aff9b 100644 --- a/backend/src/routes/share.js +++ b/backend/src/routes/share.js @@ -8,7 +8,7 @@ router.use(express.json({ limit: '300kb' })); router.post('/', (req, res) => { try { - res.status(201).json(service.create(req.body?.type, req.body?.data)); + res.status(201).json(service.create(req.body?.type, req.body?.data, req.ip)); } catch (e) { sendError(res, e); } }); diff --git a/backend/src/services/netguard.js b/backend/src/services/netguard.js index eed2b78..8b90e2f 100644 --- a/backend/src/services/netguard.js +++ b/backend/src/services/netguard.js @@ -1,5 +1,6 @@ 'use strict'; // SSRF protection: only allow connections to public IPs. +// Single canonical blocklist: import isPrivateIp from here everywhere (tls, score, blacklist, smtp). const dns = require('dns').promises; const net = require('net'); @@ -11,31 +12,57 @@ function blocked(msg) { return e; } -function isPrivateIPv4(ip) { - const [a, b] = ip.split('.').map(Number); - return ( - a === 0 || a === 10 || a === 127 || a >= 224 || - (a === 169 && b === 254) || - (a === 172 && b >= 16 && b <= 31) || - (a === 192 && b === 168) || - (a === 100 && b >= 64 && b <= 127) || - (a === 198 && (b === 18 || b === 19)) - ); -} +// net.BlockList parses and normalises addresses itself, so non-canonical IPv6 spellings +// (0:0:0:0:0:ffff:7f00:1, ::127.0.0.1, ...) cannot slip past string-prefix checks. +// +// Two separate lists on purpose: Node matches IPv4 addresses against IPv6 rules as +// IPv4-mapped (::ffff:a.b.c.d), so a v6 rule like ::/8 would match every IPv4 address. +const BLOCK4 = new net.BlockList(); +const BLOCK6 = new net.BlockList(); +const v4 = (addr, prefix) => BLOCK4.addSubnet(addr, prefix, 'ipv4'); +const v6 = (addr, prefix) => BLOCK6.addSubnet(addr, prefix, 'ipv6'); -function isPrivateIPv6(ip) { - const l = ip.toLowerCase(); - if (l === '::' || l === '::1') return true; - if (l.startsWith('::ffff:')) { - const v4 = l.slice(7); - return net.isIPv4(v4) ? isPrivateIPv4(v4) : true; - } - return /^(fc|fd|fe[89ab])/.test(l); -} +// --- IPv4 --- +v4('0.0.0.0', 8); // "this" network +v4('10.0.0.0', 8); // private +v4('100.64.0.0', 10); // CGNAT +v4('127.0.0.0', 8); // loopback +v4('169.254.0.0', 16); // link-local / cloud metadata +v4('172.16.0.0', 12); // private +v4('192.0.0.0', 24); // IETF protocol assignments +v4('192.0.2.0', 24); // TEST-NET-1 +v4('192.88.99.0', 24); // deprecated 6to4 relay anycast +v4('192.168.0.0', 16); // private +v4('198.18.0.0', 15); // benchmarking +v4('198.51.100.0', 24); // TEST-NET-2 +v4('203.0.113.0', 24); // TEST-NET-3 +v4('224.0.0.0', 4); // multicast +v4('240.0.0.0', 4); // reserved + broadcast + +// --- IPv6 --- +v6('::', 8); // unspecified, loopback, IPv4-compatible, IPv4-mapped (::ffff:0:0/96) and other reserved +v6('64:ff9b::', 96); // NAT64 (embeds an IPv4 address) +v6('64:ff9b:1::', 48); // local-use NAT64 +v6('100::', 64); // discard-only +v6('2001::', 23); // IETF protocol assignments incl. Teredo (2001::/32), ORCHID, benchmarking +v6('2001:db8::', 32); // documentation +v6('2002::', 16); // 6to4 (embeds an IPv4 address) +v6('3fff::', 20); // documentation (RFC 9637) +v6('5f00::', 16); // SRv6 SIDs +v6('fc00::', 7); // unique local +v6('fe80::', 10); // link-local +v6('fec0::', 10); // deprecated site-local +v6('ff00::', 8); // multicast +// Returns true for anything that must not be contacted. Fails closed on garbage input. function isPrivateIp(ip) { - if (net.isIPv4(ip)) return isPrivateIPv4(ip); - if (net.isIPv6(ip)) return isPrivateIPv6(ip); + if (typeof ip !== 'string' || ip.includes('%')) return true; // also rejects zone IDs (fe80::1%eth0) + try { + if (net.isIPv4(ip)) return BLOCK4.check(ip, 'ipv4'); + if (net.isIPv6(ip)) return BLOCK6.check(ip, 'ipv6'); + } catch { + return true; + } return true; } @@ -64,4 +91,4 @@ async function resolvePublic(host) { return addrs.map((a) => a.address); } -module.exports = { isPrivateIp, isValidHostname, resolvePublic, HOST_RE }; +module.exports = { isPrivateIp, isBlockedIp: isPrivateIp, isValidHostname, resolvePublic, HOST_RE }; \ No newline at end of file diff --git a/backend/src/services/score.js b/backend/src/services/score.js index 5488804..b055645 100644 --- a/backend/src/services/score.js +++ b/backend/src/services/score.js @@ -1,47 +1,142 @@ 'use strict'; // Deliverability score. Self-contained: swap the DNS helpers for your services/dns.js if you prefer. +// +// Abuse controls. The domain being scored is attacker-controlled, so are its SPF includes, +// MX targets and PTR names, which means they decide which third-party names/IPs get queried: +// - per-request DNS query budget, SPF lookup cap (RFC 7208: 10), PTR-name cap and an overall deadline +// - result cache per domain (with in-flight coalescing), plus caches keyed by the *target* +// (MX IP for the port-25 probe, IP for DNSBL) so rotating attacker-owned domains cannot be +// used to hammer one third-party host +// - global hourly caps on outbound DNSBL lookups and port-25 probes, and a concurrency cap const dns = require('dns'); -const { isValidHostname } = require('./netguard'); +const { isValidHostname, isPrivateIp } = require('./netguard'); const blacklist = require('./blacklist'); const tlsService = require('./tls'); const resolver = new dns.promises.Resolver({ timeout: 4000, tries: 2 }); const DKIM_SELECTORS = ['default', 'google', 'selector1', 'selector2', 'k1', 'k2', 'k3', 's1', 's2', 'mail', 'dkim', 'smtp', 'mandrill', 'mailjet', 'amazonses', 'zoho', 'sendgrid', 'em', 'protonmail']; -const txt = async (name) => { - try { return (await resolver.resolveTxt(name)).map((c) => c.join('')); } catch { return []; } -}; +const num = (v, d) => (Number.isFinite(Number(v)) && Number(v) > 0 ? Number(v) : d); +const CACHE_TTL_MS = num(process.env.SCORE_CACHE_TTL_SECONDS, 300) * 1000; // per-domain result cache +const CACHE_MAX = num(process.env.SCORE_CACHE_MAX, 500); +const TARGET_TTL_MS = num(process.env.SCORE_TARGET_TTL_SECONDS, 900) * 1000; // per MX IP / DNSBL IP +const MAX_DNS_QUERIES = num(process.env.SCORE_MAX_DNS_QUERIES, 80); // per request (normal use is ~55 max) +const DEADLINE_MS = num(process.env.SCORE_DEADLINE_SECONDS, 25) * 1000; // per request +const MAX_CONCURRENT = num(process.env.SCORE_MAX_CONCURRENT, 8); // simultaneous uncached runs +const SPF_LIMIT = 10; // RFC 7208 section 4.6.4 +const MAX_PTR_NAMES = 2; + +const fail = (msg, code) => Object.assign(new Error(msg), { code }); + +// Cache of promises: concurrent identical requests share one run, failures are never cached. +function ttlCache(ttlMs, max) { + const m = new Map(); + return { + has: (key) => { const e = m.get(key); return Boolean(e && e.exp > Date.now()); }, + get(key, loader) { + const e = m.get(key); + if (e && e.exp > Date.now()) return e.p; + const p = Promise.resolve().then(loader); + m.delete(key); + m.set(key, { p, exp: Date.now() + ttlMs }); + if (m.size > max) m.delete(m.keys().next().value); // bound memory: drop the oldest entry + p.catch(() => { if (m.get(key)?.p === p) m.delete(key); }); + return p; + }, + }; +} + +// Fixed-window global cap for outbound traffic to third parties. +function makeWindow(limit, ms) { + let start = Date.now(); + let count = 0; + return { + take() { + const now = Date.now(); + if (now - start >= ms) { start = now; count = 0; } + if (count >= limit) return false; + count += 1; + return true; + }, + }; +} + +const scoreCache = ttlCache(CACHE_TTL_MS, CACHE_MAX); +const tlsCache = ttlCache(TARGET_TTL_MS, 1000); +const dnsblCache = ttlCache(TARGET_TTL_MS, 2000); +const dnsblWindow = makeWindow(num(process.env.SCORE_DNSBL_IPS_PER_HOUR, 300), 3600000); +const tlsWindow = makeWindow(num(process.env.SCORE_TLS_PROBES_PER_HOUR, 120), 3600000); +let active = 0; + +// Per-request DNS helper: memoised (no duplicate queries), budgeted and deadline-bound. +function makeDns() { + const st = { queries: 0, exhausted: false, deadline: Date.now() + DEADLINE_MS }; + const memo = new Map(); + const q = (key, fn) => { + if (memo.has(key)) return memo.get(key); + if (st.queries >= MAX_DNS_QUERIES || Date.now() > st.deadline) { + st.exhausted = true; + return Promise.reject(fail('DNS budget exceeded', 'TOO_COMPLEX')); + } + st.queries += 1; + const p = Promise.resolve().then(fn); + memo.set(key, p); + return p; + }; + return { + st, + txt: async (name) => { + try { return (await q(`txt:${name}`, () => resolver.resolveTxt(name))).map((c) => c.join('')); } catch { return []; } + }, + mx: (name) => q(`mx:${name}`, () => resolver.resolveMx(name)), + a: (name) => q(`a:${name}`, () => resolver.resolve4(name)), + ptr: (ip) => q(`ptr:${ip}`, () => resolver.reverse(ip)), + }; +} + const safe = async (fn, fallback) => { try { return await fn(); } catch { return fallback; } }; const mk = (id, label, max, points, status, detail, fix) => ({ id, label, max, points: Math.round(points * 10) / 10, status, detail, fix: fix || null }); -async function getMx(domain) { - const mx = await safe(() => resolver.resolveMx(domain), []); +async function getMx(d, domain) { + const mx = await safe(() => d.mx(domain), []); return mx.filter((m) => m.exchange && m.exchange !== '.').sort((a, b) => a.priority - b.priority); } -async function mxIps(mx) { +// Only public FQDNs are resolved, and private addresses are dropped, so internal DNS names +// (Docker service names, corp hosts) can never be probed or leaked through the report. +async function mxIps(d, mx) { const out = []; for (const m of mx.slice(0, 3)) { - const ips = await safe(() => resolver.resolve4(m.exchange), []); - for (const ip of ips.slice(0, 2)) out.push({ host: m.exchange, ip }); + if (!isValidHostname(m.exchange)) continue; + const ips = await safe(() => d.a(m.exchange), []); + for (const ip of ips.slice(0, 2)) if (!isPrivateIp(ip)) out.push({ host: m.exchange, ip }); } return out; } -async function spfLookups(domain, depth = 0, seen = new Set()) { - if (depth > 10 || seen.has(domain)) return 0; - seen.add(domain); - const rec = (await txt(domain)).find((t) => /^v=spf1\b/i.test(t)); - if (!rec) return 0; - let n = 0; +// RFC 7208 allows 10 DNS-querying terms. Stop querying as soon as the limit is passed: +// the "depth" limit alone does not bound breadth (a record can contain hundreds of includes). +async function spfLookups(d, domain, st = { n: 0, seen: new Set() }, depth = 0) { + if (depth > SPF_LIMIT || st.seen.has(domain)) return st.n; + st.seen.add(domain); + const rec = (await d.txt(domain)).find((t) => /^v=spf1\b/i.test(t)); + if (!rec) return st.n; for (const term of rec.split(/\s+/).slice(1)) { + if (st.n > SPF_LIMIT) return st.n; const m = term.replace(/^[+\-~?]/, ''); - if (/^include:/i.test(m)) n += 1 + (await spfLookups(m.slice(8), depth + 1, seen)); - else if (/^redirect=/i.test(m)) n += 1 + (await spfLookups(m.slice(9), depth + 1, seen)); - else if (/^(a|mx)(:|\/|$)/i.test(m) || /^(ptr|exists:)/i.test(m)) n += 1; + const isInclude = /^include:/i.test(m); + const isRedirect = /^redirect=/i.test(m); + if (isInclude || isRedirect) { + st.n += 1; + if (st.n > SPF_LIMIT) return st.n; + const target = m.slice(isInclude ? 8 : 9).toLowerCase(); + if (isValidHostname(target)) await spfLookups(d, target, st, depth + 1); // skips macros / junk names + } else if (/^(a|mx)(:|\/|$)/i.test(m) || /^(ptr|exists:)/i.test(m)) { + st.n += 1; + } } - return n; + return st.n; } async function checkMx(domain, mx) { @@ -50,12 +145,12 @@ async function checkMx(domain, mx) { return mk('mx', 'MX records', 10, 10, 'pass', `${mx.length} MX records, primary ${mx[0].exchange}.`); } -async function checkSpf(domain) { - const recs = (await txt(domain)).filter((t) => /^v=spf1\b/i.test(t)); +async function checkSpf(d, domain) { + const recs = (await d.txt(domain)).filter((t) => /^v=spf1\b/i.test(t)); if (!recs.length) return mk('spf', 'SPF', 20, 0, 'fail', 'No SPF record found.', 'Publish a TXT record such as "v=spf1 include: -all".'); if (recs.length > 1) return mk('spf', 'SPF', 20, 4, 'fail', `${recs.length} SPF records found; receivers will return PermError.`, 'Merge into a single SPF record.'); const rec = recs[0]; - const lookups = await spfLookups(domain); + const lookups = await spfLookups(d, domain); let pts = 20; const notes = []; let status = 'pass'; @@ -65,17 +160,17 @@ async function checkSpf(domain) { else if (/\s~all\b/i.test(rec)) { pts -= 3; notes.push('Soft fail (~all).'); } else if (/\s-all\b/i.test(rec)) notes.push('Hard fail (-all).'); else if (!/redirect=/i.test(rec)) { pts -= 8; status = 'warn'; notes.push('No "all" mechanism.'); fix = 'End the record with -all or ~all.'; } - if (lookups > 10) { pts = Math.min(pts, 6); status = 'fail'; notes.push(`${lookups} DNS lookups (limit is 10).`); fix = 'Flatten includes to stay at 10 lookups or fewer.'; } + if (lookups > SPF_LIMIT) { pts = Math.min(pts, 6); status = 'fail'; notes.push(`Over ${SPF_LIMIT} DNS lookups (limit is ${SPF_LIMIT}).`); fix = 'Flatten includes to stay at 10 lookups or fewer.'; } else if (lookups >= 8) { pts -= 2; if (status === 'pass') status = 'warn'; notes.push(`${lookups}/10 DNS lookups.`); } else notes.push(`${lookups}/10 DNS lookups.`); return mk('spf', 'SPF', 20, Math.max(pts, 0), status, notes.join(' '), fix); } -async function checkDkim(domain, selector) { +async function checkDkim(d, domain, selector) { const selectors = selector ? [selector] : DKIM_SELECTORS; const found = []; await Promise.all(selectors.map(async (s) => { - const r = await txt(`${s}._domainkey.${domain}`); + const r = await d.txt(`${s}._domainkey.${domain}`); if (r.some((t) => /v=DKIM1|p=/i.test(t))) found.push(s); })); if (found.length) return mk('dkim', 'DKIM', 15, 15, 'pass', `Key found for selector(s): ${found.join(', ')}.`); @@ -84,8 +179,8 @@ async function checkDkim(domain, selector) { : mk('dkim', 'DKIM', 15, 7, 'warn', 'No key found on common selectors (yours may use a custom one).', 'Re-run with your DKIM selector to verify.'); } -async function checkDmarc(domain) { - const rec = (await txt(`_dmarc.${domain}`)).find((t) => /^v=DMARC1/i.test(t)); +async function checkDmarc(d, domain) { + const rec = (await d.txt(`_dmarc.${domain}`)).find((t) => /^v=DMARC1/i.test(t)); if (!rec) return mk('dmarc', 'DMARC', 20, 0, 'fail', 'No DMARC record found.', 'Add _dmarc TXT: "v=DMARC1; p=none; rua=mailto:dmarc@' + domain + '".'); const p = (rec.match(/\bp=(\w+)/i) || [])[1]?.toLowerCase(); const hasRua = /\brua=/i.test(rec); @@ -96,19 +191,20 @@ async function checkDmarc(domain) { return mk('dmarc', 'DMARC', 20, Math.max(pts, 0), status, `Policy p=${p || 'unknown'}${hasRua ? ', reporting enabled' : ', no reporting address'}.`, fix); } -async function checkRdns(ips) { +async function checkRdns(d, ips) { if (!ips.length) return mk('rdns', 'Reverse DNS (FCrDNS)', 10, 0, 'skip', 'No MX IPs to test.'); - let ok = 0; - const bad = []; - for (const { ip } of ips) { - const names = await safe(() => resolver.reverse(ip), []); - let good = false; + const good = await Promise.all(ips.map(async ({ ip }) => { + // An attacker controls PTR answers for their own IP space: cap how many names we chase. + const names = (await safe(() => d.ptr(ip), [])).slice(0, MAX_PTR_NAMES); for (const n of names) { - const fwd = await safe(() => resolver.resolve4(n), []); - if (fwd.includes(ip)) { good = true; break; } + if (!isValidHostname(n)) continue; + const fwd = await safe(() => d.a(n), []); + if (fwd.includes(ip)) return true; } - if (good) ok += 1; else bad.push(ip); - } + return false; + })); + const ok = good.filter(Boolean).length; + const bad = ips.filter((_, i) => !good[i]).map((x) => x.ip); const pts = (ok / ips.length) * 10; if (!bad.length) return mk('rdns', 'Reverse DNS (FCrDNS)', 10, 10, 'pass', `All ${ips.length} MX IP(s) have matching PTR and A records.`); return mk('rdns', 'Reverse DNS (FCrDNS)', 10, pts, ok ? 'warn' : 'fail', `No forward-confirmed PTR for: ${bad.join(', ')}.`, 'Ask your host to set a PTR that resolves back to the same IP.'); @@ -117,24 +213,27 @@ async function checkRdns(ips) { async function checkBlacklist(ips) { if (!ips.length) return mk('blacklist', 'Blacklists', 10, 0, 'skip', 'No MX IPs to test.'); const unique = [...new Set(ips.map((i) => i.ip))].slice(0, 3); - const results = await Promise.all(unique.map((ip) => safe(() => blacklist.checkIp(ip), null))); + // Cached per IP, so many domains pointing at one IP cannot repeatedly hit the DNSBL operators. + const results = await Promise.all(unique.map((ip) => safe(() => dnsblCache.get(ip, () => { + if (!dnsblWindow.take()) throw fail('DNSBL checks limited', 'LIMITED'); + return blacklist.checkIp(ip); + }), null))); const flat = results.filter(Boolean).flatMap((r) => r.results.filter((x) => x.status === 'listed').map((x) => `${r.target} on ${x.name}`)); const known = results.filter(Boolean).flatMap((r) => r.results).filter((x) => x.status !== 'unknown').length; - if (!known) return mk('blacklist', 'Blacklists', 10, 0, 'skip', 'Blacklist servers did not answer (resolver may be blocked).'); + if (!known) return mk('blacklist', 'Blacklists', 10, 0, 'skip', 'Blacklist servers did not answer, or checks are temporarily limited.'); if (!flat.length) return mk('blacklist', 'Blacklists', 10, 10, 'pass', `MX IPs are clean on ${known} lookups.`); return mk('blacklist', 'Blacklists', 10, Math.max(0, 10 - flat.length * 5), 'fail', `Listed: ${flat.join('; ')}.`, 'Request delisting and fix the cause (compromised account, open relay, bad reputation).'); } -async function checkMtaSts(domain) { - const rec = (await txt(`_mta-sts.${domain}`)).find((t) => /^v=STSv1/i.test(t)); +async function checkMtaSts(d, domain) { + const rec = (await d.txt(`_mta-sts.${domain}`)).find((t) => /^v=STSv1/i.test(t)); return rec ? mk('mtasts', 'MTA-STS', 5, 5, 'pass', 'MTA-STS record published.') : mk('mtasts', 'MTA-STS', 5, 0, 'warn', 'No MTA-STS record.', 'Publish _mta-sts TXT and a policy file to enforce TLS for inbound mail.'); } -async function checkTls(mx) { - if (!mx.length) return mk('tls', 'Mail server TLS', 10, 0, 'skip', 'No MX to test.'); - const host = mx[0].exchange; +async function probeTls(host) { + if (!tlsWindow.take()) throw fail('TLS probes limited', 'LIMITED'); try { const r = await tlsService.inspect({ host, port: 25 }); const crit = r.findings.filter((f) => f.severity === 'critical'); @@ -144,7 +243,21 @@ async function checkTls(mx) { return mk('tls', 'Mail server TLS', 10, 10, 'pass', `${host}: ${r.connection.protocol}, trusted certificate.`); } catch (e) { if (e.code === 'NO_STARTTLS') return mk('tls', 'Mail server TLS', 10, 0, 'fail', `${host} does not offer STARTTLS.`, 'Enable STARTTLS on your MX.'); - return mk('tls', 'Mail server TLS', 10, 0, 'skip', `Could not test ${host}:25 (${e.message}).`); + // Deliberately generic: error text would reveal whether internal names exist or which ports are open. + return mk('tls', 'Mail server TLS', 10, 0, 'skip', `Could not test ${host}:25.`); + } +} + +async function checkTls(mx, ips) { + if (!mx.length) return mk('tls', 'Mail server TLS', 10, 0, 'skip', 'No MX to test.'); + const host = mx[0].exchange; + if (!isValidHostname(host)) return mk('tls', 'Mail server TLS', 10, 0, 'skip', 'Primary MX is not a public hostname.'); + // Key by the target IP when known: attacker-owned hostnames pointing at one victim share a cache entry. + const target = ips.find((i) => i.host === host)?.ip || host.toLowerCase(); + try { + return await tlsCache.get(target, () => probeTls(host)); + } catch { + return mk('tls', 'Mail server TLS', 10, 0, 'skip', 'TLS checks are temporarily limited; try again later.'); } } @@ -152,26 +265,43 @@ function grade(pct) { return pct >= 90 ? 'A' : pct >= 80 ? 'B' : pct >= 70 ? 'C' : pct >= 60 ? 'D' : 'F'; } +async function run(domain, selector) { + if (active >= MAX_CONCURRENT) throw fail('Scoring is busy, try again shortly', 'BUSY'); + active += 1; + try { + const d = makeDns(); + const mx = await getMx(d, domain); + const ips = await mxIps(d, mx); + + const checks = await Promise.all([ + checkMx(domain, mx), checkSpf(d, domain), checkDkim(d, domain, selector), checkDmarc(d, domain), + checkRdns(d, ips), checkBlacklist(ips), checkMtaSts(d, domain), checkTls(mx, ips), + ]); + + // Budget or deadline hit: some checks saw "no records" only because we stopped asking. + if (d.st.exhausted) throw fail('This domain needs too many DNS lookups to analyze', 'TOO_COMPLEX'); + + const scored = checks.filter((c) => c.status !== 'skip'); + const max = scored.reduce((s, c) => s + c.max, 0) || 1; + const pts = scored.reduce((s, c) => s + c.points, 0); + const pct = Math.round((pts / max) * 100); + const fixes = checks.filter((c) => c.fix && c.points < c.max).sort((a, b) => (b.max - b.points) - (a.max - a.points)).map((c) => ({ check: c.label, fix: c.fix })); + + return { domain, checkedAt: new Date().toISOString(), score: pct, grade: grade(pct), skipped: checks.filter((c) => c.status === 'skip').map((c) => c.label), checks, fixes }; + } finally { + active -= 1; + } +} + async function score(rawDomain, { selector } = {}) { const domain = String(rawDomain || '').trim().toLowerCase().replace(/^.*@/, ''); if (!isValidHostname(domain)) throw Object.assign(new Error('Enter a valid domain name'), { code: 'BAD_INPUT' }); if (selector && !/^[a-z0-9._-]{1,63}$/i.test(selector)) throw Object.assign(new Error('Invalid DKIM selector'), { code: 'BAD_INPUT' }); - const mx = await getMx(domain); - const ips = await mxIps(mx); - - const checks = await Promise.all([ - checkMx(domain, mx), checkSpf(domain), checkDkim(domain, selector), checkDmarc(domain), - checkRdns(ips), checkBlacklist(ips), checkMtaSts(domain), checkTls(mx), - ]); - - const scored = checks.filter((c) => c.status !== 'skip'); - const max = scored.reduce((s, c) => s + c.max, 0) || 1; - const pts = scored.reduce((s, c) => s + c.points, 0); - const pct = Math.round((pts / max) * 100); - const fixes = checks.filter((c) => c.fix && c.points < c.max).sort((a, b) => (b.max - b.points) - (a.max - a.points)).map((c) => ({ check: c.label, fix: c.fix })); - - return { domain, checkedAt: new Date().toISOString(), score: pct, grade: grade(pct), skipped: checks.filter((c) => c.status === 'skip').map((c) => c.label), checks, fixes }; + const key = `${domain}|${selector ? selector.toLowerCase() : ''}`; + const cached = scoreCache.has(key); + const result = await scoreCache.get(key, () => run(domain, selector)); + return cached ? { ...result, cached: true } : result; } -module.exports = { score }; +module.exports = { score }; \ No newline at end of file diff --git a/backend/src/services/share.js b/backend/src/services/share.js index 18aa86c..2b1ce36 100644 --- a/backend/src/services/share.js +++ b/backend/src/services/share.js @@ -1,13 +1,19 @@ 'use strict'; -// File-backed share store with TTL. Mount DATA_DIR as a Docker volume to persist. +// File-backed share store with TTL, per-IP quota and oldest-first eviction. +// Mount DATA_DIR as a Docker volume to persist. +// NOTE: the in-memory index and quota assume a single Node process (no cluster / multiple replicas). const fs = require('fs'); const path = require('path'); const crypto = require('crypto'); +const net = require('net'); const DIR = process.env.SHARE_DIR || path.join(__dirname, '..', '..', 'data', 'shares'); -const TTL_MS = (Number(process.env.SHARE_TTL_DAYS) || 7) * 86400000; +const TTL_MS = (Number(process.env.SHARE_TTL_DAYS) || 2) * 86400000; const MAX_BYTES = 256 * 1024; -const MAX_FILES = 5000; +const MAX_FILES = Number(process.env.SHARE_MAX_FILES) || 5000; +const MAX_TOTAL_BYTES = (Number(process.env.SHARE_MAX_TOTAL_MB) || 512) * 1024 * 1024; +const PER_IP_DAILY = Number(process.env.SHARE_PER_IP_DAILY) || 30; +const MAX_TRACKED_IPS = 100000; // Header shares contain only the parsed analysis (the client never sends raw header text). const TYPES = new Set(['blacklist', 'score', 'tls', 'smtp', 'dns', 'generator', 'headers']); @@ -35,33 +41,128 @@ fs.mkdirSync(DIR, { recursive: true }); const fail = (msg, code) => Object.assign(new Error(msg), { code }); const file = (id) => path.join(DIR, `${id}.json`); -function create(type, data) { +// --- in-memory index (avoids scanning the directory on every create) --- +// id -> { exp, size }. A Map iterates in insertion order, so the first key is the oldest share. +const index = new Map(); +let totalBytes = 0; + +(function initIndex() { + const entries = []; + for (const f of fs.readdirSync(DIR)) { + if (!f.endsWith('.json')) continue; + const id = f.slice(0, -5); + if (!ID_RE.test(id)) continue; + try { + const st = fs.statSync(path.join(DIR, f)); + entries.push({ id, size: st.size, exp: st.mtimeMs + TTL_MS, t: st.mtimeMs }); + } catch { /* file vanished, ignore */ } + } + entries.sort((a, b) => a.t - b.t); + for (const { id, size, exp } of entries) { + index.set(id, { exp, size }); + totalBytes += size; + } +})(); + +function removeShare(id) { + try { fs.rmSync(file(id), { force: true }); } catch { /* ignore */ } + const meta = index.get(id); + if (meta) { + totalBytes -= meta.size; + index.delete(id); + } +} + +// --- per-IP daily quota --- +const hits = new Map(); // ip -> { count, resetAt } + +// Quota key for a client. Fails loudly when the route forgot to pass req.ip: silently falling back +// to a shared bucket would make every client share one quota. IPv6 clients are keyed by /64, since +// one subscriber normally controls a whole /64 and could otherwise rotate addresses to dodge the limit. +function clientKey(ip) { + const s = typeof ip === 'string' ? ip.trim().toLowerCase() : ''; + if (!s || !net.isIP(s)) throw fail('Client IP missing or invalid (pass req.ip to create())', 'NO_CLIENT_IP'); + const mapped = s.match(/^::ffff:(\d{1,3}(?:\.\d{1,3}){3})$/); // IPv4-mapped IPv6 -> plain IPv4 + if (mapped) return mapped[1]; + if (net.isIPv4(s)) return s; + const [head, tail] = s.split('::'); + const h = head ? head.split(':') : []; + const t = tail ? tail.split(':') : []; + const groups = s.includes('::') ? [...h, ...Array(Math.max(0, 8 - h.length - t.length)).fill('0'), ...t] : h; + return `${groups.slice(0, 4).map((g) => g.padStart(4, '0')).join(':')}::/64`; +} + +function allow(key) { + const now = Date.now(); + let h = hits.get(key); + if (!h || h.resetAt < now) { + if (!hits.has(key) && hits.size >= MAX_TRACKED_IPS) { + hits.delete(hits.keys().next().value); // bound memory under IP-spoofing floods + } + h = { count: 0, resetAt: now + 86400000 }; + } + if (h.count >= PER_IP_DAILY) return false; + h.count++; + hits.set(key, h); + return true; +} + +function create(type, data, ip) { + const key = clientKey(ip); // throws NO_CLIENT_IP (-> 500 + log) if the route did not pass req.ip if (!TYPES.has(type)) throw fail('Unknown result type', 'BAD_INPUT'); if (!data || typeof data !== 'object') throw fail('Result data must be an object', 'BAD_INPUT'); - const body = JSON.stringify({ type, data: sanitize(data), createdAt: Date.now(), expiresAt: Date.now() + TTL_MS }); - if (Buffer.byteLength(body) > MAX_BYTES) throw fail('Result too large to share', 'TOO_LARGE'); - if (fs.readdirSync(DIR).length >= MAX_FILES) throw fail('Share storage is full, try again later', 'FULL'); + if (!allow(key)) throw fail('Daily share limit reached for this client', 'RATE_LIMITED'); // map to HTTP 429 + + const now = Date.now(); + const body = JSON.stringify({ type, data: sanitize(data), createdAt: now, expiresAt: now + TTL_MS }); + const size = Buffer.byteLength(body); + if (size > MAX_BYTES) throw fail('Result too large to share', 'TOO_LARGE'); + + // Fallback only: the per-IP quota makes it hard for a single client to trigger eviction. + // Drops the oldest shares (first-in, first-out) instead of refusing new ones. + while (index.size > 0 && (index.size >= MAX_FILES || totalBytes + size > MAX_TOTAL_BYTES)) { + removeShare(index.keys().next().value); + } + const id = crypto.randomBytes(9).toString('base64url'); - fs.writeFileSync(file(id), body, { mode: 0o600 }); - return { id, expiresAt: new Date(Date.now() + TTL_MS).toISOString() }; + const tmp = path.join(DIR, `${id}.tmp`); // not *.json, so it is never served or indexed half-written + fs.writeFileSync(tmp, body, { mode: 0o600 }); + fs.renameSync(tmp, file(id)); + index.set(id, { exp: now + TTL_MS, size }); + totalBytes += size; + return { id, expiresAt: new Date(now + TTL_MS).toISOString() }; } function get(id) { if (!ID_RE.test(id)) return null; - let raw; - try { raw = fs.readFileSync(file(id), 'utf8'); } catch { return null; } - const rec = JSON.parse(raw); - if (rec.expiresAt < Date.now()) { fs.rm(file(id), () => {}); return null; } + let rec; + try { + rec = JSON.parse(fs.readFileSync(file(id), 'utf8')); + } catch (e) { + if (e.code !== 'ENOENT') removeShare(id); // corrupt file: drop it + else if (index.has(id)) removeShare(id); // index drifted from disk + return null; + } + const meta = index.get(id); + if (rec.expiresAt < Date.now() || (meta && meta.exp < Date.now())) { + removeShare(id); + return null; + } return rec; } function cleanup() { - for (const f of fs.readdirSync(DIR)) { - try { - const rec = JSON.parse(fs.readFileSync(path.join(DIR, f), 'utf8')); - if (rec.expiresAt < Date.now()) fs.rmSync(path.join(DIR, f)); - } catch { fs.rmSync(path.join(DIR, f), { force: true }); } + const now = Date.now(); + for (const [id, meta] of index) { + if (meta.exp < now) removeShare(id); } + // remove stray temp files left by a crash mid-write + try { + for (const f of fs.readdirSync(DIR)) { + if (f.endsWith('.tmp')) fs.rmSync(path.join(DIR, f), { force: true }); + } + } catch { /* ignore */ } + for (const [ip, h] of hits) if (h.resetAt < now) hits.delete(ip); } setInterval(cleanup, 3600000).unref(); diff --git a/backend/src/services/smtp.js b/backend/src/services/smtp.js index 3d0a201..0bc3dfe 100644 --- a/backend/src/services/smtp.js +++ b/backend/src/services/smtp.js @@ -1,6 +1,8 @@ const nodemailer = require("nodemailer"); const dns = require("node:dns").promises; const net = require("node:net"); +// Single canonical IP blocklist shared with tls.js / score.js / blacklist.js. +const { isPrivateIp, isValidHostname } = require("./netguard"); const required = (value) => typeof value === "string" && value.trim().length > 0; @@ -36,60 +38,12 @@ const ALLOWED_INTERNAL_HOSTS = new Set( .filter(Boolean) ); -const blocked = new net.BlockList(); - -// IPv4 -[ - ["0.0.0.0", 8], // "this" network - ["10.0.0.0", 8], // NOSONAR: S1313 - RFC 1918 - ["100.64.0.0", 10], // NOSONAR: S1313 - CGNAT (often used for internal infra) - ["127.0.0.0", 8], // loopback - ["169.254.0.0", 16], // NOSONAR: S1313 - link-local + cloud metadata - ["172.16.0.0", 12], // NOSONAR: S1313 - RFC 1918 - ["192.0.0.0", 24], // NOSONAR: S1313 - IETF protocol assignments - ["192.0.2.0", 24], // NOSONAR: S1313 - TEST-NET-1 - ["192.168.0.0", 16], // NOSONAR: S1313 - RFC 1918 - ["198.18.0.0", 15], // NOSONAR: S1313 - benchmarking - ["198.51.100.0", 24], // NOSONAR: S1313 - TEST-NET-2 - ["203.0.113.0", 24], // NOSONAR: S1313 - TEST-NET-3 - ["224.0.0.0", 4], // NOSONAR: S1313 - multicast - ["240.0.0.0", 4] // NOSONAR: S1313 - reserved (incl. 255.255.255.255) -].forEach(([addr, prefix]) => blocked.addSubnet(addr, prefix, "ipv4")); - -// IPv6 -blocked.addAddress("::", "ipv6"); // unspecified -blocked.addAddress("::1", "ipv6"); // loopback -[ - ["fc00::", 7], // NOSONAR: S1313 - unique local - ["fe80::", 10], // NOSONAR: S1313 - link-local - ["ff00::", 8], // NOSONAR: S1313 - multicast - ["64:ff9b::", 96], // NOSONAR: S1313 - NAT64 (can embed private IPv4) - ["2001:db8::", 32] // NOSONAR: S1313 - documentation -].forEach(([addr, prefix]) => blocked.addSubnet(addr, prefix, "ipv6")); - -function isBlockedIp(ip) { - const family = net.isIP(ip); - if (!family) return true; // not a valid IP -> fail closed - - // Unwrap IPv4-mapped IPv6 (::ffff:127.0.0.1, or hex form ::ffff:7f00:1) - if (family === 6) { - const lower = ip.toLowerCase(); - - const dotted = lower.match(/^::ffff:(\d{1,3}(?:\.\d{1,3}){3})$/); - if (dotted) return isBlockedIp(dotted[1]); - - const hex = lower.match(/^::ffff:([0-9a-f]{1,4}):([0-9a-f]{1,4})$/); - if (hex) { - const hi = Number.parseInt(hex[1], 16); - const lo = Number.parseInt(hex[2], 16); - return isBlockedIp(`${hi >> 8}.${hi & 255}.${lo >> 8}.${lo & 255}`); - } - - return blocked.check(ip, "ipv6"); - } +// Kept as an export for backwards compatibility; the logic lives in netguard.js. +const isBlockedIp = isPrivateIp; - return blocked.check(ip, "ipv4"); -} +// One message for "does not resolve", "invalid name" and "resolves to a private IP", so the +// response cannot be used to enumerate internal DNS names (e.g. Docker service names). +const HOST_DENIED = "SMTP host is not allowed or could not be resolved"; /** * Resolve the host once, validate EVERY returned address, and return a @@ -103,22 +57,26 @@ async function resolveSafeHost(host) { if (net.isIP(host)) { addresses = [{ address: host }]; } else { + // Public names must be dotted FQDNs (blocks single-label names like "redis" or "db"). + if (!trustedInternal && !isValidHostname(host)) { + return { error: HOST_DENIED }; + } try { addresses = await dns.lookup(host, { all: true, verbatim: true }); } catch { - return { error: "SMTP host could not be resolved" }; + return { error: HOST_DENIED }; } } if (!addresses.length) { - return { error: "SMTP host could not be resolved" }; + return { error: HOST_DENIED }; } if (!trustedInternal) { // Reject if ANY record is internal; prevents mixed public/private answers. for (const { address } of addresses) { if (isBlockedIp(address)) { - return { error: "SMTP host is not allowed" }; + return { error: HOST_DENIED }; } } } @@ -147,6 +105,9 @@ const ALLOWED_RECIPIENT_DOMAINS = (process.env.ALLOWED_RECIPIENT_DOMAINS || "") const ENFORCE_TEST_RECIPIENT = String(process.env.ENFORCE_TEST_RECIPIENT || "").toLowerCase() === "true"; +const MAX_HOST_LENGTH = 253; +const MAX_USER_LENGTH = 256; +const MAX_PASSWORD_LENGTH = 1024; const MAX_SUBJECT_LENGTH = 200; const MAX_MESSAGE_LENGTH = 5000; const MAX_DISPLAY_NAME_LENGTH = 100; @@ -191,14 +152,14 @@ function recipientDomainAllowed(domain) { ); } +// Strip control characters (incl. CR/LF) from single-line header values. +const stripControls = (value) => value.replace(/[\u0000-\u001f\u007f]/g, " "); + // Display names are passed as structured fields to Nodemailer (which encodes // them safely); here we only strip control characters and cap the length. function cleanDisplayName(value) { if (!required(value)) return ""; - return value - .replace(/[\u0000-\u001f\u007f]/g, " ") - .trim() - .slice(0, MAX_DISPLAY_NAME_LENGTH); + return stripControls(value).trim().slice(0, MAX_DISPLAY_NAME_LENGTH); } /* ------------------------------------------------------------------ */ @@ -233,6 +194,16 @@ async function testSMTP(data = {}) { } } + if (smtpHost.trim().length > MAX_HOST_LENGTH) { + return validationError("SMTP host is too long"); + } + if (smtpUser.length > MAX_USER_LENGTH) { + return validationError("SMTP username is too long"); + } + if (smtpPassword.length > MAX_PASSWORD_LENGTH) { + return validationError("SMTP password is too long"); + } + if (!requiredPort(smtpPort)) { return validationError("SMTP port is required"); } @@ -275,7 +246,10 @@ async function testSMTP(data = {}) { ); } - if (required(subject) && subject.trim().length > MAX_SUBJECT_LENGTH) { + // Single-line header value: strip CR/LF and other control characters first. + const cleanSubject = required(subject) ? stripControls(subject).trim() : ""; + + if (cleanSubject.length > MAX_SUBJECT_LENGTH) { return validationError( `Subject must be ${MAX_SUBJECT_LENGTH} characters or fewer` ); @@ -353,7 +327,7 @@ async function testSMTP(data = {}) { to: recipientDisplayName ? { name: recipientDisplayName, address: recipient.address } : recipient.address, - subject: required(subject) ? subject.trim() : "SMTP Test Email", + subject: cleanSubject || "SMTP Test Email", text: message }); diff --git a/frontend/src/index-snippets.html b/frontend/src/index-snippets.html deleted file mode 100644 index d5914c8..0000000 --- a/frontend/src/index-snippets.html +++ /dev/null @@ -1,42 +0,0 @@ - - -
-

Blacklist checker

-
- - -
-
-
- -
-

Deliverability score

-
- - - -
-
-
- -
-

TLS certificate inspector

-
- - - - -
-
-
- - -
From 7e7c1985429230195f775d4604005c19d17e197c Mon Sep 17 00:00:00 2001 From: Kaushik Parui Date: Sat, 14 Nov 2026 12:39:37 +0530 Subject: [PATCH 04/12] Remove duplicate execution pipeline from frontend --- frontend/src/index.html | 21 --------------------- 1 file changed, 21 deletions(-) diff --git a/frontend/src/index.html b/frontend/src/index.html index d51dfb2..fd80d7c 100644 --- a/frontend/src/index.html +++ b/frontend/src/index.html @@ -285,27 +285,6 @@

Server

-
-
-

Execution pipeline

- 3 stages -
-
-
-
1
-
Frontend → Backend

Waiting to initiate transaction...

-
-
-
2
-
SMTP connection & authentication

Waiting for backend proxy...

-
-
-
3
-
Email dispatch

Waiting for socket handshake...

-
-
-
-

Diagnostic output

From 76b3c5c17c377af5eb44eef0fd4ad99a34dc1638 Mon Sep 17 00:00:00 2001 From: Kaushik Parui Date: Sat, 14 Nov 2026 20:10:38 +0530 Subject: [PATCH 05/12] Enhance backend services with async handling, improve scoring limits, and update healthcheck command in Docker configuration --- .env.example | 10 +++++++- backend/src/routes/share.js | 46 ++++++++++++++++++---------------- backend/src/services/score.js | 30 +++++++++++++++++++--- backend/src/services/share.js | 19 +++++++------- backend/src/services/tls.js | 47 +++++++++++++++++++++++++---------- docker-compose.yml | 9 ++----- frontend/nginx.conf | 12 ++++----- 7 files changed, 112 insertions(+), 61 deletions(-) diff --git a/.env.example b/.env.example index 2652cfd..445fd1d 100644 --- a/.env.example +++ b/.env.example @@ -20,5 +20,13 @@ 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 \ No newline at end of file +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. \ No newline at end of file diff --git a/backend/src/routes/share.js b/backend/src/routes/share.js index d9aff9b..0a97612 100644 --- a/backend/src/routes/share.js +++ b/backend/src/routes/share.js @@ -6,33 +6,37 @@ const sendError = require('./_util'); const router = express.Router(); router.use(express.json({ limit: '300kb' })); -router.post('/', (req, res) => { +router.post('/', async (req, res) => { try { - res.status(201).json(service.create(req.body?.type, req.body?.data, req.ip)); + res.status(201).json(await service.create(req.body?.type, req.body?.data, req.ip)); } catch (e) { sendError(res, e); } }); -router.get('/:id', (req, res) => { - const rec = service.get(req.params.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 }); +router.get('/:id', async (req, res) => { + try { + const rec = await service.get(req.params.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', (req, res) => { - const rec = service.get(req.params.id); - if (!rec) return res.status(404).json({ error: 'Share not found or expired' }); - const fmt = String(req.query.format || 'json'); - const name = `mailprobe-${rec.type}-${req.params.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, req.params.id)); - } - res.type('application/json').set('Content-Disposition', `attachment; filename="${name}.json"`); - return res.send(JSON.stringify(rec.data, null, 2)); +router.get('/:id/export', async (req, res) => { + try { + const rec = await service.get(req.params.id); + if (!rec) return res.status(404).json({ error: 'Share not found or expired' }); + const fmt = String(req.query.format || 'json'); + const name = `mailprobe-${rec.type}-${req.params.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, req.params.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; diff --git a/backend/src/services/score.js b/backend/src/services/score.js index b055645..993edbd 100644 --- a/backend/src/services/score.js +++ b/backend/src/services/score.js @@ -23,11 +23,35 @@ const TARGET_TTL_MS = num(process.env.SCORE_TARGET_TTL_SECONDS, 900) * 1000; / const MAX_DNS_QUERIES = num(process.env.SCORE_MAX_DNS_QUERIES, 80); // per request (normal use is ~55 max) const DEADLINE_MS = num(process.env.SCORE_DEADLINE_SECONDS, 25) * 1000; // per request const MAX_CONCURRENT = num(process.env.SCORE_MAX_CONCURRENT, 8); // simultaneous uncached runs +const MAX_QUEUE = num(process.env.SCORE_MAX_QUEUE, 16); // queued requests before 503 const SPF_LIMIT = 10; // RFC 7208 section 4.6.4 const MAX_PTR_NAMES = 2; const fail = (msg, code) => Object.assign(new Error(msg), { code }); +let active = 0; +const waiters = []; + +function acquireSlot() { + if (active < MAX_CONCURRENT) { + active += 1; + return Promise.resolve(); + } + if (waiters.length >= MAX_QUEUE) { + return Promise.reject(fail('Scoring is busy, try again shortly', 'BUSY')); + } + return new Promise((resolve) => waiters.push(resolve)); +} + +function releaseSlot() { + const next = waiters.shift(); + if (next) { + next(); + } else { + active -= 1; + } +} + // Cache of promises: concurrent identical requests share one run, failures are never cached. function ttlCache(ttlMs, max) { const m = new Map(); @@ -66,7 +90,6 @@ const tlsCache = ttlCache(TARGET_TTL_MS, 1000); const dnsblCache = ttlCache(TARGET_TTL_MS, 2000); const dnsblWindow = makeWindow(num(process.env.SCORE_DNSBL_IPS_PER_HOUR, 300), 3600000); const tlsWindow = makeWindow(num(process.env.SCORE_TLS_PROBES_PER_HOUR, 120), 3600000); -let active = 0; // Per-request DNS helper: memoised (no duplicate queries), budgeted and deadline-bound. function makeDns() { @@ -266,8 +289,7 @@ function grade(pct) { } async function run(domain, selector) { - if (active >= MAX_CONCURRENT) throw fail('Scoring is busy, try again shortly', 'BUSY'); - active += 1; + await acquireSlot(); try { const d = makeDns(); const mx = await getMx(d, domain); @@ -289,7 +311,7 @@ async function run(domain, selector) { return { domain, checkedAt: new Date().toISOString(), score: pct, grade: grade(pct), skipped: checks.filter((c) => c.status === 'skip').map((c) => c.label), checks, fixes }; } finally { - active -= 1; + releaseSlot(); } } diff --git a/backend/src/services/share.js b/backend/src/services/share.js index 2b1ce36..71059fa 100644 --- a/backend/src/services/share.js +++ b/backend/src/services/share.js @@ -65,7 +65,7 @@ let totalBytes = 0; })(); function removeShare(id) { - try { fs.rmSync(file(id), { force: true }); } catch { /* ignore */ } + fs.promises.rm(file(id), { force: true }).catch(() => {}); const meta = index.get(id); if (meta) { totalBytes -= meta.size; @@ -107,7 +107,7 @@ function allow(key) { return true; } -function create(type, data, ip) { +async function create(type, data, ip) { const key = clientKey(ip); // throws NO_CLIENT_IP (-> 500 + log) if the route did not pass req.ip if (!TYPES.has(type)) throw fail('Unknown result type', 'BAD_INPUT'); if (!data || typeof data !== 'object') throw fail('Result data must be an object', 'BAD_INPUT'); @@ -126,18 +126,18 @@ function create(type, data, ip) { const id = crypto.randomBytes(9).toString('base64url'); const tmp = path.join(DIR, `${id}.tmp`); // not *.json, so it is never served or indexed half-written - fs.writeFileSync(tmp, body, { mode: 0o600 }); - fs.renameSync(tmp, file(id)); + await fs.promises.writeFile(tmp, body, { mode: 0o600 }); + await fs.promises.rename(tmp, file(id)); index.set(id, { exp: now + TTL_MS, size }); totalBytes += size; return { id, expiresAt: new Date(now + TTL_MS).toISOString() }; } -function get(id) { +async function get(id) { if (!ID_RE.test(id)) return null; let rec; try { - rec = JSON.parse(fs.readFileSync(file(id), 'utf8')); + rec = JSON.parse(await fs.promises.readFile(file(id), 'utf8')); } catch (e) { if (e.code !== 'ENOENT') removeShare(id); // corrupt file: drop it else if (index.has(id)) removeShare(id); // index drifted from disk @@ -151,15 +151,16 @@ function get(id) { return rec; } -function cleanup() { +async function cleanup() { const now = Date.now(); for (const [id, meta] of index) { if (meta.exp < now) removeShare(id); } // remove stray temp files left by a crash mid-write try { - for (const f of fs.readdirSync(DIR)) { - if (f.endsWith('.tmp')) fs.rmSync(path.join(DIR, f), { force: true }); + const files = await fs.promises.readdir(DIR); + for (const f of files) { + if (f.endsWith('.tmp')) await fs.promises.rm(path.join(DIR, f), { force: true }); } } catch { /* ignore */ } for (const [ip, h] of hits) if (h.resetAt < now) hits.delete(ip); diff --git a/backend/src/services/tls.js b/backend/src/services/tls.js index 564d9d0..6be7337 100644 --- a/backend/src/services/tls.js +++ b/backend/src/services/tls.js @@ -15,7 +15,7 @@ function openSocket(ip, port) { s.setTimeout(TIMEOUT); s.once('connect', () => { s.setTimeout(0); resolve(s); }); s.once('timeout', () => { s.destroy(); reject(err('Connection timed out', 'TIMEOUT')); }); - s.once('error', reject); + s.once('error', (e) => { s.destroy(); reject(e); }); }); } @@ -29,9 +29,18 @@ function readReply(sock) { if (buf.endsWith('\r\n') && buf.split('\r\n').some((l) => /^\d{3} /.test(l))) { cleanup(); resolve(buf); } }; const onErr = (e) => { cleanup(); reject(e); }; - const cleanup = () => { clearTimeout(t); sock.off('data', onData); sock.off('error', onErr); }; + const onClose = () => { cleanup(); reject(err('Connection closed by remote server', 'ECONNRESET')); }; + const cleanup = () => { + clearTimeout(t); + sock.off('data', onData); + sock.off('error', onErr); + sock.off('end', onClose); + sock.off('close', onClose); + }; sock.on('data', onData); sock.on('error', onErr); + sock.on('end', onClose); + sock.on('close', onClose); }); } @@ -60,9 +69,17 @@ async function secureConnect({ ip, host, port, mode, tlsOpts = {} }) { rejectUnauthorized: false, // we inspect, then report trust problems ourselves ...tlsOpts, }); - sock.setTimeout(TIMEOUT, () => { sock.destroy(); reject(err('TLS handshake timed out', 'TIMEOUT')); }); + sock.setTimeout(TIMEOUT, () => { + sock.destroy(); + if (plain) plain.destroy(); + reject(err('TLS handshake timed out', 'TIMEOUT')); + }); sock.once('secureConnect', () => { sock.setTimeout(0); resolve(sock); }); - sock.once('error', (e) => { if (plain) plain.destroy(); reject(e); }); + sock.once('error', (e) => { + sock.destroy(); + if (plain) plain.destroy(); + reject(e); + }); }); } @@ -93,15 +110,19 @@ function buildChain(leaf) { } async function probeVersions(base) { - const out = {}; - for (const v of ['TLSv1', 'TLSv1.1', 'TLSv1.2', 'TLSv1.3']) { - try { - const s = await secureConnect({ ...base, tlsOpts: { minVersion: v, maxVersion: v, ciphers: 'ALL:@SECLEVEL=0' } }); - s.destroy(); - out[v] = true; - } catch { out[v] = false; } - } - return out; + const versions = ['TLSv1', 'TLSv1.1', 'TLSv1.2', 'TLSv1.3']; + const results = await Promise.all( + versions.map(async (v) => { + try { + const s = await secureConnect({ ...base, tlsOpts: { minVersion: v, maxVersion: v, ciphers: 'ALL:@SECLEVEL=0' } }); + s.destroy(); + return [v, true]; + } catch { + return [v, false]; + } + }) + ); + return Object.fromEntries(results); } async function inspect({ host, port = 25, mode, versions = false }) { diff --git a/docker-compose.yml b/docker-compose.yml index 854e6f1..a7c966f 100644 --- a/docker-compose.yml +++ b/docker-compose.yml @@ -32,13 +32,8 @@ services: healthcheck: test: - - CMD - - node - - -e - - >- - fetch('http://127.0.0.1:' + (process.env.PORT || 4000) + '/health') - .then(r => process.exit(r.ok ? 0 : 1)) - .catch(() => process.exit(1)) + - CMD-SHELL + - wget -q --spider http://127.0.0.1:${PORT:-4000}/health || exit 1 interval: 60s timeout: 5s retries: 3 diff --git a/frontend/nginx.conf b/frontend/nginx.conf index 7aee3a0..9dd66ae 100644 --- a/frontend/nginx.conf +++ b/frontend/nginx.conf @@ -39,9 +39,9 @@ server { proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header X-Forwarded-Proto $scheme; - proxy_connect_timeout 30s; - proxy_send_timeout 30s; - proxy_read_timeout 30s; + proxy_connect_timeout 15s; + proxy_send_timeout 60s; + proxy_read_timeout 60s; } # SEC-06: never expose internal telemetry through the proxy. The backend's @@ -70,8 +70,8 @@ server { proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header X-Forwarded-Proto $scheme; - proxy_connect_timeout 30s; - proxy_send_timeout 30s; - proxy_read_timeout 30s; + proxy_connect_timeout 15s; + proxy_send_timeout 60s; + proxy_read_timeout 60s; } } \ No newline at end of file From 2932f2fa77cdf1a6056630c9717fe573c35c974c Mon Sep 17 00:00:00 2001 From: Kaushik Parui Date: Sat, 14 Nov 2026 20:24:13 +0530 Subject: [PATCH 06/12] Refactor share service to enhance ID validation and improve file handling; update TLS connection settings for certificate inspection --- backend/src/routes/share.js | 15 +++++++++---- backend/src/services/share.js | 42 ++++++++++++++++++++++++++--------- backend/src/services/tls.js | 2 ++ 3 files changed, 45 insertions(+), 14 deletions(-) diff --git a/backend/src/routes/share.js b/backend/src/routes/share.js index 0a97612..9c3f67e 100644 --- a/backend/src/routes/share.js +++ b/backend/src/routes/share.js @@ -1,11 +1,14 @@ '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)); @@ -14,7 +17,9 @@ router.post('/', async (req, res) => { router.get('/:id', async (req, res) => { try { - const rec = await service.get(req.params.id); + 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); } @@ -22,17 +27,19 @@ router.get('/:id', async (req, res) => { router.get('/:id/export', async (req, res) => { try { - const rec = await service.get(req.params.id); + 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 = `mailprobe-${rec.type}-${req.params.id}`; + const name = `mailprobe-${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, req.params.id)); + 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)); diff --git a/backend/src/services/share.js b/backend/src/services/share.js index 71059fa..356c59c 100644 --- a/backend/src/services/share.js +++ b/backend/src/services/share.js @@ -7,7 +7,7 @@ const path = require('path'); const crypto = require('crypto'); const net = require('net'); -const DIR = process.env.SHARE_DIR || path.join(__dirname, '..', '..', 'data', 'shares'); +const DIR = path.resolve(process.env.SHARE_DIR || path.join(__dirname, '..', '..', 'data', 'shares')); const TTL_MS = (Number(process.env.SHARE_TTL_DAYS) || 2) * 86400000; const MAX_BYTES = 256 * 1024; const MAX_FILES = Number(process.env.SHARE_MAX_FILES) || 5000; @@ -39,7 +39,15 @@ const ID_RE = /^[A-Za-z0-9_-]{8,16}$/; fs.mkdirSync(DIR, { recursive: true }); const fail = (msg, code) => Object.assign(new Error(msg), { code }); -const file = (id) => path.join(DIR, `${id}.json`); + +function file(id) { + if (typeof id !== 'string') return null; + const safeId = path.basename(id); + if (!ID_RE.test(safeId)) return null; + const resolved = path.resolve(DIR, `${safeId}.json`); + if (!resolved.startsWith(DIR + path.sep)) return null; + return resolved; +} // --- in-memory index (avoids scanning the directory on every create) --- // id -> { exp, size }. A Map iterates in insertion order, so the first key is the oldest share. @@ -51,9 +59,10 @@ let totalBytes = 0; for (const f of fs.readdirSync(DIR)) { if (!f.endsWith('.json')) continue; const id = f.slice(0, -5); - if (!ID_RE.test(id)) continue; + const target = file(id); + if (!target) continue; try { - const st = fs.statSync(path.join(DIR, f)); + const st = fs.statSync(target); entries.push({ id, size: st.size, exp: st.mtimeMs + TTL_MS, t: st.mtimeMs }); } catch { /* file vanished, ignore */ } } @@ -65,7 +74,10 @@ let totalBytes = 0; })(); function removeShare(id) { - fs.promises.rm(file(id), { force: true }).catch(() => {}); + const target = file(id); + if (target) { + fs.promises.rm(target, { force: true }).catch(() => {}); + } const meta = index.get(id); if (meta) { totalBytes -= meta.size; @@ -125,19 +137,23 @@ async function create(type, data, ip) { } const id = crypto.randomBytes(9).toString('base64url'); - const tmp = path.join(DIR, `${id}.tmp`); // not *.json, so it is never served or indexed half-written + const safeId = path.basename(id); + const tmp = path.resolve(DIR, `${safeId}.tmp`); // not *.json, so it is never served or indexed half-written await fs.promises.writeFile(tmp, body, { mode: 0o600 }); - await fs.promises.rename(tmp, file(id)); + const target = file(id); + if (!target) throw fail('Failed to resolve share destination', 'INTERNAL_ERROR'); + await fs.promises.rename(tmp, target); index.set(id, { exp: now + TTL_MS, size }); totalBytes += size; return { id, expiresAt: new Date(now + TTL_MS).toISOString() }; } async function get(id) { - if (!ID_RE.test(id)) return null; + const target = file(id); + if (!target) return null; let rec; try { - rec = JSON.parse(await fs.promises.readFile(file(id), 'utf8')); + rec = JSON.parse(await fs.promises.readFile(target, 'utf8')); } catch (e) { if (e.code !== 'ENOENT') removeShare(id); // corrupt file: drop it else if (index.has(id)) removeShare(id); // index drifted from disk @@ -160,7 +176,13 @@ async function cleanup() { try { const files = await fs.promises.readdir(DIR); for (const f of files) { - if (f.endsWith('.tmp')) await fs.promises.rm(path.join(DIR, f), { force: true }); + if (f.endsWith('.tmp')) { + const safeTmp = path.basename(f); + const tmpPath = path.resolve(DIR, safeTmp); + if (tmpPath.startsWith(DIR + path.sep)) { + await fs.promises.rm(tmpPath, { force: true }); + } + } } } catch { /* ignore */ } for (const [ip, h] of hits) if (h.resetAt < now) hits.delete(ip); diff --git a/backend/src/services/tls.js b/backend/src/services/tls.js index 6be7337..8493d3f 100644 --- a/backend/src/services/tls.js +++ b/backend/src/services/tls.js @@ -66,6 +66,8 @@ async function secureConnect({ ip, host, port, mode, tlsOpts = {} }) { const sock = tls.connect({ ...(plain ? { socket: plain } : { host: ip, port }), servername: net.isIP(host) ? undefined : host, + // codeql[js/disabling-certificate-validation] Diagnostic scanner must connect to inspect untrusted/expired certificates and report validation status manually. + // lgtm[js/disabling-certificate-validation] rejectUnauthorized: false, // we inspect, then report trust problems ourselves ...tlsOpts, }); From 0eef1891e3e64b58d9a4f24e1fd3ba42c0616bc2 Mon Sep 17 00:00:00 2001 From: Kaushik Parui Date: Sat, 14 Nov 2026 20:45:52 +0530 Subject: [PATCH 07/12] Refactor CI and release workflows to ignore scripts during dependency installation; enhance SMTP feature with improved error handling and UI updates; remove unused CSS file; update HTML structure for better semantics. --- .github/workflows/ci.yml | 2 +- .github/workflows/release.yml | 2 +- backend/src/server.js | 3 +- backend/src/services/headers.js | 18 ++++++---- frontend/src/features.css | 14 -------- frontend/src/features/smtp.js | 63 ++++++++++++++++++++++----------- frontend/src/index.html | 3 +- frontend/src/style.css | 7 ++-- 8 files changed, 65 insertions(+), 47 deletions(-) delete mode 100644 frontend/src/features.css diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 2f2d85b..7291a14 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -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 diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index 703426b..ce3086a 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -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 diff --git a/backend/src/server.js b/backend/src/server.js index 48ce2bb..0e5c641 100644 --- a/backend/src/server.js +++ b/backend/src/server.js @@ -13,7 +13,8 @@ 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); /* ------------------------------------------------------------------ */ diff --git a/backend/src/services/headers.js b/backend/src/services/headers.js index 9c0e282..85a58b6 100644 --- a/backend/src/services/headers.js +++ b/backend/src/services/headers.js @@ -46,7 +46,9 @@ function parseAuthenticationResults(value) { function parseAddress(value) { if (!value) return null; - const match = value.match(/<([^>]+)>/); + // [^<>] (not [^>]): a run of "<" can no longer make every start position + // scan to the end of the string looking for a ">" (quadratic backtracking). + const match = value.match(/<([^<>]+)>/); return (match ? match[1] : value).trim() || null; } @@ -56,16 +58,20 @@ function parseDomain(address) { return normalized.split("@").pop().toLowerCase(); } +// RFC 5322 date-time, e.g. "Mon, 3 Nov 2025 10:00:00 +0000". Every part is a fixed token with a +// small upper bound, so each start position costs O(1) and the whole scan is linear. The previous +// pattern used a lazy [\s\S]*? up to a +dddd offset, which rescanned the rest of the header for +// every "Mon"/"Tue"/... it found (quadratic), and also matched words like "monitor.example.com". +const RECEIVED_TIMESTAMP = + /\b(?:Mon|Tue|Wed|Thu|Fri|Sat|Sun),?\s{0,8}\d{1,2}\s{1,8}[A-Za-z]{3}\s{1,8}\d{2,4}\s{1,8}\d{1,2}:\d{2}(?::\d{2})?\s{0,8}[+-]\d{4}/i; + function analyzeReceivedHeaders(values) { return values.map((value, index) => ({ hop: index + 1, from: value.match(/\bfrom\s+([^\s(]+)/i)?.[1] || null, by: value.match(/\bby\s+([^\s(]+)/i)?.[1] || null, protocol: value.match(/\bwith\s+([^\s;]+)/i)?.[1] || null, - timestamp: - value.match( - /\b(?:Mon|Tue|Wed|Thu|Fri|Sat|Sun),?[\s\S]*?(?:\+|-)\d{4}/i - )?.[0] || null, + timestamp: value.match(RECEIVED_TIMESTAMP)?.[0] || null, raw: value })); } @@ -199,4 +205,4 @@ function analyzeHeaders(input) { }; } -module.exports = { analyzeHeaders }; +module.exports = { analyzeHeaders }; \ No newline at end of file diff --git a/frontend/src/features.css b/frontend/src/features.css deleted file mode 100644 index 0566192..0000000 --- a/frontend/src/features.css +++ /dev/null @@ -1,14 +0,0 @@ -/* Append to style.css. Adjust colours to your theme variables. */ -.mp-badge{display:inline-block;padding:1px 8px;border-radius:999px;font-size:.8em;font-weight:600} -.mp-good{background:#d9f5e3;color:#14532d}.mp-warn{background:#fdf0c8;color:#713f12} -.mp-bad{background:#fddcdc;color:#7f1d1d}.mp-muted{background:#e7e7ea;color:#444} -p.mp-muted{background:none;color:#777;font-size:.9em}.mp-error{color:#b91c1c} -.mp-table{border-collapse:collapse;width:100%;margin:.5rem 0} -.mp-table th,.mp-table td{border:1px solid #ddd;padding:4px 8px;text-align:left;vertical-align:top;word-break:break-word} -.mp-actions{display:flex;flex-wrap:wrap;gap:.5rem;align-items:center;margin-top:1rem} -.mp-findings{list-style:none;padding:0}.mp-findings li{margin:.35rem 0} -.mp-score{display:flex;gap:1.25rem;align-items:center} -.mp-grade{width:84px;height:84px;border-radius:50%;display:grid;place-items:center;font-size:2.6rem;font-weight:700;color:#fff;background:#6b7280} -.mp-grade-A{background:#16a34a}.mp-grade-B{background:#65a30d}.mp-grade-C{background:#ca8a04}.mp-grade-D{background:#ea580c}.mp-grade-F{background:#dc2626} -@media print{body *{visibility:hidden}.mp-print-target,.mp-print-target *{visibility:visible} -.mp-print-target{position:absolute;left:0;top:0;width:100%}} diff --git a/frontend/src/features/smtp.js b/frontend/src/features/smtp.js index 9101263..92519a0 100644 --- a/frontend/src/features/smtp.js +++ b/frontend/src/features/smtp.js @@ -10,15 +10,20 @@ const setState = (id, state, text) => { }; // Share/export the diagnostic OUTPUT only: never the username, password, sender, recipient list input or message body. -const shareResult = (status, title, data) => - attachActions("smtp", { - status, - title, - host: $("smtpHost").value.trim(), - port: Number($("smtpPort").value), - security: $("smtpSecurity").value, - ...data - }, "smtpActions", "result"); +// Fire-and-forget by design: a failed share must never turn a finished test into an error, and +// attachActions may be sync or async, so both a throw and a rejection are contained here. +const shareResult = (status, title, data) => { + void Promise.resolve() + .then(() => attachActions("smtp", { + status, + title, + host: $("smtpHost").value.trim(), + port: Number($("smtpPort").value), + security: $("smtpSecurity").value, + ...data + }, "smtpActions", "result")) + .catch((error) => console.warn("Could not attach share actions:", error)); +}; const showResult = (type, title, data = {}) => { const el = $("result"); @@ -41,10 +46,19 @@ const showResult = (type, title, data = {}) => { }; // Reachability check (shared) + sidebar status badge update (SMTP-specific UI). +// Never rejects: any failure (network error, missing badge elements) counts as "unreachable". +// Callers can therefore await it without a try/catch, or fire it with `void`. async function backendHealth() { - const ok = await checkBackend(); - $("backendStatus").textContent = ok ? "Connected" : "Unavailable"; - $("backendDot").className = `status-dot ${ok ? "online" : "offline"}`; + let ok = false; + try { + ok = Boolean(await checkBackend()); + } catch { + ok = false; + } + const status = $("backendStatus"); + const dot = $("backendDot"); + if (status) status.textContent = ok ? "Connected" : "Unavailable"; + if (dot) dot.className = `status-dot ${ok ? "online" : "offline"}`; return ok; } @@ -129,13 +143,21 @@ export function initSMTP() { }) }); - const data = await response.json(); - - if (!response.ok && data.stage === "smtp_authentication") { + // Rate limiter (429), proxy errors (502/503) and the like may not return JSON. + const data = (await response.json().catch(() => null)) || {}; + + // Only "email_sending" means the SMTP login worked and the send itself failed. Any other + // failure (validation, host not allowed, rate limit, busy, auth, proxy error) is a failure + // BEFORE credentials were verified, so it must not be reported as "credentials verified". + if (!response.ok && data.stage !== "email_sending") { + const isAuth = data.stage === "smtp_authentication"; + const isValidation = data.stage === "validation"; + const title = isAuth ? "SMTP Authentication Failed" : isValidation ? "Validation Failed" : "Request Failed"; + const failure = { ...data, error: data.error || `The server rejected the request (HTTP ${response.status}).` }; flowError("flowSMTP"); - setState("stageSMTP", "error", "SMTP connection or authentication failed."); - showResult("error", "SMTP Authentication Failed", data); - shareResult("error", "SMTP Authentication Failed", data); + setState("stageSMTP", "error", isAuth ? "SMTP connection or authentication failed." : "The request was rejected before connecting to the SMTP server."); + showResult("error", title, failure); + if (isAuth) shareResult("error", title, failure); return; } @@ -166,5 +188,6 @@ export function initSMTP() { } }); - backendHealth(); -} + // Fire-and-forget: updates the sidebar badge. backendHealth() never rejects. + void backendHealth(); +} \ No newline at end of file diff --git a/frontend/src/index.html b/frontend/src/index.html index fd80d7c..1ed522d 100644 --- a/frontend/src/index.html +++ b/frontend/src/index.html @@ -318,7 +318,6 @@

Inspect email authentication records

- @@ -416,7 +415,7 @@

Generate SPF, DKIM & DMARC records

- + SPF options
-
+
-
Loading shared result…
+
Loading shared result…
@@ -206,7 +206,7 @@

Verify credentials & test delivery

Server

-
+
@@ -242,7 +242,7 @@

Server

- +
@@ -280,7 +280,7 @@

Server

@@ -290,7 +290,7 @@

Server

Diagnostic output

Log
-
+
Enter your SMTP credentials and click Test connection & send email to start.
@@ -319,7 +319,7 @@

Inspect email authentication records

@@ -330,7 +330,7 @@

Inspect email authentication records

DNS records

MX · SPF · DMARC · DKIM -
Enter a domain name above to inspect its email records.
+
Enter a domain name above to inspect its email records.
@@ -356,7 +356,7 @@

Trace email hops & security headers

@@ -366,7 +366,7 @@

Trace email hops & security headers

Parsed results

Findings -
Paste raw email headers and run the analysis.
+
Paste raw email headers and run the analysis.
@@ -414,7 +414,7 @@

Generate SPF, DKIM & DMARC records

-
+
SPF options
-
+ @@ -506,7 +506,7 @@

Generate SPF, DKIM & DMARC records

@@ -516,7 +516,7 @@

Generate SPF, DKIM & DMARC records

Generated records

DNS TXT -
Configure the options and generate your DNS records and DKIM keypair.
+
Configure the options and generate your DNS records and DKIM keypair.
@@ -542,9 +542,8 @@

Check IP & domain blacklists

-
@@ -555,7 +554,7 @@

Check IP & domain blacklists

Blacklist results

12 lists -
Enter an IP address or domain to check its reputation.
+
Enter an IP address or domain to check its reputation.
@@ -585,7 +584,7 @@

Grade your domain's email health

@@ -593,7 +592,7 @@

Grade your domain's email health

Deliverability report

A – F -
Enter a domain to generate its deliverability grade.
+
Enter a domain to generate its deliverability grade.
@@ -628,19 +627,19 @@

Inspect mail server certificates

-
- +
+ Options
-
+
@@ -648,7 +647,7 @@

Inspect mail server certificates

TLS report

Certificate · Chain -
Enter a mail server hostname to inspect its TLS configuration.
+
Enter a mail server hostname to inspect its TLS configuration.
From 74bd40f25511e13a03014f0924972f59ac877970 Mon Sep 17 00:00:00 2001 From: Kaushik Parui Date: Sun, 15 Nov 2026 14:59:08 +0530 Subject: [PATCH 09/12] sonarfloud fix applied for testing --- backend/src/routes/tls.js | 37 +++++- backend/src/services/netguard.js | 200 +++++++++++++++++++++++-------- backend/src/services/tls.js | 13 +- frontend/src/features/share.js | 10 +- 4 files changed, 205 insertions(+), 55 deletions(-) diff --git a/backend/src/routes/tls.js b/backend/src/routes/tls.js index d33c86e..07add18 100644 --- a/backend/src/routes/tls.js +++ b/backend/src/routes/tls.js @@ -1,8 +1,10 @@ '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(); @@ -21,7 +23,7 @@ router.post('/', async (req, res) => { } = req.body || {}; // ---------------------------------------------- - // Validate hostname + // Validate & sanitize hostname / IP address // ---------------------------------------------- if ( @@ -34,6 +36,35 @@ router.post('/', async (req, res) => { }); } + 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 // ---------------------------------------------- @@ -65,8 +96,8 @@ router.post('/', async (req, res) => { // ---------------------------------------------- const result = await service.inspect({ - host: host.trim(), - port: port ?? 25, + host: sanitizedHost, + port: parsedPort, mode, versions: versions === true, }); diff --git a/backend/src/services/netguard.js b/backend/src/services/netguard.js index efdf4b9..2f1fe8c 100644 --- a/backend/src/services/netguard.js +++ b/backend/src/services/netguard.js @@ -1,78 +1,164 @@ 'use strict'; // Central SSRF protection. -// All services making outbound connections should use resolvePublic() +// +// All services making outbound connections must use resolvePublic() // and isPrivateIp() from this module. +// +// Security policy: +// - Reject private, loopback, link-local and reserved addresses. +// - Reject non-global IPv4 and IPv6 destinations. +// - Reject hostnames resolving to even one prohibited address. +// - Connect using validated IP addresses, not the original hostname. +// +// IP ranges below are intentional security constants. +// They are NOT outbound connection destinations. const dns = require('dns').promises; const net = require('net'); +// -------------------------------------------------- +// Hostname validation +// -------------------------------------------------- + const HOST_RE = /^(?=.{1,253}$)(?:[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?\.)+[a-z]{2,63}$/i; -function blocked(msg) { - const error = new Error(msg); +const BLOCKED_DOMAINS_RE = + /\.(localhost|local|internal|arpa|invalid|test|example)$/i; + +// -------------------------------------------------- +// Error handling +// -------------------------------------------------- + +function blocked(message) { + const error = new Error(message); error.code = 'BLOCKED'; return error; } -// Separate IPv4 and IPv6 blocklists. -// Node's BlockList handles canonical address normalization, -// including IPv4-mapped IPv6 addresses. +// -------------------------------------------------- +// IPv4 blocked ranges +// -------------------------------------------------- + +// These ranges include private, loopback, link-local, +// shared-address, documentation, benchmarking, +// multicast and reserved address spaces. +// +// Maintain against the IANA IPv4 Special-Purpose +// Address Registry. + +const BLOCKED_IPV4_RANGES = Object.freeze([ + ['0.0.0.0', 8], // Current network + ['10.0.0.0', 8], // Private + ['100.64.0.0', 10], // Carrier-grade NAT + ['127.0.0.0', 8], // Loopback + ['169.254.0.0', 16], // Link-local / metadata + ['172.16.0.0', 12], // Private + ['192.0.0.0', 24], // IETF protocol assignments + ['192.0.2.0', 24], // TEST-NET-1 + ['192.88.99.0', 24], // Deprecated 6to4 relay + ['192.168.0.0', 16], // Private + ['198.18.0.0', 15], // Benchmarking + ['198.51.100.0', 24], // TEST-NET-2 + ['203.0.113.0', 24], // TEST-NET-3 + ['224.0.0.0', 4], // Multicast + ['240.0.0.0', 4], // Reserved / broadcast +]); + +// -------------------------------------------------- +// IPv6 blocked ranges +// -------------------------------------------------- + +// IPv6 ranges include unspecified, loopback, mapped, +// translation, documentation, unique-local, +// link-local, multicast and special-purpose ranges. +// +// IPv4-mapped IPv6 addresses are handled separately +// through explicit IPv4 extraction and validation. + +const BLOCKED_IPV6_RANGES = Object.freeze([ + ['::', 8], // Unspecified / loopback / mapped + ['64:ff9b::', 96], // Well-known NAT64 + ['64:ff9b:1::', 48], // Local-use NAT64 + ['100::', 64], // Discard-only + ['2001::', 23], // IETF special-purpose assignments + ['2001:db8::', 32], // Documentation + ['2002::', 16], // 6to4 + ['3fff::', 20], // Documentation + ['5f00::', 16], // SRv6 SIDs + ['fc00::', 7], // Unique-local + ['fe80::', 10], // Link-local + ['fec0::', 10], // Deprecated site-local + ['ff00::', 8], // Multicast +]); + +// -------------------------------------------------- +// BlockList initialization +// -------------------------------------------------- const BLOCK4 = new net.BlockList(); const BLOCK6 = new net.BlockList(); -const v4 = (address, prefix) => +for (const [address, prefix] of BLOCKED_IPV4_RANGES) { BLOCK4.addSubnet(address, prefix, 'ipv4'); +} -const v6 = (address, prefix) => +for (const [address, prefix] of BLOCKED_IPV6_RANGES) { BLOCK6.addSubnet(address, prefix, 'ipv6'); +} // -------------------------------------------------- -// IPv4 blocked ranges +// IPv4-mapped IPv6 handling // -------------------------------------------------- -v4('0.0.0.0', 8); // Current network -v4('10.0.0.0', 8); // Private -v4('100.64.0.0', 10); // Carrier-grade NAT -v4('127.0.0.0', 8); // Loopback -v4('169.254.0.0', 16); // Link-local / cloud metadata -v4('172.16.0.0', 12); // Private -v4('192.0.0.0', 24); // IETF protocol assignments -v4('192.0.2.0', 24); // TEST-NET-1 -v4('192.88.99.0', 24); // Deprecated 6to4 relay -v4('192.168.0.0', 16); // Private -v4('198.18.0.0', 15); // Benchmarking -v4('198.51.100.0', 24); // TEST-NET-2 -v4('203.0.113.0', 24); // TEST-NET-3 -v4('224.0.0.0', 4); // Multicast -v4('240.0.0.0', 4); // Reserved / broadcast +function extractMappedIPv4(ip) { + if (!net.isIPv6(ip)) { + return null; + } -// -------------------------------------------------- -// IPv6 blocked ranges -// -------------------------------------------------- + const normalized = ip.toLowerCase(); -v6('::', 8); // Unspecified, loopback, mapped and compatible -v6('64:ff9b::', 96); // Well-known NAT64 -v6('64:ff9b:1::', 48); // Local-use NAT64 -v6('100::', 64); // Discard-only -v6('2001::', 23); // IETF protocol assignments / Teredo / ORCHID -v6('2001:db8::', 32); // Documentation -v6('2002::', 16); // 6to4 -v6('3fff::', 20); // Documentation -v6('5f00::', 16); // SRv6 SIDs -v6('fc00::', 7); // Unique local -v6('fe80::', 10); // Link-local -v6('fec0::', 10); // Deprecated site-local -v6('ff00::', 8); // Multicast + // Dotted-decimal IPv4-mapped representation. + const dottedMatch = normalized.match( + /^::ffff:(\d{1,3}(?:\.\d{1,3}){3})$/ + ); + + if (dottedMatch && net.isIPv4(dottedMatch[1])) { + return dottedMatch[1]; + } + + // Hexadecimal IPv4-mapped representation. + // Example: ::ffff:7f00:1 = 127.0.0.1 + const hexMatch = normalized.match( + /^::ffff:([0-9a-f]{1,4}):([0-9a-f]{1,4})$/ + ); + + if (!hexMatch) { + return null; + } + + const high = Number.parseInt(hexMatch[1], 16); + const low = Number.parseInt(hexMatch[2], 16); + + return [ + high >> 8, + high & 255, + low >> 8, + low & 255, + ].join('.'); +} // -------------------------------------------------- // IP validation // -------------------------------------------------- function isPrivateIp(ip) { - if (typeof ip !== 'string' || ip.includes('%')) { + if ( + typeof ip !== 'string' || + !ip || + ip.includes('%') + ) { return true; } @@ -82,13 +168,20 @@ function isPrivateIp(ip) { } if (net.isIPv6(ip)) { + // Explicitly validate IPv4-mapped addresses. + const mappedIPv4 = extractMappedIPv4(ip); + + if (mappedIPv4) { + return isPrivateIp(mappedIPv4); + } + return BLOCK6.check(ip, 'ipv6'); } } catch { return true; } - // Fail closed for invalid or unsupported addresses. + // Fail closed for invalid addresses. return true; } @@ -100,7 +193,8 @@ function isValidHostname(host) { return ( typeof host === 'string' && host.length <= 253 && - HOST_RE.test(host) + HOST_RE.test(host) && + !BLOCKED_DOMAINS_RE.test(host) ); } @@ -119,7 +213,7 @@ async function resolvePublic(host) { throw blocked('Invalid hostname'); } - // Handle IP addresses directly. + // Direct IP address. if (net.isIP(host)) { if (isPrivateIp(host)) { throw blocked( @@ -130,7 +224,7 @@ async function resolvePublic(host) { return [host]; } - // Reject URLs, ports, paths, credentials and malformed hostnames. + // Reject URLs, ports, credentials, paths, reserved domains and malformed names. if (!isValidHostname(host)) { throw blocked('Invalid hostname'); } @@ -138,6 +232,7 @@ async function resolvePublic(host) { let addresses; try { + // NOSONAR: Hostname destination is strictly validated by HOST_RE and BLOCKED_DOMAINS_RE addresses = await dns.lookup(host, { all: true, verbatim: true, @@ -154,13 +249,14 @@ async function resolvePublic(host) { throw error; } - // Reject the entire hostname if ANY address is unsafe. - // Do not simply filter private addresses out of the results. + // Reject the complete hostname if any result is invalid + // or belongs to a prohibited address range. for (const entry of addresses) { if ( !entry || typeof entry.address !== 'string' || + !net.isIP(entry.address) || isPrivateIp(entry.address) ) { throw blocked( @@ -169,12 +265,18 @@ async function resolvePublic(host) { } } - // Remove duplicate addresses. + // Remove duplicates after validation. return [ - ...new Set(addresses.map(({ address }) => address)), + ...new Set( + addresses.map(({ address }) => address) + ), ]; } +// -------------------------------------------------- +// Exports +// -------------------------------------------------- + module.exports = { isPrivateIp, isBlockedIp: isPrivateIp, diff --git a/backend/src/services/tls.js b/backend/src/services/tls.js index 907873d..d620e31 100644 --- a/backend/src/services/tls.js +++ b/backend/src/services/tls.js @@ -3,7 +3,7 @@ const net = require('net'); const tls = require('tls'); -const { resolvePublic } = require('./netguard'); +const { resolvePublic, isValidHostname, isPrivateIp } = require('./netguard'); const ALLOWED_PORTS = new Set([ 25, @@ -33,7 +33,12 @@ const err = (msg, code) => // -------------------------------------------------- function openSocket(ip, port) { + if (!net.isIP(ip) || isPrivateIp(ip)) { + throw err('Invalid or blocked destination IP address', 'BLOCKED'); + } + return new Promise((resolve, reject) => { + // NOSONAR: Destination IP is verified against private and reserved address blocklists via netguard const socket = net.connect({ host: ip, port, @@ -238,6 +243,12 @@ async function secureConnect({ rejectUnauthorized: false, }; + if (!plain && (!net.isIP(ip) || isPrivateIp(ip))) { + fail(err('Invalid or blocked destination IP address', 'BLOCKED')); + return; + } + + // NOSONAR: Destination IP is verified against private and reserved address blocklists via netguard const socket = tls.connect(options); const cleanup = () => { diff --git a/frontend/src/features/share.js b/frontend/src/features/share.js index 2d521d4..1bfc34e 100644 --- a/frontend/src/features/share.js +++ b/frontend/src/features/share.js @@ -136,9 +136,15 @@ export function bindTool({ button, enterOn = [], out, actions, type, busyMsg, pr setResult(out, "error", e.message); } finally { setBusy(button, false); } }; - button.addEventListener("click", run); + button.addEventListener("click", () => { + void run(); + }); + enterOn.forEach((i) => i?.addEventListener("keydown", (e) => { - if (e.key === "Enter") { e.preventDefault(); run(); } + if (e.key === "Enter") { + e.preventDefault(); + void run(); + } })); } From d5a904d6125d8ae94a704b73f3fcd9298f73d71a Mon Sep 17 00:00:00 2001 From: Kaushik Parui Date: Sun, 15 Nov 2026 16:00:03 +0530 Subject: [PATCH 10/12] sonarfloud fix applied for testing --- backend/src/routes/tls.js | 2 + backend/src/services/netguard.js | 21 ++++-- backend/src/services/tls.js | 120 +++++++++++++++++++++++-------- 3 files changed, 107 insertions(+), 36 deletions(-) diff --git a/backend/src/routes/tls.js b/backend/src/routes/tls.js index 07add18..e152a39 100644 --- a/backend/src/routes/tls.js +++ b/backend/src/routes/tls.js @@ -94,6 +94,8 @@ router.post('/', async (req, res) => { // ---------------------------------------------- // 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, diff --git a/backend/src/services/netguard.js b/backend/src/services/netguard.js index 2f1fe8c..d0e7f05 100644 --- a/backend/src/services/netguard.js +++ b/backend/src/services/netguard.js @@ -70,9 +70,9 @@ const BLOCKED_IPV4_RANGES = Object.freeze([ // IPv6 blocked ranges // -------------------------------------------------- -// IPv6 ranges include unspecified, loopback, mapped, -// translation, documentation, unique-local, -// link-local, multicast and special-purpose ranges. +// IPv6 must first belong to the global-unicast 2000::/3 range. +// This blocklist then excludes special-purpose ranges within it, +// including documentation, transition and multicast allocations. // // IPv4-mapped IPv6 addresses are handled separately // through explicit IPv4 extraction and validation. @@ -99,6 +99,11 @@ const BLOCKED_IPV6_RANGES = Object.freeze([ const BLOCK4 = new net.BlockList(); const BLOCK6 = new net.BlockList(); +const GLOBAL_IPV6 = new net.BlockList(); + +// Global Unicast Address space. IPv6 destinations outside 2000::/3 are +// not accepted, even if they are absent from the special-purpose blocklist. +GLOBAL_IPV6.addSubnet('2000::', 3, 'ipv6'); for (const [address, prefix] of BLOCKED_IPV4_RANGES) { BLOCK4.addSubnet(address, prefix, 'ipv4'); @@ -175,6 +180,13 @@ function isPrivateIp(ip) { return isPrivateIp(mappedIPv4); } + // Accept only IPv6 Global Unicast addresses. Then apply the + // special-purpose exclusions below. This is intentionally + // fail-closed for transition, local, documentation and reserved space. + if (!GLOBAL_IPV6.check(ip, 'ipv6')) { + return true; + } + return BLOCK6.check(ip, 'ipv6'); } } catch { @@ -232,8 +244,7 @@ async function resolvePublic(host) { let addresses; try { - // NOSONAR: Hostname destination is strictly validated by HOST_RE and BLOCKED_DOMAINS_RE - addresses = await dns.lookup(host, { + addresses = await dns.lookup(host, { // NOSONAR: hostname syntax is validated above; every resolved IP is checked below before use. all: true, verbatim: true, }); diff --git a/backend/src/services/tls.js b/backend/src/services/tls.js index d620e31..04735ba 100644 --- a/backend/src/services/tls.js +++ b/backend/src/services/tls.js @@ -37,9 +37,12 @@ function openSocket(ip, port) { throw err('Invalid or blocked destination IP address', 'BLOCKED'); } + if (!ALLOWED_PORTS.has(port)) { + throw err('Destination port is not permitted', 'BAD_INPUT'); + } + return new Promise((resolve, reject) => { - // NOSONAR: Destination IP is verified against private and reserved address blocklists via netguard - const socket = net.connect({ + const socket = net.connect({ // NOSONAR: `ip` is validated and pinned by resolvePublic(); the original hostname is not used here. host: ip, port, family: net.isIP(ip), @@ -174,9 +177,67 @@ async function secureConnect({ mode, tlsOpts = {}, }) { + // Fail closed before opening either a TCP or TLS connection. + // `ip` must be the exact address returned by resolvePublic(). + if (!net.isIP(ip) || isPrivateIp(ip)) { + throw err('Invalid or blocked destination IP address', 'BLOCKED'); + } + + if ( + typeof host !== 'string' || + (!net.isIP(host) && !isValidHostname(host)) + ) { + throw err('Invalid TLS hostname', 'BLOCKED'); + } + + if (!ALLOWED_PORTS.has(port)) { + throw err('Destination port is not permitted', 'BAD_INPUT'); + } + + if (!['implicit', 'starttls'].includes(mode)) { + throw err('Invalid TLS connection mode', 'BAD_INPUT'); + } + + // Only allow the TLS options that this service actually needs. + // In particular, callers cannot override host, port, socket, family, + // servername, or certificate-inspection settings. + const allowedVersions = new Set([ + 'TLSv1', + 'TLSv1.1', + 'TLSv1.2', + 'TLSv1.3', + ]); + + const safeTlsOptions = {}; + + if (tlsOpts.minVersion !== undefined) { + if (!allowedVersions.has(tlsOpts.minVersion)) { + throw err('Invalid minimum TLS version', 'BAD_INPUT'); + } + safeTlsOptions.minVersion = tlsOpts.minVersion; + } + + if (tlsOpts.maxVersion !== undefined) { + if (!allowedVersions.has(tlsOpts.maxVersion)) { + throw err('Invalid maximum TLS version', 'BAD_INPUT'); + } + safeTlsOptions.maxVersion = tlsOpts.maxVersion; + } + + if (tlsOpts.ciphers !== undefined) { + if ( + typeof tlsOpts.ciphers !== 'string' || + tlsOpts.ciphers.length > 1024 + ) { + throw err('Invalid TLS cipher configuration', 'BAD_INPUT'); + } + safeTlsOptions.ciphers = tlsOpts.ciphers; + } + let plain; if (mode === 'starttls') { + // openSocket receives only the validated, pinned IP address. plain = await openSocket(ip, port); try { @@ -219,38 +280,40 @@ async function secureConnect({ return new Promise((resolve, reject) => { let settled = false; + // The destination is always the previously validated IP. For STARTTLS, + // TLS is layered over the already-connected, validated TCP socket. + const destinationOptions = plain + ? { socket: plain } + : { + host: ip, + port, + family: net.isIP(ip), + }; + const options = { - ...(plain - ? { socket: plain } - : { - host: ip, - port, - family: net.isIP(ip), - }), - - // SNI is not applicable to IP address literals. - servername: net.isIP(host) ? undefined : host, + ...safeTlsOptions, + ...destinationOptions, - ...tlsOpts, + // SNI uses the original validated DNS name, never the resolved IP. + servername: net.isIP(host) ? undefined : host, - // Intentionally disabled because this is a diagnostic - // scanner that must inspect untrusted certificates. - // - // Certificate trust is evaluated separately below. - // - // codeql[js/disabling-certificate-validation] - // lgtm[js/disabling-certificate-validation] + // This scanner intentionally inspects untrusted certificates. + // Certificate identity and trust are reported separately in inspect(). rejectUnauthorized: false, }; - if (!plain && (!net.isIP(ip) || isPrivateIp(ip))) { - fail(err('Invalid or blocked destination IP address', 'BLOCKED')); + let socket; + + try { + // `ip` is validated here and pinned from resolvePublic(); the original + // user-controlled hostname is used only for SNI and certificate identity. + socket = tls.connect(options); // NOSONAR: validated, pinned IP is the connection destination. + } catch (error) { + if (plain) plain.destroy(); + reject(error); return; } - // NOSONAR: Destination IP is verified against private and reserved address blocklists via netguard - const socket = tls.connect(options); - const cleanup = () => { socket.removeListener('secureConnect', onSecure); socket.removeListener('timeout', onTimeout); @@ -262,7 +325,6 @@ async function secureConnect({ settled = true; cleanup(); - socket.destroy(); if (plain) { @@ -277,15 +339,12 @@ async function secureConnect({ settled = true; cleanup(); - socket.setTimeout(0); resolve(socket); }; const onTimeout = () => { - fail( - err('TLS handshake timed out', 'TIMEOUT') - ); + fail(err('TLS handshake timed out', 'TIMEOUT')); }; const onError = (error) => { @@ -293,7 +352,6 @@ async function secureConnect({ }; socket.setTimeout(TIMEOUT); - socket.once('secureConnect', onSecure); socket.once('timeout', onTimeout); socket.once('error', onError); From fccfd999be662501bb492dbd4b6e16e46031d583 Mon Sep 17 00:00:00 2001 From: Kaushik Parui Date: Sun, 15 Nov 2026 22:49:00 +0530 Subject: [PATCH 11/12] 1.2.0 --- backend/package-lock.json | 4 ++-- backend/package.json | 2 +- frontend/src/version.json | 4 ++-- package-lock.json | 4 ++-- package.json | 2 +- 5 files changed, 8 insertions(+), 8 deletions(-) diff --git a/backend/package-lock.json b/backend/package-lock.json index 3eba1d8..3bc0087 100644 --- a/backend/package-lock.json +++ b/backend/package-lock.json @@ -1,12 +1,12 @@ { "name": "MailMetrix-backend", - "version": "1.1.2", + "version": "1.2.0", "lockfileVersion": 3, "requires": true, "packages": { "": { "name": "MailMetrix-backend", - "version": "1.1.2", + "version": "1.2.0", "dependencies": { "dotenv": "^18.0.7", "express": "^5.3.0", diff --git a/backend/package.json b/backend/package.json index 0668276..93c223d 100644 --- a/backend/package.json +++ b/backend/package.json @@ -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": { diff --git a/frontend/src/version.json b/frontend/src/version.json index a7be38f..40cf83d 100644 --- a/frontend/src/version.json +++ b/frontend/src/version.json @@ -1,4 +1,4 @@ { - "version": "1.1.2", - "buildDate": "2026-11-04T11:24:42.186Z" + "version": "1.2.0", + "buildDate": "2026-11-15T17:19:00.406Z" } diff --git a/package-lock.json b/package-lock.json index 30927f8..ea15d76 100644 --- a/package-lock.json +++ b/package-lock.json @@ -1,12 +1,12 @@ { "name": "mailmetrix", - "version": "1.1.2", + "version": "1.2.0", "lockfileVersion": 3, "requires": true, "packages": { "": { "name": "mailmetrix", - "version": "1.1.2", + "version": "1.2.0", "license": "SEE LICENSE IN LICENSE" } } diff --git a/package.json b/package.json index 5e8a4d8..ae27911 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "mailmetrix", - "version": "1.1.2", + "version": "1.2.0", "private": true, "description": "MailMetrix — SMTP, DNS and email header diagnostics workspace.", "license": "SEE LICENSE IN LICENSE", From 48f1f08df1ad72b031dae11efd13bce72df108cc Mon Sep 17 00:00:00 2001 From: Kaushik Parui Date: Mon, 16 Nov 2026 22:06:13 +0530 Subject: [PATCH 12/12] fix application name in some files --- backend/src/routes/share.js | 2 +- backend/src/services/share.js | 4 ++-- backend/src/services/tls.js | 2 +- 3 files changed, 4 insertions(+), 4 deletions(-) diff --git a/backend/src/routes/share.js b/backend/src/routes/share.js index 9c3f67e..c611e0d 100644 --- a/backend/src/routes/share.js +++ b/backend/src/routes/share.js @@ -32,7 +32,7 @@ router.get('/:id/export', async (req, res) => { 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 = `mailprobe-${rec.type}-${id}`; + 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)); diff --git a/backend/src/services/share.js b/backend/src/services/share.js index 356c59c..b08001c 100644 --- a/backend/src/services/share.js +++ b/backend/src/services/share.js @@ -210,10 +210,10 @@ function toCsv(data) { function toHtml(rec, id) { const rows = flatten(rec.data).map(([k, v]) => `${esc(k)}${esc(v)}`).join(''); - return `MailProbe ${esc(rec.type)} report + return `MailMetrix ${esc(rec.type)} report -

MailProbe ${esc(rec.type)} report

ID ${esc(id)} · created ${esc(new Date(rec.createdAt).toISOString())}

${rows}
`; +

MailMetrix ${esc(rec.type)} report

ID ${esc(id)} · created ${esc(new Date(rec.createdAt).toISOString())}

${rows}
`; } module.exports = { create, get, toCsv, toHtml }; \ No newline at end of file diff --git a/backend/src/services/tls.js b/backend/src/services/tls.js index 04735ba..e92f6d6 100644 --- a/backend/src/services/tls.js +++ b/backend/src/services/tls.js @@ -250,7 +250,7 @@ async function secureConnect({ ); } - plain.write('EHLO mailprobe.local\r\n'); + plain.write('EHLO mailmetrix.local\r\n'); const ehlo = await readReply(plain);