diff --git a/.env.example b/.env.example index 445fd1d..c3e1a18 100644 --- a/.env.example +++ b/.env.example @@ -29,4 +29,11 @@ SCORE_TLS_PROBES_PER_HOUR=120 # port 25 by default. Contact your provider to unblock port 25 if live mail server TLS checks fail. # 2. DNSBL / Blacklist checks: Public DNS resolvers (8.8.8.8, 1.1.1.1) are blocked by Spamhaus # and Barracuda. For accurate blacklist checks, configure your VPS host to use a local -# recursive resolver (e.g. Unbound / Bind) instead of public open resolvers. \ No newline at end of file +# recursive resolver (e.g. Unbound / Bind) instead of public open resolvers. + +## Update notifications (checks GitHub for a newer release) +## Set this to your GitHub "owner/repo". Leave it empty or set DISABLE_UPDATE_CHECK=true to turn the feature off. +UPDATE_CHECK_REPO=devindevops/mailmetrix +# DISABLE_UPDATE_CHECK=true +# UPDATE_CHECK_INTERVAL_HOURS=6 +# RATE_LIMIT_VERSION=60 \ No newline at end of file diff --git a/README.md b/README.md index 0051b2b..c3f4135 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. It also includes blacklist checking, a domain deliverability score, a TLS certificate inspector, and shareable, exportable results. +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. An optional update notice tells you when a new release is published. Run MailMetrix in your own environment and maintain control over how you deploy and access your email diagnostic tools. @@ -31,6 +31,7 @@ Self-hosting helps reduce dependence on third-party diagnostic services, but it - **Modular:** Keep backend routes, services, and frontend feature logic separated. - **Practical:** Bring commonly used email diagnostics into one interface. - **Hardened by default:** Outbound-connection guardrails, rate limiting, security headers, and non-root containers are built in. +- **Stay current:** An optional in-app notice tells you when a new release is available, and it can be turned off. - **Transparent:** Inspect the source code, report issues, and contribute improvements. ## Features @@ -132,6 +133,8 @@ Content-Type: application/json `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. +Each score run is bounded by configurable limits on DNS queries per run, concurrent runs, hourly blacklist and TLS probes, and total run time (see the `SCORE_*` settings under [Configuration](#configuration)). + **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 @@ -178,6 +181,42 @@ Notes: - 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. +### 9. Update Notifications + +MailMetrix can tell you when a newer release is available, so a self-hosted instance does not quietly fall behind. The check is on by default and can be turned off. + +How it works: + +1. When the page loads, the frontend reads its own version from `frontend/src/version.json` and asks the backend whether a newer release exists (`GET /api/version/check`). +2. The backend asks GitHub's API for the latest published release of the project and caches the answer in memory (6 hours by default; after a failed lookup it retries after 15 minutes). Your browser never contacts GitHub directly. +3. If the latest release is newer than the installed version, the interface shows a banner ("MailMetrix vX.Y.Z is ready") with a link to the release, and an **Update available** badge next to the version in the footer. +4. Dismissing the banner hides it for that version only (remembered in your browser). The footer badge stays, and the banner returns when an even newer release is published. + +```http +GET /api/version/check +``` + +```json +{ + "enabled": true, + "latest": "1.2.0", + "releaseUrl": "https://github.com/devindevops/mailmetrix/releases/tag/v1.2.0", + "publishedAt": "2026-11-16T00:00:00Z", + "checkedAt": "2026-11-17T04:00:00.000Z" +} +``` + +When the check is turned off, or no release is available yet, `enabled` is `false` or `latest` is `null`, and no notice is shown. + +Notes: + +- Only a **published GitHub Release** counts. A bare git tag, a draft, or a pre-release does not trigger the notice. Release tags must look like `1.2.0` or `v1.2.0`. +- Versions are compared numerically, so `1.10.0` is correctly newer than `1.9.0`. +- The check never gets in the way. If the server is offline, GitHub is unreachable or rate limiting, or the check is disabled, no notice is shown and nothing else is affected. +- The backend sends a plain request for the public latest-release data. No diagnostic data, credentials, or user input is sent (see [Understand external connections](#understand-external-connections)). +- To turn it off, set `DISABLE_UPDATE_CHECK=true` in `.env`. A fork can point the check at its own repository with `UPDATE_CHECK_REPO=owner/repo`, and a private repository also needs `GITHUB_TOKEN`. See [Configuration](#configuration). +- The notice only tells you that an update exists. It does not update anything; see [Updating MailMetrix](#updating-mailmetrix). + ## Architecture MailMetrix separates the backend API from the frontend application. @@ -194,15 +233,16 @@ backend/ ├── package-lock.json └── src ├── routes - │ ├── _util.js - │ ├── blacklist.js - │ ├── dns.js - │ ├── generator.js - │ ├── headers.js - │ ├── score.js - │ ├── share.js - │ ├── smtp.js - │ └── tls.js + │   ├── blacklist.js + │   ├── dns.js + │   ├── generator.js + │   ├── headers.js + │   ├── score.js + │   ├── share.js + │   ├── smtp.js + │   ├── tls.js + │   ├── _util.js + │   └── version.js ├── server.js └── services ├── blacklist.js @@ -213,7 +253,8 @@ backend/ ├── score.js ├── share.js ├── smtp.js - └── tls.js + ├── tls.js + └── version.js ``` ### Frontend @@ -225,26 +266,28 @@ 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 + │   ├── blacklist.js + │   ├── dns.js + │   ├── flow.js + │   ├── generator.js + │   ├── headers.js + │   ├── mobile-nav.js + │   ├── renderers.js + │   ├── score.js + │   ├── share.js + │   ├── smtp.js + │   ├── tabs.js + │   ├── tls.js + │   ├── ui.js + │   ├── update.js + │   └── utils.js ├── icons - │ ├── android-chrome-192x192.png - │ ├── android-chrome-512x512.png - │ ├── apple-touch-icon.png - │ ├── favicon-16x16.png - │ ├── favicon-32x32.png - │ └── favicon.ico + │   ├── android-chrome-192x192.png + │   ├── android-chrome-512x512.png + │   ├── apple-touch-icon.png + │   ├── favicon-16x16.png + │   ├── favicon-32x32.png + │   └── favicon.ico ├── index.html ├── sitemap.xml ├── site.webmanifest @@ -252,6 +295,22 @@ frontend/ └── version.json ``` +### Github Page for Project Website + +```text +docs/ +├── assets +│   └── screenshots +│   ├── blacklist-check.png +│   ├── deliverability-score.png +│   ├── dkim-dmarc-generator.png +│   ├── dns-checker.png +│   ├── header-analyzer.png +│   ├── smtp-tester.png +│   └── tls-inspector.png +└── index.html +``` + `server.js` and `app.js` serve as the backend and frontend bootstrap/orchestration files. Backend routes and services separate API handling from feature logic. Frontend feature modules organize the corresponding user-interface behavior. @@ -262,6 +321,8 @@ 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`. +- `backend/src/services/version.js` looks up the latest GitHub release and caches it, and `frontend/src/features/update.js` compares it with `version.json` and shows the update banner and footer badge (see [Update Notifications](#9-update-notifications)). +- `frontend/src/features/mobile-nav.js` collapses the tool list behind a menu button on small screens; on desktop the sidebar is unchanged. ## Version Management @@ -276,7 +337,7 @@ When executed through npm's `version` lifecycle hook, the script synchronizes th | File | Purpose | |---|---| | `package.json` | Defines the source version | -| `frontend/src/version.json` | Provides version information to the frontend footer | +| `frontend/src/version.json` | Provides version information to the frontend footer and to the update check | | `backend/package.json` | Keeps the backend package version synchronized | | `backend/package-lock.json` | Updates the backend lockfile version metadata | @@ -341,6 +402,8 @@ If the `version` script already exists, integrate the command into the existing - Review the generated changes before publishing. - Confirm that the frontend footer displays the updated version. - Ensure the backend package and lockfile remain synchronized. +- Publish a **GitHub Release** for each version, using a tag such as `1.2.0` or `v1.2.0` that matches the version in `package.json`. Running instances learn about new versions from the latest published release, so a bare git tag, a draft, or a pre-release does not notify anyone (see [Update Notifications](#9-update-notifications)). +- Make sure the build you publish contains the matching `frontend/src/version.json`. Otherwise an instance running that build would keep reporting the older version and keep showing the update notice. The script updates local project files; it does not publish Docker images, create a GitHub Release, or deploy the application by itself. @@ -428,6 +491,18 @@ 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. +### Updating MailMetrix + +When the in-app update notice (see [Update Notifications](#9-update-notifications)) says a new release is available, review its release notes, then fetch the new source and rebuild: + +```bash +git pull +docker compose build +docker compose up -d +``` + +To run a specific release instead of the latest commit, check out its tag before building (for example `git fetch --tags && git checkout v1.2.0`). Shared results stay in the `mailmetrix-data` volume across rebuilds. Review `.env.example` after updating in case new settings were added. + ### Development with Docker Compose Watch If your Docker Compose configuration defines file-watch actions, you can use: @@ -447,6 +522,7 @@ The following endpoints are currently documented by the project. | Method | Endpoint | Purpose | |---|---|---| | `GET` | `/api/health` | Minimal liveness probe (returns only a status) | +| `GET` | `/api/version/check` | Report the latest published GitHub release, so the interface can show an update notice (see [Update Notifications](#9-update-notifications)) | | `POST` | `/api/smtp/test` | Run an SMTP test | | `GET` | `/api/dns/check?domain=example.com` | Check email-related DNS records | | `GET` | `/api/dns/dkim?domain=example.com&selector=google` | Check a DKIM selector | @@ -493,13 +569,14 @@ MailMetrix is designed to support self-hosted email diagnostics. Deploy it with | **Outbound connection abuse (SSRF)** | The SMTP test resolves the target host once, validates every returned address, and connects only to the validated IP, which mitigates DNS-rebinding. Loopback, private (RFC 1918), CGNAT, link-local (including the `169.254.169.254` cloud metadata address), multicast, and reserved ranges are blocked, including IPv6 and IPv4-mapped forms. Ports are limited to `25`, `465`, `587`, and `2525` by default. | | **Port-scanning oracle** | Network-level SMTP failures (refused, timeout, reset) return one generic message, so responses cannot be used to map internal hosts. Genuine SMTP protocol errors, such as rejected credentials, are still reported. | | **Email abuse** | From and Recipient must each be a single valid address; address lists, `Name ` forms, and header-injection attempts are rejected. Display names cannot add recipients. Subject is limited to 200 characters and message to 5,000. Optional recipient-domain restrictions are available. | -| **Rate limiting** | Per-IP limits on every API route, with stricter limits for the SMTP, generator, and DNS endpoints. | -| **Resource exhaustion** | DKIM key generation runs off the main thread with a concurrency cap and a bounded queue; excess requests receive `503` instead of stalling the server. | +| **Rate limiting** | Per-IP limits on every API route, with stricter limits for the SMTP, generator, DNS, blacklist, score, and TLS endpoints. | +| **Resource exhaustion** | DKIM key generation runs off the main thread with a concurrency cap and a bounded queue; excess requests receive `503` instead of stalling the server. Deliverability scoring is also bounded by configurable limits on DNS queries per run, concurrent runs, hourly blacklist and TLS probes, and total run time (the `SCORE_*` settings). | | **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. | +| **Update check** | The backend, not the browser, contacts GitHub, with a short timeout, a cached result, and no user input in the request. Only plain release tags such as `1.2.0` are accepted, only `https://github.com/` release links are shown, text is rendered as escaped text, and a failed lookup never affects the rest of the application. The check has its own rate limit and can be disabled with `DISABLE_UPDATE_CHECK=true`. | These controls reduce risk but do **not** replace authentication. Please read the limitations below. @@ -559,7 +636,7 @@ Then: - Put authentication in front of the application (see above) before exposing it to any untrusted network. - Use HTTPS when accessing the application remotely. If TLS terminates in front of the Nginx container, enable `Strict-Transport-Security` there. - Set `TRUST_PROXY` correctly so rate limiting identifies real client addresses (see [Configuration](#configuration)). -- Keep Docker, the host operating system, base images, and application dependencies updated. Pinned image tags do not update themselves; consider Renovate or Dependabot to propose bumps. +- Keep Docker, the host operating system, base images, and application dependencies updated. Pinned image tags do not update themselves; consider Renovate or Dependabot to propose bumps. MailMetrix itself shows an in-app notice when a new release is published (see [Update Notifications](#9-update-notifications)). - Do not publish the backend port. The default Compose file uses `expose`, not `ports`, for the backend; keep it that way, because `TRUST_PROXY` and the internal-only health endpoint assume that Nginx is the only way in. - If other services share the Compose network, consider placing them on a separate network so a compromised or misconfigured container cannot reach MailMetrix's backend directly. - Review the application's logging and error-handling behavior before processing sensitive information. @@ -587,6 +664,7 @@ For example: - 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. +- The update check makes a request from the backend to GitHub's API (`api.github.com`) to read the latest release of the project. It sends no diagnostic data or user input, and your browser does not contact GitHub for it. GitHub can see the request's source address. Turn it off with `DISABLE_UPDATE_CHECK=true` if your environment should make no such connection. Review the source code to understand which services receive requests or data during each operation. @@ -631,6 +709,7 @@ All of the following are optional. Add them to `.env` (or the backend `environme | `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. | +| `RATE_LIMIT_VERSION` | `60` | Max update-check 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. | @@ -639,6 +718,10 @@ All of the following are optional. Add them to `.env` (or the backend `environme | `ENFORCE_TEST_RECIPIENT` | `false` | When `true`, the test email may only be sent to the From address. | | `DKIM_MAX_CONCURRENT` | `2` | Maximum simultaneous DKIM key generations. | | `DKIM_MAX_QUEUE` | `10` | Maximum queued key generations before returning `503`. | +| `DISABLE_UPDATE_CHECK` | `false` | Set to `true` to turn off the update check. The backend then makes no request to GitHub and no update notice is shown. | +| `UPDATE_CHECK_REPO` | `devindevops/mailmetrix` | GitHub `owner/repo` whose latest release is checked. Set it only if you maintain a fork. | +| `UPDATE_CHECK_INTERVAL_HOURS` | `6` | How long the backend caches the latest-release answer before asking GitHub again. | +| `GITHUB_TOKEN` | *(empty)* | Only needed if `UPDATE_CHECK_REPO` points at a private repository. Needs read access to releases. Never commit it. | Example for a shared or internet-adjacent deployment: @@ -649,6 +732,29 @@ ENFORCE_TEST_RECIPIENT=true RATE_LIMIT_SMTP=10 ``` +Example for an environment that should make no outbound call to GitHub: + +```dotenv +DISABLE_UPDATE_CHECK=true +``` + +### Advanced share and score limits + +These tune how much the share store and the deliverability score may use. The values shown are example values from a sample `.env`, not guaranteed defaults; check `.env.example` and the backend code before relying on them. + +| Variable | Example value | Purpose | +|---|---|---| +| `SHARE_PER_IP_DAILY` | `30` | Maximum number of share links one client IP can create per day. | +| `SHARE_MAX_TOTAL_MB` | `512` | Maximum total size, in MB, of stored shared results. | +| `SHARE_MAX_FILES` | `5000` | Maximum number of stored shared results. | +| `SCORE_CACHE_TTL_SECONDS` | `300` | How long, in seconds, a deliverability score is cached. | +| `SCORE_TARGET_TTL_SECONDS` | `900` | Per-domain time window, in seconds, applied to repeated scoring requests. | +| `SCORE_MAX_DNS_QUERIES` | `80` | Maximum DNS queries a single score run may issue. | +| `SCORE_DEADLINE_SECONDS` | `25` | Maximum total time, in seconds, for one score run. | +| `SCORE_MAX_CONCURRENT` | `8` | Maximum score runs processed at the same time. | +| `SCORE_DNSBL_IPS_PER_HOUR` | `300` | Maximum IP addresses the score may check against blacklists per hour. | +| `SCORE_TLS_PROBES_PER_HOUR` | `120` | Maximum TLS probes the score may make per hour. | + Keep `.env.example` in sync with this list when you add or change settings. ## Quality and Security Checks @@ -666,7 +772,7 @@ These checks reduce risk but do not guarantee that the software is free of vulne ## Privacy Policy -*Last updated: 11 November 2026* +*Last updated: 17 November 2026* ### In short @@ -674,7 +780,7 @@ These checks reduce risk but do not guarantee that the software is free of vulne - 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. +- Data leaves your instance only to destinations **you** specify, such as the SMTP server you test and DNS resolvers. The one other connection is the optional update check, which asks GitHub's API for the project's latest release without sending any of your data, and which you can turn off with `DISABLE_UPDATE_CHECK=true`. ### Scope and responsibility @@ -690,6 +796,7 @@ This policy applies to the MailMetrix software and to the project's GitHub Pages | 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. | +| Update check (latest release information) | To tell you when a newer MailMetrix release is available. | The backend requests the public latest-release data from GitHub's API. The request carries no user input or diagnostic data; GitHub can see the server's source address and a `mailmetrix-update-check` User-Agent. The answer is cached in memory (6 hours by default) and not written to disk. The browser remembers only which version's banner you dismissed, in its local storage. Disabled with `DISABLE_UPDATE_CHECK=true`. | | 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. | @@ -704,11 +811,12 @@ This policy applies to the MailMetrix software and to the project's GitHub Pages - 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. +- The update check contacts GitHub's API from your backend to read the project's latest release. GitHub handles that request under [its privacy statement](https://docs.github.com/en/site-policy/privacy-policies/github-general-privacy-statement). No data from your diagnostics is included, and you can turn the check off. - Your hosting provider, network, or reverse proxy can observe traffic to your instance. Use HTTPS for remote access. ### Cookies and browser storage -The MailMetrix web interface is designed not to use tracking cookies or third-party scripts. If you add authentication or other components in front of it, those may set their own cookies, which are your responsibility. +The MailMetrix web interface is designed not to use tracking cookies or third-party scripts. It keeps a few harmless preferences in your browser's local storage, such as the chosen light or dark theme and which update notice you dismissed. If you add authentication or other components in front of it, those may set their own cookies, which are your responsibility. ### The project website @@ -721,6 +829,7 @@ The MailMetrix GitHub Pages site is a static page. It does not use analytics, co - 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. +- Set `DISABLE_UPDATE_CHECK=true` if your instance should not contact GitHub. - Do not post credentials, private keys, or personal data in public issues. ### Changes to this policy diff --git a/backend/package-lock.json b/backend/package-lock.json index 3bc0087..9071a33 100644 --- a/backend/package-lock.json +++ b/backend/package-lock.json @@ -1,12 +1,12 @@ { "name": "MailMetrix-backend", - "version": "1.2.0", + "version": "1.2.1", "lockfileVersion": 3, "requires": true, "packages": { "": { "name": "MailMetrix-backend", - "version": "1.2.0", + "version": "1.2.1", "dependencies": { "dotenv": "^18.0.7", "express": "^5.3.0", diff --git a/backend/package.json b/backend/package.json index 93c223d..006b721 100644 --- a/backend/package.json +++ b/backend/package.json @@ -1,6 +1,6 @@ { "name": "MailMetrix-backend", - "version": "1.2.0", + "version": "1.2.1", "description": "MailMetrix SMTP and email infrastructure diagnostics backend", "main": "src/server.js", "scripts": { diff --git a/backend/src/routes/version.js b/backend/src/routes/version.js new file mode 100644 index 0000000..b9f28f9 --- /dev/null +++ b/backend/src/routes/version.js @@ -0,0 +1,18 @@ +"use strict"; + +const express = require("express"); +const { getLatestRelease } = require("../services/version"); + +const router = express.Router(); + +// GET /version/check (also reachable as /api/version/check, see server.js) +router.get("/check", async (_req, res, next) => { + try { + res.set("Cache-Control", "no-store"); + res.json(await getLatestRelease()); + } catch (err) { + next(err); + } +}); + +module.exports = router; \ No newline at end of file diff --git a/backend/src/server.js b/backend/src/server.js index 0e5c641..0a05369 100644 --- a/backend/src/server.js +++ b/backend/src/server.js @@ -12,8 +12,9 @@ const blacklistRoutes = require("./routes/blacklist"); const scoreRoutes = require("./routes/score"); const tlsRoutes = require("./routes/tls"); const shareRoutes = require("./routes/share"); +const versionRoutes = require("./routes/version"); -const app = express(); +const app = express(); app.disable("x-powered-by"); // don't advertise "X-Powered-By: Express" on every response const PORT = Number(process.env.PORT || 4000); @@ -105,6 +106,13 @@ const shareLimiter = createLimiter( "Share limit reached. Please try again later." ); +// Update check: answered from an in-memory cache (GitHub is contacted at most every +// few hours), so this is cheap, but it is public and runs on every page load. +const versionLimiter = createLimiter( + positiveInt(process.env.RATE_LIMIT_VERSION, 60), + "Too many requests, please try again later." +); + // HTTP request logging (registered first so 429 responses are logged too). app.use((req, res, next) => { const startTime = Date.now(); @@ -130,6 +138,8 @@ app.use("/blacklist", blacklistLimiter); app.use("/score", scoreLimiter); app.use("/tls", tlsLimiter); app.use("/share", shareLimiter); +app.use("/version", versionLimiter); +app.use("/api/version", versionLimiter); // Share allows larger payloads (up to 300kb) and parses its own body, so it // must be mounted BEFORE the global 100kb parser below. @@ -160,14 +170,22 @@ app.get("/", (_req, res) => { // ("backend" is kept only so a UI that checks it for a status badge keeps // working; it carries no sensitive information.) function healthHandler(_req, res) { + res.set("Cache-Control", "no-store"); + res.status(200).json({ status: "healthy", - backend: "connected" + backend: "connected", + uptimeSeconds: Math.round(process.uptime()), + cpuPercent: sampleCpuPercent(), + memory: { + rssMb: toMb(process.memoryUsage().rss), + heapUsedMb: toMb(process.memoryUsage().heapUsed), + heapTotalMb: toMb(process.memoryUsage().heapTotal) + } }); } app.get("/health", healthHandler); -// Also map /api/health to the same handler if your frontend polls /api/health app.get("/api/health", healthHandler); // INTERNAL telemetry: for monitoring from inside the Docker network only. @@ -240,6 +258,22 @@ app.get("/internal/health", (req, res, next) => { }); }); +app.get("/api/telemetry", (req, res) => { + if (!isInternalRequest(req)) { + return res.status(404).end(); + } + + res.set("Cache-Control", "no-store"); + + res.json({ + status: "healthy", + cpuPercent: sampleCpuPercent(), + memory: { + rssMb: toMb(process.memoryUsage().rss) + } + }); +}); + // Application routes. app.use("/smtp", smtpRoutes); app.use("/dns", dnsRoutes); @@ -249,6 +283,11 @@ app.use("/blacklist", blacklistRoutes); app.use("/score", scoreRoutes); app.use("/tls", tlsRoutes); +// Update check. Mounted at both paths because the frontend calls /api/version/check and +// nginx may or may not strip the /api prefix (same reason /api/health exists above). +app.use("/version", versionRoutes); +app.use("/api/version", versionRoutes); + // Handle unmatched routes. app.use((req, res) => { res.status(404).json({ diff --git a/backend/src/services/version.js b/backend/src/services/version.js new file mode 100644 index 0000000..1f26f68 --- /dev/null +++ b/backend/src/services/version.js @@ -0,0 +1,111 @@ +"use strict"; + +/* ------------------------------------------------------------------ */ +/* Update check */ +/* */ +/* Asks GitHub for the latest published release of this project and */ +/* caches the answer, so the browser never talks to GitHub itself and */ +/* GitHub's unauthenticated rate limit (60 req/h per IP) is never hit. */ +/* */ +/* The backend only reports what the latest release is. The frontend */ +/* compares it against the version it was built with (version.json). */ +/* */ +/* Config (all optional except the repo): */ +/* UPDATE_CHECK_REPO "owner/repo" on GitHub */ +/* DISABLE_UPDATE_CHECK "true" to turn the feature off */ +/* UPDATE_CHECK_INTERVAL_HOURS cache lifetime, default 6 */ +/* GITHUB_TOKEN only needed for a private repo */ +/* ------------------------------------------------------------------ */ + +const REPO = (process.env.UPDATE_CHECK_REPO || "").trim(); +const DISABLED = + String(process.env.DISABLE_UPDATE_CHECK || "").trim().toLowerCase() === "true"; +const REPO_RE = /^[A-Za-z0-9_.-]+\/[A-Za-z0-9_.-]+$/; +const ENABLED = !DISABLED && REPO_RE.test(REPO); + +if (!DISABLED && !ENABLED) { + console.warn( + "Update check is off: set UPDATE_CHECK_REPO to \"owner/repo\" (or DISABLE_UPDATE_CHECK=true to silence this)." + ); +} + +const intervalHours = Number(process.env.UPDATE_CHECK_INTERVAL_HOURS); +const TTL_OK_MS = + (Number.isFinite(intervalHours) && intervalHours > 0 ? intervalHours : 6) * + 60 * 60 * 1000; +const TTL_FAIL_MS = 15 * 60 * 1000; // after a failure, retry sooner but not on every page load +const TIMEOUT_MS = 5000; + +// Plain releases only (1.1.0 or v1.1.0). GitHub's /releases/latest already skips +// drafts and pre-releases; this also ignores odd tags such as "1.1.0-rc1". +const SEMVER_RE = /^v?(\d+)\.(\d+)\.(\d+)$/; + +let cache = { at: 0, ttl: 0, data: null }; +let inflight = null; + +async function fetchLatest() { + const headers = { + "User-Agent": "mailmetrix-update-check", + Accept: "application/vnd.github+json" + }; + if (process.env.GITHUB_TOKEN) { + headers.Authorization = `Bearer ${process.env.GITHUB_TOKEN}`; + } + + const res = await fetch(`https://api.github.com/repos/${REPO}/releases/latest`, { + headers, + signal: AbortSignal.timeout(TIMEOUT_MS) + }); + + if (res.status === 404) return null; // no published release yet + if (!res.ok) throw new Error(`GitHub API responded ${res.status}`); + + const json = await res.json(); + const m = SEMVER_RE.exec(String(json.tag_name || "").trim()); + if (!m) return null; + + const url = typeof json.html_url === "string" ? json.html_url : ""; + return { + latest: `${m[1]}.${m[2]}.${m[3]}`, + releaseUrl: url.startsWith("https://github.com/") ? url : null, + publishedAt: typeof json.published_at === "string" ? json.published_at : null + }; +} + +async function getLatestRelease() { + const base = { + enabled: ENABLED, + latest: null, + releaseUrl: null, + publishedAt: null, + checkedAt: null + }; + if (!ENABLED) return base; + + if (Date.now() - cache.at >= cache.ttl) { + // One shared request even if many browsers load the page at the same moment. + if (!inflight) { + inflight = fetchLatest() + .then((data) => { + cache = { at: Date.now(), ttl: TTL_OK_MS, data }; + }) + .catch((err) => { + // Keep serving the last good answer; an update check must never break the app. + console.warn("Update check failed:", err.message); + cache = { at: Date.now(), ttl: TTL_FAIL_MS, data: cache.data }; + }) + .finally(() => { + inflight = null; + }); + } + await inflight; + } + + return { + ...base, + ...(cache.data || {}), + checkedAt: cache.at ? new Date(cache.at).toISOString() : null + }; +} + +module.exports = { getLatestRelease }; \ No newline at end of file diff --git a/docs/assets/screenshots/blacklist-check.png b/docs/assets/screenshots/blacklist-check.png new file mode 100644 index 0000000..848f56c Binary files /dev/null and b/docs/assets/screenshots/blacklist-check.png differ diff --git a/docs/assets/screenshots/deliverability-score.png b/docs/assets/screenshots/deliverability-score.png new file mode 100644 index 0000000..242dab2 Binary files /dev/null and b/docs/assets/screenshots/deliverability-score.png differ diff --git a/docs/assets/screenshots/dkim-dmarc-generator.png b/docs/assets/screenshots/dkim-dmarc-generator.png index 59efba6..2e9218a 100644 Binary files a/docs/assets/screenshots/dkim-dmarc-generator.png and b/docs/assets/screenshots/dkim-dmarc-generator.png differ diff --git a/docs/assets/screenshots/dns-checker.png b/docs/assets/screenshots/dns-checker.png index d2e5028..0a50d5d 100644 Binary files a/docs/assets/screenshots/dns-checker.png and b/docs/assets/screenshots/dns-checker.png differ diff --git a/docs/assets/screenshots/header-analyzer.png b/docs/assets/screenshots/header-analyzer.png index d537aca..2651d7f 100644 Binary files a/docs/assets/screenshots/header-analyzer.png and b/docs/assets/screenshots/header-analyzer.png differ diff --git a/docs/assets/screenshots/smtp-tester.png b/docs/assets/screenshots/smtp-tester.png index fe64fa2..5f678aa 100644 Binary files a/docs/assets/screenshots/smtp-tester.png and b/docs/assets/screenshots/smtp-tester.png differ diff --git a/docs/assets/screenshots/tls-inspector.png b/docs/assets/screenshots/tls-inspector.png new file mode 100644 index 0000000..21ce5ec Binary files /dev/null and b/docs/assets/screenshots/tls-inspector.png differ diff --git a/docs/index.html b/docs/index.html index 19227a2..8f8fab3 100644 --- a/docs/index.html +++ b/docs/index.html @@ -8,7 +8,7 @@ MailMetrix — Self-Hosted Email Diagnostics - + @@ -71,7 +71,7 @@ /* marquee */ .marquee{overflow:hidden;border-block:1px solid var(--border);background:rgba(18,26,44,.5);padding:14px 0;white-space:nowrap;-webkit-mask-image:linear-gradient(90deg,transparent,#000 12%,#000 88%,transparent);mask-image:linear-gradient(90deg,transparent,#000 12%,#000 88%,transparent)} -.track{display:inline-flex;width:max-content;animation:scroll 30s linear infinite;color:var(--muted);font-size:.8rem;font-weight:700;letter-spacing:.1em;text-transform:uppercase} +.track{display:inline-flex;width:max-content;animation:scroll 42s linear infinite;color:var(--muted);font-size:.8rem;font-weight:700;letter-spacing:.1em;text-transform:uppercase} .track span{padding:0 26px} .track span::before{content:"✦";margin-right:52px;color:var(--accent)} @keyframes scroll{to{transform:translateX(-50%)}} @@ -85,6 +85,10 @@ .subhead::before,.subhead::after{content:"";flex:1;height:1px;background:linear-gradient(90deg,transparent,var(--border))} .subhead::after{background:linear-gradient(270deg,transparent,var(--border))} .grid{display:grid;grid-template-columns:repeat(2,minmax(0,1fr));gap:18px} +/* a lone last card in a two-column grid sits centered at normal card width */ +.grid:not(.grid-one)>.card:last-child:nth-child(odd){grid-column:1/-1;justify-self:center;width:calc(50% - 9px)} +/* a grid with a single card */ +.grid-one{grid-template-columns:minmax(0,720px);justify-content:center} .card{position:relative;overflow:hidden;min-width:0;padding:28px 24px;background:var(--surface);border:1px solid var(--border);border-radius:16px;transition:transform .3s var(--ease),border-color .3s,box-shadow .3s} .card::before{content:"";position:absolute;inset:0;pointer-events:none;opacity:0;transition:opacity .3s;background:radial-gradient(280px circle at var(--mx,50%) var(--my,0),rgba(112,225,193,.15),transparent 70%)} .card::after{content:"";position:absolute;top:0;left:20%;right:20%;height:1px;background:linear-gradient(90deg,transparent,var(--accent),transparent);opacity:.55} @@ -102,6 +106,34 @@ .notice{max-width:800px;margin:26px auto 0;padding:18px 22px;border:1px solid rgba(255, 0, 0, 0.541);border-radius:60px;background:var(--surface);color:var(--muted)} .notice a{color:var(--accent)} +/* update banner preview: a coded mock of the in-app banner (no screenshot needed) */ +.ud-window{margin-bottom:22px;overflow:hidden;text-align:left;background:#0b0d14;border:1px solid var(--border);border-radius:12px;box-shadow:0 30px 60px -34px rgba(79,70,229,.55)} +.ud-bar{display:flex;align-items:center;gap:7px;padding:11px 14px;border-bottom:1px solid var(--border);background:#0c1220} +.ud-bar i{width:10px;height:10px;border-radius:50%;background:#ff5f57} +.ud-bar i:nth-child(2){background:#febc2e} +.ud-bar i:nth-child(3){background:#28c840} +.ud-tag{margin-left:auto;padding:1px 9px;border:1px solid var(--border);border-radius:999px;color:var(--muted);font-size:.68rem;font-weight:700;letter-spacing:.08em;text-transform:uppercase} +.ud-stage{padding:18px 16px 14px;background-image:linear-gradient(rgba(255,255,255,.035) 1px,transparent 1px),linear-gradient(90deg,rgba(255,255,255,.035) 1px,transparent 1px);background-size:40px 40px} +.ud-banner{position:relative;isolation:isolate;display:flex;align-items:center;gap:14px;padding:14px 12px 14px 16px;border-radius:14px;overflow:hidden;background:radial-gradient(120% 140% at 0% 0%,rgba(124,131,255,.2),transparent 55%),radial-gradient(90% 120% at 100% 100%,rgba(168,85,247,.14),transparent 60%),#131622;box-shadow:0 14px 36px -16px rgba(124,131,255,.55)} +.ud-banner::before{content:"";position:absolute;inset:0;z-index:-1;padding:1px;border-radius:inherit;background:linear-gradient(120deg,#6366f1,#a855f7 45%,#38bdf8);-webkit-mask:linear-gradient(#000 0 0) content-box,linear-gradient(#000 0 0);-webkit-mask-composite:xor;mask:linear-gradient(#000 0 0) content-box exclude,linear-gradient(#000 0 0);opacity:.9} +.ud-banner::after{content:"";position:absolute;top:0;bottom:0;left:-40%;z-index:-1;width:40%;background:linear-gradient(100deg,transparent,rgba(255,255,255,.14),transparent);transform:skewX(-18deg);animation:udsheen 6s ease-in-out infinite;pointer-events:none} +@keyframes udsheen{0%{left:-40%}45%,100%{left:120%}} +.ud-icon{position:relative;display:grid;place-items:center;width:42px;height:42px;flex:0 0 42px;border-radius:13px;color:#fff;background:linear-gradient(135deg,#6366f1,#a855f7);box-shadow:0 8px 18px -6px rgba(99,102,241,.65),inset 0 1px 0 rgba(255,255,255,.3)} +.ud-icon::after{content:"";position:absolute;inset:-5px;border-radius:17px;border:1px solid rgba(124,131,255,.45);animation:udring 2.6s ease-out infinite} +@keyframes udring{0%{opacity:.9;transform:scale(.92)}70%,100%{opacity:0;transform:scale(1.18)}} +.ud-text{flex:1;min-width:0} +.ud-head{display:flex;align-items:center;flex-wrap:wrap;gap:6px 10px} +.ud-badge{padding:2px 9px;border-radius:999px;color:#fff;background:linear-gradient(135deg,#6366f1,#a855f7);font-size:.62rem;font-weight:700;letter-spacing:.07em;text-transform:uppercase;line-height:1.6} +.ud-head strong{color:#e9ecf5;font-size:.95rem;font-weight:650;letter-spacing:-.01em} +.ud-text p{margin:3px 0 0;color:#a4adc4;font-size:.82rem;line-height:1.45} +.ud-btn{display:inline-flex;align-items:center;gap:6px;padding:8px 14px;border-radius:10px;color:#fff;background:linear-gradient(135deg,#6366f1,#7c3aed);box-shadow:0 8px 18px -8px rgba(99,102,241,.75),inset 0 1px 0 rgba(255,255,255,.25);font-size:.8rem;font-weight:700;white-space:nowrap} +.ud-x{padding:0 4px;color:#6b758f;font-size:1.2rem;line-height:1} +.ud-foot{display:flex;flex-wrap:wrap;align-items:center;gap:8px;padding:16px 2px 0;color:#6b758f;font-size:.74rem} +.ud-foot b{color:#e9ecf5} +.ud-ver{padding:1px 8px;border:1px solid #323959;border-radius:999px;background:#0e111b;color:#a4adc4;font:600 .72rem ui-monospace,SFMono-Regular,Consolas,monospace} +.ud-chip{display:inline-flex;align-items:center;gap:6px;padding:1px 9px 1px 8px;border:1px solid rgba(124,131,255,.3);border-radius:999px;background:rgba(124,131,255,.13);color:#7c83ff;font-weight:700} +.ud-chip::before{content:"";width:6px;height:6px;border-radius:50%;background:currentColor;animation:pulse 2s infinite} + /* architecture */ .architecture{display:grid;grid-template-columns:1fr auto 1fr;align-items:center;gap:16px;max-width:860px;margin:0 auto} .architecture .card{height:100%;display:grid;align-content:center} @@ -135,6 +167,10 @@ .hero{padding:70px 0 55px} section{padding:55px 0} .grid,.architecture{grid-template-columns:1fr} +.grid:not(.grid-one)>.card:last-child:nth-child(odd){grid-column:auto;justify-self:stretch;width:auto} +.ud-banner{flex-wrap:wrap} +.ud-text{flex-basis:calc(100% - 60px)} +.ud-btn{flex:1;justify-content:center} .flow{width:2px;height:56px;margin:auto} .flow::after{top:0;left:-4px;animation-name:dotv} } @@ -174,7 +210,7 @@ OPEN SOURCE · SELF-HOSTED

