diff --git a/.env.example b/.env.example index b3ea698..445fd1d 100644 --- a/.env.example +++ b/.env.example @@ -2,4 +2,31 @@ # Keep this file free of real credentials and secrets. # Port on which the backend server listens inside its container. -PORT=4000 \ No newline at end of file +PORT=4000 +RATE_LIMIT_BLACKLIST=30 +RATE_LIMIT_SCORE=15 +RATE_LIMIT_TLS=20 +RATE_LIMIT_SHARE=60 +SHARE_TTL_DAYS=1 + +## Optional Variables for Share +SHARE_PER_IP_DAILY=30 +SHARE_MAX_TOTAL_MB=512 +SHARE_MAX_FILES=5000 + +## Optional Variables for Score +SCORE_CACHE_TTL_SECONDS=300 +SCORE_TARGET_TTL_SECONDS=900 +SCORE_MAX_DNS_QUERIES=80 +SCORE_DEADLINE_SECONDS=25 +SCORE_MAX_CONCURRENT=8 +SCORE_MAX_QUEUE=16 +SCORE_DNSBL_IPS_PER_HOUR=300 +SCORE_TLS_PROBES_PER_HOUR=120 + +# NOTE FOR CLOUD / VPS DEPLOYMENTS: +# 1. Port 25 Outbound: Cloud providers (AWS, GCP, DigitalOcean, Linode, Hetzner) block outbound +# port 25 by default. Contact your provider to unblock port 25 if live mail server TLS checks fail. +# 2. DNSBL / Blacklist checks: Public DNS resolvers (8.8.8.8, 1.1.1.1) are blocked by Spamhaus +# and Barracuda. For accurate blacklist checks, configure your VPS host to use a local +# recursive resolver (e.g. Unbound / Bind) instead of public open resolvers. \ No newline at end of file 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/.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/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/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/backend/src/routes/_util.js b/backend/src/routes/_util.js new file mode 100644 index 0000000..bc808a1 --- /dev/null +++ b/backend/src/routes/_util.js @@ -0,0 +1,16 @@ +'use strict'; +// Maps service errors to HTTP responses. +const CLIENT = new Set(['BAD_INPUT', 'BLOCKED', 'ENOTFOUND']); +module.exports = function sendError(res, e) { + if (CLIENT.has(e.code)) return res.status(400).json({ error: e.message }); + if (e.code === 'TOO_LARGE') return res.status(413).json({ error: e.message }); + if (e.code === 'RATE_LIMITED') return res.status(429).json({ error: e.message }); + if (e.code === 'BUSY') return res.status(503).set('Retry-After', '5').json({ error: e.message }); + if (e.code === 'TOO_COMPLEX') return res.status(422).json({ error: e.message }); + if (e.code === 'FULL') return res.status(507).json({ error: e.message }); + if (['TIMEOUT', 'ECONNREFUSED', 'ECONNRESET', 'EHOSTUNREACH', 'NO_STARTTLS', 'STARTTLS_REJECTED', 'BAD_GREETING', 'NO_CERT'].includes(e.code)) { + return res.status(502).json({ error: e.message }); + } + console.error(e); + return res.status(500).json({ error: 'Internal error' }); +}; 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..c611e0d --- /dev/null +++ b/backend/src/routes/share.js @@ -0,0 +1,49 @@ +'use strict'; +const express = require('express'); +const path = require('path'); +const service = require('../services/share'); +const sendError = require('./_util'); + +const router = express.Router(); +router.use(express.json({ limit: '300kb' })); + +const ID_RE = /^[A-Za-z0-9_-]{8,16}$/; + +router.post('/', async (req, res) => { + try { + res.status(201).json(await service.create(req.body?.type, req.body?.data, req.ip)); + } catch (e) { sendError(res, e); } +}); + +router.get('/:id', async (req, res) => { + try { + const id = path.basename(String(req.params.id || '')); + if (!ID_RE.test(id)) return res.status(404).json({ error: 'Share not found or expired' }); + const rec = await service.get(id); + if (!rec) return res.status(404).json({ error: 'Share not found or expired' }); + res.json({ type: rec.type, data: rec.data, createdAt: rec.createdAt, expiresAt: rec.expiresAt }); + } catch (e) { sendError(res, e); } +}); + +router.get('/:id/export', async (req, res) => { + try { + const id = path.basename(String(req.params.id || '')); + if (!ID_RE.test(id)) return res.status(404).json({ error: 'Share not found or expired' }); + const rec = await service.get(id); + if (!rec) return res.status(404).json({ error: 'Share not found or expired' }); + const fmt = String(req.query.format || 'json'); + const name = `mailmetrix-${rec.type}-${id}`; + if (fmt === 'csv') { + res.type('text/csv').set('Content-Disposition', `attachment; filename="${name}.csv"`); + return res.send(service.toCsv(rec.data)); + } + if (fmt === 'html') { + res.set('Content-Security-Policy', "default-src 'none'; style-src 'unsafe-inline'"); + return res.type('html').send(service.toHtml(rec, id)); + } + res.type('application/json').set('Content-Disposition', `attachment; filename="${name}.json"`); + return res.send(JSON.stringify(rec.data, null, 2)); + } catch (e) { sendError(res, e); } +}); + +module.exports = router; diff --git a/backend/src/routes/tls.js b/backend/src/routes/tls.js new file mode 100644 index 0000000..e152a39 --- /dev/null +++ b/backend/src/routes/tls.js @@ -0,0 +1,113 @@ +'use strict'; + +const express = require('express'); +const net = require('net'); + +const service = require('../services/tls'); +const { isValidHostname, isPrivateIp } = require('../services/netguard'); +const sendError = require('./_util'); + +const router = express.Router(); + +router.use(express.json({ + limit: '10kb', +})); + +router.post('/', async (req, res) => { + try { + const { + host, + port = 25, + mode, + versions, + } = req.body || {}; + + // ---------------------------------------------- + // Validate & sanitize hostname / IP address + // ---------------------------------------------- + + if ( + typeof host !== 'string' || + !host.trim() || + host.length > 253 + ) { + return res.status(400).json({ + error: 'A valid hostname or IP address is required', + }); + } + + const sanitizedHost = host.trim().toLowerCase(); + + const isIp = net.isIP(sanitizedHost); + + // Host must be either a valid public hostname or a valid IP literal + if (!isIp && !isValidHostname(sanitizedHost)) { + return res.status(400).json({ + error: 'A valid public hostname or IP address is required', + }); + } + + // Direct check: reject private, loopback, or reserved IP addresses immediately + if (isIp && isPrivateIp(sanitizedHost)) { + return res.status(400).json({ + error: 'Private or reserved IP addresses are not permitted', + }); + } + + // ---------------------------------------------- + // Validate port + // ---------------------------------------------- + + const parsedPort = Number(port ?? 25); + if (!Number.isInteger(parsedPort) || !service.ALLOWED_PORTS.has(parsedPort)) { + return res.status(400).json({ + error: `Port must be one of: ${[...service.ALLOWED_PORTS].join(', ')}`, + }); + } + + // ---------------------------------------------- + // Validate mode + // ---------------------------------------------- + + if ( + mode !== undefined && + !['implicit', 'starttls'].includes(mode) + ) { + return res.status(400).json({ + error: 'mode must be implicit or starttls', + }); + } + + // ---------------------------------------------- + // Validate versions + // ---------------------------------------------- + + if ( + versions !== undefined && + typeof versions !== 'boolean' + ) { + return res.status(400).json({ + error: 'versions must be a boolean', + }); + } + + // ---------------------------------------------- + // TLS inspection + // ---------------------------------------------- + // The service performs DNS resolution, validates every returned IP, + // and connects only to a validated IP (never to this hostname directly). + + const result = await service.inspect({ + host: sanitizedHost, + port: parsedPort, + mode, + versions: versions === true, + }); + + return res.json(result); + } catch (error) { + return sendError(res, error); + } +}); + +module.exports = router; \ No newline at end of file diff --git a/backend/src/server.js b/backend/src/server.js index b3d2b4c..0e5c641 100644 --- a/backend/src/server.js +++ b/backend/src/server.js @@ -8,8 +8,13 @@ const smtpRoutes = require("./routes/smtp"); const dnsRoutes = require("./routes/dns"); const headerRoutes = require("./routes/headers"); const generatorRoutes = require("./routes/generator"); +const blacklistRoutes = require("./routes/blacklist"); +const scoreRoutes = require("./routes/score"); +const tlsRoutes = require("./routes/tls"); +const shareRoutes = require("./routes/share"); -const app = express(); +const app = express(); +app.disable("x-powered-by"); // don't advertise "X-Powered-By: Express" on every response const PORT = Number(process.env.PORT || 4000); /* ------------------------------------------------------------------ */ @@ -76,6 +81,30 @@ const headersLimiter = createLimiter( "Too many requests, please try again later." ); +// Each blacklist check sends 9-12 DNS queries per IP. +const blacklistLimiter = createLimiter( + positiveInt(process.env.RATE_LIMIT_BLACKLIST, 30), + "Blacklist check limit reached. Please try again later." +); + +// One score run = ~40 DNS queries + outbound TLS connection. +const scoreLimiter = createLimiter( + positiveInt(process.env.RATE_LIMIT_SCORE, 15), + "Deliverability score limit reached. Please try again later." +); + +// Opens outbound sockets to user-chosen hosts (SSRF-guarded in services/netguard.js). +const tlsLimiter = createLimiter( + positiveInt(process.env.RATE_LIMIT_TLS, 20), + "TLS inspection limit reached. Please try again later." +); + +// Creating shares writes to disk; viewing them is cheap. +const shareLimiter = createLimiter( + positiveInt(process.env.RATE_LIMIT_SHARE, 60), + "Share limit reached. Please try again later." +); + // HTTP request logging (registered first so 429 responses are logged too). app.use((req, res, next) => { const startTime = Date.now(); @@ -97,6 +126,20 @@ app.use("/smtp", smtpLimiter); app.use("/generator", generatorLimiter); app.use("/dns", dnsLimiter); app.use("/headers", headersLimiter); +app.use("/blacklist", blacklistLimiter); +app.use("/score", scoreLimiter); +app.use("/tls", tlsLimiter); +app.use("/share", shareLimiter); + +// Share allows larger payloads (up to 300kb) and parses its own body, so it +// must be mounted BEFORE the global 100kb parser below. +app.use("/share", shareRoutes); + +// Raw email headers can be large (long ARC/DKIM chains, or a whole message pasted by mistake), +// so /headers gets a higher body limit than the global 100kb. Mounted BEFORE the global parser, +// which skips requests that are already parsed. +const HEADERS_BODY_LIMIT = process.env.HEADERS_BODY_LIMIT || "512kb"; +app.use("/headers", express.json({ limit: HEADERS_BODY_LIMIT })); // Parse JSON request bodies with a size limit. app.use(express.json({ limit: "100kb" })); @@ -202,6 +245,9 @@ app.use("/smtp", smtpRoutes); app.use("/dns", dnsRoutes); app.use("/headers", headerRoutes); app.use("/generator", generatorRoutes); +app.use("/blacklist", blacklistRoutes); +app.use("/score", scoreRoutes); +app.use("/tls", tlsRoutes); // Handle unmatched routes. app.use((req, res) => { 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/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/backend/src/services/netguard.js b/backend/src/services/netguard.js new file mode 100644 index 0000000..d0e7f05 --- /dev/null +++ b/backend/src/services/netguard.js @@ -0,0 +1,297 @@ +'use strict'; + +// Central SSRF protection. +// +// 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; + +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; +} + +// -------------------------------------------------- +// 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 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. + +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 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'); +} + +for (const [address, prefix] of BLOCKED_IPV6_RANGES) { + BLOCK6.addSubnet(address, prefix, 'ipv6'); +} + +// -------------------------------------------------- +// IPv4-mapped IPv6 handling +// -------------------------------------------------- + +function extractMappedIPv4(ip) { + if (!net.isIPv6(ip)) { + return null; + } + + const normalized = ip.toLowerCase(); + + // 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 || + ip.includes('%') + ) { + return true; + } + + try { + if (net.isIPv4(ip)) { + return BLOCK4.check(ip, 'ipv4'); + } + + if (net.isIPv6(ip)) { + // Explicitly validate IPv4-mapped addresses. + const mappedIPv4 = extractMappedIPv4(ip); + + if (mappedIPv4) { + 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 { + return true; + } + + // Fail closed for invalid addresses. + return true; +} + +// -------------------------------------------------- +// Hostname validation +// -------------------------------------------------- + +function isValidHostname(host) { + return ( + typeof host === 'string' && + host.length <= 253 && + HOST_RE.test(host) && + !BLOCKED_DOMAINS_RE.test(host) + ); +} + +// -------------------------------------------------- +// Public DNS resolution +// -------------------------------------------------- + +async function resolvePublic(host) { + if (typeof host !== 'string') { + throw blocked('Invalid hostname'); + } + + host = host.trim().toLowerCase(); + + if (!host || host.length > 253) { + throw blocked('Invalid hostname'); + } + + // Direct IP address. + if (net.isIP(host)) { + if (isPrivateIp(host)) { + throw blocked( + 'Private or reserved IP addresses are not allowed' + ); + } + + return [host]; + } + + // Reject URLs, ports, credentials, paths, reserved domains and malformed names. + if (!isValidHostname(host)) { + throw blocked('Invalid hostname'); + } + + let addresses; + + try { + addresses = await dns.lookup(host, { // NOSONAR: hostname syntax is validated above; every resolved IP is checked below before use. + all: true, + verbatim: true, + }); + } catch { + const error = new Error(`Could not resolve ${host}`); + error.code = 'ENOTFOUND'; + throw error; + } + + if (!Array.isArray(addresses) || addresses.length === 0) { + const error = new Error(`No addresses for ${host}`); + error.code = 'ENOTFOUND'; + throw error; + } + + // 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( + 'Host resolves to a private or reserved address' + ); + } + } + + // Remove duplicates after validation. + return [ + ...new Set( + addresses.map(({ address }) => address) + ), + ]; +} + +// -------------------------------------------------- +// Exports +// -------------------------------------------------- + +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 new file mode 100644 index 0000000..383a730 --- /dev/null +++ b/backend/src/services/score.js @@ -0,0 +1,356 @@ +'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, 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 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 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(); + 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); + +// 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(d, domain) { + const mx = await safe(() => d.mx(domain), []); + return mx.filter((m) => m.exchange && m.exchange !== '.').sort((a, b) => a.priority - b.priority); +} + +// 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)) { + 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; +} + +// 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 = null, depth = 0) { + const state = st || { + n: 0, + seen: new Set(), + }; + + if (depth > SPF_LIMIT || state.seen.has(domain)) { + return state.n; + } + + state.seen.add(domain); + + const rec = (await d.txt(domain)).find( + (t) => /^v=spf1\b/i.test(t) + ); + + if (!rec) return state.n; + + for (const term of rec.split(/\s+/).slice(1)) { + if (state.n > SPF_LIMIT) return state.n; + + const m = term.replace(/^[+\-~?]/, ''); + + const isInclude = /^include:/i.test(m); + const isRedirect = /^redirect=/i.test(m); + + if (isInclude || isRedirect) { + state.n += 1; + + if (state.n > SPF_LIMIT) return state.n; + + const target = m + .slice(isInclude ? 8 : 9) + .toLowerCase(); + + if (isValidHostname(target)) { + await spfLookups(d, target, state, depth + 1); + } + } else if ( + /^(a|mx)(:|\/|$)/i.test(m) || + /^(ptr|exists:)/i.test(m) + ) { + state.n += 1; + } + } + + return state.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(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(d, 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 > 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(d, domain, selector) { + const selectors = selector ? [selector] : DKIM_SELECTORS; + const found = []; + await Promise.all(selectors.map(async (s) => { + 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(', ')}.`); + 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(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); + 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(d, ips) { + if (!ips.length) return mk('rdns', 'Reverse DNS (FCrDNS)', 10, 0, 'skip', 'No MX IPs to test.'); + 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) { + if (!isValidHostname(n)) continue; + const fwd = await safe(() => d.a(n), []); + if (fwd.includes(ip)) return true; + } + 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.'); +} + +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); + // 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, 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(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 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'); + 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.'); + // 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.'); + } +} + +function grade(pct) { + return pct >= 90 ? 'A' : pct >= 80 ? 'B' : pct >= 70 ? 'C' : pct >= 60 ? 'D' : 'F'; +} + +async function run(domain, selector) { + await acquireSlot(); + 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 { + releaseSlot(); + } +} + +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 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 }; \ No newline at end of file diff --git a/backend/src/services/share.js b/backend/src/services/share.js new file mode 100644 index 0000000..b08001c --- /dev/null +++ b/backend/src/services/share.js @@ -0,0 +1,219 @@ +'use strict'; +// 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 = 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; +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']); + +// 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 }); + +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. +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); + const target = file(id); + if (!target) continue; + try { + const st = fs.statSync(target); + 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) { + const target = file(id); + if (target) { + fs.promises.rm(target, { force: true }).catch(() => {}); + } + 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; +} + +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'); + 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'); + 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 }); + 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) { + const target = file(id); + if (!target) return null; + let rec; + try { + 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 + return null; + } + const meta = index.get(id); + if (rec.expiresAt < Date.now() || (meta && meta.exp < Date.now())) { + removeShare(id); + return null; + } + return rec; +} + +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 { + const files = await fs.promises.readdir(DIR); + for (const f of files) { + 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); +} +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 `MailMetrix ${esc(rec.type)} report + +

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/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/backend/src/services/tls.js b/backend/src/services/tls.js new file mode 100644 index 0000000..e92f6d6 --- /dev/null +++ b/backend/src/services/tls.js @@ -0,0 +1,772 @@ +'use strict'; + +const net = require('net'); +const tls = require('tls'); + +const { resolvePublic, isValidHostname, isPrivateIp } = 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 MAX_REPLY_SIZE = 8192; + +const err = (msg, code) => + Object.assign(new Error(msg), { code }); + +// -------------------------------------------------- +// Socket connection +// -------------------------------------------------- + +function openSocket(ip, port) { + if (!net.isIP(ip) || isPrivateIp(ip)) { + 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) => { + 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), + }); + + let settled = false; + + const cleanup = () => { + socket.removeListener('connect', onConnect); + socket.removeListener('timeout', onTimeout); + socket.removeListener('error', onError); + }; + + const fail = (error) => { + if (settled) return; + + settled = true; + cleanup(); + socket.destroy(); + reject(error); + }; + + const onConnect = () => { + if (settled) return; + + settled = true; + cleanup(); + + socket.setTimeout(0); + resolve(socket); + }; + + const onTimeout = () => { + fail(err('Connection timed out', 'TIMEOUT')); + }; + + const onError = (error) => { + fail(error); + }; + + socket.setTimeout(TIMEOUT); + + socket.once('connect', onConnect); + socket.once('timeout', onTimeout); + socket.once('error', onError); + }); +} + +// -------------------------------------------------- +// SMTP response reader +// -------------------------------------------------- + +function readReply(socket) { + return new Promise((resolve, reject) => { + let buffer = ''; + + const timer = setTimeout(() => { + cleanup(); + reject( + err('SMTP server did not respond in time', 'TIMEOUT') + ); + }, TIMEOUT); + + const cleanup = () => { + clearTimeout(timer); + + socket.off('data', onData); + socket.off('error', onError); + socket.off('end', onClose); + socket.off('close', onClose); + }; + + const onData = (data) => { + buffer += data.toString('utf8'); + + if (buffer.length > MAX_REPLY_SIZE) { + cleanup(); + + reject( + err('SMTP reply too large', 'BAD_REPLY') + ); + + return; + } + + // SMTP multiline responses terminate with: + // 250 + // Previous lines normally use 250-. + const lines = buffer.split('\r\n'); + + const complete = lines.some((line) => + /^\d{3} /.test(line) + ); + + if (buffer.endsWith('\r\n') && complete) { + cleanup(); + resolve(buffer); + } + }; + + const onError = (error) => { + cleanup(); + reject(error); + }; + + const onClose = () => { + cleanup(); + + reject( + err( + 'Connection closed by remote server', + 'ECONNRESET' + ) + ); + }; + + socket.on('data', onData); + socket.on('error', onError); + socket.on('end', onClose); + socket.on('close', onClose); + }); +} + +// -------------------------------------------------- +// TLS connection +// -------------------------------------------------- + +async function secureConnect({ + ip, + host, + port, + 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 { + const greeting = await readReply(plain); + + if (!/^220(?:[ -])/m.test(greeting)) { + throw err( + `Unexpected SMTP greeting: ${greeting.trim().slice(0, 120)}`, + 'BAD_GREETING' + ); + } + + plain.write('EHLO mailmetrix.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 response = await readReply(plain); + + if (!/^220(?:[ -])/m.test(response)) { + throw err( + `STARTTLS rejected: ${response.trim().slice(0, 120)}`, + 'STARTTLS_REJECTED' + ); + } + } catch (error) { + plain.destroy(); + throw error; + } + } + + 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 = { + ...safeTlsOptions, + ...destinationOptions, + + // SNI uses the original validated DNS name, never the resolved IP. + servername: net.isIP(host) ? undefined : host, + + // This scanner intentionally inspects untrusted certificates. + // Certificate identity and trust are reported separately in inspect(). + rejectUnauthorized: false, + }; + + 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; + } + + const cleanup = () => { + socket.removeListener('secureConnect', onSecure); + socket.removeListener('timeout', onTimeout); + socket.removeListener('error', onError); + }; + + const fail = (error) => { + if (settled) return; + + settled = true; + cleanup(); + socket.destroy(); + + if (plain) { + plain.destroy(); + } + + reject(error); + }; + + const onSecure = () => { + if (settled) return; + + settled = true; + cleanup(); + socket.setTimeout(0); + resolve(socket); + }; + + const onTimeout = () => { + fail(err('TLS handshake timed out', 'TIMEOUT')); + }; + + const onError = (error) => { + fail(error); + }; + + socket.setTimeout(TIMEOUT); + socket.once('secureConnect', onSecure); + socket.once('timeout', onTimeout); + socket.once('error', onError); + }); +} + +// -------------------------------------------------- +// Certificate summary +// -------------------------------------------------- + +function summarizeCert(cert) { + return { + subject: cert.subject, + issuer: cert.issuer, + validFrom: cert.valid_from, + validTo: cert.valid_to, + serialNumber: cert.serialNumber, + fingerprint256: cert.fingerprint256, + bits: cert.bits, + curve: cert.asn1Curve || null, + + altNames: cert.subjectaltname + ? cert.subjectaltname.split(', ').slice(0, 50) + : [], + }; +} + +// -------------------------------------------------- +// Certificate chain +// -------------------------------------------------- + +function buildChain(leaf) { + const chain = []; + const seen = new Set(); + + let cert = leaf; + + while ( + cert && + cert.fingerprint256 && + !seen.has(cert.fingerprint256) + ) { + seen.add(cert.fingerprint256); + + chain.push(summarizeCert(cert)); + + cert = cert.issuerCertificate; + } + + return chain; +} + +// -------------------------------------------------- +// TLS version probing +// -------------------------------------------------- + +async function probeVersions(base) { + const versions = [ + 'TLSv1', + 'TLSv1.1', + 'TLSv1.2', + 'TLSv1.3', + ]; + + const results = await Promise.all( + versions.map(async (version) => { + try { + const socket = await secureConnect({ + ...base, + + tlsOpts: { + minVersion: version, + maxVersion: version, + ciphers: 'ALL:@SECLEVEL=0', + }, + }); + + socket.destroy(); + + return [version, true]; + } catch { + return [version, false]; + } + }) + ); + + return Object.fromEntries(results); +} + +// -------------------------------------------------- +// Input validation +// -------------------------------------------------- + +function validatePort(value) { + if (value === undefined || value === null || value === '') { + return 25; + } + + const port = Number(value); + + if (!Number.isInteger(port) || !ALLOWED_PORTS.has(port)) { + throw err( + `Port must be one of: ${[...ALLOWED_PORTS].join(', ')}`, + 'BAD_INPUT' + ); + } + + return port; +} + +// -------------------------------------------------- +// TLS inspection +// -------------------------------------------------- + +async function inspect({ + host, + port = 25, + mode, + versions = false, +}) { + // Hostname validation + if (typeof host !== 'string') { + throw err( + 'A valid hostname or IP address is required', + 'BAD_INPUT' + ); + } + + host = host.trim().toLowerCase(); + + if (!host || host.length > 253) { + throw err('Invalid hostname', 'BAD_INPUT'); + } + + // Port validation + port = validatePort(port); + + // Connection mode validation + mode = mode || ( + IMPLICIT_PORTS.has(port) + ? 'implicit' + : 'starttls' + ); + + if (!['implicit', 'starttls'].includes(mode)) { + throw err( + 'mode must be implicit or starttls', + 'BAD_INPUT' + ); + } + + // ------------------------------------------------ + // SSRF protection + // ------------------------------------------------ + + // Resolve and validate ALL addresses before connecting. + // Never pass the original hostname to the network layer. + + const addresses = await resolvePublic(host); + + if (!addresses.length) { + throw err('No public IP addresses available', 'BLOCKED'); + } + + // Use a validated IP address. + // This prevents a second DNS lookup during connection. + + const ip = addresses[0]; + + const base = { + ip, + host, + port, + mode, + }; + + const socket = await secureConnect(base); + + try { + const leaf = socket.getPeerCertificate(true); + + if (!leaf || !leaf.fingerprint256) { + throw err( + 'Server presented no certificate', + 'NO_CERT' + ); + } + + const chain = buildChain(leaf); + + const protocol = socket.getProtocol(); + const cipher = socket.getCipher(); + + const validTo = new Date(leaf.valid_to); + + const daysRemaining = Math.floor( + (validTo.getTime() - Date.now()) / 86400000 + ); + + // Check identity for both DNS names and IP addresses. + // SNI is still disabled for IP literals. + + const identityError = tls.checkServerIdentity( + host, + leaf + ); + + const selfSigned = + chain.length === 1 || + leaf.issuerCertificate === leaf; + + const findings = []; + + const add = (severity, title, detail) => { + findings.push({ + severity, + title, + detail, + }); + }; + + // ---------------------------------------------- + // Certificate expiration + // ---------------------------------------------- + + 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.` + ); + } + + // ---------------------------------------------- + // Hostname verification + // ---------------------------------------------- + + if (identityError) { + add( + 'critical', + 'Hostname mismatch', + identityError.reason || identityError.message + ); + } else { + add( + 'ok', + 'Hostname matches certificate', + host + ); + } + + // ---------------------------------------------- + // Certificate trust + // ---------------------------------------------- + + if (!socket.authorized) { + add( + mode === 'starttls' && port === 25 + ? 'warning' + : 'critical', + 'Certificate not trusted', + + `${socket.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.` + ); + } + + // ---------------------------------------------- + // TLS protocol + // ---------------------------------------------- + + 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.` + ); + } + + // ---------------------------------------------- + // Cipher strength + // ---------------------------------------------- + + if ( + cipher && + /RC4|3DES|NULL|EXPORT|MD5|DES-CBC/i.test(cipher.name) + ) { + add( + 'critical', + 'Weak cipher suite', + cipher.name + ); + } + + // ---------------------------------------------- + // Public key strength + // ---------------------------------------------- + + if ( + !leaf.asn1Curve && + leaf.bits && + leaf.bits < 2048 + ) { + add( + 'warning', + 'Weak RSA key', + `${leaf.bits}-bit key (2048+ recommended).` + ); + } + + // ---------------------------------------------- + // Result + // ---------------------------------------------- + + const result = { + host, + ip, + port, + mode, + + checkedAt: new Date().toISOString(), + + connection: { + protocol, + cipher: cipher ? cipher.name : null, + authorized: socket.authorized, + + authorizationError: socket.authorizationError + ? String(socket.authorizationError) + : null, + }, + + certificate: { + ...summarizeCert(leaf), + daysRemaining, + selfSigned, + hostnameMatch: !identityError, + }, + + chain, + findings, + }; + + socket.destroy(); + + // ---------------------------------------------- + // Optional TLS version probing + // ---------------------------------------------- + + if (versions === true) { + result.supportedVersions = await probeVersions(base); + + const legacy = [ + 'TLSv1', + 'TLSv1.1', + ].filter( + (version) => result.supportedVersions[version] + ); + + if (legacy.length) { + result.findings.push({ + severity: 'warning', + title: 'Legacy protocols enabled', + detail: legacy.join(', '), + }); + } + } + + return result; + } finally { + socket.destroy(); + } +} + +module.exports = { + inspect, + ALLOWED_PORTS, +}; \ No newline at end of file diff --git a/docker-compose.yml b/docker-compose.yml index 7d056ae..a7c966f 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}" @@ -27,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 @@ -114,4 +114,7 @@ services: networks: network: - driver: bridge \ No newline at end of file + driver: bridge + +volumes: + mailmetrix-data: 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 diff --git a/frontend/src/app.js b/frontend/src/app.js index 5a995c5..36aaea7 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() { @@ -52,6 +69,40 @@ initGenerator(); }); })(); +/* ---------------- Accessibility: mirror CSS-class state into ARIA ---------------- + tabs.js and the flow helpers signal state only through CSS classes ("active", "success", + "error"), which assistive technology cannot see. Rather than touch every module, watch the + classes here and reflect them as ARIA state. This works however those modules toggle them. */ +(function initA11ySync() { + const observe = (nodes, onChange) => { + const observer = new MutationObserver((records) => records.forEach((r) => onChange(r.target))); + nodes.forEach((node) => { + onChange(node); + observer.observe(node, { attributes: true, attributeFilter: ['class'] }); + }); + }; + + // Sidebar tabs: the active tool is announced as the current item. + observe(document.querySelectorAll('.tool-tabs .tab'), (tab) => { + if (tab.classList.contains('active')) tab.setAttribute('aria-current', 'true'); + else tab.removeAttribute('aria-current'); + }); + + // Workflow steps: colour alone shows progress, so add the state as visually hidden text. + const stepText = { active: 'in progress', success: 'completed', error: 'failed' }; + const stepLabels = new Map(); + document.querySelectorAll('.flow-step').forEach((step) => { + const label = document.createElement('span'); + label.className = 'sr-only'; + (step.querySelector('div') || step).appendChild(label); + stepLabels.set(step, label); + }); + observe(document.querySelectorAll('.flow-step'), (step) => { + const state = Object.keys(stepText).find((s) => step.classList.contains(s)); + stepLabels.get(step).textContent = state ? ` (${stepText[state]})` : ''; + }); +})(); + /* ---------------- Backend telemetry ---------------- */ function setBackendState(online, duration, data) { const latencyEl = document.getElementById('backendLatency'); @@ -70,8 +121,10 @@ function setBackendState(online, duration, data) { streamEl.textContent = '● Connected'; streamEl.style.color = 'var(--success)'; } - if (cpuEl) cpuEl.textContent = (data && data.cpu) || '0.5 %'; - if (memEl) memEl.textContent = (data && data.memory) || '35.0 MB'; + // Only show figures the backend actually reported. /api/health is intentionally minimal + // (no process internals), so these stay "--" rather than showing invented numbers. + if (cpuEl) cpuEl.textContent = (data && data.cpu) || '--'; + if (memEl) memEl.textContent = (data && data.memory) || '--'; if (statusVal) { statusVal.textContent = 'Healthy'; statusVal.classList.remove('is-down'); @@ -98,10 +151,15 @@ function setBackendState(online, duration, data) { } } +let telemetryInFlight = false; + async function updateBackendTelemetry() { + // Skip background tabs and overlapping polls (a hung backend must not pile up requests). + if (document.hidden || telemetryInFlight) return; + telemetryInFlight = true; const startTime = performance.now(); try { - const response = await fetch('/api/health'); + const response = await fetch('/api/health', { cache: 'no-store', signal: AbortSignal.timeout(4000) }); const duration = Math.round(performance.now() - startTime); if (!response.ok) throw new Error('Unhealthy response'); @@ -109,11 +167,17 @@ async function updateBackendTelemetry() { setBackendState(true, duration, data); } catch (err) { setBackendState(false); + } finally { + telemetryInFlight = false; } } updateBackendTelemetry(); setInterval(updateBackendTelemetry, 5000); +// Refresh immediately when the user comes back to the tab instead of showing stale status. +document.addEventListener('visibilitychange', () => { + if (!document.hidden) updateBackendTelemetry(); +}); /* ---------------- App version (footer) ---------------- */ async function loadAppVersion() { 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..1c6d818 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,102 @@ const badge = (status) => { return `${escapeHtml(value)}`; }; +/* ---------- sharing: parsed analysis only, never the raw header text ---------- */ + +const EMAIL_RE = + /\b[A-Z0-9._%+-]+@(?:[A-Z0-9](?:[A-Z0-9-]{0,61}[A-Z0-9])?\.)+[A-Z]{2,63}\b/gi; + +const maskEmails = (value) => { + if (typeof value === "string") { + return value.replace(EMAIL_RE, (email) => { + const separator = email.lastIndexOf("@"); + return `***${email.slice(separator)}`; + }); + } + + if (Array.isArray(value)) { + return value.map(maskEmails); + } + + if (value && typeof value === "object") { + return Object.fromEntries( + Object.entries(value).map(([key, val]) => [ + key, + maskEmails(val) + ]) + ); + } + + 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 +112,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 +144,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 +169,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 +182,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 +202,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..1bfc34e --- /dev/null +++ b/frontend/src/features/share.js @@ -0,0 +1,172 @@ +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", () => { + void run(); + }); + + enterOn.forEach((i) => i?.addEventListener("keydown", (e) => { + if (e.key === "Enter") { + e.preventDefault(); + void 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..3d0b437 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,11 +9,20 @@ 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. +// 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 = {}) => { @@ -34,19 +45,21 @@ 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() { + let ok = false; 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; + ok = Boolean(await checkBackend()); } catch { - $("backendStatus").textContent = "Unavailable"; - $("backendDot").className = "status-dot offline"; - return false; + 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; } export function initSMTP() { @@ -57,10 +70,13 @@ export function initSMTP() { const port = $("smtpPort"); const password = $("smtpPassword"); - $("togglePassword")?.addEventListener("click", () => { + const toggle = $("togglePassword"); + toggle?.addEventListener("click", () => { const visible = password.type === "text"; password.type = visible ? "password" : "text"; - $("togglePassword").textContent = visible ? "Show" : "Hide"; + toggle.textContent = visible ? "Show" : "Hide"; + // The visible word alone ("Show") doesn't say what is shown; keep the accessible name in sync. + toggle.setAttribute("aria-label", visible ? "Show password" : "Hide password"); }); security?.addEventListener("change", () => { @@ -68,6 +84,7 @@ export function initSMTP() { }); button.addEventListener("click", async () => { + clearActions("smtpActions"); const fields = [ [$("smtpHost"), "SMTP host is required"], [port, "SMTP port is required"], @@ -88,15 +105,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 +123,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 { @@ -130,32 +146,43 @@ export function initSMTP() { }) }); - const data = await response.json(); - - if (!response.ok && data.stage === "smtp_authentication") { - setFlow("flowSMTP", "error"); - setState("stageSMTP", "error", "SMTP connection or authentication failed."); - showResult("error", "SMTP Authentication Failed", data); + // 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", 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; } - 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 { @@ -164,5 +191,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/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.html b/frontend/src/index.html index a617c59..9a1abbd 100644 --- a/frontend/src/index.html +++ b/frontend/src/index.html @@ -50,31 +50,49 @@ - +
@@ -115,8 +133,8 @@