Email diagnostics.
Under your control.

- Test SMTP connectivity, inspect email authentication records, analyze message headers, and generate DKIM/DMARC configuration material with a self-hosted toolkit built for developers and system administrators. + Test SMTP connectivity, inspect email authentication records, analyze message headers, generate DKIM/DMARC configuration material, check blacklists, grade deliverability, and inspect TLS certificates with a self-hosted toolkit built for developers and system administrators.

Explore on GitHub @@ -185,6 +221,7 @@

Email diagnostics.
Under your control.

🐳 Docker Compose 🛡️ Built-in safeguards 📦 Non-root containers + 🔔 Update notifications 🔓 Open source

Build locally with Docker Compose. No public demo instance required.

@@ -193,8 +230,8 @@

Email diagnostics.
Under your control.

@@ -213,7 +250,7 @@

Self-hosted by design

Focused email diagnostics

-

Access common SMTP, DNS, header-analysis, and authentication-generation tools in one interface.

+

Access common SMTP, DNS, header-analysis, authentication-generation, blacklist, deliverability, and TLS tools in one interface.

@@ -225,7 +262,7 @@

Focused email diagnostics

-

Four tools. One self-hosted workspace.

+

Seven tools. One self-hosted workspace.

Explore the tools available in MailMetrix.