MailMetrix

SMTP, DNS, DKIM, DMARC and header diagnostics for developers and sysadmins.

@@ -161,7 +179,16 @@

SMTP delivery path

-
+
+ + +
@@ -179,7 +206,7 @@

Verify credentials & test delivery

Server

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

Server

- +
@@ -253,40 +280,20 @@

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

Log
-
+
Enter your SMTP credentials and click Test connection & send email to start.
+
@@ -311,9 +318,8 @@

Inspect email authentication records

-
@@ -324,7 +330,8 @@

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.
+
@@ -349,7 +356,7 @@

Trace email hops & security headers

@@ -359,7 +366,8 @@

Trace email hops & security headers

Parsed results

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

Generate SPF, DKIM & DMARC records

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

Generate SPF, DKIM & DMARC records

@@ -508,12 +516,142 @@

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.
+
+ + + + + + + + +
diff --git a/frontend/src/style.css b/frontend/src/style.css index 2edadc8..2676d4c 100644 --- a/frontend/src/style.css +++ b/frontend/src/style.css @@ -544,7 +544,6 @@ select option { background: var(--surface); color: var(--text); } .dns-input-grid { align-items: end; } .dns-input-grid .test-button { margin-bottom: 0; } -.dns-input-grid .action-field label { visibility: hidden; } /* ================= PIPELINE STAGES ================= */ .stages { display: grid; gap: 8px; position: relative; } @@ -910,7 +909,11 @@ html { align-self: center; margin: 0; } - +.form-group legend { + display: block; padding: 0; margin-bottom: 6px; + color: var(--text-soft); font-size: 12.5px; font-weight: 600; +} +fieldset.form-group { margin: 0; padding: 0; border: 0; min-width: 0; } /* ================= VERSION BADGE (footer) ================= */ .footer-left { align-items: center; } .version-badge { @@ -927,4 +930,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; } +} 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",