@@ -249,6 +286,46 @@

03. Email Header Analyzer

04. DKIM & DMARC Generator

Generate email authentication configuration material for review and deployment. Key generation runs off the main thread with a concurrency limit.

+
+ MailMetrix Blacklist Check interface +

05. Blacklist Check

+

See whether a sending IPv4 address or domain is listed on major DNS blacklists, including Spamhaus, Barracuda, and SpamCop, with results from 12 lists in one run.

+
+
+ MailMetrix Deliverability Score interface +

06. Deliverability Score

+

Combine MX, SPF, DKIM, DMARC, reverse DNS, blacklists, MTA-STS, and TLS into a single A–F grade for your domain, with prioritised fixes.

+
+
+ MailMetrix TLS Inspector interface +

07. TLS Inspector

+

Negotiate STARTTLS or implicit TLS with a mail server and review its certificate chain, expiry, hostname match, protocol, and cipher. Optionally probe which TLS versions it supports.

+
+
+ +

Stay up to date

+
+
+ +

Automatic update notifications

+

Whenever a new release is published on GitHub, MailMetrix shows a banner like the one above and a footer badge, so you know it is time to update. The backend checks the latest release and caches the answer (6 hours by default); your browser never contacts GitHub directly. Prefer no outbound check? Set DISABLE_UPDATE_CHECK=true in your .env file to turn it off.

+
@@ -265,7 +342,7 @@

Simple, containerized architecture.

Backend

Node.js · Diagnostic API · Not published to the host

- Only the Nginx container is published (host port 50000); the backend is reachable only through the proxy or from the Compose network. SMTP and DNS operations may communicate with external servers or resolvers. Review the source code to understand the connections made by each feature. + Only the Nginx container is published (host port 50000); the backend is reachable only through the proxy or from the Compose network. SMTP, DNS, blacklist, and TLS operations communicate with external servers, resolvers, and DNS blocklists, and the update check contacts GitHub's API (it can be turned off with DISABLE_UPDATE_CHECK=true). Review the source code to understand the connections made by each feature.

@@ -305,7 +382,7 @@

Built-in safeguards

Outbound connection guardrails

-

The SMTP tester validates its destination before connecting. Loopback, private, link-local, and cloud-metadata addresses are blocked, the validated address is the one connected to, and ports are limited to 25, 465, 587, and 2525 by default.

+

The SMTP tester validates its destination before connecting. Loopback, private, link-local, and cloud-metadata addresses are blocked, the validated address is the one connected to, and ports are limited to 25, 465, 587, and 2525 by default. The TLS inspector applies the same network guard to its outbound connections.

@@ -315,12 +392,12 @@

Email abuse limits

Rate limiting

-

Every API route is limited per client IP, with stricter limits for SMTP tests, record generation, and DNS checks. Limits are configurable through environment variables.

+

Every API route is limited per client IP, with stricter limits for SMTP tests, record generation, DNS checks, blacklist lookups, deliverability scoring, and TLS inspections. Limits are configurable through environment variables.

Bounded resource use

-

DKIM key generation runs off the main thread with a concurrency cap and bounded queue. When the server is busy it answers 503 instead of stalling.

+

DKIM key generation runs off the main thread with a concurrency cap and bounded queue. When the server is busy it answers 503 instead of stalling. Deliverability scoring is capped too, with configurable limits on DNS queries per run, concurrent runs, hourly probes, and total run time.

@@ -354,7 +431,7 @@

Configure the proxy chain

Keep everything updated

-

Pinned images and dependencies do not update themselves. Rebuild regularly, and consider automated update tooling.

+

Pinned images and dependencies do not update themselves. MailMetrix shows an in-app notice when a new release is published, so rebuild when it appears and consider automated update tooling for base images.

diff --git a/frontend/src/app.js b/frontend/src/app.js index 36aaea7..bc4462b 100644 --- a/frontend/src/app.js +++ b/frontend/src/app.js @@ -7,9 +7,12 @@ 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 { initUpdateCheck } from "./features/update.js"; +import { initMobileNav } from "./features/mobile-nav.js"; import { renderSmtp, renderDns, renderGenerator, renderHeaders } from "./features/renderers.js"; initTabs(); +initMobileNav(); initSMTP(); initDNS(); initHeaders(); @@ -123,8 +126,17 @@ function setBackendState(online, duration, data) { } // 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 (cpuEl) { + cpuEl.textContent = Number.isFinite(data?.cpuPercent) + ? `${data.cpuPercent}%` + : '--'; + } + + if (memEl) { + memEl.textContent = Number.isFinite(data?.memory?.rssMb) + ? `${data.memory.rssMb} MB` + : '--'; + } if (statusVal) { statusVal.textContent = 'Healthy'; statusVal.classList.remove('is-down'); @@ -154,18 +166,30 @@ 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', { cache: 'no-store', signal: AbortSignal.timeout(4000) }); + 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'); + const data = await response.json(); + + if (data.status !== 'healthy') { + throw new Error('Backend unhealthy'); + } + setBackendState(true, duration, data); - } catch (err) { + + } catch { setBackendState(false); } finally { telemetryInFlight = false; @@ -173,16 +197,17 @@ async function updateBackendTelemetry() { } updateBackendTelemetry(); -setInterval(updateBackendTelemetry, 5000); +setInterval(updateBackendTelemetry, 30000); // 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) ---------------- */ +// Resolves to the installed version string (or null), so the update check can reuse it. async function loadAppVersion() { const el = document.getElementById('appVersion'); - if (!el) return; + if (!el) return null; try { // no-store so a new release shows immediately, even behind nginx/browser caching const res = await fetch('version.json', { cache: 'no-store' }); @@ -196,8 +221,16 @@ async function loadAppVersion() { if (!isNaN(d)) el.title = `Version ${version} · released ${d.toLocaleDateString(undefined, { year: 'numeric', month: 'short', day: 'numeric' })}`; } el.hidden = false; + return version; } catch (err) { el.hidden = true; // fail quietly — the footer simply omits the badge + return null; } } -loadAppVersion(); \ No newline at end of file + +/* ---------------- Update notification ---------------- + Compares the installed version (version.json) with the latest GitHub release, + which the backend looks up and caches. See features/update.js. */ +loadAppVersion().then((installed) => { + if (installed) initUpdateCheck(installed); +}); \ No newline at end of file diff --git a/frontend/src/features/mobile-nav.js b/frontend/src/features/mobile-nav.js new file mode 100644 index 0000000..8618ada --- /dev/null +++ b/frontend/src/features/mobile-nav.js @@ -0,0 +1,40 @@ +/* ---------------- Mobile navigation ---------------- + On small screens the tool list is collapsed behind a three-line button (see #navToggle in + index.html; CSS hides the button on desktop, so this does nothing there). Tapping a tool, + pressing Escape, tapping outside the bar, or resizing to desktop closes the list again. + It only toggles a class on the sidebar; tab switching itself is still handled by tabs.js. */ + +export function initMobileNav() { + const sidebar = document.querySelector('.sidebar'); + const button = document.getElementById('navToggle'); + const menu = document.getElementById('toolTabs'); + if (!sidebar || !button || !menu) return; + + const isOpen = () => sidebar.classList.contains('nav-open'); + + const setOpen = (open) => { + sidebar.classList.toggle('nav-open', open); + button.setAttribute('aria-expanded', String(open)); + button.setAttribute('aria-label', open ? 'Close menu' : 'Open menu'); + }; + + button.addEventListener('click', () => setOpen(!isOpen())); + + // Choosing a tool closes the list (tabs.js switches the panel on the same click). + menu.addEventListener('click', (e) => { + if (e.target.closest('.tab')) setOpen(false); + }); + + document.addEventListener('click', (e) => { + if (isOpen() && !sidebar.contains(e.target)) setOpen(false); + }); + + document.addEventListener('keydown', (e) => { + if (e.key === 'Escape' && isOpen()) { + setOpen(false); + button.focus(); + } + }); + + window.matchMedia('(max-width: 900px)').addEventListener('change', () => setOpen(false)); +} \ No newline at end of file diff --git a/frontend/src/features/update.js b/frontend/src/features/update.js new file mode 100644 index 0000000..0416f1d --- /dev/null +++ b/frontend/src/features/update.js @@ -0,0 +1,89 @@ +/* ---------------- Update notification ---------------- + Asks the backend what the latest GitHub release is and compares it with the version this + frontend was built with. Shows a dismissible banner plus a permanent chip in the footer. + Fails silently: an update check must never get in the way of the tools. */ + +const CHECK_URL = '/api/version/check'; +const DISMISS_KEY = 'mm-dismissed-update'; + +const SEMVER_RE = /^v?(\d+)\.(\d+)\.(\d+)/; + +function parseVersion(v) { + const m = SEMVER_RE.exec(String(v || '').trim()); + return m ? [Number(m[1]), Number(m[2]), Number(m[3])] : null; +} + +// Numeric compare, so 1.10.0 is correctly newer than 1.9.0. +function isNewer(candidate, installed) { + const a = parseVersion(candidate); + const b = parseVersion(installed); + if (!a || !b) return false; + for (let i = 0; i < 3; i++) { + if (a[i] !== b[i]) return a[i] > b[i]; + } + return false; +} + +function getDismissed() { + try { return localStorage.getItem(DISMISS_KEY); } catch (e) { return null; } +} + +function setDismissed(version) { + try { localStorage.setItem(DISMISS_KEY, version); } catch (e) { /* storage unavailable */ } +} + +function safeReleaseUrl(url) { + return typeof url === 'string' && url.startsWith('https://github.com/') ? url : null; +} + +function setText(id, text) { + const el = document.getElementById(id); + if (el) el.textContent = text; +} + +export async function initUpdateCheck(installedVersion) { + const banner = document.getElementById('updateBanner'); + const chip = document.getElementById('updateChip'); + if (!banner && !chip) return; + + try { + const res = await fetch(CHECK_URL, { cache: 'no-store', signal: AbortSignal.timeout(6000) }); + if (!res.ok) return; + const info = await res.json(); + if (!info || !info.enabled || !isNewer(info.latest, installedVersion)) return; + + const releaseUrl = safeReleaseUrl(info.releaseUrl); + + // Permanent hint next to the version badge (never dismissed). + if (chip) { + chip.textContent = `Update available: v${info.latest}`; + if (releaseUrl) chip.href = releaseUrl; + chip.classList.remove('hidden'); + } + + // Banner: shown once per new version; dismissing it hides it until a newer release exists. + if (!banner || getDismissed() === info.latest) return; + + setText('updateTitle', `MailMetrix v${info.latest} is ready`); + setText('updateDetail', `You're on v${installedVersion}. Update your installation to get the latest fixes and features.`); + setText('updateFrom', `v${installedVersion}`); + setText('updateTo', `v${info.latest}`); + + const link = document.getElementById('updateLink'); + if (link) { + if (releaseUrl) link.href = releaseUrl; + else link.classList.add('hidden'); + } + + const dismiss = document.getElementById('updateDismiss'); + if (dismiss) { + dismiss.addEventListener('click', () => { + setDismissed(info.latest); + banner.classList.add('hidden'); + }, { once: true }); + } + banner.classList.remove('hidden'); + } catch (e) { + /* offline, backend down, GitHub unreachable: stay quiet */ + } +} \ No newline at end of file diff --git a/frontend/src/index.html b/frontend/src/index.html index 9a1abbd..01e5ad0 100644 --- a/frontend/src/index.html +++ b/frontend/src/index.html @@ -47,7 +47,12 @@ -