Archived
initial
This commit is contained in:
59 files changed
+11046
No files matched your search
@@ -0,0 +1,26 @@
|
||||
.git
|
||||
.github
|
||||
.idea
|
||||
.vscode
|
||||
.next
|
||||
.vinext
|
||||
.wrangler
|
||||
dist
|
||||
web-dist
|
||||
node_modules
|
||||
data
|
||||
backups
|
||||
coverage
|
||||
secrets
|
||||
.env
|
||||
.env.*
|
||||
*.db
|
||||
*.sqlite
|
||||
*.pem
|
||||
*.key
|
||||
*.log
|
||||
mailctl
|
||||
meovv-mail
|
||||
README.md
|
||||
docs
|
||||
tests
|
||||
@@ -0,0 +1,18 @@
|
||||
root = true
|
||||
|
||||
[*]
|
||||
charset = utf-8
|
||||
end_of_line = lf
|
||||
insert_final_newline = true
|
||||
indent_style = space
|
||||
indent_size = 2
|
||||
trim_trailing_whitespace = true
|
||||
|
||||
[*.go]
|
||||
indent_style = tab
|
||||
|
||||
[Makefile]
|
||||
indent_style = tab
|
||||
|
||||
[*.md]
|
||||
trim_trailing_whitespace = false
|
||||
@@ -0,0 +1,5 @@
|
||||
# Documentation only. Run `mailctl init`; do not deploy this file as `.env`.
|
||||
MEOVV_VERSION=0.1.0
|
||||
MAIL_HOSTNAME=mail.example.com
|
||||
STALWART_RECOVERY_ADMIN=
|
||||
API_SUBMISSION_USER=
|
||||
@@ -0,0 +1,12 @@
|
||||
* text=auto eol=lf
|
||||
|
||||
*.png binary
|
||||
*.jpg binary
|
||||
*.jpeg binary
|
||||
*.gif binary
|
||||
*.ico binary
|
||||
*.woff binary
|
||||
*.woff2 binary
|
||||
|
||||
package-lock.json linguist-generated=true
|
||||
go.sum linguist-generated=true
|
||||
@@ -0,0 +1,49 @@
|
||||
name: Bug report
|
||||
description: Report a reproducible problem in MEOVV Mail
|
||||
title: "[Bug]: "
|
||||
labels: [bug]
|
||||
body:
|
||||
- type: markdown
|
||||
attributes:
|
||||
value: Do not report vulnerabilities or include credentials, message content, or customer data here. Use the private process in SECURITY.md.
|
||||
- type: input
|
||||
id: version
|
||||
attributes:
|
||||
label: MEOVV Mail version or commit
|
||||
placeholder: v0.1.0 or commit SHA
|
||||
validations:
|
||||
required: true
|
||||
- type: dropdown
|
||||
id: platform
|
||||
attributes:
|
||||
label: Platform
|
||||
options:
|
||||
- Ubuntu 24.04 amd64
|
||||
- Ubuntu 24.04 arm64
|
||||
- Debian 13 amd64
|
||||
- Debian 13 arm64
|
||||
- Development workstation
|
||||
- Other
|
||||
validations:
|
||||
required: true
|
||||
- type: textarea
|
||||
id: description
|
||||
attributes:
|
||||
label: What happened?
|
||||
description: Include expected behavior and sanitized reproduction steps.
|
||||
validations:
|
||||
required: true
|
||||
- type: textarea
|
||||
id: diagnostics
|
||||
attributes:
|
||||
label: Sanitized diagnostics
|
||||
description: Include relevant `mailctl doctor` results or logs after removing sensitive data.
|
||||
- type: checkboxes
|
||||
id: checks
|
||||
attributes:
|
||||
label: Safety checks
|
||||
options:
|
||||
- label: I removed credentials, domains, IP addresses, mailbox content, and customer information.
|
||||
required: true
|
||||
- label: This is not a security vulnerability.
|
||||
required: true
|
||||
@@ -0,0 +1 @@
|
||||
blank_issues_enabled: false
|
||||
@@ -0,0 +1,23 @@
|
||||
name: Feature request
|
||||
description: Suggest a product or operational improvement
|
||||
title: "[Feature]: "
|
||||
labels: [enhancement]
|
||||
body:
|
||||
- type: textarea
|
||||
id: problem
|
||||
attributes:
|
||||
label: Problem
|
||||
description: What user or operator problem should be solved?
|
||||
validations:
|
||||
required: true
|
||||
- type: textarea
|
||||
id: proposal
|
||||
attributes:
|
||||
label: Proposed behavior
|
||||
description: Describe the desired outcome and any compatibility constraints.
|
||||
validations:
|
||||
required: true
|
||||
- type: textarea
|
||||
id: alternatives
|
||||
attributes:
|
||||
label: Alternatives considered
|
||||
@@ -0,0 +1,24 @@
|
||||
version: 2
|
||||
updates:
|
||||
- package-ecosystem: npm
|
||||
directory: /
|
||||
schedule:
|
||||
interval: weekly
|
||||
open-pull-requests-limit: 5
|
||||
- package-ecosystem: gomod
|
||||
directory: /
|
||||
schedule:
|
||||
interval: weekly
|
||||
open-pull-requests-limit: 5
|
||||
- package-ecosystem: docker
|
||||
directory: /
|
||||
schedule:
|
||||
interval: weekly
|
||||
open-pull-requests-limit: 3
|
||||
ignore:
|
||||
- dependency-name: stalwartlabs/stalwart
|
||||
- package-ecosystem: github-actions
|
||||
directory: /
|
||||
schedule:
|
||||
interval: monthly
|
||||
open-pull-requests-limit: 3
|
||||
@@ -0,0 +1,17 @@
|
||||
## Summary
|
||||
|
||||
Describe the problem and the outcome of this change.
|
||||
|
||||
## Verification
|
||||
|
||||
- [ ] `npm run check`
|
||||
- [ ] `go test ./cmd/... ./internal/...`
|
||||
- [ ] `go vet ./cmd/... ./internal/...`
|
||||
- [ ] Relevant browser, contract, or Compose checks
|
||||
|
||||
## Release impact
|
||||
|
||||
- [ ] Documentation and OpenAPI are updated where required.
|
||||
- [ ] No credentials, personal data, runtime state, or generated output is included.
|
||||
- [ ] Stalwart version/digest and compatibility policy are unchanged, or the required contract and release review is included.
|
||||
- [ ] Security, migration, backup, and rollback effects are described below.
|
||||
@@ -0,0 +1,52 @@
|
||||
name: CI
|
||||
|
||||
on:
|
||||
push:
|
||||
branches: [main]
|
||||
pull_request:
|
||||
|
||||
permissions:
|
||||
contents: read
|
||||
|
||||
concurrency:
|
||||
group: ci-${{ github.ref }}
|
||||
cancel-in-progress: true
|
||||
|
||||
jobs:
|
||||
frontend:
|
||||
name: Frontend
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
- uses: actions/setup-node@v4
|
||||
with:
|
||||
node-version: 22
|
||||
cache: npm
|
||||
- run: npm ci --ignore-scripts
|
||||
- run: npm run check
|
||||
- run: npm audit --omit=dev --audit-level=high
|
||||
|
||||
backend:
|
||||
name: Go backend
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
- uses: actions/setup-go@v5
|
||||
with:
|
||||
go-version-file: go.mod
|
||||
cache: true
|
||||
- run: go test ./cmd/... ./internal/...
|
||||
- run: go vet ./cmd/... ./internal/...
|
||||
- run: go build ./cmd/...
|
||||
|
||||
appliance:
|
||||
name: Appliance bundle
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
- name: Validate Compose configuration
|
||||
env:
|
||||
MAIL_HOSTNAME: mail.example.com
|
||||
run: docker compose config --quiet
|
||||
- name: Build the application image
|
||||
run: docker build --tag meovv-mail:ci .
|
||||
@@ -0,0 +1,16 @@
|
||||
name: Dependency review
|
||||
|
||||
on:
|
||||
pull_request:
|
||||
|
||||
permissions:
|
||||
contents: read
|
||||
|
||||
jobs:
|
||||
review:
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
- uses: actions/dependency-review-action@v4
|
||||
with:
|
||||
fail-on-severity: high
|
||||
+47
@@ -0,0 +1,47 @@
|
||||
# Dependencies and generated frontend output
|
||||
/node_modules/
|
||||
/web-dist/
|
||||
/dist/
|
||||
/coverage/
|
||||
*.tsbuildinfo
|
||||
|
||||
# Runtime state and credentials
|
||||
.env
|
||||
.env.*
|
||||
!.env.example
|
||||
/secrets/
|
||||
/data/
|
||||
/backups/
|
||||
*.db
|
||||
*.db-shm
|
||||
*.db-wal
|
||||
*.sqlite
|
||||
*.sqlite-shm
|
||||
*.sqlite-wal
|
||||
*.pem
|
||||
*.key
|
||||
|
||||
# Local binaries and diagnostic output
|
||||
/mailctl
|
||||
/meovv-mail
|
||||
/outputs/
|
||||
/work/
|
||||
*.log
|
||||
npm-debug.log*
|
||||
yarn-debug.log*
|
||||
yarn-error.log*
|
||||
.pnpm-debug.log*
|
||||
|
||||
# Editors and operating systems
|
||||
.DS_Store
|
||||
.idea/
|
||||
.vscode/
|
||||
*.swp
|
||||
*~
|
||||
|
||||
# Legacy/local preview tooling
|
||||
/.next/
|
||||
/.vinext/
|
||||
/.wrangler/
|
||||
/.openai/
|
||||
/public/
|
||||
@@ -0,0 +1,22 @@
|
||||
# Changelog
|
||||
|
||||
All notable project changes will be recorded here. This project follows
|
||||
[Semantic Versioning](https://semver.org/) after the first stable release.
|
||||
|
||||
## [Unreleased]
|
||||
|
||||
### Added
|
||||
|
||||
- Initial three-container self-hosted appliance architecture.
|
||||
- React/Vite mailbox, setup, authentication, and administration interfaces.
|
||||
- Go control plane, REST send API, JMAP session proxy, delivery events, and
|
||||
signed webhook delivery.
|
||||
- SQLite state store, `mailctl` operations, signed compatibility manifest,
|
||||
OpenAPI contract, and operator documentation.
|
||||
|
||||
### Security
|
||||
|
||||
- OAuth authorization code flow with PKCE and encrypted server-side tokens.
|
||||
- Hashed, scoped, sender-bound API keys and encrypted webhook secrets.
|
||||
- HTML sanitization, remote-content blocking, CSRF defenses, webhook SSRF
|
||||
controls, and strict public protocol exposure.
|
||||
@@ -0,0 +1,42 @@
|
||||
# Contributing
|
||||
|
||||
Thank you for helping improve MEOVV Mail.
|
||||
|
||||
## Before opening a change
|
||||
|
||||
- Search existing issues and pull requests.
|
||||
- Use a discussion or feature request for substantial product or protocol
|
||||
changes before investing in an implementation.
|
||||
- Use the private process in `SECURITY.md` for vulnerabilities.
|
||||
- Never commit real domains, credentials, mailbox content, database files,
|
||||
backups, or customer logs.
|
||||
|
||||
The MEOVV product layer is currently published under an all-rights-reserved
|
||||
license. Opening a pull request does not change ownership of your contribution
|
||||
or grant the project additional rights. Maintainers may ask for a separate
|
||||
contribution agreement before accepting code. Issue reports and documentation
|
||||
corrections are welcome while that policy is finalized.
|
||||
|
||||
## Development checks
|
||||
|
||||
Install Node.js 22+, Go 1.24+, and Docker with Compose. Then run:
|
||||
|
||||
```bash
|
||||
npm ci
|
||||
npm run check
|
||||
go test ./cmd/... ./internal/...
|
||||
go vet ./cmd/... ./internal/...
|
||||
go build ./cmd/...
|
||||
MAIL_HOSTNAME=mail.example.com docker compose config --quiet
|
||||
docker build -t meovv-mail:local .
|
||||
```
|
||||
|
||||
Changes to Stalwart integration must also pass contract tests against the exact
|
||||
image and digest in `compose.yaml`. Do not update that image independently of
|
||||
the signed compatibility manifest.
|
||||
|
||||
## Pull requests
|
||||
|
||||
Keep changes focused, add tests for changed behavior, update public contracts
|
||||
and operational documentation, and explain security or compatibility effects.
|
||||
Generated output, local environment files, and secrets must remain untracked.
|
||||
+29
@@ -0,0 +1,29 @@
|
||||
# syntax=docker/dockerfile:1.7
|
||||
FROM node:22.23.1-alpine AS web-builder
|
||||
WORKDIR /src
|
||||
COPY package.json package-lock.json ./
|
||||
RUN npm ci
|
||||
COPY app ./app
|
||||
COPY web ./web
|
||||
COPY vite.frontend.config.ts tsconfig.json ./
|
||||
RUN npm run build:web
|
||||
|
||||
FROM golang:1.26.5-alpine AS go-builder
|
||||
WORKDIR /src
|
||||
RUN apk add --no-cache ca-certificates
|
||||
COPY go.mod go.sum ./
|
||||
RUN go mod download
|
||||
COPY cmd ./cmd
|
||||
COPY internal ./internal
|
||||
RUN CGO_ENABLED=0 GOOS=linux go build -trimpath -ldflags="-s -w" -o /out/meovv-mail ./cmd/meovv-mail && \
|
||||
CGO_ENABLED=0 GOOS=linux go build -trimpath -ldflags="-s -w" -o /out/mailctl ./cmd/mailctl
|
||||
|
||||
FROM alpine:3.22
|
||||
RUN apk add --no-cache ca-certificates tzdata && addgroup -S -g 2001 meovv && adduser -S -D -H -u 2001 -G meovv meovv
|
||||
COPY --from=go-builder /out/meovv-mail /usr/local/bin/meovv-mail
|
||||
COPY --from=go-builder /out/mailctl /usr/local/bin/mailctl
|
||||
COPY --from=web-builder /src/web-dist /app/web
|
||||
RUN mkdir -p /var/lib/meovv-mail && chown -R meovv:meovv /var/lib/meovv-mail
|
||||
USER meovv
|
||||
EXPOSE 8080
|
||||
ENTRYPOINT ["/usr/local/bin/meovv-mail"]
|
||||
@@ -0,0 +1,10 @@
|
||||
Copyright (c) 2026 MEOVV Mail authors
|
||||
|
||||
All rights reserved.
|
||||
|
||||
No permission is granted to use, copy, modify, merge, publish, distribute,
|
||||
sublicense, or sell any portion of this software except under a separate
|
||||
written agreement with the copyright holder.
|
||||
|
||||
Third-party components remain subject to their own license terms. See
|
||||
THIRD_PARTY_NOTICES.md and the LICENSES directory.
|
||||
@@ -0,0 +1,11 @@
|
||||
Stalwart Mail Server v0.16.17 is distributed unmodified under the GNU Affero
|
||||
General Public License, version 3. The complete corresponding source for the
|
||||
exact distributed version is available at:
|
||||
|
||||
https://github.com/stalwartlabs/stalwart/tree/v0.16.17
|
||||
|
||||
The image digest used by this release is:
|
||||
sha256:a8108e19bd927e172d4d8c128907b8dfc93fd180ae8ee07dccdd42cb97eb9dfa
|
||||
|
||||
This notice does not replace the license text or legal review required for a
|
||||
customer distribution.
|
||||
@@ -0,0 +1,170 @@
|
||||
# MEOVV Mail
|
||||
|
||||

|
||||
|
||||
MEOVV Mail is a single-tenant, self-hosted email appliance for one organization.
|
||||
It combines a polished web inbox and administration experience with a pinned Stalwart mail core,
|
||||
a Go control plane, and automatic HTTPS through Caddy.
|
||||
|
||||
> [!IMPORTANT]
|
||||
> MEOVV Mail is pre-1.0 software under active development. The architecture,
|
||||
> UI, API contract, and local test suite are implemented, but a release must not
|
||||
> be used for production correspondence until the Stalwart contract suite,
|
||||
> open-relay/security review, supported-Linux restore drills, and documented
|
||||
> performance acceptance tests pass for that exact release.
|
||||
|
||||
Version `0.1.0` targets one Linux host, multiple domains, and up to 500 local users.
|
||||
It exposes SMTP on 25/465/587, IMAP over TLS on 993, JMAP and OAuth over HTTPS,
|
||||
and a scoped REST send API. POP3 and plaintext IMAP are not published.
|
||||
|
||||
## Architecture
|
||||
|
||||
The production bundle runs exactly three containers:
|
||||
|
||||
- `caddy` terminates public TLS, publishes discovery routes, and sends product traffic to MEOVV.
|
||||
- `meovv` serves the web application, encrypted OAuth sessions, REST API, setup, delivery metadata, webhook jobs, audit events, and operational endpoints.
|
||||
- `stalwart` stores accounts and all mailbox data and provides SMTP, IMAP, JMAP, filtering, queues, and delivery telemetry.
|
||||
|
||||
Stalwart is pinned to `v0.16.17` and multi-architecture digest `sha256:a8108e19bd927e172d4d8c128907b8dfc93fd180ae8ee07dccdd42cb97eb9dfa`.
|
||||
Mail bodies and attachments never enter the MEOVV SQLite database.
|
||||
|
||||
## Host requirements
|
||||
|
||||
- Ubuntu 24.04 or Debian 13 on amd64 or arm64
|
||||
- Docker Engine with the Compose plugin
|
||||
- 4 vCPU, 8 GB RAM, and SSD storage for the reference 500-account deployment
|
||||
- A public static IP and control of DNS for direct delivery
|
||||
- Inbound TCP 25, 80, 443, 465, 587, and 993
|
||||
- Outbound TCP 25, or an authenticated TLS smart host
|
||||
|
||||
Direct delivery also needs working reverse DNS and acceptable IP reputation. If the hosting provider blocks port 25 or cannot set PTR, use relay mode.
|
||||
|
||||
## Install
|
||||
|
||||
Build the local operator utility, initialize the bundle, and start it:
|
||||
|
||||
```bash
|
||||
go build -o mailctl ./cmd/mailctl
|
||||
./mailctl init --hostname mail.example.com
|
||||
docker compose up -d --build
|
||||
```
|
||||
|
||||
`mailctl init` prints a one-time browser bootstrap token and temporary Stalwart recovery credential. Store both securely. Visit `https://mail.example.com`, complete the three-step wizard, and save the one-time result shown on the final screen.
|
||||
|
||||
After setup:
|
||||
|
||||
```bash
|
||||
docker compose restart stalwart meovv
|
||||
./mailctl doctor --hostname mail.example.com
|
||||
```
|
||||
|
||||
Sign in with the permanent Stalwart administrator, create the dedicated `API_SUBMISSION_USER` account referenced by `.env`, put that account's application password in `secrets/api_submission_password`, verify REST submission, then remove the recovery backdoor:
|
||||
|
||||
```bash
|
||||
./mailctl harden
|
||||
```
|
||||
|
||||
Never leave `STALWART_RECOVERY_ADMIN` set on a production deployment. `mailctl reset-password` re-enables a temporary recovery credential during a lockout; reset and verify the permanent account, then immediately run `mailctl harden` again.
|
||||
|
||||
## DNS checklist
|
||||
|
||||
The dashboard and `mailctl doctor` cover the local checks. Before production traffic, verify:
|
||||
|
||||
- A and/or AAAA for the mail hostname
|
||||
- MX for each hosted domain
|
||||
- PTR from every sending IP back to the mail hostname
|
||||
- SPF authorizing the appliance or relay
|
||||
- Stalwart-generated DKIM records
|
||||
- DMARC, initially in monitoring mode if desired
|
||||
- HTTPS certificate and autoconfiguration discovery
|
||||
- External inbound and outbound port 25 reachability
|
||||
|
||||
The Stalwart domain object contains the generated DNS zone material. Missing PTR, blocked outbound port 25, or poor IP reputation is a relay recommendation, not an appliance failure.
|
||||
|
||||
## REST API
|
||||
|
||||
The complete OpenAPI 3.1 contract is in [`api/openapi.yaml`](api/openapi.yaml). Administrator-created keys are displayed once, stored as SHA-256 digests, scoped to `messages.send` and/or `messages.status`, and restricted to approved sender identities.
|
||||
|
||||
```bash
|
||||
curl https://mail.example.com/api/v1/messages \
|
||||
-H 'Authorization: Bearer meovv_REPLACE_ME' \
|
||||
-H 'Idempotency-Key: welcome-customer-1042' \
|
||||
-H 'Content-Type: application/json' \
|
||||
--data '{
|
||||
"from":"Notifications <notifications@example.com>",
|
||||
"to":["person@example.net"],
|
||||
"subject":"Welcome",
|
||||
"text":"Welcome to our service.",
|
||||
"html":"<p>Welcome to our service.</p>"
|
||||
}'
|
||||
```
|
||||
|
||||
A successful submission returns `202 Accepted`. `delivered` means the destination mail server accepted the recipient; it does not mean a person read the message.
|
||||
|
||||
## Operations
|
||||
|
||||
Create a consistency-safe backup:
|
||||
|
||||
```bash
|
||||
./mailctl backup
|
||||
```
|
||||
|
||||
The command stops Stalwart and MEOVV writers, archives all five named volumes plus Compose configuration and secrets, writes SHA-256 checksums, and restarts the services. Restore is intentionally destructive and only accepts a backup from the same MEOVV and Stalwart release:
|
||||
|
||||
```bash
|
||||
./mailctl restore --from backups/20260812T103000Z --yes
|
||||
```
|
||||
|
||||
Upgrades verify the Ed25519 signature in `release/compatibility.sig`, reject unapproved Stalwart versions or digests, run diagnostics, and create a pre-upgrade backup:
|
||||
|
||||
```bash
|
||||
./mailctl upgrade
|
||||
```
|
||||
|
||||
Other useful commands:
|
||||
|
||||
```bash
|
||||
./mailctl doctor
|
||||
./mailctl version
|
||||
docker compose exec meovv mailctl create-api-key \
|
||||
--name 'Production app' \
|
||||
--senders 'notifications@example.com,*@internal.example.com'
|
||||
```
|
||||
|
||||
## Observability
|
||||
|
||||
- Liveness: `GET /health/live`
|
||||
- Readiness: `GET /health/ready`
|
||||
- Prometheus text format: `GET /metrics`
|
||||
- Structured application logs: standard output
|
||||
- Stalwart delivery diagnostics and queues: administrator dashboard through the authenticated adapter
|
||||
|
||||
Default retention is 30 days for delivery metadata, 7 days for webhook attempts, and 180 days for administrator audit events. Override with `MEOVV_MESSAGE_RETENTION`, `MEOVV_WEBHOOK_RETENTION`, and `MEOVV_AUDIT_RETENTION` duration values.
|
||||
|
||||
## Development and verification
|
||||
|
||||
```bash
|
||||
npm ci
|
||||
npm run dev
|
||||
npm run check
|
||||
go test ./cmd/... ./internal/...
|
||||
go vet ./cmd/... ./internal/...
|
||||
go build ./cmd/...
|
||||
MAIL_HOSTNAME=mail.example.com docker compose config --quiet
|
||||
docker build -t meovv-mail:local .
|
||||
```
|
||||
|
||||
The standalone appliance UI is produced by `npm run build:web` in `web-dist`; the container image builds it automatically. See [`docs/architecture.md`](docs/architecture.md), [`docs/operations.md`](docs/operations.md), and [`docs/security.md`](docs/security.md) for system boundaries, production runbooks, and threat controls.
|
||||
|
||||
Pull requests run frontend checks, Go tests/vetting/builds, Compose validation,
|
||||
container construction, and dependency review. See [`CONTRIBUTING.md`](CONTRIBUTING.md)
|
||||
and report vulnerabilities through the private process in [`SECURITY.md`](SECURITY.md).
|
||||
|
||||
## Licensing
|
||||
|
||||
Stalwart is distributed unmodified as a separate AGPL service. MEOVV Mail does not link to its code. License notices and corresponding-source information are in [`THIRD_PARTY_NOTICES.md`](THIRD_PARTY_NOTICES.md). This repository is not a substitute for legal review before customer distribution.
|
||||
|
||||
The MEOVV product layer is currently **all rights reserved**; public source
|
||||
availability is not an open-source license grant. See [`LICENSE`](LICENSE). If
|
||||
the project adopts an open-source license later, update `LICENSE`, contribution
|
||||
terms, package metadata, and release notices together.
|
||||
+31
@@ -0,0 +1,31 @@
|
||||
# Security policy
|
||||
|
||||
MEOVV Mail handles credentials, private correspondence, and internet-facing
|
||||
mail protocols. Please report suspected vulnerabilities privately.
|
||||
|
||||
## Supported versions
|
||||
|
||||
This repository is currently pre-1.0. Security fixes are applied to the latest
|
||||
release and the `main` branch only. Older snapshots are not supported.
|
||||
|
||||
## Reporting a vulnerability
|
||||
|
||||
Use the repository's **Security → Report a vulnerability** form to open a
|
||||
private GitHub Security Advisory. Do not include exploit details, credentials,
|
||||
message contents, or customer information in a public issue.
|
||||
|
||||
Include the affected version or commit, deployment topology, reproduction
|
||||
steps, expected impact, and any suggested mitigation. You should receive an
|
||||
initial acknowledgement within three business days. Disclosure timing will be
|
||||
coordinated after the report is validated and a remediation is available.
|
||||
|
||||
If private vulnerability reporting has not yet been enabled on the repository,
|
||||
contact the repository owner privately and ask them to enable it; do not open a
|
||||
public issue containing vulnerability details.
|
||||
|
||||
## Deployment reports
|
||||
|
||||
Configuration questions, spam-delivery problems, and ordinary operational
|
||||
failures are not vulnerabilities. Remove domains, IP addresses, credentials,
|
||||
email addresses, message bodies, and logs containing personal information
|
||||
before sharing a diagnostic report.
|
||||
@@ -0,0 +1,21 @@
|
||||
# Third-party notices
|
||||
|
||||
## Stalwart Mail Server
|
||||
|
||||
MEOVV Mail distributes the unmodified Stalwart Mail Server as a separate container:
|
||||
|
||||
- Project: Stalwart Mail Server
|
||||
- Version: `v0.16.17`
|
||||
- Image: `stalwartlabs/stalwart:v0.16.17`
|
||||
- Digest: `sha256:a8108e19bd927e172d4d8c128907b8dfc93fd180ae8ee07dccdd42cb97eb9dfa`
|
||||
- License: GNU Affero General Public License, version 3
|
||||
- Corresponding source: https://github.com/stalwartlabs/stalwart/tree/v0.16.17
|
||||
- Release: https://github.com/stalwartlabs/stalwart/releases/tag/v0.16.17
|
||||
|
||||
Stalwart is not linked into the MEOVV application. MEOVV communicates with it over documented HTTP/JMAP and SMTP interfaces and ships it unmodified as its own service. Any future modifications to Stalwart must be published with corresponding source under the applicable license. Obtain legal review before customer distribution.
|
||||
|
||||
Other JavaScript and Go dependencies retain their respective upstream licenses.
|
||||
Their exact versions are recorded in `package-lock.json` and `go.sum`. Every
|
||||
published binary or appliance release must include a generated software bill of
|
||||
materials and the applicable third-party license texts; this source repository
|
||||
does not replace those release artifacts.
|
||||
@@ -0,0 +1,228 @@
|
||||
openapi: 3.1.0
|
||||
info:
|
||||
title: MEOVV Mail Send API
|
||||
version: 1.0.0
|
||||
description: |
|
||||
Submit application email and inspect destination-server acceptance state.
|
||||
A `delivered` result means that the destination mail server accepted the
|
||||
message; it does not mean that a person opened or read it.
|
||||
servers:
|
||||
- url: https://mail.example.com
|
||||
security:
|
||||
- bearerAuth: []
|
||||
paths:
|
||||
/api/v1/messages:
|
||||
post:
|
||||
operationId: submitMessage
|
||||
summary: Submit a message
|
||||
description: Requires `messages.send`. A key may only use its approved sender identities.
|
||||
parameters:
|
||||
- $ref: '#/components/parameters/IdempotencyKey'
|
||||
requestBody:
|
||||
required: true
|
||||
content:
|
||||
application/json:
|
||||
schema:
|
||||
$ref: '#/components/schemas/SubmitMessage'
|
||||
examples:
|
||||
welcome:
|
||||
value:
|
||||
from: Notifications <notifications@example.com>
|
||||
to: [person@example.net]
|
||||
subject: Welcome
|
||||
text: Welcome to our service.
|
||||
html: <p>Welcome to our service.</p>
|
||||
responses:
|
||||
'202':
|
||||
description: Accepted by the local submission service.
|
||||
headers:
|
||||
Location:
|
||||
schema: { type: string }
|
||||
content:
|
||||
application/json:
|
||||
schema: { $ref: '#/components/schemas/SubmissionReceipt' }
|
||||
example:
|
||||
id: msg_E6uFQ2YfANvHfZrC
|
||||
status: queued
|
||||
submitted_at: '2026-08-12T08:30:00Z'
|
||||
'400': { $ref: '#/components/responses/Problem' }
|
||||
'401': { $ref: '#/components/responses/Problem' }
|
||||
'403': { $ref: '#/components/responses/Problem' }
|
||||
'409': { $ref: '#/components/responses/Problem' }
|
||||
'413': { $ref: '#/components/responses/Problem' }
|
||||
'422': { $ref: '#/components/responses/Problem' }
|
||||
'429':
|
||||
description: Per-key submission limit exceeded.
|
||||
headers:
|
||||
Retry-After:
|
||||
schema: { type: integer }
|
||||
content:
|
||||
application/problem+json:
|
||||
schema: { $ref: '#/components/schemas/Problem' }
|
||||
get:
|
||||
operationId: listMessages
|
||||
summary: List message status history
|
||||
description: Requires `messages.status`. Results are restricted to the calling API key.
|
||||
parameters:
|
||||
- { name: cursor, in: query, schema: { type: string } }
|
||||
- { name: limit, in: query, schema: { type: integer, minimum: 1, maximum: 100, default: 25 } }
|
||||
- { name: status, in: query, schema: { $ref: '#/components/schemas/MessageState' } }
|
||||
- { name: sender, in: query, schema: { type: string, format: email } }
|
||||
- { name: recipient, in: query, schema: { type: string, format: email } }
|
||||
- { name: from, in: query, schema: { type: string, format: date-time } }
|
||||
- { name: to, in: query, schema: { type: string, format: date-time } }
|
||||
responses:
|
||||
'200':
|
||||
description: Cursor-paginated messages.
|
||||
content:
|
||||
application/json:
|
||||
schema:
|
||||
type: object
|
||||
required: [data]
|
||||
properties:
|
||||
data: { type: array, items: { $ref: '#/components/schemas/MessageStatus' } }
|
||||
next_cursor: { type: [string, 'null'] }
|
||||
'401': { $ref: '#/components/responses/Problem' }
|
||||
'403': { $ref: '#/components/responses/Problem' }
|
||||
/api/v1/messages/{id}:
|
||||
get:
|
||||
operationId: getMessage
|
||||
summary: Read overall and per-recipient delivery state
|
||||
description: Requires `messages.status`; only the API key that submitted the message may read it.
|
||||
parameters:
|
||||
- name: id
|
||||
in: path
|
||||
required: true
|
||||
schema: { type: string, pattern: '^msg_' }
|
||||
responses:
|
||||
'200':
|
||||
description: Current delivery state.
|
||||
content:
|
||||
application/json:
|
||||
schema: { $ref: '#/components/schemas/MessageStatus' }
|
||||
'401': { $ref: '#/components/responses/Problem' }
|
||||
'403': { $ref: '#/components/responses/Problem' }
|
||||
'404': { $ref: '#/components/responses/Problem' }
|
||||
webhooks:
|
||||
deliveryEvent:
|
||||
post:
|
||||
summary: Versioned at-least-once delivery event
|
||||
description: |
|
||||
Verify `X-MEOVV-Signature` as HMAC-SHA256 over
|
||||
`{X-MEOVV-Timestamp}.{raw_body}`. Event IDs stay constant across retries.
|
||||
Duplicates and cross-message reordering are possible.
|
||||
parameters:
|
||||
- { name: X-MEOVV-Timestamp, in: header, required: true, schema: { type: string } }
|
||||
- { name: X-MEOVV-Signature, in: header, required: true, schema: { type: string, pattern: '^v1=' } }
|
||||
- { name: X-MEOVV-Event-ID, in: header, required: true, schema: { type: string } }
|
||||
requestBody:
|
||||
required: true
|
||||
content:
|
||||
application/json:
|
||||
schema: { $ref: '#/components/schemas/WebhookEvent' }
|
||||
responses:
|
||||
'204': { description: Event accepted. }
|
||||
components:
|
||||
securitySchemes:
|
||||
bearerAuth:
|
||||
type: http
|
||||
scheme: bearer
|
||||
bearerFormat: MEOVV API key
|
||||
parameters:
|
||||
IdempotencyKey:
|
||||
name: Idempotency-Key
|
||||
in: header
|
||||
description: Replays the original receipt for 24 hours; re-use with different content is rejected.
|
||||
schema: { type: string, minLength: 1, maxLength: 255 }
|
||||
responses:
|
||||
Problem:
|
||||
description: Request failed.
|
||||
content:
|
||||
application/problem+json:
|
||||
schema: { $ref: '#/components/schemas/Problem' }
|
||||
schemas:
|
||||
SubmitMessage:
|
||||
type: object
|
||||
required: [from, to, subject]
|
||||
anyOf:
|
||||
- required: [text]
|
||||
- required: [html]
|
||||
properties:
|
||||
from: { type: string, description: Must match a sender identity approved for the API key. }
|
||||
to: { type: array, maxItems: 100, items: { type: string, format: email } }
|
||||
cc: { type: array, items: { type: string, format: email } }
|
||||
bcc: { type: array, items: { type: string, format: email } }
|
||||
reply_to: { type: string, format: email }
|
||||
subject: { type: string }
|
||||
text: { type: string }
|
||||
html: { type: string }
|
||||
headers:
|
||||
type: object
|
||||
additionalProperties: { type: string }
|
||||
description: X-* headers plus List-Unsubscribe and List-Unsubscribe-Post.
|
||||
attachments:
|
||||
type: array
|
||||
items:
|
||||
type: object
|
||||
required: [filename, content_base64]
|
||||
properties:
|
||||
filename: { type: string }
|
||||
content_type: { type: string, default: application/octet-stream }
|
||||
content_base64: { type: string, contentEncoding: base64 }
|
||||
description: The decoded message may not exceed 25 MiB and all recipient fields combined may not exceed 100 addresses.
|
||||
MessageState:
|
||||
type: string
|
||||
enum: [queued, processing, deferred, delivered, partial, bounced, failed]
|
||||
RecipientState:
|
||||
type: object
|
||||
required: [address, status]
|
||||
properties:
|
||||
address: { type: string, format: email }
|
||||
status: { type: string, enum: [queued, processing, deferred, delivered, bounced, failed] }
|
||||
last_response: { type: string }
|
||||
last_attempt_at: { type: [string, 'null'], format: date-time }
|
||||
SubmissionReceipt:
|
||||
type: object
|
||||
required: [id, status, submitted_at]
|
||||
properties:
|
||||
id: { type: string }
|
||||
status: { const: queued }
|
||||
submitted_at: { type: string, format: date-time }
|
||||
MessageStatus:
|
||||
type: object
|
||||
required: [id, sender, subject, status, submitted_at, recipients]
|
||||
properties:
|
||||
id: { type: string }
|
||||
sender: { type: string }
|
||||
subject: { type: string }
|
||||
status: { $ref: '#/components/schemas/MessageState' }
|
||||
size_bytes: { type: integer }
|
||||
submitted_at: { type: string, format: date-time }
|
||||
updated_at: { type: string, format: date-time }
|
||||
failure_reason: { type: string }
|
||||
recipients: { type: array, items: { $ref: '#/components/schemas/RecipientState' } }
|
||||
WebhookEvent:
|
||||
type: object
|
||||
required: [id, type, created_at, data]
|
||||
properties:
|
||||
id: { type: string }
|
||||
type:
|
||||
type: string
|
||||
enum: [message.queued, message.delivered, message.deferred, message.bounced, message.failed]
|
||||
created_at: { type: string, format: date-time }
|
||||
data:
|
||||
type: object
|
||||
required: [message_id, status]
|
||||
properties:
|
||||
message_id: { type: string }
|
||||
recipient: { type: [string, 'null'] }
|
||||
status: { type: string }
|
||||
Problem:
|
||||
type: object
|
||||
required: [type, title, status, detail, code]
|
||||
properties:
|
||||
type: { type: string, format: uri }
|
||||
title: { type: string }
|
||||
status: { type: integer }
|
||||
detail: { type: string }
|
||||
code: { type: string }
|
||||
+220
@@ -0,0 +1,220 @@
|
||||
:root {
|
||||
--bg: #f5f5f8;
|
||||
--surface: #ffffff;
|
||||
--surface-muted: #f8f8fb;
|
||||
--surface-hover: #f1f0f8;
|
||||
--border: #e5e4ea;
|
||||
--border-strong: #d7d5df;
|
||||
--text: #201f28;
|
||||
--text-soft: #65636f;
|
||||
--text-muted: #94919d;
|
||||
--accent: #6756e8;
|
||||
--accent-strong: #5949d1;
|
||||
--accent-soft: #eeebff;
|
||||
--green: #1e9b67;
|
||||
--green-soft: #eaf8f1;
|
||||
--amber: #bf7818;
|
||||
--amber-soft: #fff5df;
|
||||
--red: #cf4d55;
|
||||
--shadow: 0 18px 45px rgba(32, 29, 48, .12);
|
||||
}
|
||||
|
||||
:root[data-theme="dark"] {
|
||||
--bg: #15151a;
|
||||
--surface: #1e1e24;
|
||||
--surface-muted: #24242c;
|
||||
--surface-hover: #2a2933;
|
||||
--border: #32313b;
|
||||
--border-strong: #41404b;
|
||||
--text: #f4f3f8;
|
||||
--text-soft: #b9b6c3;
|
||||
--text-muted: #868390;
|
||||
--accent-soft: #2f294f;
|
||||
--green-soft: #18372a;
|
||||
--amber-soft: #3a2d18;
|
||||
color-scheme: dark;
|
||||
}
|
||||
|
||||
* { box-sizing: border-box; }
|
||||
html, body { min-height: 100%; }
|
||||
body { margin: 0; background: var(--bg); color: var(--text); font-family: Inter, ui-sans-serif, system-ui, -apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif; font-size: 14px; -webkit-font-smoothing: antialiased; }
|
||||
button, input, textarea { color: inherit; font: inherit; }
|
||||
button { border: 0; background: none; cursor: pointer; }
|
||||
button:focus-visible, input:focus-visible, textarea:focus-visible { outline: 2px solid var(--accent); outline-offset: 2px; }
|
||||
svg { stroke-width: 1.8; }
|
||||
|
||||
.brand { display: flex; align-items: center; height: 36px; gap: 8px; white-space: nowrap; }
|
||||
.brand-mark { width: 34px; height: 34px; border-radius: 10px; display: grid; place-items: center; color: #fff; background: var(--accent); box-shadow: 0 5px 12px rgba(103, 86, 232, .22); }
|
||||
.brand-name { font-weight: 760; letter-spacing: -.02em; font-size: 17px; }
|
||||
.brand-product { color: var(--text-soft); font-weight: 470; font-size: 16px; margin-left: -3px; }
|
||||
|
||||
.mail-shell { height: 100vh; min-height: 690px; overflow: hidden; background: var(--bg); }
|
||||
.mail-header { height: 68px; display: grid; grid-template-columns: 230px minmax(280px, 720px) 1fr; align-items: center; gap: 24px; padding: 0 22px; border-bottom: 1px solid var(--border); background: var(--surface); position: relative; z-index: 20; }
|
||||
.search-box { height: 42px; border: 1px solid transparent; border-radius: 11px; background: var(--surface-muted); display: flex; align-items: center; gap: 10px; padding: 0 13px; transition: border-color .2s, background .2s; }
|
||||
.search-box:focus-within { border-color: var(--border-strong); background: var(--surface); }
|
||||
.search-box > svg { width: 18px; color: var(--text-muted); }
|
||||
.search-box input { flex: 1; min-width: 0; border: 0; outline: 0; background: transparent; color: var(--text); }
|
||||
.search-box input::placeholder { color: var(--text-muted); }
|
||||
.search-box kbd { font-family: inherit; font-size: 11px; color: var(--text-muted); border: 1px solid var(--border); background: var(--surface); border-radius: 6px; padding: 3px 6px; }
|
||||
.search-box > svg:last-child { border-left: 1px solid var(--border); padding-left: 10px; width: 27px; }
|
||||
.header-actions { justify-self: end; display: flex; align-items: center; gap: 4px; }
|
||||
.header-actions > button, .admin-top-actions > button:not(.view-inbox) { width: 36px; height: 36px; border-radius: 9px; display: grid; place-items: center; color: var(--text-soft); position: relative; }
|
||||
.header-actions > button:hover, .admin-top-actions > button:hover { background: var(--surface-hover); color: var(--text); }
|
||||
.header-actions svg { width: 19px; }
|
||||
.sync-status { display: flex; align-items: center; gap: 7px; color: var(--text-muted); font-size: 12px; margin-right: 12px; }
|
||||
.sync-status i { width: 7px; height: 7px; border-radius: 50%; background: #29a66e; box-shadow: 0 0 0 3px var(--green-soft); }
|
||||
.header-actions .user-avatar { background: #2e2c39; color: white; font-size: 12px; font-weight: 650; margin-left: 6px; position: relative; }
|
||||
.user-avatar span { position: absolute; width: 9px; height: 9px; border: 2px solid var(--surface); border-radius: 50%; right: -1px; bottom: -1px; background: #32ac74; }
|
||||
.mobile-menu { display: none; }
|
||||
|
||||
.mail-layout { display: grid; grid-template-columns: 230px minmax(360px, 430px) minmax(500px, 1fr); height: calc(100vh - 68px); }
|
||||
.mail-sidebar { border-right: 1px solid var(--border); background: var(--surface); padding: 18px 12px; overflow-y: auto; }
|
||||
.compose-button { height: 42px; margin: 0 6px 18px; width: calc(100% - 12px); border-radius: 10px; background: var(--accent); color: #fff; display: flex; align-items: center; justify-content: center; gap: 9px; font-weight: 650; box-shadow: 0 7px 16px rgba(103, 86, 232, .22); }
|
||||
.compose-button:hover { background: var(--accent-strong); transform: translateY(-1px); }
|
||||
.compose-button svg { width: 17px; }
|
||||
.folders, .labels { display: grid; gap: 2px; }
|
||||
.folders button { display: grid; grid-template-columns: 22px 1fr auto; align-items: center; height: 36px; border-radius: 8px; padding: 0 11px; color: var(--text-soft); text-align: left; }
|
||||
.folders button svg { width: 17px; }
|
||||
.folders button:hover, .folders button.active { background: var(--surface-hover); color: var(--text); }
|
||||
.folders button.active { color: var(--accent); font-weight: 620; background: var(--accent-soft); }
|
||||
.folders button b { font-size: 11px; font-weight: 650; color: inherit; }
|
||||
.label-heading { border-top: 1px solid var(--border); margin: 18px 7px 8px; padding-top: 17px; display: flex; justify-content: space-between; align-items: center; color: var(--text-muted); text-transform: uppercase; font-size: 10px; font-weight: 700; letter-spacing: .08em; }
|
||||
.label-heading button { width: 24px; height: 24px; display: grid; place-items: center; color: var(--text-muted); }
|
||||
.label-heading svg { width: 15px; }
|
||||
.labels button { display: grid; grid-template-columns: 20px 1fr auto; align-items: center; height: 33px; border-radius: 7px; padding: 0 11px; color: var(--text-soft); text-align: left; font-size: 13px; }
|
||||
.labels button:hover { background: var(--surface-hover); }
|
||||
.labels button span { color: var(--text-muted); font-size: 11px; }
|
||||
.label-dot { width: 7px; height: 7px; border-radius: 50%; }
|
||||
.label-dot.clients { background: #5678dc; }.label-dot.design { background: #d85f81; }.label-dot.team { background: #52a874; }.label-dot.updates { background: #ad76d8; }
|
||||
.storage-widget { margin: 25px 8px 4px; padding-top: 17px; border-top: 1px solid var(--border); }
|
||||
.storage-widget > div:first-child { display: flex; justify-content: space-between; font-size: 11px; color: var(--text-muted); }
|
||||
.storage-widget strong { color: var(--text-soft); font-weight: 600; }
|
||||
.storage-track { margin: 8px 0 6px; background: var(--border); height: 4px; border-radius: 5px; overflow: hidden; }
|
||||
.storage-track i { display: block; width: 34%; height: 100%; background: var(--accent); }
|
||||
.storage-widget p { color: var(--text-muted); font-size: 10px; margin: 0; }
|
||||
.storage-widget button { margin-top: 14px; display: flex; align-items: center; gap: 7px; color: var(--accent); font-size: 11px; }
|
||||
.storage-widget button svg { width: 14px; }
|
||||
|
||||
.inbox-panel { min-width: 0; border-right: 1px solid var(--border); background: var(--surface); display: flex; flex-direction: column; }
|
||||
.list-toolbar, .reader-toolbar { height: 50px; min-height: 50px; padding: 0 13px; border-bottom: 1px solid var(--border); display: flex; align-items: center; gap: 3px; color: var(--text-muted); }
|
||||
.list-toolbar button, .reader-toolbar button { width: 32px; height: 32px; display: grid; place-items: center; border-radius: 8px; }
|
||||
.list-toolbar button:hover, .reader-toolbar button:hover { color: var(--text); background: var(--surface-hover); }
|
||||
.list-toolbar svg, .reader-toolbar svg { width: 17px; }
|
||||
.list-toolbar > div:first-child { display: flex; align-items: center; gap: 0; margin-right: 2px; }
|
||||
.list-toolbar > div:first-child > button { width: 22px; height: 22px; border: 1.5px solid var(--border-strong); border-radius: 6px; }
|
||||
.list-toolbar > div:first-child > button.checked { border-color: var(--accent); color: white; background: var(--accent); }
|
||||
.list-toolbar > div:first-child > svg { width: 13px; }
|
||||
.toolbar-divider { height: 19px; width: 1px; background: var(--border); margin: 0 5px; }
|
||||
.list-toolbar .range { margin-left: auto; font-size: 11px; }
|
||||
.message-list { overflow-y: auto; flex: 1; }
|
||||
.list-title { padding: 19px 20px 12px; display: flex; align-items: baseline; justify-content: space-between; }
|
||||
.list-title h1 { margin: 0; font-size: 19px; letter-spacing: -.02em; }
|
||||
.list-title span { color: var(--text-muted); font-size: 11px; }
|
||||
.message-list article { height: 114px; border-bottom: 1px solid var(--border); display: grid; grid-template-columns: 22px 36px minmax(0, 1fr) 26px; align-items: start; gap: 10px; padding: 13px 13px 11px; cursor: pointer; position: relative; transition: background .15s; }
|
||||
.message-list article:hover { background: var(--surface-muted); }
|
||||
.message-list article.selected { background: var(--accent-soft); box-shadow: inset 3px 0 var(--accent); }
|
||||
.message-list article.unread .message-meta strong, .message-list article.unread h2 { font-weight: 720; color: var(--text); }
|
||||
.row-check { width: 16px; height: 16px; border: 1.5px solid var(--border-strong); border-radius: 5px; display: grid; place-items: center; margin-top: 8px; opacity: 0; }
|
||||
article:hover .row-check, .row-check.active { opacity: 1; }
|
||||
.row-check.active { background: var(--accent); border-color: var(--accent); color: white; }
|
||||
.row-check svg { width: 11px; }
|
||||
.avatar { width: 34px; height: 34px; border-radius: 10px; display: grid; place-items: center; color: white; font-size: 10px; font-weight: 700; margin-top: 1px; }
|
||||
.avatar.small { width: 29px; height: 29px; }
|
||||
.avatar.coral { background: #d86f67; }.avatar.ink { background: #373641; }.avatar.violet { background: #7967c7; }.avatar.blue { background: #527dc4; }.avatar.green { background: #429b6d; }.avatar.amber { background: #c18a48; }
|
||||
.message-summary { min-width: 0; }
|
||||
.message-meta { display: flex; justify-content: space-between; gap: 7px; align-items: center; }
|
||||
.message-meta strong { font-size: 12px; color: var(--text-soft); white-space: nowrap; overflow: hidden; text-overflow: ellipsis; }
|
||||
.message-meta span { color: var(--text-muted); font-size: 10px; white-space: nowrap; }
|
||||
.subject-line { display: flex; align-items: center; gap: 5px; margin-top: 3px; }
|
||||
.subject-line h2 { margin: 0; font-size: 12px; font-weight: 590; line-height: 1.4; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; }
|
||||
.subject-line b { color: var(--text-muted); font-size: 9px; font-weight: 600; }
|
||||
.message-summary > p { margin: 3px 0 0; color: var(--text-muted); font-size: 11px; line-height: 1.35; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; }
|
||||
.row-labels { display: flex; gap: 5px; margin-top: 7px; }
|
||||
.row-labels span { font-size: 8px; text-transform: uppercase; letter-spacing: .04em; padding: 2px 5px; border-radius: 4px; background: var(--surface-hover); color: var(--text-muted); display: flex; align-items: center; gap: 2px; }
|
||||
.row-labels svg { width: 9px; }
|
||||
.star { width: 27px; height: 27px; display: grid; place-items: center; border-radius: 6px; color: var(--text-muted); }
|
||||
.star svg { width: 16px; }
|
||||
.star.active { color: #e0a62e; }
|
||||
.star.active svg { fill: currentColor; }
|
||||
.empty-state { min-height: 400px; display: grid; place-content: center; justify-items: center; color: var(--text-muted); }
|
||||
.empty-state > svg { width: 36px; height: 36px; opacity: .5; }
|
||||
.empty-state h2 { font-size: 15px; color: var(--text-soft); margin: 12px 0 2px; }.empty-state p { margin: 0; font-size: 12px; }
|
||||
|
||||
.reader-panel { background: var(--surface); min-width: 0; display: flex; flex-direction: column; }
|
||||
.reader-toolbar span { flex: 1; }
|
||||
.reader-back { display: none !important; }
|
||||
.reader-content { overflow-y: auto; padding: 28px clamp(28px, 4vw, 64px) 60px; max-width: 920px; width: 100%; margin: 0 auto; }
|
||||
.subject-header { display: flex; align-items: flex-start; gap: 12px; margin-bottom: 24px; }
|
||||
.subject-header > div { flex: 1; min-width: 0; }
|
||||
.subject-header h1 { margin: 0 0 9px; font-size: clamp(21px, 2.2vw, 28px); letter-spacing: -.035em; line-height: 1.25; }
|
||||
.subject-header > div > div { display: flex; gap: 5px; }
|
||||
.subject-header span { font-size: 9px; text-transform: uppercase; letter-spacing: .05em; border-radius: 4px; background: var(--surface-hover); color: var(--text-muted); padding: 3px 6px; }
|
||||
.sender-header { display: grid; grid-template-columns: 38px 1fr auto 32px; align-items: center; gap: 10px; border-bottom: 1px solid var(--border); padding-bottom: 18px; }
|
||||
.sender-header strong { font-size: 13px; }.sender-header p { display: flex; align-items: center; margin: 2px 0 0; color: var(--text-muted); font-size: 10px; }.sender-header p svg { width: 11px; }.sender-header time { color: var(--text-muted); font-size: 10px; }.sender-header button { color: var(--text-muted); }.sender-header button svg { width: 17px; }
|
||||
.remote-images { margin-top: 18px; height: 36px; padding: 0 11px; border: 1px solid var(--border); background: var(--surface-muted); color: var(--text-muted); border-radius: 7px; display: flex; align-items: center; gap: 8px; font-size: 10px; }
|
||||
.remote-images svg { width: 14px; color: var(--green); }.remote-images button { margin-left: auto; color: var(--accent); font-weight: 600; font-size: 10px; }
|
||||
.message-body { color: var(--text-soft); font-size: 14px; line-height: 1.75; padding: 22px 2px; }
|
||||
.message-body p { margin: 0 0 17px; }.message-body strong { color: var(--text); }.message-body ul { padding-left: 21px; }.message-body code { font-family: ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, monospace; background: var(--surface-hover); padding: 2px 5px; border-radius: 4px; font-size: 12px; }
|
||||
.attachments { border-top: 1px solid var(--border); padding: 18px 0; }.attachments > p { color: var(--text-muted); font-size: 10px; display: flex; align-items: center; gap: 5px; }.attachments > p svg { width: 13px; }.attachments > button { width: min(320px, 100%); height: 58px; padding: 8px; border: 1px solid var(--border); border-radius: 9px; display: grid; grid-template-columns: 40px 1fr 30px; align-items: center; gap: 9px; text-align: left; }.attachments > button:hover { border-color: var(--border-strong); background: var(--surface-muted); }.attachments > button > span { width: 40px; height: 40px; border-radius: 7px; background: #fff0f1; color: #ce505c; display: grid; place-items: center; }.attachments > button svg { width: 17px; }.attachments strong, .attachments small { display: block; }.attachments strong { font-size: 11px; }.attachments small { color: var(--text-muted); font-size: 9px; margin-top: 3px; }.attachments > button > svg { color: var(--text-muted); }
|
||||
.reply-actions { display: flex; gap: 8px; margin-top: 9px; }.reply-actions button { height: 36px; padding: 0 14px; display: flex; align-items: center; gap: 7px; border: 1px solid var(--border-strong); border-radius: 8px; color: var(--text-soft); font-size: 11px; }.reply-actions button:hover { background: var(--surface-hover); color: var(--text); }.reply-actions svg { width: 15px; }
|
||||
|
||||
.compose { position: fixed; right: 28px; bottom: 0; z-index: 50; width: min(570px, calc(100vw - 32px)); height: 570px; border: 1px solid var(--border); border-bottom: 0; border-radius: 13px 13px 0 0; background: var(--surface); box-shadow: var(--shadow); display: flex; flex-direction: column; overflow: hidden; animation: compose-in .22s ease-out; }
|
||||
@keyframes compose-in { from { transform: translateY(18px); opacity: 0; } }
|
||||
.compose header { min-height: 45px; background: #302e3d; color: #fff; padding: 0 13px 0 16px; display: flex; justify-content: space-between; align-items: center; font-size: 12px; font-weight: 600; }.compose header > div:first-child { display: flex; align-items: center; gap: 8px; }.compose-dot { width: 7px; height: 7px; border-radius: 50%; background: #9485ff; }.compose-actions { display: flex; }.compose-actions button { color: #cfccd7; width: 29px; height: 29px; display: grid; place-items: center; border-radius: 6px; }.compose-actions button:hover { background: rgba(255,255,255,.1); color: white; }
|
||||
.compose-fields { position: relative; padding: 4px 16px 0; }.compose-fields label { min-height: 41px; display: flex; align-items: center; border-bottom: 1px solid var(--border); gap: 8px; }.compose-fields label span { color: var(--text-muted); font-size: 11px; }.compose-fields input { width: 100%; border: 0; outline: 0; background: transparent; font-size: 12px; }.cc-button { position: absolute; right: 17px; top: 14px; color: var(--text-muted); font-size: 10px; }
|
||||
.compose > textarea { flex: 1; resize: none; border: 0; outline: 0; padding: 18px; background: transparent; color: var(--text); line-height: 1.6; }.compose > textarea::placeholder { color: var(--text-muted); }
|
||||
.compose footer { min-height: 58px; border-top: 1px solid var(--border); padding: 8px 11px; display: flex; align-items: center; justify-content: space-between; }.compose-tools, .compose-status { display: flex; align-items: center; gap: 3px; }.compose footer button:not(.send-button) { width: 34px; height: 34px; border-radius: 7px; display: grid; place-items: center; color: var(--text-muted); }.compose footer button:hover:not(.send-button) { background: var(--surface-hover); color: var(--text); }.send-button { height: 36px; padding: 0 12px; border-radius: 8px; background: var(--accent); color: white; display: flex; align-items: center; gap: 7px; font-weight: 600; }.send-button kbd { font: inherit; font-size: 8px; padding-left: 5px; opacity: .7; }.format-a { font-family: Georgia, serif; font-size: 18px; text-decoration: underline; }.compose-status span { color: var(--text-muted); font-size: 9px; margin-right: 4px; }
|
||||
.toast { position: fixed; left: 50%; bottom: 25px; transform: translateX(-50%); z-index: 80; min-width: 290px; height: 44px; padding: 0 10px 0 14px; background: #292731; color: white; box-shadow: var(--shadow); border-radius: 9px; display: flex; align-items: center; gap: 9px; font-size: 12px; animation: toast-in .2s ease-out; }.toast > svg { width: 17px; color: #6fd2a3; }.toast button { margin-left: auto; color: #b9b6c3; width: 28px; height: 28px; display: grid; place-items: center; }.toast button svg { width: 15px; }@keyframes toast-in { from { opacity: 0; transform: translate(-50%, 8px); } }
|
||||
|
||||
/* Administration */
|
||||
.admin-shell { min-height: 100vh; display: grid; grid-template-columns: 244px 1fr; background: var(--bg); }
|
||||
.admin-sidebar { min-height: 100vh; position: sticky; top: 0; height: 100vh; background: #22212b; color: #d9d7e2; padding: 18px 14px; display: flex; flex-direction: column; }
|
||||
.admin-sidebar .brand { margin: 0 8px 27px; }.admin-sidebar .brand-product { color: #9c99a8; }.admin-sidebar .brand-name { color: #fff; }
|
||||
.admin-sidebar nav { display: grid; gap: 3px; }.admin-sidebar nav button, .sidebar-bottom > button:not(.admin-user) { min-height: 40px; border-radius: 8px; padding: 0 11px; display: flex; align-items: center; gap: 10px; color: #aaa7b5; text-align: left; font-size: 12px; }.admin-sidebar nav button:hover, .admin-sidebar nav button.active, .sidebar-bottom > button:hover { background: #302e3d; color: #fff; }.admin-sidebar nav button.active { color: #fff; box-shadow: inset 2px 0 #8b7cf2; }.admin-sidebar nav svg, .sidebar-bottom svg { width: 17px; }.nav-badge { margin-left: auto; background: #4b425a; color: #d8cbff; border-radius: 10px; padding: 2px 6px; font-size: 9px; }
|
||||
.sidebar-bottom { margin-top: auto; display: grid; gap: 3px; }.admin-user { margin-top: 12px; border-top: 1px solid #393744; padding: 15px 7px 0; display: grid; grid-template-columns: 32px 1fr 20px; align-items: center; gap: 9px; color: #d9d7e2; text-align: left; }.admin-user > span { width: 31px; height: 31px; display: grid; place-items: center; border-radius: 8px; background: #57506b; font-size: 10px; font-weight: 700; }.admin-user strong,.admin-user small { display: block; }.admin-user strong { font-size: 11px; }.admin-user small { color: #8f8b99; font-size: 9px; margin-top: 2px; }.admin-user > svg { width: 16px; color: #777481; }
|
||||
.admin-main { min-width: 0; }.admin-top { height: 72px; border-bottom: 1px solid var(--border); background: var(--surface); padding: 0 30px; display: flex; align-items: center; }.admin-top h1 { font-size: 16px; margin: 0; letter-spacing: -.02em; }.admin-top p { color: var(--text-muted); font-size: 10px; margin: 3px 0 0; }.admin-top-actions { margin-left: auto; display: flex; align-items: center; gap: 7px; }.admin-top-actions .view-inbox { height: 34px; padding: 0 12px; display: flex; align-items: center; gap: 7px; border: 1px solid var(--border); border-radius: 8px; color: var(--text-soft); font-size: 11px; }.admin-top-actions .view-inbox:hover { background: var(--surface-muted); color: var(--text); }.admin-top-actions i { position: absolute; width: 6px; height: 6px; right: 7px; top: 7px; border-radius: 50%; background: var(--red); }
|
||||
.overview, .admin-section { width: min(1200px, calc(100% - 56px)); margin: 26px auto 60px; }
|
||||
.status-banner { min-height: 68px; padding: 12px 15px; display: grid; grid-template-columns: 39px 1fr auto; align-items: center; gap: 12px; background: var(--surface); border: 1px solid var(--border); border-radius: 11px; }.status-banner > span { width: 37px; height: 37px; border-radius: 9px; color: var(--green); background: var(--green-soft); display: grid; place-items: center; }.status-banner svg { width: 19px; }.status-banner strong { font-size: 12px; }.status-banner p { color: var(--text-muted); margin: 3px 0 0; font-size: 10px; }.status-banner button { color: var(--accent); display: flex; align-items: center; gap: 5px; font-size: 10px; font-weight: 600; }.status-banner button svg { width: 14px; }
|
||||
.metric-grid { display: grid; grid-template-columns: repeat(4, 1fr); gap: 13px; margin: 14px 0; }.metric-grid article { min-width: 0; min-height: 146px; padding: 17px; border: 1px solid var(--border); background: var(--surface); border-radius: 11px; }.metric-grid header { display: flex; align-items: center; justify-content: space-between; }.metric-grid header small { color: var(--text-muted); font-size: 9px; }.metric-icon { width: 31px; height: 31px; border-radius: 8px; display: grid; place-items: center; }.metric-icon svg { width: 16px; }.metric-icon.purple { color: var(--accent); background: var(--accent-soft); }.metric-icon.green { color: var(--green); background: var(--green-soft); }.metric-icon.blue { color: #4c78c9; background: #edf3ff; }.metric-icon.amber { color: var(--amber); background: var(--amber-soft); }.metric-grid article > strong { display: block; font-size: 25px; letter-spacing: -.04em; margin-top: 15px; }.metric-grid article > p { margin: 3px 0 0; color: var(--text-muted); font-size: 10px; }.metric-grid em { color: var(--green); font-style: normal; margin-left: 5px; }.storage-line { display: block; margin-top: 10px; height: 4px; background: var(--border); border-radius: 3px; overflow: hidden; }.storage-line i { display: block; width: 34%; height: 100%; background: #cf9242; }
|
||||
.overview-grid { display: grid; grid-template-columns: minmax(0, 1.7fr) minmax(280px, .8fr); gap: 14px; margin-top: 14px; }.overview-grid > article { background: var(--surface); border: 1px solid var(--border); border-radius: 11px; min-width: 0; }.delivery-chart { padding: 17px; }.delivery-chart > header, .domain-card > header, .recent-card > header { display: flex; justify-content: space-between; align-items: flex-start; }.overview h2 { margin: 0; font-size: 12px; }.overview header p { margin: 4px 0 0; color: var(--text-muted); font-size: 9px; }.delivery-chart header button { height: 29px; padding: 0 8px; border: 1px solid var(--border); border-radius: 7px; color: var(--text-soft); display: flex; align-items: center; gap: 5px; font-size: 9px; }.delivery-chart header button svg { width: 12px; }.chart { height: 158px; margin-top: 15px; display: grid; grid-template-columns: 25px 1fr; }.y-labels { display: flex; flex-direction: column; justify-content: space-between; color: var(--text-muted); font-size: 8px; padding-bottom: 2px; }.bars { border-left: 1px solid var(--border); border-bottom: 1px solid var(--border); display: flex; align-items: flex-end; justify-content: space-around; gap: 3px; padding: 0 8px; }.bars span { display: block; flex: 1; max-width: 11px; background: #bcb5eb; border-radius: 3px 3px 0 0; opacity: .65; }.bars span.recent { background: var(--accent); opacity: .9; }.x-labels { margin: 8px 2px 0 26px; display: flex; justify-content: space-between; color: var(--text-muted); font-size: 8px; }
|
||||
.attention-card { padding: 16px; }.attention-card header { display: flex; align-items: center; justify-content: space-between; border-bottom: 1px solid var(--border); padding-bottom: 12px; }.attention-card header span { min-width: 19px; height: 19px; padding: 0 6px; border-radius: 10px; background: #fff0e1; color: #bc6b1f; display: grid; place-items: center; font-size: 9px; }.attention-item { display: grid; grid-template-columns: 31px 1fr; gap: 10px; padding: 15px 0; border-bottom: 1px solid var(--border); }.attention-item:last-child { border: 0; padding-bottom: 0; }.attention-item > span { width: 31px; height: 31px; border-radius: 8px; display: grid; place-items: center; }.attention-item .warning { background: var(--amber-soft); color: var(--amber); }.attention-item .info { background: var(--accent-soft); color: var(--accent); }.attention-item svg { width: 15px; }.attention-item strong { font-size: 10px; }.attention-item p { color: var(--text-muted); margin: 3px 0 6px; font-size: 9px; line-height: 1.4; }.attention-item button { color: var(--accent); font-size: 9px; display: flex; align-items: center; gap: 4px; }.attention-item button svg { width: 11px; }
|
||||
.overview-grid.lower { grid-template-columns: 1fr 1fr; }.domain-card,.recent-card { padding: 16px; }.domain-card header,.recent-card header { padding-bottom: 11px; border-bottom: 1px solid var(--border); }.domain-card header button { color: var(--accent); font-size: 9px; }.recent-card header button { color: var(--text-muted); }.recent-card header svg { width: 14px; }.domain-row { min-height: 57px; display: grid; grid-template-columns: 32px 1fr auto; align-items: center; gap: 10px; border-bottom: 1px solid var(--border); }.domain-row:last-child,.delivery-row:last-child { border: 0; }.domain-icon { width: 30px; height: 30px; border-radius: 8px; display: grid; place-items: center; color: var(--accent); background: var(--accent-soft); }.domain-icon svg { width: 14px; }.domain-row strong,.domain-row small { display: block; }.domain-row strong { font-size: 10px; }.domain-row small { margin-top: 3px; color: var(--text-muted); font-size: 8px; }.domain-row > span:last-child { font-size: 8px; display: flex; align-items: center; gap: 5px; }.domain-row .healthy { color: var(--green); }.domain-row .pending { color: var(--amber); }.domain-row > span:last-child i { width: 6px; height: 6px; border-radius: 50%; background: currentColor; }.delivery-row { min-height: 57px; display: grid; grid-template-columns: 29px 1fr auto; align-items: center; gap: 9px; border-bottom: 1px solid var(--border); }.delivery-row > span { width: 27px; height: 27px; display: grid; place-items: center; border-radius: 50%; }.delivery-row > span.delivered { color: var(--green); background: var(--green-soft); }.delivery-row > span.deferred { color: var(--amber); background: var(--amber-soft); }.delivery-row svg { width: 13px; }.delivery-row strong,.delivery-row small { display: block; }.delivery-row strong { font-size: 10px; }.delivery-row small { color: var(--text-muted); font-size: 8px; margin-top: 3px; }.delivery-row em { color: var(--text-muted); font-style: normal; font-size: 8px; }
|
||||
.section-heading { display: flex; justify-content: space-between; align-items: flex-end; margin-bottom: 18px; }.section-heading h2 { font-size: 21px; margin: 0; letter-spacing: -.03em; }.section-heading p { margin: 5px 0 0; color: var(--text-muted); font-size: 11px; }.section-heading button { background: var(--accent); color: white; border-radius: 8px; padding: 0 13px; height: 36px; display: flex; align-items: center; gap: 7px; font-size: 11px; font-weight: 600; }.section-heading button svg { width: 15px; }.settings-card { border: 1px solid var(--border); background: var(--surface); border-radius: 11px; overflow: hidden; }.table-head { height: 39px; display: grid; grid-template-columns: minmax(200px, 1fr) 1fr 170px 40px; align-items: center; padding: 0 15px 0 62px; background: var(--surface-muted); color: var(--text-muted); font-size: 9px; text-transform: uppercase; letter-spacing: .05em; }.settings-row { min-height: 66px; display: grid; grid-template-columns: 36px minmax(150px, 1fr) 1fr 170px 40px; align-items: center; gap: 10px; padding: 0 15px; border-top: 1px solid var(--border); }.row-icon { width: 31px; height: 31px; border-radius: 8px; display: grid; place-items: center; color: var(--accent); background: var(--accent-soft); }.row-icon svg { width: 15px; }.settings-row strong { font-size: 11px; }.settings-row > span:not(.row-icon) { color: var(--text-soft); font-size: 10px; }.settings-row em { font-style: normal; display: flex; align-items: center; gap: 6px; font-size: 9px; }.settings-row em i { width: 6px; height: 6px; border-radius: 50%; background: currentColor; }.settings-row em.good { color: var(--green); }.settings-row em.warn { color: var(--amber); }.settings-row button { color: var(--text-muted); }.settings-row button svg { width: 17px; }
|
||||
|
||||
.admin-empty { min-height: 210px; display: grid; place-content: center; justify-items: center; color: var(--text-muted); }.admin-empty > svg { width: 30px; height: 30px; opacity: .5; }.admin-empty strong { margin-top: 11px; color: var(--text-soft); font-size: 12px; }.admin-empty span { margin-top: 4px; font-size: 9px; }.admin-modal-backdrop { position: fixed; inset: 0; z-index: 90; display: grid; place-items: center; padding: 20px; background: rgba(27,25,35,.58); }.admin-modal { width: min(480px,100%); max-height: calc(100vh - 40px); overflow-y: auto; padding: 20px; border: 1px solid var(--border); border-radius: 14px; background: var(--surface); box-shadow: var(--shadow); animation: fade-in .18s ease-out; }.admin-modal > header { display: grid; grid-template-columns: 38px 1fr 32px; gap: 11px; align-items: center; padding-bottom: 17px; border-bottom: 1px solid var(--border); }.admin-modal h3 { margin: 0; font-size: 16px; }.admin-modal header p { margin: 4px 0 0; color: var(--text-muted); font-size: 9px; }.admin-modal header > button { width: 31px; height: 31px; display: grid; place-items: center; border-radius: 7px; color: var(--text-muted); }.admin-modal header > button:hover { background: var(--surface-hover); }.admin-modal header > button svg { width: 17px; }.admin-modal label { display: block; margin-top: 18px; color: var(--text-soft); font-size: 11px; font-weight: 650; }.admin-modal input { display: block; width: 100%; height: 43px; margin-top: 7px; padding: 0 11px; border: 1px solid var(--border-strong); border-radius: 8px; background: var(--surface); outline: 0; }.admin-modal input:focus { border-color: var(--accent); box-shadow: 0 0 0 3px var(--accent-soft); }.admin-modal label small { display: block; color: var(--text-muted); font-size: 9px; margin-top: 7px; font-weight: 400; }.admin-modal > footer { display: flex; justify-content: flex-end; gap: 8px; margin-top: 22px; }.admin-modal > footer button { height: 36px; padding: 0 13px; border: 1px solid var(--border); border-radius: 8px; font-size: 10px; }.admin-modal > footer .primary { border-color: var(--accent); background: var(--accent); color: #fff; }.secret-result { padding: 26px 4px 6px; text-align: center; }.secret-result > svg { width: 32px; height: 32px; color: var(--green); }.secret-result strong { display: block; margin-top: 11px; }.secret-result p { color: var(--text-muted); font-size: 10px; }.secret-result code { display: block; overflow-wrap: anywhere; margin: 18px 0 12px; padding: 13px; border: 1px solid var(--border); border-radius: 8px; background: var(--surface-muted); color: var(--text); font-size: 11px; text-align: left; }.secret-result button { height: 34px; padding: 0 12px; display: inline-flex; align-items: center; gap: 7px; border-radius: 8px; background: var(--accent); color: #fff; font-size: 10px; }.secret-result button svg { width: 14px; }
|
||||
|
||||
/* Setup */
|
||||
.setup-screen { min-height: 100vh; display: grid; grid-template-columns: minmax(370px, 44%) 1fr; background: var(--surface); }
|
||||
.setup-aside { position: relative; min-height: 100vh; background: #22212b; color: white; padding: 38px clamp(35px, 6vw, 90px); display: flex; flex-direction: column; overflow: hidden; }.setup-aside::after { content: ""; position: absolute; width: 380px; height: 380px; border: 1px solid #3c3948; border-radius: 50%; right: -210px; bottom: 70px; box-shadow: 0 0 0 70px #292733, 0 0 0 71px #3c3948, 0 0 0 140px #25232f, 0 0 0 141px #34323f; }.setup-aside .brand { position: relative; z-index: 1; }.setup-aside .brand-product { color: #a7a3b1; }.setup-copy { margin: auto 0; max-width: 480px; position: relative; z-index: 1; }.eyebrow { color: #a99cff; font-size: 10px; letter-spacing: .14em; font-weight: 700; }.setup-copy h1 { font-size: clamp(34px, 4vw, 56px); letter-spacing: -.055em; line-height: 1.02; margin: 20px 0; }.setup-copy p { color: #aaa7b4; font-size: 15px; line-height: 1.65; max-width: 390px; }.setup-assurance { display: grid; grid-template-columns: 28px 1fr; gap: 11px; position: relative; z-index: 1; }.setup-assurance > svg { color: #9c8eff; width: 21px; }.setup-assurance strong,.setup-assurance span { display: block; }.setup-assurance strong { font-size: 11px; }.setup-assurance span { margin-top: 4px; color: #8e8b98; font-size: 9px; }
|
||||
.setup-main { min-height: 100vh; display: flex; flex-direction: column; padding: 34px clamp(35px, 7vw, 110px); }.setup-progress { display: grid; grid-template-columns: 50px 1fr 50px; align-items: center; gap: 12px; color: var(--text-muted); text-transform: uppercase; letter-spacing: .08em; font-size: 9px; }.setup-progress > span:last-child { text-align: right; }.setup-progress > div { display: grid; grid-template-columns: repeat(3, 1fr); gap: 5px; }.setup-progress i { height: 3px; border-radius: 4px; background: var(--border); }.setup-progress i.active { background: var(--accent); }.setup-main section { width: min(510px, 100%); margin: auto; animation: fade-in .25s ease-out; }@keyframes fade-in { from { opacity: .4; transform: translateY(5px); } }.step-icon { width: 45px; height: 45px; border-radius: 12px; display: grid; place-items: center; color: var(--accent); background: var(--accent-soft); }.step-icon svg { width: 21px; }.setup-main section h2 { margin: 19px 0 8px; font-size: 27px; letter-spacing: -.04em; }.setup-main section > p { color: var(--text-muted); margin: 0 0 27px; line-height: 1.5; }.setup-main label { display: block; color: var(--text-soft); font-size: 11px; margin-top: 18px; font-weight: 600; }.setup-main input { display: block; margin-top: 7px; width: 100%; height: 43px; border: 1px solid var(--border-strong); border-radius: 8px; background: var(--surface); padding: 0 12px; outline: 0; }.setup-main input:focus { border-color: var(--accent); box-shadow: 0 0 0 3px var(--accent-soft); }.field-note { margin-top: 12px; display: flex; gap: 7px; align-items: center; color: var(--green); font-size: 10px; }.field-note svg { width: 14px; }.accent-choice { display: flex; gap: 9px; margin-top: 9px; }.color-choice { width: 28px; height: 28px; border-radius: 50%; box-shadow: none; }.color-choice.active { box-shadow: 0 0 0 3px var(--surface), 0 0 0 5px var(--accent); }.delivery-choice { width: 100%; min-height: 80px; margin-bottom: 10px; border: 1px solid var(--border); border-radius: 10px; padding: 12px; display: grid; grid-template-columns: 42px 1fr 24px; gap: 12px; align-items: center; text-align: left; }.delivery-choice:hover,.delivery-choice.active { border-color: var(--accent); background: var(--accent-soft); }.delivery-choice > span { width: 40px; height: 40px; display: grid; place-items: center; border-radius: 9px; color: var(--accent); background: var(--surface); }.delivery-choice > span svg { width: 19px; }.delivery-choice strong { font-size: 12px; }.delivery-choice p { margin: 4px 0 0; color: var(--text-muted); font-size: 10px; }.delivery-choice > svg { color: var(--accent); width: 19px; }.setup-main > footer { display: flex; justify-content: space-between; align-items: center; }.setup-main footer button { height: 39px; border-radius: 8px; padding: 0 15px; font-size: 11px; font-weight: 600; }.setup-main footer .secondary { border: 1px solid var(--border); }.setup-main footer .secondary:disabled { opacity: 0; pointer-events: none; }.setup-main footer .primary { background: var(--accent); color: #fff; display: flex; align-items: center; gap: 8px; }.setup-main footer svg { width: 15px; }
|
||||
|
||||
.setup-finished { min-height: 100vh; display: grid; place-items: center; padding: 28px; background: var(--bg); }.setup-finished > div { width: min(620px,100%); padding: clamp(24px,5vw,48px); border: 1px solid var(--border); border-radius: 16px; background: var(--surface); box-shadow: var(--shadow); }.setup-finished h1 { margin: 20px 0 10px; font-size: 30px; letter-spacing: -.04em; }.setup-finished p { color: var(--text-soft); line-height: 1.6; }.setup-finished p code { color: var(--accent); font-weight: 650; }.setup-finished pre { max-height: 250px; overflow: auto; margin: 22px 0 12px; padding: 15px; border: 1px solid var(--border); border-radius: 9px; background: var(--surface-muted); font: 10px/1.6 ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, monospace; white-space: pre-wrap; overflow-wrap: anywhere; }.setup-warning { display: flex; align-items: center; gap: 7px; color: var(--green); font-size: 10px; }.setup-warning svg { width: 15px; }.setup-finished .primary { height: 42px; margin-top: 24px; padding: 0 15px; display: flex; align-items: center; gap: 8px; border-radius: 9px; background: var(--accent); color: #fff; font-weight: 650; }.setup-finished .primary svg { width: 16px; }
|
||||
|
||||
/* Authentication */
|
||||
.app-loading { min-height: 100vh; display: grid; place-content: center; justify-items: center; gap: 18px; background: var(--surface); color: var(--text-muted); }.app-loading .brand { margin-bottom: 18px; }.app-loading > svg { width: 21px; color: var(--accent); }.app-loading > span { font-size: 11px; }
|
||||
.spin { animation: spin .8s linear infinite; }@keyframes spin { to { transform: rotate(360deg); } }
|
||||
.login-screen { min-height: 100vh; display: grid; grid-template-columns: minmax(390px, 43%) 1fr; background: var(--surface); }.login-story { min-height: 100vh; padding: 40px clamp(36px,6vw,92px); color: #fff; background: #22212b; display: flex; flex-direction: column; position: relative; overflow: hidden; }.login-story::before,.login-story::after { content: ""; position: absolute; border: 1px solid #3d394b; border-radius: 50%; }.login-story::before { width: 520px; height: 520px; right: -290px; top: 20%; box-shadow: 0 0 0 85px #292733,0 0 0 86px #3a3745; }.login-story::after { width: 180px; height: 180px; left: -110px; bottom: 14%; }.login-story .brand,.login-story > div,.login-security { position: relative; z-index: 1; }.login-story .brand-product { color: #aaa6b5; }.login-story > div { margin: auto 0; max-width: 450px; }.login-story h1 { margin: 20px 0 13px; font-size: clamp(43px,5vw,68px); line-height: 1; letter-spacing: -.06em; }.login-story p { color: #aaa7b4; line-height: 1.65; font-size: 15px; }.login-security { display: flex; align-items: center; gap: 9px; color: #aaa7b4; font-size: 10px; }.login-security svg { width: 18px; color: #9f92ff; }.login-screen > main { display: grid; place-items: center; padding: 32px; }.login-card { width: min(410px,100%); }.login-icon { width: 48px; height: 48px; display: grid; place-items: center; border-radius: 13px; color: var(--accent); background: var(--accent-soft); }.login-icon svg { width: 22px; }.login-card h2 { margin: 22px 0 7px; font-size: 27px; letter-spacing: -.04em; }.login-card > p { margin: 0 0 28px; color: var(--text-muted); }.login-card label { display: block; margin-top: 18px; color: var(--text-soft); font-size: 11px; font-weight: 650; }.login-card input { display: block; width: 100%; height: 45px; margin-top: 7px; padding: 0 12px; border: 1px solid var(--border-strong); border-radius: 9px; background: var(--surface); outline: 0; }.login-card input:focus { border-color: var(--accent); box-shadow: 0 0 0 3px var(--accent-soft); }.form-error { min-height: 39px; margin-top: 16px; padding: 9px 11px; display: flex; align-items: center; gap: 8px; border-radius: 8px; background: #fff0f1; color: #ae3f49; font-size: 10px; line-height: 1.4; }.form-error svg { width: 16px; min-width: 16px; }.login-submit { width: 100%; height: 43px; margin-top: 19px; display: flex; justify-content: center; align-items: center; gap: 8px; border-radius: 9px; background: var(--accent); color: #fff; font-weight: 650; }.login-submit:hover { background: var(--accent-strong); }.login-submit:disabled,.setup-main .primary:disabled { opacity: .7; cursor: wait; }.login-submit svg { width: 17px; }.login-card > small { display: block; margin-top: 16px; color: var(--text-muted); text-align: center; font-size: 9px; }
|
||||
|
||||
@media (max-width: 1180px) {
|
||||
.mail-header { grid-template-columns: 200px minmax(260px, 1fr) auto; }.sync-status { display: none; }
|
||||
.mail-layout { grid-template-columns: 205px minmax(340px, 400px) 1fr; }
|
||||
.reader-content { padding-inline: 28px; }
|
||||
}
|
||||
|
||||
@media (max-width: 960px) {
|
||||
.mail-header { grid-template-columns: 34px 160px 1fr auto; padding-inline: 13px; gap: 10px; }.mail-header > .mobile-menu { display: grid; place-items: center; color: var(--text-soft); }.search-box { grid-column: 3; }.header-actions > button:not(.user-avatar):not(:first-of-type) { display: none; }.brand-product { display: none; }
|
||||
.mail-layout { grid-template-columns: minmax(330px, 390px) 1fr; }.mail-sidebar { position: fixed; left: 0; top: 68px; bottom: 0; width: 230px; z-index: 30; transform: translateX(-100%); box-shadow: var(--shadow); transition: transform .2s; }.mail-sidebar.open { transform: translateX(0); }.inbox-panel { grid-column: 1; }.reader-panel { grid-column: 2; }
|
||||
.metric-grid { grid-template-columns: 1fr 1fr; }.overview-grid { grid-template-columns: 1fr; }
|
||||
.setup-screen { grid-template-columns: 1fr; }.setup-aside { min-height: 300px; padding-block: 28px; }.setup-copy { margin: 60px 0 40px; }.setup-copy h1 { max-width: 600px; }.setup-assurance { display: none; }.setup-main { min-height: 660px; }
|
||||
.login-screen { grid-template-columns: 1fr; }.login-story { min-height: 260px; padding-block: 28px; }.login-story > div { margin: 52px 0 25px; }.login-story h1 { font-size: 39px; }.login-security { display: none; }.login-screen > main { min-height: 580px; }
|
||||
}
|
||||
|
||||
@media (max-width: 720px) {
|
||||
.mail-shell { min-height: 100vh; height: auto; }.mail-header { height: 62px; grid-template-columns: 32px 38px 1fr auto; }.mail-header .brand-name { display: none; }.search-box { height: 38px; }.search-box kbd,.search-box > svg:last-child { display: none; }.mail-layout { display: block; height: calc(100vh - 62px); }.mail-sidebar { top: 62px; }.inbox-panel { height: 100%; }.reader-panel { position: fixed; inset: 62px 0 0; z-index: 18; transform: translateX(100%); }.message-list article.selected + * {} .reader-panel { display: none; }
|
||||
.compose { width: 100%; height: calc(100vh - 20px); max-height: none; left: 0; right: 0; }
|
||||
.admin-shell { display: block; }.admin-sidebar { display: none; }.admin-top { padding-inline: 16px; }.admin-top .mobile-menu { display: grid; margin-right: 10px; }.overview,.admin-section { width: calc(100% - 26px); margin-top: 14px; }.status-banner { grid-template-columns: 38px 1fr; }.status-banner button { display: none; }.metric-grid { grid-template-columns: 1fr; }.overview-grid.lower { grid-template-columns: 1fr; }.table-head { display: none; }.settings-row { grid-template-columns: 36px 1fr 30px; padding: 12px; }.settings-row > span:not(.row-icon),.settings-row em { grid-column: 2; }.settings-row button { grid-column: 3; grid-row: 1; }
|
||||
.setup-aside { min-height: 250px; }.setup-copy { margin: 45px 0 20px; }.setup-copy h1 { font-size: 34px; }.setup-main { padding: 25px 22px; min-height: 620px; }.setup-main section h2 { font-size: 23px; }
|
||||
.login-story { min-height: 205px; padding: 25px 24px; }.login-story > div { margin: 34px 0 10px; }.login-story h1 { font-size: 34px; margin-block: 13px 8px; }.login-story p { font-size: 12px; margin: 0; }.login-screen > main { min-height: calc(100vh - 205px); padding: 28px 24px; }.login-card h2 { font-size: 23px; }
|
||||
}
|
||||
|
||||
@media (prefers-reduced-motion: reduce) { *, *::before, *::after { scroll-behavior: auto !important; animation-duration: .01ms !important; transition-duration: .01ms !important; } }
|
||||
+646
@@ -0,0 +1,646 @@
|
||||
"use client";
|
||||
/* eslint-disable jsx-a11y/no-autofocus -- Focus is moved into the newly opened modal dialog. */
|
||||
/* eslint-disable @typescript-eslint/no-explicit-any -- Stalwart JMAP payloads are runtime-discovered until the pinned adapter returns them. */
|
||||
/* eslint-disable react-hooks/set-state-in-effect -- Initial JMAP and admin data are intentionally loaded from effects. */
|
||||
/* eslint-disable jsx-a11y/no-static-element-interactions -- The modal backdrop supplements its explicit close button. */
|
||||
/* eslint-disable jsx-a11y/no-noninteractive-element-to-interactive-role -- Mail rows are keyboard-operable composites with nested selection and star controls. */
|
||||
|
||||
import DOMPurify from "dompurify";
|
||||
import {
|
||||
AlertTriangle,
|
||||
Archive,
|
||||
ArrowLeft,
|
||||
ArrowRight,
|
||||
Bell,
|
||||
Check,
|
||||
CheckCircle2,
|
||||
ChevronDown,
|
||||
ChevronRight,
|
||||
CircleUserRound,
|
||||
Clock3,
|
||||
Copy,
|
||||
Download,
|
||||
FileText,
|
||||
Forward,
|
||||
Gauge,
|
||||
Globe2,
|
||||
HelpCircle,
|
||||
Inbox,
|
||||
KeyRound,
|
||||
LifeBuoy,
|
||||
Mail,
|
||||
Menu,
|
||||
Moon,
|
||||
MoreHorizontal,
|
||||
Paperclip,
|
||||
Pencil,
|
||||
Plus,
|
||||
RefreshCw,
|
||||
Reply,
|
||||
Search,
|
||||
Send,
|
||||
Server,
|
||||
Settings,
|
||||
ShieldCheck,
|
||||
SlidersHorizontal,
|
||||
Smile,
|
||||
Sparkles,
|
||||
Star,
|
||||
Sun,
|
||||
Tag,
|
||||
Trash2,
|
||||
Users,
|
||||
Webhook,
|
||||
X,
|
||||
Zap,
|
||||
} from "lucide-react";
|
||||
import { useCallback, useEffect, useMemo, useRef, useState } from "react";
|
||||
|
||||
type FolderName = "Inbox" | "Starred" | "Snoozed" | "Sent" | "Drafts" | "Archive" | "Spam" | "Trash";
|
||||
type Message = {
|
||||
id: number | string;
|
||||
sender: string;
|
||||
email: string;
|
||||
initials: string;
|
||||
color: string;
|
||||
subject: string;
|
||||
preview: string;
|
||||
time: string;
|
||||
date: string;
|
||||
unread: boolean;
|
||||
starred: boolean;
|
||||
labels: string[];
|
||||
folder: FolderName;
|
||||
body: string;
|
||||
attachments?: { name: string; size: string; kind: string }[];
|
||||
threadCount?: number;
|
||||
serverId?: string;
|
||||
mailboxIds?: string[];
|
||||
};
|
||||
|
||||
type ComposeMessage = { to: string; cc: string; bcc: string; subject: string; body: string };
|
||||
|
||||
const initialMessages: Message[] = [
|
||||
{
|
||||
id: 1,
|
||||
sender: "Lina Park",
|
||||
email: "lina@northstar.studio",
|
||||
initials: "LP",
|
||||
color: "coral",
|
||||
subject: "Q3 design review — final notes",
|
||||
preview: "I pulled the final comments into one place. The new navigation feels much calmer now…",
|
||||
time: "10:42",
|
||||
date: "Aug 12, 2026, 10:42 AM",
|
||||
unread: true,
|
||||
starred: true,
|
||||
labels: ["Design"],
|
||||
folder: "Inbox",
|
||||
threadCount: 4,
|
||||
body: `<p>Hi Alex,</p><p>I pulled the final comments into one place. The new navigation feels much calmer now, and the product team is aligned on the reduced color palette.</p><p>The only open item is the export flow. I’ve attached the marked-up review so we can close it in tomorrow’s session.</p><p>Thanks,<br><strong>Lina</strong></p>`,
|
||||
attachments: [{ name: "Q3-design-review.pdf", size: "2.4 MB", kind: "PDF" }],
|
||||
},
|
||||
{
|
||||
id: 2,
|
||||
sender: "GitHub",
|
||||
email: "notifications@github.com",
|
||||
initials: "GH",
|
||||
color: "ink",
|
||||
subject: "[acme/platform] Production deploy succeeded",
|
||||
preview: "Deployment #2841 completed successfully in 3m 12s. All health checks are passing.",
|
||||
time: "9:18",
|
||||
date: "Aug 12, 2026, 9:18 AM",
|
||||
unread: true,
|
||||
starred: false,
|
||||
labels: ["Updates"],
|
||||
folder: "Inbox",
|
||||
body: `<p><strong>Production deploy succeeded</strong></p><p>Deployment <code>#2841</code> completed successfully in 3m 12s.</p><p>All 18 health checks are passing. Version <strong>2026.08.12-rc3</strong> is now serving 100% of production traffic.</p>`,
|
||||
},
|
||||
{
|
||||
id: 3,
|
||||
sender: "Owen Chen",
|
||||
email: "owen@springlabs.io",
|
||||
initials: "OC",
|
||||
color: "violet",
|
||||
subject: "Re: Partnership timeline",
|
||||
preview: "Thursday at 2 PM works. I’ll bring our solutions architect so we can cover the SSO questions…",
|
||||
time: "8:51",
|
||||
date: "Aug 12, 2026, 8:51 AM",
|
||||
unread: false,
|
||||
starred: false,
|
||||
labels: ["Clients"],
|
||||
folder: "Inbox",
|
||||
threadCount: 3,
|
||||
body: `<p>Thursday at 2 PM works for us.</p><p>I’ll bring our solutions architect so we can cover the SSO and data-residency questions in the same call. The pilot scope looks right from our side.</p><p>Looking forward to it,<br>Owen</p>`,
|
||||
},
|
||||
{
|
||||
id: 4,
|
||||
sender: "Maya Thompson",
|
||||
email: "maya@meovv.company",
|
||||
initials: "MT",
|
||||
color: "blue",
|
||||
subject: "Team offsite: venue options",
|
||||
preview: "I found three places that fit the dates and budget. My vote is for the lakeside workshop space…",
|
||||
time: "Yesterday",
|
||||
date: "Aug 11, 2026, 4:26 PM",
|
||||
unread: false,
|
||||
starred: true,
|
||||
labels: ["Team"],
|
||||
folder: "Inbox",
|
||||
body: `<p>Hey team,</p><p>I found three places that fit the dates and budget. My vote is for the lakeside workshop space—the main room has enough wall space for planning, and there’s a quiet garden for one-on-ones.</p><p>Please add your preference before Friday.</p>`,
|
||||
attachments: [{ name: "venue-comparison.xlsx", size: "148 KB", kind: "XLSX" }],
|
||||
},
|
||||
{
|
||||
id: 5,
|
||||
sender: "Postmaster",
|
||||
email: "postmaster@mail.meovv.company",
|
||||
initials: "PM",
|
||||
color: "green",
|
||||
subject: "Weekly deliverability report",
|
||||
preview: "98.7% of outbound mail was accepted on the first attempt. No blocklist listings detected.",
|
||||
time: "Yesterday",
|
||||
date: "Aug 11, 2026, 7:00 AM",
|
||||
unread: false,
|
||||
starred: false,
|
||||
labels: ["System"],
|
||||
folder: "Inbox",
|
||||
body: `<p>Your weekly deliverability summary is ready.</p><ul><li><strong>98.7%</strong> accepted on first attempt</li><li><strong>0.3%</strong> temporarily deferred</li><li><strong>0</strong> blocklist listings detected</li></ul><p>SPF, DKIM, and DMARC are aligned for all active domains.</p>`,
|
||||
},
|
||||
{
|
||||
id: 6,
|
||||
sender: "Nora Ibrahim",
|
||||
email: "nora@meovv.company",
|
||||
initials: "NI",
|
||||
color: "amber",
|
||||
subject: "Updated hiring plan",
|
||||
preview: "Finance approved the two platform roles. I’ve updated the headcount model and interview loop…",
|
||||
time: "Mon",
|
||||
date: "Aug 10, 2026, 3:14 PM",
|
||||
unread: false,
|
||||
starred: false,
|
||||
labels: ["Team"],
|
||||
folder: "Inbox",
|
||||
body: `<p>Finance approved the two platform roles.</p><p>I’ve updated the headcount model and interview loop. We can publish both positions after your final review.</p>`,
|
||||
attachments: [{ name: "hiring-plan-v4.pdf", size: "864 KB", kind: "PDF" }],
|
||||
},
|
||||
{
|
||||
id: 7,
|
||||
sender: "Linear",
|
||||
email: "updates@linear.app",
|
||||
initials: "LI",
|
||||
color: "violet",
|
||||
subject: "Your workspace digest",
|
||||
preview: "14 issues completed, 9 created, and 2 projects moved to the next milestone this week.",
|
||||
time: "Mon",
|
||||
date: "Aug 10, 2026, 8:05 AM",
|
||||
unread: false,
|
||||
starred: false,
|
||||
labels: ["Updates"],
|
||||
folder: "Inbox",
|
||||
body: `<p>Here’s what happened in your workspace this week:</p><p><strong>14</strong> issues completed · <strong>9</strong> created · <strong>2</strong> projects advanced</p>`,
|
||||
},
|
||||
{
|
||||
id: 8,
|
||||
sender: "Alex Morgan",
|
||||
email: "meghdad@meovv.company",
|
||||
initials: "ME",
|
||||
color: "blue",
|
||||
subject: "Re: Architecture decision record",
|
||||
preview: "The signed decision record and follow-up actions are attached for the platform group.",
|
||||
time: "Sun",
|
||||
date: "Aug 9, 2026, 2:31 PM",
|
||||
unread: false,
|
||||
starred: false,
|
||||
labels: ["Engineering"],
|
||||
folder: "Sent",
|
||||
body: `<p>Hi all,</p><p>The signed decision record and follow-up actions are attached for the platform group. Please use this as the source of truth going forward.</p>`,
|
||||
},
|
||||
];
|
||||
|
||||
const folders: { name: FolderName; icon: typeof Inbox; count?: number }[] = [
|
||||
{ name: "Inbox", icon: Inbox, count: 5 },
|
||||
{ name: "Starred", icon: Star },
|
||||
{ name: "Snoozed", icon: Clock3 },
|
||||
{ name: "Sent", icon: Send },
|
||||
{ name: "Drafts", icon: FileText, count: 2 },
|
||||
{ name: "Archive", icon: Archive },
|
||||
{ name: "Spam", icon: ShieldCheck },
|
||||
{ name: "Trash", icon: Trash2 },
|
||||
];
|
||||
|
||||
const adminNav = [
|
||||
{ id: "overview", label: "Overview", icon: Gauge },
|
||||
{ id: "domains", label: "Domains", icon: Globe2 },
|
||||
{ id: "people", label: "People & aliases", icon: Users },
|
||||
{ id: "delivery", label: "Delivery", icon: Send },
|
||||
{ id: "api", label: "API keys", icon: KeyRound },
|
||||
{ id: "webhooks", label: "Webhooks", icon: Webhook },
|
||||
{ id: "backups", label: "Backups", icon: Download },
|
||||
];
|
||||
|
||||
function SafeHtml({ html }: { html: string }) {
|
||||
const sanitized = useMemo(() => DOMPurify.sanitize(html, { FORBID_TAGS: ["style", "iframe", "form"], FORBID_ATTR: ["style"] }), [html]);
|
||||
return <div className="message-body" dir="auto" dangerouslySetInnerHTML={{ __html: sanitized }} />;
|
||||
}
|
||||
|
||||
function Logo({ compact = false }: { compact?: boolean }) {
|
||||
return (
|
||||
<div className="brand" aria-label="MEOVV Mail">
|
||||
<span className="brand-mark"><Mail size={18} strokeWidth={2.25} /></span>
|
||||
{!compact && <><span className="brand-name">MEOVV</span><span className="brand-product">Mail</span></>}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function base64url(bytes: ArrayBuffer) {
|
||||
return btoa(String.fromCharCode(...new Uint8Array(bytes))).replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, "");
|
||||
}
|
||||
|
||||
function escapeHTML(value: string) {
|
||||
return value.replace(/&/g, "&").replace(/</g, "<").replace(/>/g, ">").replace(/"/g, """);
|
||||
}
|
||||
|
||||
function addressList(value: string) {
|
||||
return value.split(",").map((email) => email.trim()).filter(Boolean).map((email) => ({ email }));
|
||||
}
|
||||
|
||||
function Login({ onAuthenticated }: { onAuthenticated: () => void }) {
|
||||
const [account, setAccount] = useState("");
|
||||
const [password, setPassword] = useState("");
|
||||
const [busy, setBusy] = useState(false);
|
||||
const [error, setError] = useState("");
|
||||
const signIn = async (event: React.FormEvent) => {
|
||||
event.preventDefault();
|
||||
setBusy(true); setError("");
|
||||
try {
|
||||
const verifier = base64url(crypto.getRandomValues(new Uint8Array(48)).buffer);
|
||||
const challenge = base64url(await crypto.subtle.digest("SHA-256", new TextEncoder().encode(verifier)));
|
||||
const redirectUri = `${location.origin}/auth/callback`;
|
||||
const authorization = await fetch("/api/auth", {
|
||||
method: "POST", headers: { "Content-Type": "application/json" },
|
||||
body: JSON.stringify({ type: "authCode", accountName: account, secret: password, clientId: "meovv-web", redirectUri, codeChallenge: challenge, codeChallengeMethod: "S256" }),
|
||||
});
|
||||
const authorized = await authorization.json();
|
||||
const clientCode = authorized.clientCode ?? authorized.client_code ?? authorized.code;
|
||||
if (!authorization.ok || authorized.authenticated === false || !clientCode) throw new Error(authorized.detail ?? authorized.error ?? "The email address or password was not accepted.");
|
||||
setPassword("");
|
||||
const exchange = await fetch("/api/session/exchange", {
|
||||
method: "POST", headers: { "Content-Type": "application/json" },
|
||||
body: JSON.stringify({ client_code: clientCode, code_verifier: verifier, account, client_id: "meovv-web", redirect_uri: redirectUri }),
|
||||
});
|
||||
const result = await exchange.json();
|
||||
if (!exchange.ok) throw new Error(result.detail ?? "Could not establish a secure session.");
|
||||
onAuthenticated();
|
||||
} catch (reason) { setError(reason instanceof Error ? reason.message : "Sign-in failed."); }
|
||||
finally { setBusy(false); }
|
||||
};
|
||||
return <div className="login-screen"><aside className="login-story"><Logo /><div><span className="eyebrow">YOUR MAIL. YOUR INFRASTRUCTURE.</span><h1>Welcome back.</h1><p>A calm, private inbox for work that matters.</p></div><span className="login-security"><ShieldCheck /> Credentials go directly to your mail server.</span></aside><main><form className="login-card" onSubmit={signIn}><span className="login-icon"><Mail /></span><h2>Sign in to MEOVV Mail</h2><p>Use your organization email account.</p><label>Email address<input type="email" autoComplete="username" required value={account} onChange={(event) => setAccount(event.target.value)} placeholder="you@example.com" /></label><label>Password<input type="password" autoComplete="current-password" required value={password} onChange={(event) => setPassword(event.target.value)} /></label>{error && <div className="form-error" role="alert"><AlertTriangle />{error}</div>}<button className="primary login-submit" disabled={busy}>{busy ? <><RefreshCw className="spin" /> Signing in…</> : <>Sign in <ArrowRight /></>}</button><small>Protected with OAuth authorization code and PKCE.</small></form></main></div>;
|
||||
}
|
||||
|
||||
function Avatar({ message, small = false }: { message: Message; small?: boolean }) {
|
||||
return <span className={`avatar ${message.color} ${small ? "small" : ""}`}>{message.initials}</span>;
|
||||
}
|
||||
|
||||
function Compose({ onClose, onSend }: { onClose: () => void; onSend: (message: ComposeMessage) => Promise<void> | void }) {
|
||||
const [more, setMore] = useState(false);
|
||||
const [to, setTo] = useState("");
|
||||
const [cc, setCC] = useState("");
|
||||
const [bcc, setBCC] = useState("");
|
||||
const [subject, setSubject] = useState("");
|
||||
const [body, setBody] = useState("");
|
||||
const [status, setStatus] = useState("Draft saved");
|
||||
useEffect(() => {
|
||||
const timer = setTimeout(() => setStatus("Draft saved"), 650);
|
||||
return () => clearTimeout(timer);
|
||||
}, [subject, body]);
|
||||
return (
|
||||
<div className="compose" role="dialog" aria-modal="true" aria-label="New message">
|
||||
<header><div><span className="compose-dot" />New message</div><div className="compose-actions"><button aria-label="Minimize"><span>—</span></button><button onClick={onClose} aria-label="Close"><X size={17} /></button></div></header>
|
||||
<div className="compose-fields">
|
||||
<label><span>To</span><input required aria-label="Recipients" placeholder="name@example.com" value={to} onChange={(e) => setTo(e.target.value)} /></label>
|
||||
<button className="cc-button" onClick={() => setMore(!more)}>Cc Bcc</button>
|
||||
{more && <><label><span>Cc</span><input aria-label="CC recipients" value={cc} onChange={(e) => setCC(e.target.value)} /></label><label><span>Bcc</span><input aria-label="BCC recipients" value={bcc} onChange={(e) => setBCC(e.target.value)} /></label></>}
|
||||
<label><input aria-label="Subject" placeholder="Subject" value={subject} onChange={(e) => { setSubject(e.target.value); setStatus("Saving…"); }} /></label>
|
||||
</div>
|
||||
<textarea aria-label="Message body" placeholder="Write your message…" value={body} onChange={(e) => { setBody(e.target.value); setStatus("Saving…"); }} />
|
||||
<footer>
|
||||
<div className="compose-tools"><button className="send-button" disabled={!to.trim()} onClick={() => onSend({ to, cc, bcc, subject, body })}><Send size={16} /> Send <kbd>⌘↵</kbd></button><button aria-label="Formatting"><span className="format-a">A</span></button><button aria-label="Attach file"><Paperclip size={18} /></button><button aria-label="Insert emoji"><Smile size={18} /></button></div>
|
||||
<div className="compose-status"><span>{status}</span><button aria-label="Discard"><Trash2 size={17} /></button></div>
|
||||
</footer>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function SetupWizard({ onComplete }: { onComplete: () => void }) {
|
||||
const [step, setStep] = useState(1);
|
||||
const [delivery, setDelivery] = useState<"direct" | "relay">("direct");
|
||||
const [form, setForm] = useState({ hostname: "mail.example.com", domain: "example.com", organization: "My organization", admin: "admin@example.com", accent: "#6d4aff", relay: "", token: "" });
|
||||
const [busy, setBusy] = useState(false);
|
||||
const [error, setError] = useState("");
|
||||
const [bootstrapResult, setBootstrapResult] = useState<unknown>(null);
|
||||
const set = (key: keyof typeof form, value: string) => setForm((current) => ({ ...current, [key]: value }));
|
||||
const finish = async () => {
|
||||
setBusy(true); setError("");
|
||||
try {
|
||||
const response = await fetch("/api/setup/complete", { method: "POST", headers: { "Content-Type": "application/json", "X-Bootstrap-Token": form.token }, body: JSON.stringify({ hostname: form.hostname, primary_domain: form.domain, admin_email: form.admin, organization: form.organization, accent: form.accent, delivery_mode: delivery, relay_host: delivery === "relay" ? form.relay : "" }) });
|
||||
const result = await response.json();
|
||||
if (!response.ok) throw new Error(result.detail ?? "Setup could not be completed.");
|
||||
setBootstrapResult(result.mail_core_result ?? { configured: true });
|
||||
} catch (reason) { setError(reason instanceof Error ? reason.message : "Setup failed."); }
|
||||
finally { setBusy(false); }
|
||||
};
|
||||
if (bootstrapResult) return <div className="setup-finished"><div><span className="step-icon"><CheckCircle2 /></span><h1>Your mail appliance is configured.</h1><p>Save the one-time mail-core result below, restart the mail core, verify the permanent administrator account, and remove recovery access with <code>mailctl harden</code>.</p><pre>{JSON.stringify(bootstrapResult, null, 2)}</pre><div className="setup-warning"><ShieldCheck />This result is not stored by MEOVV Mail.</div><button className="primary" onClick={onComplete}>I saved it — continue to sign in <ArrowRight /></button></div></div>;
|
||||
return (
|
||||
<div className="setup-screen">
|
||||
<aside className="setup-aside">
|
||||
<Logo />
|
||||
<div className="setup-copy"><span className="eyebrow">PRIVATE EMAIL, BEAUTIFULLY RUN</span><h1>Your organization’s inbox, on your infrastructure.</h1><p>A secure, modern mail service with no maze of components to maintain.</p></div>
|
||||
<div className="setup-assurance"><ShieldCheck size={20} /><div><strong>Your data stays yours</strong><span>Messages never leave infrastructure you control.</span></div></div>
|
||||
</aside>
|
||||
<main className="setup-main">
|
||||
<div className="setup-progress"><span>Setup</span><div>{[1,2,3].map((n) => <i key={n} className={n <= step ? "active" : ""} />)}</div><span>{step} of 3</span></div>
|
||||
{step === 1 && <section><span className="step-icon"><Globe2 /></span><h2>Let’s name your mail server</h2><p>This is the public address mail apps and other servers will use.</p><label>Mail server hostname<input value={form.hostname} onChange={(e) => set("hostname", e.target.value)} /></label><label>Primary email domain<input value={form.domain} onChange={(e) => set("domain", e.target.value)} /></label><label>One-time bootstrap token<input type="password" value={form.token} onChange={(e) => set("token", e.target.value)} placeholder="Printed by mailctl init" /></label><div className="field-note"><CheckCircle2 /> You can add more domains later.</div></section>}
|
||||
{step === 2 && <section><span className="step-icon"><CircleUserRound /></span><h2>Create your organization</h2><p>Choose the name and administrator for this installation.</p><label>Organization name<input value={form.organization} onChange={(e) => set("organization", e.target.value)} /></label><label>Administrator email<input type="email" value={form.admin} onChange={(e) => set("admin", e.target.value)} /></label><label>Accent color<div className="accent-choice">{["#6d4aff", "#9d4276", "#2674d9", "#25856d"].map((color, index) => <button key={color} aria-label={`Choose accent ${index + 1}`} style={{ background: color }} className={`color-choice ${form.accent === color ? "active" : ""}`} onClick={() => set("accent", color)} />)}</div></label><div className="field-note"><ShieldCheck /> The mail core provisions a permanent administrator during bootstrap.</div></section>}
|
||||
{step === 3 && <section><span className="step-icon"><Send /></span><h2>How should mail leave?</h2><p>You can change this any time without reinstalling.</p><button className={`delivery-choice ${delivery === "direct" ? "active" : ""}`} onClick={() => setDelivery("direct")}><span><Zap /></span><div><strong>Deliver directly</strong><p>Best when your server has a static IP and reverse DNS.</p></div>{delivery === "direct" && <CheckCircle2 />}</button><button className={`delivery-choice ${delivery === "relay" ? "active" : ""}`} onClick={() => setDelivery("relay")}><span><Server /></span><div><strong>Use a smart host</strong><p>Route outbound messages through an authenticated relay.</p></div>{delivery === "relay" && <CheckCircle2 />}</button>{delivery === "relay" && <label>Relay host<input value={form.relay} onChange={(e) => set("relay", e.target.value)} placeholder="smtp.example.com:587" /></label>}{error && <div className="form-error"><AlertTriangle />{error}</div>}</section>}
|
||||
<footer><button className="secondary" disabled={step === 1 || busy} onClick={() => setStep(step - 1)}>Back</button><button className="primary" disabled={busy} onClick={() => step < 3 ? setStep(step + 1) : finish()}>{busy ? "Configuring…" : step < 3 ? "Continue" : "Finish setup"}{busy ? <RefreshCw className="spin" /> : <ArrowRight size={17} />}</button></footer>
|
||||
</main>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function AdminDashboard({ onMail }: { onMail: () => void }) {
|
||||
const [section, setSection] = useState("overview");
|
||||
return (
|
||||
<div className="admin-shell">
|
||||
<aside className="admin-sidebar">
|
||||
<Logo />
|
||||
<nav>{adminNav.map(({ id, label, icon: Icon }) => <button key={id} className={section === id ? "active" : ""} onClick={() => setSection(id)}><Icon size={18} />{label}{id === "delivery" && <span className="nav-badge">2</span>}</button>)}</nav>
|
||||
<div className="sidebar-bottom"><button><LifeBuoy />Help & docs</button><button><Settings />Settings</button><button className="admin-user"><span>AM</span><div><strong>Alex Morgan</strong><small>Administrator</small></div><MoreHorizontal /></button></div>
|
||||
</aside>
|
||||
<main className="admin-main">
|
||||
<header className="admin-top"><button className="mobile-menu"><Menu /></button><div><h1>{adminNav.find((item) => item.id === section)?.label}</h1><p>mail.meovv.company</p></div><div className="admin-top-actions"><button className="view-inbox" onClick={onMail}><Inbox size={16} /> Open inbox</button><button aria-label="Notifications"><Bell size={19} /><i /></button></div></header>
|
||||
{section === "overview" ? <Overview /> : <AdminSection section={section} />}
|
||||
</main>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function Overview() {
|
||||
const bars = [34, 44, 39, 62, 51, 58, 72, 66, 84, 73, 89, 82, 91, 78, 96, 88, 104, 94, 112, 101, 118, 108, 124, 117];
|
||||
return (
|
||||
<div className="overview">
|
||||
<section className="status-banner"><span><CheckCircle2 /></span><div><strong>Everything is running smoothly</strong><p>All services are healthy. Last checked just now.</p></div><button>View diagnostics <ChevronRight /></button></section>
|
||||
<div className="metric-grid">
|
||||
<article><header><span className="metric-icon purple"><Send /></span><small>Last 24 hours</small></header><strong>12,486</strong><p>Messages handled <em>+8.4%</em></p></article>
|
||||
<article><header><span className="metric-icon green"><Check /></span><small>First attempt</small></header><strong>98.7%</strong><p>Delivery rate <em>+0.6%</em></p></article>
|
||||
<article><header><span className="metric-icon blue"><Users /></span><small>500 limit</small></header><strong>184</strong><p>Active mailboxes</p></article>
|
||||
<article><header><span className="metric-icon amber"><Server /></span><small>2 TB available</small></header><strong>684 GB</strong><p>Storage used <span className="storage-line"><i /></span></p></article>
|
||||
</div>
|
||||
<div className="overview-grid">
|
||||
<article className="delivery-chart">
|
||||
<header><div><h2>Mail activity</h2><p>Messages accepted and sent</p></div><button>Last 24 hours <ChevronDown /></button></header>
|
||||
<div className="chart"><div className="y-labels"><span>150</span><span>100</span><span>50</span><span>0</span></div><div className="bars">{bars.map((height, i) => <span key={i} style={{ height: `${height}px` }} className={i > 18 ? "recent" : ""} />)}</div></div>
|
||||
<div className="x-labels"><span>12 AM</span><span>6 AM</span><span>12 PM</span><span>6 PM</span><span>Now</span></div>
|
||||
</article>
|
||||
<article className="attention-card"><header><h2>Needs attention</h2><span>2</span></header><div className="attention-item"><span className="warning"><AlertTriangle /></span><div><strong>Reverse DNS not detected</strong><p>Outbound delivery may be affected.</p><button>Review DNS <ArrowRight /></button></div></div><div className="attention-item"><span className="info"><Webhook /></span><div><strong>Webhook retrying</strong><p>billing-production has failed 3 times.</p><button>View attempts <ArrowRight /></button></div></div></article>
|
||||
</div>
|
||||
<div className="overview-grid lower">
|
||||
<article className="domain-card"><header><div><h2>Domains</h2><p>3 domains configured</p></div><button>Manage</button></header>{[["meovv.company","Primary","Healthy"],["studio-meovv.com","","Healthy"],["meovv.dev","","DKIM pending"]].map(([domain,badge,status]) => <div className="domain-row" key={domain}><span className="domain-icon"><Globe2 /></span><div><strong>{domain}</strong><small>{badge || "Email domain"}</small></div><span className={status === "Healthy" ? "healthy" : "pending"}><i />{status}</span></div>)}</article>
|
||||
<article className="recent-card"><header><div><h2>Recent delivery</h2><p>Live status from the mail queue</p></div><button><RefreshCw /></button></header>{[["Quarterly report","sara@northstar.com","Delivered","12 sec"],["Welcome to MEOVV","alex@meovv.dev","Delivered","1 min"],["Invoice #1042","billing@client.io","Deferred","4 min"]].map(([subject,to,status,time]) => <div className="delivery-row" key={subject}><span className={status.toLowerCase()}>{status === "Delivered" ? <Check /> : <Clock3 />}</span><div><strong>{subject}</strong><small>to {to}</small></div><em>{time}</em></div>)}</article>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function AdminSection({ section }: { section: string }) {
|
||||
const [items, setItems] = useState<any[]>([]);
|
||||
const [modal, setModal] = useState(false);
|
||||
const [name, setName] = useState("");
|
||||
const [senders, setSenders] = useState("");
|
||||
const [url, setURL] = useState("");
|
||||
const [createdSecret, setCreatedSecret] = useState("");
|
||||
const [error, setError] = useState("");
|
||||
const [loaded, setLoaded] = useState(false);
|
||||
const dynamic = section === "api" || section === "webhooks";
|
||||
const load = useCallback(async () => {
|
||||
if (!dynamic) return;
|
||||
await Promise.resolve();
|
||||
setItems([]); setLoaded(false);
|
||||
try { const response = await fetch(`/api/admin/${section === "api" ? "api-keys" : "webhooks"}`); if (response.ok) { setItems((await response.json()).data ?? []); setLoaded(true); } } catch { /* The design preview uses representative rows. */ }
|
||||
}, [dynamic, section]);
|
||||
useEffect(() => { void load(); }, [load]);
|
||||
const content: Record<string, { title: string; description: string; action: string; icon: typeof Globe2; rows: string[][] }> = {
|
||||
domains: { title: "Email domains", description: "Manage sender identity and DNS health.", action: "Add domain", icon: Globe2, rows: [["meovv.company", "Primary domain", "Healthy"], ["studio-meovv.com", "184 addresses", "Healthy"], ["meovv.dev", "24 addresses", "DKIM pending"]] },
|
||||
people: { title: "People & aliases", description: "Accounts, addresses, aliases, and quotas.", action: "Add person", icon: Users, rows: [["Alex Morgan", "alex@meovv.example", "Administrator"], ["Maya Thompson", "maya@meovv.example", "24.6 GB of 50 GB"], ["Nora Ibrahim", "nora@meovv.example", "18.2 GB of 50 GB"]] },
|
||||
delivery: { title: "Delivery center", description: "Follow queued, deferred, and failed mail.", action: "Run diagnostics", icon: Send, rows: [["Quarterly report", "northstar.com", "Delivered"], ["Invoice #1042", "client.io", "Deferred"], ["Password reset", "example.net", "Delivered"]] },
|
||||
api: { title: "API keys", description: "Scoped credentials for application delivery.", action: "Create API key", icon: KeyRound, rows: [["Production app", "meovv_live_8K…", "Used 4 min ago"], ["Billing service", "meovv_live_3F…", "Used yesterday"], ["Staging", "meovv_test_9Q…", "Never used"]] },
|
||||
webhooks: { title: "Webhook endpoints", description: "Signed, at-least-once delivery events.", action: "Add endpoint", icon: Webhook, rows: [["billing-production", "5 event types", "Retrying"], ["analytics", "3 event types", "Healthy"], ["audit mirror", "All failures", "Healthy"]] },
|
||||
backups: { title: "Backups", description: "Verified snapshots of mail, configuration, and secrets.", action: "Create backup", icon: Download, rows: [["backup-2026-08-12", "684 GB", "Verified"], ["backup-2026-08-11", "681 GB", "Verified"], ["backup-2026-08-10", "677 GB", "Verified"]] },
|
||||
};
|
||||
const item = content[section] ?? content.domains;
|
||||
const liveRows = dynamic && loaded ? items.map((entry) => section === "api" ? [entry.name, `${entry.prefix}… · ${entry.scopes?.join(", ")}`, entry.last_used_at ? "Active" : "Never used", entry.id] : [entry.name, `${entry.events?.length ?? 0} event types · ${entry.url}`, entry.enabled ? "Healthy" : "Paused", entry.id]) : item.rows;
|
||||
const create = async (event: React.FormEvent) => {
|
||||
event.preventDefault(); setError("");
|
||||
try {
|
||||
const endpoint = section === "api" ? "api-keys" : "webhooks";
|
||||
const body = section === "api" ? { name, scopes: ["messages.send", "messages.status"], allowed_senders: senders.split(",").map((value) => value.trim()).filter(Boolean), rate_limit: 60 } : { name, url, events: ["message.queued", "message.delivered", "message.deferred", "message.bounced", "message.failed"] };
|
||||
const response = await fetch(`/api/admin/${endpoint}`, { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify(body) });
|
||||
const result = await response.json();
|
||||
if (!response.ok) throw new Error(result.detail ?? "Could not create this item.");
|
||||
setCreatedSecret(result.secret); setName(""); setSenders(""); setURL(""); void load();
|
||||
} catch (reason) { setError(reason instanceof Error ? reason.message : "Request failed."); }
|
||||
};
|
||||
const remove = async (id: string) => {
|
||||
const endpoint = section === "api" ? "api-keys" : "webhooks";
|
||||
const response = await fetch(`/api/admin/${endpoint}/${id}`, { method: "DELETE" });
|
||||
if (response.ok) { setItems((current) => current.filter((entry) => entry.id !== id)); }
|
||||
};
|
||||
return <div className="admin-section"><div className="section-heading"><div><h2>{item.title}</h2><p>{item.description}</p></div><button onClick={() => dynamic && setModal(true)}><Plus />{item.action}</button></div><div className="settings-card"><div className="table-head"><span>Name</span><span>Details</span><span>Status</span><span /></div>{liveRows.length === 0 ? <div className="admin-empty"><item.icon /><strong>Nothing here yet</strong><span>{item.description}</span></div> : liveRows.map((row) => <div className="settings-row" key={row[3] ?? row[0]}><span className="row-icon"><item.icon /></span><strong>{row[0]}</strong><span>{row[1]}</span><em className={row[2].match(/Healthy|Verified|Delivered|Administrator|Active/) ? "good" : "warn"}><i />{row[2]}</em>{dynamic && row[3] ? <button onClick={() => void remove(row[3])} aria-label={`Remove ${row[0]}`}><Trash2 /></button> : <button><MoreHorizontal /></button>}</div>)}</div>{modal && <div className="admin-modal-backdrop" onMouseDown={(event) => event.target === event.currentTarget && setModal(false)}><form className="admin-modal" onSubmit={create}><header><span className="row-icon">{section === "api" ? <KeyRound /> : <Webhook />}</span><div><h3>{section === "api" ? "Create API key" : "Add webhook endpoint"}</h3><p>{section === "api" ? "The secret will be shown only once." : "Events are signed and retried for 24 hours."}</p></div><button type="button" onClick={() => setModal(false)}><X /></button></header>{createdSecret ? <div className="secret-result"><CheckCircle2 /><strong>Created successfully</strong><p>Copy this secret now. It cannot be recovered later.</p><code>{createdSecret}</code><button type="button" onClick={() => navigator.clipboard.writeText(createdSecret)}><Copy /> Copy secret</button></div> : <><label>Name<input autoFocus required value={name} onChange={(event) => setName(event.target.value)} placeholder={section === "api" ? "Production application" : "Billing production"} /></label>{section === "api" ? <label>Approved senders<input required value={senders} onChange={(event) => setSenders(event.target.value)} placeholder="notifications@example.com, *@example.com" /><small>Send and status scopes · 60 submissions per minute</small></label> : <label>HTTPS endpoint URL<input required type="url" value={url} onChange={(event) => setURL(event.target.value)} placeholder="https://example.com/hooks/mail" /><small>All five delivery event types are selected.</small></label>}{error && <div className="form-error"><AlertTriangle />{error}</div>}<footer><button type="button" onClick={() => setModal(false)}>Cancel</button><button className="primary">Create</button></footer></>}</form></div>}</div>;
|
||||
}
|
||||
|
||||
function MailApp({ onAdmin, onSetup }: { onAdmin: () => void; onSetup: () => void }) {
|
||||
const [messages, setMessages] = useState(initialMessages);
|
||||
const [folder, setFolder] = useState<FolderName>("Inbox");
|
||||
const [selected, setSelected] = useState<number | string>(1);
|
||||
const [checked, setChecked] = useState<(number | string)[]>([]);
|
||||
const [search, setSearch] = useState("");
|
||||
const [compose, setCompose] = useState(false);
|
||||
const [toast, setToast] = useState("");
|
||||
const [theme, setTheme] = useState<"light" | "dark">("light");
|
||||
const [sidebar, setSidebar] = useState(false);
|
||||
const [jmap, setJmap] = useState<{ accountId: string; identityId: string; email: string; mailboxes: Record<string, string>; connected: boolean }>({ accountId: "", identityId: "", email: "", mailboxes: {}, connected: false });
|
||||
const searchRef = useRef<HTMLInputElement>(null);
|
||||
const filtered = useMemo(() => messages.filter((m) => {
|
||||
const belongs = folder === "Starred" ? m.starred : m.folder === folder;
|
||||
return belongs && `${m.sender} ${m.subject} ${m.preview}`.toLowerCase().includes(search.toLowerCase());
|
||||
}), [messages, folder, search]);
|
||||
const active = messages.find((m) => m.id === selected) ?? filtered[0];
|
||||
|
||||
const syncMail = useCallback(async () => {
|
||||
try {
|
||||
const sessionResponse = await fetch("/api/mail/session", { headers: { Accept: "application/json" } });
|
||||
if (!sessionResponse.ok || !(sessionResponse.headers.get("content-type") ?? "").includes("json")) return;
|
||||
const session = await sessionResponse.json();
|
||||
const accountId = session.primaryAccounts?.["urn:ietf:params:jmap:mail"] ?? Object.keys(session.accounts ?? {})[0];
|
||||
if (!accountId) return;
|
||||
const response = await fetch("/api/mail/jmap", { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ using: ["urn:ietf:params:jmap:core", "urn:ietf:params:jmap:mail", "urn:ietf:params:jmap:submission"], methodCalls: [
|
||||
["Mailbox/get", { accountId, properties: ["id", "name", "role", "totalEmails", "unreadEmails"] }, "mailboxes"],
|
||||
["Identity/get", { accountId }, "identities"],
|
||||
["Email/query", { accountId, sort: [{ property: "receivedAt", isAscending: false }], limit: 100 }, "query"],
|
||||
["Email/get", { accountId, "#ids": { resultOf: "query", name: "Email/query", path: "/ids" }, properties: ["id", "threadId", "mailboxIds", "keywords", "from", "subject", "receivedAt", "preview", "hasAttachment", "bodyValues", "htmlBody", "textBody"] }, "emails"],
|
||||
] }) });
|
||||
if (!response.ok) return;
|
||||
const result = await response.json();
|
||||
const method = (id: string) => result.methodResponses?.find((item: [string, unknown, string]) => item[2] === id)?.[1];
|
||||
const mailboxList = method("mailboxes")?.list ?? [];
|
||||
const roleByID: Record<string, string> = {};
|
||||
const mailboxByRole: Record<string, string> = {};
|
||||
for (const mailbox of mailboxList) { roleByID[mailbox.id] = mailbox.role ?? ""; if (mailbox.role) mailboxByRole[mailbox.role] = mailbox.id; }
|
||||
const identities = method("identities")?.list ?? [];
|
||||
const palette = ["coral", "ink", "violet", "blue", "green", "amber"];
|
||||
const mapped: Message[] = (method("emails")?.list ?? []).map((email: any, index: number) => {
|
||||
const roles = Object.keys(email.mailboxIds ?? {}).map((id) => roleByID[id]);
|
||||
const role = roles.find(Boolean) ?? "inbox";
|
||||
const folderMap: Record<string, FolderName> = { inbox: "Inbox", archive: "Archive", drafts: "Drafts", sent: "Sent", junk: "Spam", trash: "Trash" };
|
||||
const sender = email.from?.[0] ?? { name: "Unknown sender", email: "" };
|
||||
const display = sender.name || sender.email || "Unknown sender";
|
||||
const initials = display.split(/\s+/).slice(0, 2).map((part: string) => part[0]).join("").toUpperCase();
|
||||
const values = email.bodyValues ?? {};
|
||||
const html = (email.htmlBody ?? []).map((part: any) => values[part.partId]?.value ?? "").join("");
|
||||
const text = (email.textBody ?? []).map((part: any) => values[part.partId]?.value ?? "").join("\n");
|
||||
const received = email.receivedAt ? new Date(email.receivedAt) : new Date();
|
||||
return { id: email.id, serverId: email.id, mailboxIds: Object.keys(email.mailboxIds ?? {}), sender: display, email: sender.email ?? "", initials: initials || "?", color: palette[index % palette.length], subject: email.subject || "(No subject)", preview: email.preview ?? text.slice(0, 160), time: received.toLocaleTimeString([], { hour: "numeric", minute: "2-digit" }), date: received.toLocaleString([], { dateStyle: "medium", timeStyle: "short" }), unread: !email.keywords?.["$seen"], starred: Boolean(email.keywords?.["$flagged"]), labels: [], folder: folderMap[role] ?? "Inbox", body: html || `<p>${escapeHTML(text).replace(/\n/g, "<br>")}</p>`, attachments: email.hasAttachment ? [{ name: "Attachment", size: "Open message to download", kind: "FILE" }] : undefined };
|
||||
});
|
||||
setMessages(mapped);
|
||||
setSelected((current) => mapped.some((message) => message.id === current) ? current : (mapped[0]?.id ?? ""));
|
||||
setJmap({ accountId, identityId: identities[0]?.id ?? "", email: identities[0]?.email ?? session.username ?? "", mailboxes: mailboxByRole, connected: true });
|
||||
} catch { /* Local visual preview and transient reconnects retain the current view. */ }
|
||||
}, []);
|
||||
|
||||
const notify = useCallback((text: string) => { setToast(text); window.setTimeout(() => setToast(""), 2200); }, []);
|
||||
const callJMAP = useCallback(async (methodCalls: unknown[]) => {
|
||||
if (!jmap.connected) return null;
|
||||
const response = await fetch("/api/mail/jmap", { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ using: ["urn:ietf:params:jmap:core", "urn:ietf:params:jmap:mail", "urn:ietf:params:jmap:submission"], methodCalls }) });
|
||||
if (!response.ok) throw new Error("The mail server did not accept this change.");
|
||||
return response.json();
|
||||
}, [jmap.connected]);
|
||||
const move = (target: FolderName) => {
|
||||
const ids = checked.length ? checked : [selected];
|
||||
const role: Partial<Record<FolderName, string>> = { Inbox: "inbox", Archive: "archive", Drafts: "drafts", Sent: "sent", Spam: "junk", Trash: "trash" };
|
||||
const targetID = role[target] ? jmap.mailboxes[role[target]!] : "";
|
||||
for (const message of messages.filter((item) => ids.includes(item.id) && item.serverId)) {
|
||||
if (targetID) {
|
||||
const mailboxIds: Record<string, boolean | null> = Object.fromEntries((message.mailboxIds ?? []).map((id) => [id, null])); mailboxIds[targetID] = true;
|
||||
void callJMAP([["Email/set", { accountId: jmap.accountId, update: { [message.serverId!]: { mailboxIds } } }, "move"]]).catch(() => notify("Move could not be synchronized"));
|
||||
}
|
||||
}
|
||||
setMessages((items) => items.map((m) => ids.includes(m.id) ? { ...m, folder: target, unread: false } : m));
|
||||
setChecked([]); notify(`Moved ${ids.length > 1 ? `${ids.length} messages` : "message"} to ${target}`);
|
||||
};
|
||||
const toggleStar = (id: number | string) => {
|
||||
const message = messages.find((item) => item.id === id);
|
||||
if (message?.serverId) void callJMAP([["Email/set", { accountId: jmap.accountId, update: { [message.serverId]: { "keywords/$flagged": message.starred ? null : true } } }, "star"]]).catch(() => notify("Star could not be synchronized"));
|
||||
setMessages((items) => items.map((m) => m.id === id ? { ...m, starred: !m.starred } : m));
|
||||
};
|
||||
const openMessage = (id: number | string) => {
|
||||
const message = messages.find((item) => item.id === id);
|
||||
if (message?.serverId && message.unread) void callJMAP([["Email/set", { accountId: jmap.accountId, update: { [message.serverId]: { "keywords/$seen": true } } }, "read"]]);
|
||||
setSelected(id); setMessages((items) => items.map((m) => m.id === id ? { ...m, unread: false } : m));
|
||||
};
|
||||
const sendComposed = async (draft: ComposeMessage) => {
|
||||
if (!jmap.connected) { setCompose(false); notify("Message queued for delivery"); return; }
|
||||
try {
|
||||
const draftMailbox = jmap.mailboxes.drafts;
|
||||
const email = { mailboxIds: draftMailbox ? { [draftMailbox]: true } : {}, keywords: { "$draft": true, "$seen": true }, from: [{ email: jmap.email }], to: addressList(draft.to), cc: addressList(draft.cc), bcc: addressList(draft.bcc), subject: draft.subject, bodyValues: { body: { value: draft.body, charset: "utf-8", isTruncated: false } }, textBody: [{ partId: "body", type: "text/plain" }] };
|
||||
const result = await callJMAP([["Email/set", { accountId: jmap.accountId, create: { draft: email } }, "create"], ["EmailSubmission/set", { accountId: jmap.accountId, create: { submission: { emailId: "#draft", identityId: jmap.identityId } } }, "submit"]]);
|
||||
if (result?.methodResponses?.some((item: [string]) => item[0] === "error") || result?.methodResponses?.some((item: [string, any]) => item[1]?.notCreated)) throw new Error("The message was not accepted.");
|
||||
setCompose(false); notify("Message queued for delivery"); void syncMail();
|
||||
} catch (reason) { notify(reason instanceof Error ? reason.message : "Send failed"); }
|
||||
};
|
||||
useEffect(() => { document.documentElement.dataset.theme = theme; }, [theme]);
|
||||
useEffect(() => { void syncMail(); }, [syncMail]);
|
||||
useEffect(() => {
|
||||
if (!jmap.connected) return;
|
||||
const events = new EventSource("/api/mail/events");
|
||||
const refresh = () => void syncMail();
|
||||
events.onmessage = refresh;
|
||||
events.addEventListener("state", refresh);
|
||||
return () => events.close();
|
||||
}, [jmap.connected, syncMail]);
|
||||
useEffect(() => {
|
||||
const shortcut = (event: KeyboardEvent) => {
|
||||
if ((event.metaKey || event.ctrlKey) && event.key === "k") { event.preventDefault(); searchRef.current?.focus(); }
|
||||
if (event.key === "c" && !["INPUT", "TEXTAREA"].includes((event.target as HTMLElement).tagName)) setCompose(true);
|
||||
if (event.key === "Escape") setCompose(false);
|
||||
};
|
||||
window.addEventListener("keydown", shortcut); return () => window.removeEventListener("keydown", shortcut);
|
||||
}, []);
|
||||
|
||||
return (
|
||||
<div className="mail-shell">
|
||||
<header className="mail-header">
|
||||
<button className="mobile-menu" onClick={() => setSidebar(!sidebar)} aria-label="Toggle navigation"><Menu /></button>
|
||||
<Logo />
|
||||
<label className="search-box"><Search /><input ref={searchRef} value={search} onChange={(e) => setSearch(e.target.value)} placeholder="Search mail" aria-label="Search mail" /><kbd>⌘ K</kbd><SlidersHorizontal /></label>
|
||||
<div className="header-actions"><span className="sync-status"><i /> All systems operational</span><button onClick={() => setTheme(theme === "light" ? "dark" : "light")} aria-label="Toggle theme">{theme === "light" ? <Moon /> : <Sun />}</button><button aria-label="Help"><HelpCircle /></button><button aria-label="Settings" onClick={onAdmin}><Settings /></button><button className="user-avatar" aria-label="Account menu">AM<span /></button></div>
|
||||
</header>
|
||||
<div className="mail-layout">
|
||||
<aside className={`mail-sidebar ${sidebar ? "open" : ""}`}>
|
||||
<button className="compose-button" onClick={() => setCompose(true)}><Pencil /> Compose</button>
|
||||
<nav className="folders">{folders.map(({ name, icon: Icon, count }) => <button key={name} className={folder === name ? "active" : ""} onClick={() => { setFolder(name); setSidebar(false); }}><Icon /> <span>{name}</span>{count ? <b>{count}</b> : null}</button>)}</nav>
|
||||
<div className="label-heading"><span>Labels</span><button aria-label="Add label"><Plus /></button></div>
|
||||
<nav className="labels"><button><i className="label-dot clients" />Clients<span>12</span></button><button><i className="label-dot design" />Design<span>6</span></button><button><i className="label-dot team" />Team<span>9</span></button><button><i className="label-dot updates" />Updates</button></nav>
|
||||
<div className="storage-widget"><div><span>Storage</span><strong>34%</strong></div><div className="storage-track"><i /></div><p>17.1 GB of 50 GB used</p><button onClick={onSetup}><Sparkles /> Setup preview</button></div>
|
||||
</aside>
|
||||
<main className="inbox-panel">
|
||||
<div className="list-toolbar">
|
||||
<div><button className={checked.length ? "checked" : ""} aria-label="Select all" onClick={() => setChecked(checked.length ? [] : filtered.map((m) => m.id))}>{checked.length ? <Check /> : null}</button><ChevronDown /></div>
|
||||
<button aria-label="Refresh" onClick={() => notify("Inbox is up to date")}><RefreshCw /></button>
|
||||
{checked.length > 0 && <><span className="toolbar-divider" /><button onClick={() => move("Archive")} aria-label="Archive"><Archive /></button><button onClick={() => move("Spam")} aria-label="Mark as spam"><ShieldCheck /></button><button onClick={() => move("Trash")} aria-label="Delete"><Trash2 /></button></>}
|
||||
<button aria-label="More"><MoreHorizontal /></button><span className="range">1–{filtered.length} of {filtered.length}</span><button aria-label="Previous"><ArrowLeft /></button><button aria-label="Next"><ArrowRight /></button>
|
||||
</div>
|
||||
<div className="message-list" role="list">
|
||||
<div className="list-title"><h1>{folder}</h1><span>{filtered.filter((m) => m.unread).length} unread</span></div>
|
||||
{filtered.length ? filtered.map((message) => <article key={message.id} role="button" tabIndex={0} className={`${message.id === selected ? "selected" : ""} ${message.unread ? "unread" : ""}`} onClick={() => openMessage(message.id)} onKeyDown={(event) => { if (event.key === "Enter" || event.key === " ") { event.preventDefault(); openMessage(message.id); } }}>
|
||||
<button className={`row-check ${checked.includes(message.id) ? "active" : ""}`} onClick={(e) => { e.stopPropagation(); setChecked((ids) => ids.includes(message.id) ? ids.filter((id) => id !== message.id) : [...ids, message.id]); }} aria-label={`Select ${message.subject}`}>{checked.includes(message.id) && <Check />}</button>
|
||||
<Avatar message={message} />
|
||||
<div className="message-summary"><div className="message-meta"><strong>{message.sender}</strong><span>{message.time}</span></div><div className="subject-line"><h2>{message.subject}</h2>{message.threadCount && <b>{message.threadCount}</b>}</div><p>{message.preview}</p><div className="row-labels">{message.labels.map((label) => <span key={label}>{label}</span>)}{message.attachments && <span><Paperclip />{message.attachments.length}</span>}</div></div>
|
||||
<button className={`star ${message.starred ? "active" : ""}`} onClick={(e) => { e.stopPropagation(); toggleStar(message.id); }} aria-label="Star message"><Star /></button>
|
||||
</article>) : <div className="empty-state"><Inbox /><h2>Nothing here</h2><p>This folder is beautifully empty.</p></div>}
|
||||
</div>
|
||||
</main>
|
||||
{active && <aside className="reader-panel">
|
||||
<div className="reader-toolbar"><button className="reader-back" aria-label="Back"><ArrowLeft /></button><button onClick={() => move("Archive")}><Archive /></button><button onClick={() => move("Spam")}><ShieldCheck /></button><button onClick={() => move("Trash")}><Trash2 /></button><span /><button><Clock3 /></button><button><Tag /></button><button><MoreHorizontal /></button></div>
|
||||
<div className="reader-content">
|
||||
<div className="subject-header"><div><h1>{active.subject}</h1><div>{active.labels.map((label) => <span key={label}>{label}</span>)}</div></div><button className={`star ${active.starred ? "active" : ""}`} onClick={() => toggleStar(active.id)}><Star /></button></div>
|
||||
<div className="sender-header"><Avatar message={active} /><div><strong>{active.sender}</strong><p>to me <ChevronDown /></p></div><time>{active.date}</time><button><MoreHorizontal /></button></div>
|
||||
<div className="remote-images"><ShieldCheck /><span>Remote images are blocked for your privacy.</span><button onClick={(e) => (e.currentTarget.parentElement!.style.display = "none")}>Show images</button></div>
|
||||
<SafeHtml html={active.body} />
|
||||
{active.attachments && <div className="attachments"><p><Paperclip /> {active.attachments.length} attachment{active.attachments.length > 1 ? "s" : ""}</p>{active.attachments.map((file) => <button key={file.name}><span><FileText /></span><div><strong>{file.name}</strong><small>{file.kind} · {file.size}</small></div><Download /></button>)}</div>}
|
||||
<div className="reply-actions"><button onClick={() => setCompose(true)}><Reply /> Reply</button><button onClick={() => setCompose(true)}><Forward /> Forward</button></div>
|
||||
</div>
|
||||
</aside>}
|
||||
</div>
|
||||
{compose && <Compose onClose={() => setCompose(false)} onSend={sendComposed} />}
|
||||
{toast && <div className="toast"><CheckCircle2 />{toast}<button onClick={() => setToast("")}><X /></button></div>}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
export default function Home() {
|
||||
const [view, setView] = useState<"loading" | "login" | "mail" | "admin" | "setup">("loading");
|
||||
useEffect(() => {
|
||||
(async () => {
|
||||
try {
|
||||
const setup = await fetch("/api/setup/status", { headers: { Accept: "application/json" } });
|
||||
if (!setup.ok || !(setup.headers.get("content-type") ?? "").includes("json")) throw new Error("preview");
|
||||
const status = await setup.json();
|
||||
if (!status.configured) { setView("setup"); return; }
|
||||
const session = await fetch("/api/session", { headers: { Accept: "application/json" } });
|
||||
setView(session.ok ? "mail" : "login");
|
||||
} catch { setView("mail"); }
|
||||
})();
|
||||
}, []);
|
||||
if (view === "loading") return <div className="app-loading"><Logo /><RefreshCw className="spin" /><span>Opening your inbox…</span></div>;
|
||||
if (view === "login") return <Login onAuthenticated={() => setView("mail")} />;
|
||||
return view === "admin" ? <AdminDashboard onMail={() => setView("mail")} /> : view === "setup" ? <SetupWizard onComplete={() => setView("login")} /> : <MailApp onAdmin={() => setView("admin")} onSetup={() => setView("setup")} />;
|
||||
}
|
||||
@@ -0,0 +1,653 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"archive/tar"
|
||||
"compress/gzip"
|
||||
"context"
|
||||
"crypto/ed25519"
|
||||
"crypto/rand"
|
||||
"crypto/sha256"
|
||||
"encoding/base64"
|
||||
"encoding/hex"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"flag"
|
||||
"fmt"
|
||||
"io"
|
||||
"net"
|
||||
"os"
|
||||
"os/exec"
|
||||
"path/filepath"
|
||||
"sort"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/meovv-mail/meovv-mail/internal/app"
|
||||
"github.com/meovv-mail/meovv-mail/internal/store"
|
||||
)
|
||||
|
||||
const (
|
||||
version = "0.1.0"
|
||||
stalwartVersion = "0.16.17"
|
||||
stalwartDigest = "sha256:a8108e19bd927e172d4d8c128907b8dfc93fd180ae8ee07dccdd42cb97eb9dfa"
|
||||
// Replaced by the release key when a compatibility manifest is cut.
|
||||
compatibilityPublicKey = "LcI9Tk7sfc6//uMsUiubzg+PY+HCJOZGPV1RVN+JJKs"
|
||||
)
|
||||
|
||||
var volumeArchives = map[string]string{
|
||||
"meovv-mail-caddy-data": "caddy-data.tgz",
|
||||
"meovv-mail-caddy-config": "caddy-config.tgz",
|
||||
"meovv-mail-app-data": "meovv-data.tgz",
|
||||
"meovv-mail-stalwart-config": "stalwart-config.tgz",
|
||||
"meovv-mail-stalwart-data": "stalwart-data.tgz",
|
||||
}
|
||||
|
||||
type backupManifest struct {
|
||||
Format int `json:"format"`
|
||||
CreatedAt time.Time `json:"created_at"`
|
||||
MEOVVVersion string `json:"meovv_version"`
|
||||
StalwartVersion string `json:"stalwart_version"`
|
||||
Files map[string]string `json:"sha256"`
|
||||
}
|
||||
|
||||
func main() {
|
||||
if len(os.Args) < 2 {
|
||||
usage()
|
||||
os.Exit(2)
|
||||
}
|
||||
var err error
|
||||
switch os.Args[1] {
|
||||
case "init":
|
||||
err = initialize(os.Args[2:])
|
||||
case "doctor":
|
||||
err = doctor(os.Args[2:])
|
||||
case "create-api-key":
|
||||
err = createAPIKey(os.Args[2:])
|
||||
case "backup":
|
||||
err = backup(os.Args[2:])
|
||||
case "restore":
|
||||
err = restore(os.Args[2:])
|
||||
case "upgrade":
|
||||
err = upgrade(os.Args[2:])
|
||||
case "reset-password":
|
||||
err = resetPassword(os.Args[2:])
|
||||
case "harden":
|
||||
err = harden(os.Args[2:])
|
||||
case "version":
|
||||
fmt.Printf("mailctl %s (Stalwart %s, %s)\n", version, stalwartVersion, stalwartDigest)
|
||||
case "help", "--help", "-h":
|
||||
usage()
|
||||
default:
|
||||
err = fmt.Errorf("unknown command %q", os.Args[1])
|
||||
}
|
||||
if err != nil {
|
||||
fmt.Fprintln(os.Stderr, "mailctl:", err)
|
||||
os.Exit(1)
|
||||
}
|
||||
}
|
||||
|
||||
func usage() {
|
||||
fmt.Print(`MEOVV Mail appliance utility
|
||||
|
||||
Usage: mailctl <command> [options]
|
||||
|
||||
init Create .env and one-time installation secrets
|
||||
doctor Check DNS, ports, files, and the running appliance
|
||||
create-api-key Create a hashed REST API key (run inside app container)
|
||||
backup Stop mail writers and create a checksummed backup
|
||||
restore Verify and restore a same-release backup
|
||||
upgrade Verify compatibility, back up, and apply an approved release
|
||||
reset-password Enable a temporary recovery administrator credential
|
||||
harden Remove the recovery credential and restart Stalwart
|
||||
version Print the appliance and pinned Stalwart versions
|
||||
`)
|
||||
}
|
||||
|
||||
func initialize(args []string) error {
|
||||
fs := flag.NewFlagSet("init", flag.ContinueOnError)
|
||||
hostname := fs.String("hostname", "", "public mail hostname")
|
||||
dir := fs.String("directory", ".", "Compose bundle directory")
|
||||
if err := fs.Parse(args); err != nil {
|
||||
return err
|
||||
}
|
||||
if !dnsName(*hostname) {
|
||||
return errors.New("--hostname must be a fully-qualified DNS name")
|
||||
}
|
||||
root, err := filepath.Abs(*dir)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if _, err = os.Stat(filepath.Join(root, ".env")); err == nil {
|
||||
return errors.New(".env already exists; initialization is intentionally non-destructive")
|
||||
} else if !errors.Is(err, os.ErrNotExist) {
|
||||
return err
|
||||
}
|
||||
secretDir := filepath.Join(root, "secrets")
|
||||
if err = os.MkdirAll(secretDir, 0o700); err != nil {
|
||||
return err
|
||||
}
|
||||
values := map[string]string{
|
||||
"bootstrap_token": randomSecret(32),
|
||||
"session_key": randomSecret(32),
|
||||
"internal_webhook_secret": randomSecret(32),
|
||||
"api_submission_password": randomSecret(32),
|
||||
}
|
||||
for name, value := range values {
|
||||
if err = writeExclusive(filepath.Join(secretDir, name), []byte(value+"\n"), 0o600); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
recovery := "admin:" + randomSecret(24)
|
||||
env := fmt.Sprintf("MEOVV_VERSION=%s\nMAIL_HOSTNAME=%s\nSTALWART_RECOVERY_ADMIN=%s\nAPI_SUBMISSION_USER=api-sender@%s\n", version, *hostname, recovery, strings.TrimPrefix(*hostname, "mail."))
|
||||
if err = writeExclusive(filepath.Join(root, ".env"), []byte(env), 0o600); err != nil {
|
||||
return err
|
||||
}
|
||||
fmt.Printf("Initialized %s\nBootstrap token: %s\nTemporary Stalwart recovery user: admin\nTemporary Stalwart recovery password: %s\n\nStore these values securely. Run 'docker compose up -d --build', complete setup, create a permanent administrator, then run 'mailctl harden'.\n", root, values["bootstrap_token"], strings.TrimPrefix(recovery, "admin:"))
|
||||
return nil
|
||||
}
|
||||
|
||||
func doctor(args []string) error {
|
||||
fs := flag.NewFlagSet("doctor", flag.ContinueOnError)
|
||||
hostname := fs.String("hostname", "", "public mail hostname; defaults to .env")
|
||||
dir := fs.String("directory", ".", "Compose bundle directory")
|
||||
if err := fs.Parse(args); err != nil {
|
||||
return err
|
||||
}
|
||||
root, _ := filepath.Abs(*dir)
|
||||
env, _ := readEnv(filepath.Join(root, ".env"))
|
||||
if *hostname == "" {
|
||||
*hostname = env["MAIL_HOSTNAME"]
|
||||
}
|
||||
failed := false
|
||||
check := func(name string, err error) {
|
||||
if err != nil {
|
||||
failed = true
|
||||
fmt.Printf("WARN %-18s %v\n", name, err)
|
||||
} else {
|
||||
fmt.Printf("OK %s\n", name)
|
||||
}
|
||||
}
|
||||
_, err := os.Stat(filepath.Join(root, "compose.yaml"))
|
||||
check("Compose bundle", err)
|
||||
_, err = os.Stat(filepath.Join(root, "secrets", "session_key"))
|
||||
check("Secrets", err)
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
|
||||
defer cancel()
|
||||
addresses, err := net.DefaultResolver.LookupHost(ctx, *hostname)
|
||||
if err == nil && len(addresses) == 0 {
|
||||
err = errors.New("no A or AAAA record")
|
||||
}
|
||||
check("A/AAAA", err)
|
||||
domain := strings.TrimPrefix(*hostname, "mail.")
|
||||
mx, mxErr := net.DefaultResolver.LookupMX(ctx, domain)
|
||||
if mxErr == nil {
|
||||
found := false
|
||||
for _, record := range mx {
|
||||
if strings.EqualFold(strings.TrimSuffix(record.Host, "."), *hostname) {
|
||||
found = true
|
||||
}
|
||||
}
|
||||
if !found {
|
||||
mxErr = fmt.Errorf("MX for %s does not point to %s", domain, *hostname)
|
||||
}
|
||||
}
|
||||
check("MX", mxErr)
|
||||
client := &net.Dialer{Timeout: 2 * time.Second}
|
||||
conn, httpErr := client.DialContext(ctx, "tcp", net.JoinHostPort(*hostname, "443"))
|
||||
if conn != nil {
|
||||
conn.Close()
|
||||
}
|
||||
check("HTTPS reachability", httpErr)
|
||||
if _, err = exec.LookPath("docker"); err == nil {
|
||||
err = run(root, "docker", "compose", "config", "--quiet")
|
||||
}
|
||||
check("Compose validation", err)
|
||||
if failed {
|
||||
return errors.New("one or more checks need attention; PTR, port 25 reachability, and IP reputation must also be verified with your hosting provider")
|
||||
}
|
||||
fmt.Println("Remember to confirm PTR, outbound port 25, SPF, DKIM, DMARC, and IP reputation externally.")
|
||||
return nil
|
||||
}
|
||||
|
||||
func createAPIKey(args []string) error {
|
||||
fs := flag.NewFlagSet("create-api-key", flag.ContinueOnError)
|
||||
dbPath := fs.String("db", "/var/lib/meovv-mail/meovv.sqlite", "MEOVV SQLite path")
|
||||
name := fs.String("name", "Application", "key name")
|
||||
scopes := fs.String("scopes", "messages.send,messages.status", "comma-separated scopes")
|
||||
senders := fs.String("senders", "", "comma-separated approved senders")
|
||||
rate := fs.Int("rate", 60, "submissions per minute")
|
||||
if err := fs.Parse(args); err != nil {
|
||||
return err
|
||||
}
|
||||
if strings.TrimSpace(*senders) == "" {
|
||||
return errors.New("--senders is required")
|
||||
}
|
||||
db, err := store.Open(*dbPath)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer db.Close()
|
||||
secret := app.RandomID("meovv_")
|
||||
key := store.APIKey{ID: app.RandomID("key_"), Name: *name, Prefix: secret[:14], Scopes: splitCSV(*scopes), AllowedSenders: splitCSV(*senders), RateLimit: *rate, CreatedAt: time.Now().UTC()}
|
||||
if err = db.CreateAPIKey(context.Background(), key, secret); err != nil {
|
||||
return err
|
||||
}
|
||||
fmt.Printf("API key created. Copy it now; it cannot be recovered.\n%s\n", secret)
|
||||
return nil
|
||||
}
|
||||
|
||||
func backup(args []string) error {
|
||||
fs := flag.NewFlagSet("backup", flag.ContinueOnError)
|
||||
dir := fs.String("directory", ".", "Compose bundle directory")
|
||||
destination := fs.String("output", "backups", "backup destination")
|
||||
if err := fs.Parse(args); err != nil {
|
||||
return err
|
||||
}
|
||||
root, _ := filepath.Abs(*dir)
|
||||
outRoot := *destination
|
||||
if !filepath.IsAbs(outRoot) {
|
||||
outRoot = filepath.Join(root, outRoot)
|
||||
}
|
||||
path := filepath.Join(outRoot, time.Now().UTC().Format("20060102T150405Z"))
|
||||
if err := os.MkdirAll(path, 0o700); err != nil {
|
||||
return err
|
||||
}
|
||||
if err := run(root, "docker", "compose", "stop", "meovv", "stalwart"); err != nil {
|
||||
return err
|
||||
}
|
||||
defer func() { _ = run(root, "docker", "compose", "up", "-d", "stalwart", "meovv") }()
|
||||
names := make([]string, 0, len(volumeArchives))
|
||||
for volume := range volumeArchives {
|
||||
names = append(names, volume)
|
||||
}
|
||||
sort.Strings(names)
|
||||
for _, volume := range names {
|
||||
archive := volumeArchives[volume]
|
||||
if err := run(root, "docker", "run", "--rm", "-v", volume+":/source:ro", "-v", path+":/backup", "alpine:3.22", "tar", "-czf", "/backup/"+archive, "-C", "/source", "."); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
if err := archiveConfiguration(root, filepath.Join(path, "configuration.tgz")); err != nil {
|
||||
return err
|
||||
}
|
||||
manifest := backupManifest{Format: 1, CreatedAt: time.Now().UTC(), MEOVVVersion: version, StalwartVersion: stalwartVersion, Files: map[string]string{}}
|
||||
for _, file := range append(mapsValues(volumeArchives), "configuration.tgz") {
|
||||
digest, err := fileDigest(filepath.Join(path, file))
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
manifest.Files[file] = digest
|
||||
}
|
||||
raw, _ := json.MarshalIndent(manifest, "", " ")
|
||||
if err := os.WriteFile(filepath.Join(path, "manifest.json"), append(raw, '\n'), 0o600); err != nil {
|
||||
return err
|
||||
}
|
||||
fmt.Println("Backup complete:", path)
|
||||
return nil
|
||||
}
|
||||
|
||||
func restore(args []string) error {
|
||||
fs := flag.NewFlagSet("restore", flag.ContinueOnError)
|
||||
dir := fs.String("directory", ".", "clean Compose bundle directory")
|
||||
from := fs.String("from", "", "backup directory")
|
||||
yes := fs.Bool("yes", false, "confirm destructive replacement of appliance data")
|
||||
if err := fs.Parse(args); err != nil {
|
||||
return err
|
||||
}
|
||||
if !*yes || *from == "" {
|
||||
return errors.New("restore requires --from and --yes; it replaces all appliance volumes")
|
||||
}
|
||||
root, _ := filepath.Abs(*dir)
|
||||
backupDir, _ := filepath.Abs(*from)
|
||||
manifest, err := verifyBackup(backupDir)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if manifest.MEOVVVersion != version || manifest.StalwartVersion != stalwartVersion {
|
||||
return fmt.Errorf("backup release is MEOVV %s / Stalwart %s; this binary is %s / %s", manifest.MEOVVVersion, manifest.StalwartVersion, version, stalwartVersion)
|
||||
}
|
||||
if err = run(root, "docker", "compose", "stop", "meovv", "stalwart", "caddy"); err != nil {
|
||||
return err
|
||||
}
|
||||
for volume, archive := range volumeArchives {
|
||||
script := "find /target -mindepth 1 -maxdepth 1 -exec rm -rf -- {} + && tar -xzf /backup/" + archive + " -C /target"
|
||||
if err = run(root, "docker", "run", "--rm", "-v", volume+":/target", "-v", backupDir+":/backup:ro", "alpine:3.22", "sh", "-c", script); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
if err = restoreConfiguration(root, filepath.Join(backupDir, "configuration.tgz")); err != nil {
|
||||
return err
|
||||
}
|
||||
if err = run(root, "docker", "compose", "up", "-d"); err != nil {
|
||||
return err
|
||||
}
|
||||
fmt.Println("Restore complete. Run 'mailctl doctor' before accepting traffic.")
|
||||
return nil
|
||||
}
|
||||
|
||||
func upgrade(args []string) error {
|
||||
fs := flag.NewFlagSet("upgrade", flag.ContinueOnError)
|
||||
dir := fs.String("directory", ".", "Compose bundle directory")
|
||||
manifestPath := fs.String("manifest", "release/compatibility.json", "signed compatibility manifest")
|
||||
signaturePath := fs.String("signature", "release/compatibility.sig", "manifest signature")
|
||||
if err := fs.Parse(args); err != nil {
|
||||
return err
|
||||
}
|
||||
root, _ := filepath.Abs(*dir)
|
||||
manifest := *manifestPath
|
||||
if !filepath.IsAbs(manifest) {
|
||||
manifest = filepath.Join(root, manifest)
|
||||
}
|
||||
signature := *signaturePath
|
||||
if !filepath.IsAbs(signature) {
|
||||
signature = filepath.Join(root, signature)
|
||||
}
|
||||
if err := verifyCompatibility(manifest, signature); err != nil {
|
||||
return err
|
||||
}
|
||||
if err := doctor([]string{"--directory", root}); err != nil {
|
||||
return fmt.Errorf("pre-upgrade diagnostics: %w", err)
|
||||
}
|
||||
if err := backup([]string{"--directory", root}); err != nil {
|
||||
return fmt.Errorf("pre-upgrade backup: %w", err)
|
||||
}
|
||||
if err := run(root, "docker", "compose", "pull"); err != nil {
|
||||
return err
|
||||
}
|
||||
if err := run(root, "docker", "compose", "build", "--pull", "meovv"); err != nil {
|
||||
return err
|
||||
}
|
||||
return run(root, "docker", "compose", "up", "-d")
|
||||
}
|
||||
|
||||
func resetPassword(args []string) error {
|
||||
fs := flag.NewFlagSet("reset-password", flag.ContinueOnError)
|
||||
dir := fs.String("directory", ".", "Compose bundle directory")
|
||||
username := fs.String("user", "recovery-admin", "temporary recovery username")
|
||||
password := fs.String("password", "", "temporary recovery password; generated when omitted")
|
||||
if err := fs.Parse(args); err != nil {
|
||||
return err
|
||||
}
|
||||
if *password == "" {
|
||||
*password = randomSecret(24)
|
||||
}
|
||||
root, _ := filepath.Abs(*dir)
|
||||
if err := setEnv(filepath.Join(root, ".env"), "STALWART_RECOVERY_ADMIN", *username+":"+*password); err != nil {
|
||||
return err
|
||||
}
|
||||
if err := run(root, "docker", "compose", "up", "-d", "--force-recreate", "stalwart"); err != nil {
|
||||
return err
|
||||
}
|
||||
fmt.Printf("Temporary recovery access enabled for %s. Sign in, reset the permanent account, verify it, then immediately run 'mailctl harden'.\nPassword: %s\n", *username, *password)
|
||||
return nil
|
||||
}
|
||||
|
||||
func harden(args []string) error {
|
||||
fs := flag.NewFlagSet("harden", flag.ContinueOnError)
|
||||
dir := fs.String("directory", ".", "Compose bundle directory")
|
||||
if err := fs.Parse(args); err != nil {
|
||||
return err
|
||||
}
|
||||
root, _ := filepath.Abs(*dir)
|
||||
if err := setEnv(filepath.Join(root, ".env"), "STALWART_RECOVERY_ADMIN", ""); err != nil {
|
||||
return err
|
||||
}
|
||||
if err := run(root, "docker", "compose", "up", "-d", "--force-recreate", "stalwart", "meovv"); err != nil {
|
||||
return err
|
||||
}
|
||||
fmt.Println("Recovery administrator removed from the running environment.")
|
||||
return nil
|
||||
}
|
||||
|
||||
func verifyBackup(path string) (backupManifest, error) {
|
||||
raw, err := os.ReadFile(filepath.Join(path, "manifest.json"))
|
||||
if err != nil {
|
||||
return backupManifest{}, err
|
||||
}
|
||||
var manifest backupManifest
|
||||
if err = json.Unmarshal(raw, &manifest); err != nil {
|
||||
return manifest, err
|
||||
}
|
||||
if manifest.Format != 1 {
|
||||
return manifest, fmt.Errorf("unsupported backup format %d", manifest.Format)
|
||||
}
|
||||
for file, expected := range manifest.Files {
|
||||
actual, err := fileDigest(filepath.Join(path, file))
|
||||
if err != nil {
|
||||
return manifest, err
|
||||
}
|
||||
if !strings.EqualFold(actual, expected) {
|
||||
return manifest, fmt.Errorf("checksum mismatch for %s", file)
|
||||
}
|
||||
}
|
||||
return manifest, nil
|
||||
}
|
||||
|
||||
func verifyCompatibility(manifestPath, signaturePath string) error {
|
||||
raw, err := os.ReadFile(manifestPath)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
sigText, err := os.ReadFile(signaturePath)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
publicKey, err := base64.RawStdEncoding.DecodeString(compatibilityPublicKey)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
signature, err := base64.RawStdEncoding.DecodeString(strings.TrimSpace(string(sigText)))
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if !ed25519.Verify(ed25519.PublicKey(publicKey), raw, signature) {
|
||||
return errors.New("compatibility manifest signature is invalid")
|
||||
}
|
||||
var manifest struct {
|
||||
MEOVVVersion string `json:"meovv_version"`
|
||||
Stalwart struct {
|
||||
Version string `json:"version"`
|
||||
Digest string `json:"digest"`
|
||||
} `json:"stalwart"`
|
||||
}
|
||||
if err = json.Unmarshal(raw, &manifest); err != nil {
|
||||
return err
|
||||
}
|
||||
if manifest.MEOVVVersion != version || manifest.Stalwart.Version != stalwartVersion || manifest.Stalwart.Digest != stalwartDigest {
|
||||
return errors.New("compatibility manifest does not approve the versions embedded in this release")
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func archiveConfiguration(root, destination string) error {
|
||||
out, err := os.OpenFile(destination, os.O_CREATE|os.O_EXCL|os.O_WRONLY, 0o600)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer out.Close()
|
||||
gz := gzip.NewWriter(out)
|
||||
defer gz.Close()
|
||||
tw := tar.NewWriter(gz)
|
||||
defer tw.Close()
|
||||
paths := []string{".env", "compose.yaml", "deploy/caddy/Caddyfile"}
|
||||
_ = filepath.WalkDir(filepath.Join(root, "secrets"), func(path string, entry os.DirEntry, walkErr error) error {
|
||||
if walkErr == nil && !entry.IsDir() {
|
||||
rel, _ := filepath.Rel(root, path)
|
||||
paths = append(paths, rel)
|
||||
}
|
||||
return walkErr
|
||||
})
|
||||
for _, relative := range paths {
|
||||
path := filepath.Join(root, relative)
|
||||
info, err := os.Stat(path)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
header, _ := tar.FileInfoHeader(info, "")
|
||||
header.Name = filepath.ToSlash(relative)
|
||||
if err = tw.WriteHeader(header); err != nil {
|
||||
return err
|
||||
}
|
||||
file, err := os.Open(path)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
_, err = io.Copy(tw, file)
|
||||
file.Close()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func restoreConfiguration(root, archive string) error {
|
||||
file, err := os.Open(archive)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer file.Close()
|
||||
gz, err := gzip.NewReader(file)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer gz.Close()
|
||||
tr := tar.NewReader(gz)
|
||||
for {
|
||||
header, err := tr.Next()
|
||||
if errors.Is(err, io.EOF) {
|
||||
return nil
|
||||
}
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
clean := filepath.Clean(header.Name)
|
||||
if filepath.IsAbs(clean) || strings.HasPrefix(clean, "..") || (clean != ".env" && clean != "compose.yaml" && clean != "deploy/caddy/Caddyfile" && !strings.HasPrefix(clean, "secrets/")) {
|
||||
return fmt.Errorf("unsafe configuration archive entry %q", header.Name)
|
||||
}
|
||||
target := filepath.Join(root, clean)
|
||||
if err = os.MkdirAll(filepath.Dir(target), 0o700); err != nil {
|
||||
return err
|
||||
}
|
||||
mode := os.FileMode(header.Mode) & 0o700
|
||||
if mode == 0 {
|
||||
mode = 0o600
|
||||
}
|
||||
out, err := os.OpenFile(target, os.O_CREATE|os.O_TRUNC|os.O_WRONLY, mode)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
_, err = io.CopyN(out, tr, header.Size)
|
||||
out.Close()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func run(directory, name string, args ...string) error {
|
||||
command := exec.Command(name, args...)
|
||||
command.Dir = directory
|
||||
command.Stdout = os.Stdout
|
||||
command.Stderr = os.Stderr
|
||||
command.Stdin = os.Stdin
|
||||
return command.Run()
|
||||
}
|
||||
|
||||
func fileDigest(path string) (string, error) {
|
||||
file, err := os.Open(path)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
defer file.Close()
|
||||
digest := sha256.New()
|
||||
if _, err = io.Copy(digest, file); err != nil {
|
||||
return "", err
|
||||
}
|
||||
return hex.EncodeToString(digest.Sum(nil)), nil
|
||||
}
|
||||
|
||||
func randomSecret(size int) string {
|
||||
raw := make([]byte, size)
|
||||
_, _ = rand.Read(raw)
|
||||
return base64.RawURLEncoding.EncodeToString(raw)
|
||||
}
|
||||
|
||||
func writeExclusive(path string, contents []byte, mode os.FileMode) error {
|
||||
file, err := os.OpenFile(path, os.O_CREATE|os.O_EXCL|os.O_WRONLY, mode)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer file.Close()
|
||||
_, err = file.Write(contents)
|
||||
return err
|
||||
}
|
||||
|
||||
func readEnv(path string) (map[string]string, error) {
|
||||
raw, err := os.ReadFile(path)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
out := map[string]string{}
|
||||
for _, line := range strings.Split(string(raw), "\n") {
|
||||
key, value, ok := strings.Cut(line, "=")
|
||||
if ok && !strings.HasPrefix(strings.TrimSpace(key), "#") {
|
||||
out[strings.TrimSpace(key)] = strings.TrimSpace(value)
|
||||
}
|
||||
}
|
||||
return out, nil
|
||||
}
|
||||
|
||||
func setEnv(path, key, value string) error {
|
||||
raw, err := os.ReadFile(path)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
lines := strings.Split(strings.TrimRight(string(raw), "\n"), "\n")
|
||||
found := false
|
||||
for i, line := range lines {
|
||||
if strings.HasPrefix(line, key+"=") {
|
||||
lines[i] = key + "=" + value
|
||||
found = true
|
||||
}
|
||||
}
|
||||
if !found {
|
||||
lines = append(lines, key+"="+value)
|
||||
}
|
||||
temporary := path + ".tmp"
|
||||
if err = os.WriteFile(temporary, []byte(strings.Join(lines, "\n")+"\n"), 0o600); err != nil {
|
||||
return err
|
||||
}
|
||||
return os.Rename(temporary, path)
|
||||
}
|
||||
|
||||
func dnsName(value string) bool {
|
||||
if len(value) < 3 || len(value) > 253 || !strings.Contains(value, ".") || strings.ContainsAny(value, " /:@") {
|
||||
return false
|
||||
}
|
||||
for _, part := range strings.Split(value, ".") {
|
||||
if part == "" || strings.HasPrefix(part, "-") || strings.HasSuffix(part, "-") {
|
||||
return false
|
||||
}
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
func splitCSV(value string) []string {
|
||||
var out []string
|
||||
for _, item := range strings.Split(value, ",") {
|
||||
if item = strings.TrimSpace(item); item != "" {
|
||||
out = append(out, item)
|
||||
}
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
func mapsValues(values map[string]string) []string {
|
||||
out := make([]string, 0, len(values))
|
||||
for _, value := range values {
|
||||
out = append(out, value)
|
||||
}
|
||||
sort.Strings(out)
|
||||
return out
|
||||
}
|
||||
@@ -0,0 +1,9 @@
|
||||
package main
|
||||
|
||||
import "testing"
|
||||
|
||||
func TestSignedCompatibilityManifest(t *testing.T) {
|
||||
if err := verifyCompatibility("../../release/compatibility.json", "../../release/compatibility.sig"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,83 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"context"
|
||||
"crypto/tls"
|
||||
"log/slog"
|
||||
"net/http"
|
||||
"os"
|
||||
"os/signal"
|
||||
"path/filepath"
|
||||
"syscall"
|
||||
"time"
|
||||
|
||||
"github.com/meovv-mail/meovv-mail/internal/app"
|
||||
"github.com/meovv-mail/meovv-mail/internal/config"
|
||||
"github.com/meovv-mail/meovv-mail/internal/httpapi"
|
||||
"github.com/meovv-mail/meovv-mail/internal/mailer"
|
||||
"github.com/meovv-mail/meovv-mail/internal/stalwart"
|
||||
"github.com/meovv-mail/meovv-mail/internal/store"
|
||||
"github.com/meovv-mail/meovv-mail/internal/webhook"
|
||||
)
|
||||
|
||||
func main() {
|
||||
logger := slog.New(slog.NewJSONHandler(os.Stdout, nil))
|
||||
cfg, err := config.Load()
|
||||
if err != nil {
|
||||
logger.Error("load configuration", "error", err)
|
||||
os.Exit(1)
|
||||
}
|
||||
if err = os.MkdirAll(cfg.DataDir, 0o700); err != nil {
|
||||
logger.Error("create data directory", "error", err)
|
||||
os.Exit(1)
|
||||
}
|
||||
db, err := store.Open(filepath.Join(cfg.DataDir, "meovv.sqlite"))
|
||||
if err != nil {
|
||||
logger.Error("open database", "error", err)
|
||||
os.Exit(1)
|
||||
}
|
||||
defer db.Close()
|
||||
cipher, err := app.NewTokenCipher(cfg.SessionKey)
|
||||
if err != nil {
|
||||
logger.Error("initialize token encryption", "error", err)
|
||||
os.Exit(1)
|
||||
}
|
||||
stalwartClient := stalwart.New(cfg.StalwartURL, cfg.StalwartTLSInsecure)
|
||||
smtpSender := mailer.SMTP{Address: cfg.SMTPAddress, Username: cfg.SMTPUsername, Password: cfg.SMTPPassword, TLSConfig: &tls.Config{ServerName: cfg.SMTPTLSServerName, MinVersion: tls.VersionTLS12}}
|
||||
api := httpapi.New(cfg, db, smtpSender, stalwartClient, cipher, logger, env("MEOVV_STATIC_DIR", "/app/web"))
|
||||
server := &http.Server{Addr: cfg.Addr, Handler: api.Handler(), ReadHeaderTimeout: 10 * time.Second, ReadTimeout: 30 * time.Second, WriteTimeout: 60 * time.Second, IdleTimeout: 2 * time.Minute}
|
||||
ctx, stop := signal.NotifyContext(context.Background(), syscall.SIGINT, syscall.SIGTERM)
|
||||
defer stop()
|
||||
dispatcher := webhook.New(db, cipher)
|
||||
go dispatcher.Run(ctx)
|
||||
go func() {
|
||||
ticker := time.NewTicker(24 * time.Hour)
|
||||
defer ticker.Stop()
|
||||
for {
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
return
|
||||
case <-ticker.C:
|
||||
now := time.Now()
|
||||
_ = db.Cleanup(ctx, now.Add(-cfg.MessageRetention), now.Add(-cfg.WebhookRetention), now.Add(-cfg.AuditRetention))
|
||||
}
|
||||
}
|
||||
}()
|
||||
go func() {
|
||||
logger.Info("MEOVV Mail listening", "address", cfg.Addr)
|
||||
if err := server.ListenAndServe(); err != nil && err != http.ErrServerClosed {
|
||||
logger.Error("HTTP server failed", "error", err)
|
||||
stop()
|
||||
}
|
||||
}()
|
||||
<-ctx.Done()
|
||||
shutdownCtx, cancel := context.WithTimeout(context.Background(), 15*time.Second)
|
||||
defer cancel()
|
||||
_ = server.Shutdown(shutdownCtx)
|
||||
}
|
||||
func env(name, fallback string) string {
|
||||
if value := os.Getenv(name); value != "" {
|
||||
return value
|
||||
}
|
||||
return fallback
|
||||
}
|
||||
@@ -0,0 +1,86 @@
|
||||
name: meovv-mail
|
||||
|
||||
services:
|
||||
caddy:
|
||||
image: caddy:2.10.2-alpine
|
||||
restart: unless-stopped
|
||||
environment:
|
||||
MAIL_HOSTNAME: ${MAIL_HOSTNAME:?Set MAIL_HOSTNAME in .env}
|
||||
ports:
|
||||
- "80:80"
|
||||
- "443:443"
|
||||
volumes:
|
||||
- ./deploy/caddy/Caddyfile:/etc/caddy/Caddyfile:ro
|
||||
- caddy_data:/data
|
||||
- caddy_config:/config
|
||||
networks: [mail]
|
||||
depends_on:
|
||||
meovv:
|
||||
condition: service_healthy
|
||||
stalwart:
|
||||
condition: service_started
|
||||
|
||||
meovv:
|
||||
build:
|
||||
context: .
|
||||
image: meovv-mail:${MEOVV_VERSION:-0.1.0}
|
||||
restart: unless-stopped
|
||||
environment:
|
||||
MEOVV_ADDR: :8080
|
||||
MEOVV_DATA_DIR: /var/lib/meovv-mail
|
||||
MEOVV_PUBLIC_URL: https://${MAIL_HOSTNAME}
|
||||
MEOVV_BOOTSTRAP_TOKEN_FILE: /run/secrets/bootstrap_token
|
||||
MEOVV_INTERNAL_WEBHOOK_SECRET_FILE: /run/secrets/internal_webhook_secret
|
||||
MEOVV_SESSION_KEY_FILE: /run/secrets/session_key
|
||||
STALWART_URL: https://stalwart:443
|
||||
STALWART_BOOTSTRAP_URL: http://stalwart:8080
|
||||
STALWART_TLS_INSECURE: "true"
|
||||
STALWART_RECOVERY_ADMIN: ${STALWART_RECOVERY_ADMIN:-}
|
||||
STALWART_SMTP_ADDRESS: stalwart:587
|
||||
STALWART_TLS_SERVER_NAME: ${MAIL_HOSTNAME}
|
||||
STALWART_SMTP_USERNAME: ${API_SUBMISSION_USER:-}
|
||||
STALWART_SMTP_PASSWORD_FILE: /run/secrets/api_submission_password
|
||||
volumes:
|
||||
- meovv_data:/var/lib/meovv-mail
|
||||
- ./secrets:/run/secrets:ro
|
||||
networks: [mail]
|
||||
depends_on:
|
||||
stalwart:
|
||||
condition: service_started
|
||||
healthcheck:
|
||||
test: ["CMD", "wget", "-q", "--spider", "http://127.0.0.1:8080/health/live"]
|
||||
interval: 15s
|
||||
timeout: 3s
|
||||
retries: 5
|
||||
|
||||
stalwart:
|
||||
image: stalwartlabs/stalwart:v0.16.17@sha256:a8108e19bd927e172d4d8c128907b8dfc93fd180ae8ee07dccdd42cb97eb9dfa
|
||||
restart: unless-stopped
|
||||
environment:
|
||||
STALWART_PUBLIC_URL: https://${MAIL_HOSTNAME}
|
||||
STALWART_RECOVERY_ADMIN: ${STALWART_RECOVERY_ADMIN:-}
|
||||
ports:
|
||||
- "25:25"
|
||||
- "465:465"
|
||||
- "587:587"
|
||||
- "993:993"
|
||||
volumes:
|
||||
- stalwart_config:/etc/stalwart
|
||||
- stalwart_data:/var/lib/stalwart
|
||||
networks: [mail]
|
||||
|
||||
networks:
|
||||
mail:
|
||||
driver: bridge
|
||||
|
||||
volumes:
|
||||
caddy_data:
|
||||
name: meovv-mail-caddy-data
|
||||
caddy_config:
|
||||
name: meovv-mail-caddy-config
|
||||
meovv_data:
|
||||
name: meovv-mail-app-data
|
||||
stalwart_config:
|
||||
name: meovv-mail-stalwart-config
|
||||
stalwart_data:
|
||||
name: meovv-mail-stalwart-data
|
||||
@@ -0,0 +1,26 @@
|
||||
{$MAIL_HOSTNAME} {
|
||||
encode zstd gzip
|
||||
|
||||
@meovv path / /assets/* /favicon.svg /health/* /metrics /api/setup/* /api/session/* /api/mail/* /api/admin/* /api/internal/* /api/v1/*
|
||||
handle @meovv {
|
||||
reverse_proxy meovv:8080
|
||||
}
|
||||
|
||||
@stalwart path /.well-known/* /jmap /jmap/* /auth/* /api/auth /api/discover/* /api/account /api/token/* /mail/config-v1.1.xml /autodiscover/*
|
||||
handle @stalwart {
|
||||
reverse_proxy https://stalwart:443 {
|
||||
transport http {
|
||||
tls_insecure_skip_verify
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
handle {
|
||||
reverse_proxy meovv:8080
|
||||
}
|
||||
|
||||
header {
|
||||
Strict-Transport-Security "max-age=31536000; includeSubDomains"
|
||||
-Server
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,38 @@
|
||||
# Architecture
|
||||
|
||||
## Trust and data boundaries
|
||||
|
||||
Public HTTPS reaches Caddy first. Caddy sends product UI, session, administration, health, and REST API routes to the Go service. Standards discovery, OAuth authorization, public JMAP, mail-client configuration, and ACME challenge routes go to Stalwart. Mail protocols reach Stalwart directly on their dedicated TLS-capable ports, so Stalwart obtains its own certificate for SMTP and IMAP while Caddy independently manages the public web certificate.
|
||||
|
||||
The branded sign-in form posts the password directly to same-origin `/api/auth`, which Caddy routes to Stalwart. The browser creates a PKCE verifier and sends only the one-time authorization code and verifier to MEOVV. The Go service exchanges that code, encrypts access and refresh tokens with AES-GCM, and returns an opaque Secure, HttpOnly, SameSite cookie. User passwords are never sent to or persisted by MEOVV.
|
||||
|
||||
Authenticated browser JMAP calls go through `/api/mail/jmap`; discovery goes through `/api/mail/session`; the event stream uses `/api/mail/events`. The Stalwart adapter is the only Go package that knows these upstream routes, which contains pre-1.0 compatibility changes.
|
||||
|
||||
## Persistence
|
||||
|
||||
Stalwart RocksDB/filesystem volumes contain:
|
||||
|
||||
- local principals, password hashes, application passwords, and authorization state
|
||||
- message bodies, MIME source, attachments, mailboxes, search indexes, and queue state
|
||||
- spam-filter data, DKIM material, and mail-server configuration
|
||||
|
||||
MEOVV SQLite in WAL mode contains:
|
||||
|
||||
- installation and product configuration
|
||||
- hashed REST API keys and approved senders
|
||||
- message envelope, size, submission, and per-recipient delivery state
|
||||
- idempotency records with a 24-hour expiry
|
||||
- webhook endpoints, encrypted-at-rest deployment secrets, attempts, and jobs
|
||||
- encrypted OAuth tokens, sessions, preferences, and administrator audit events
|
||||
|
||||
The database deliberately has no message-body or attachment column.
|
||||
|
||||
## Delivery flow
|
||||
|
||||
REST submissions are validated, MIME-encoded, and written to SQLite in `queued` state in a single transaction with any idempotency record. The application then uses authenticated STARTTLS submission to Stalwart. It returns `202` only after Stalwart accepts the message. Stalwart is therefore the durable queue for every acknowledged submission.
|
||||
|
||||
Stalwart posts signed internal telemetry events. MEOVV normalizes these into `queued`, `processing`, `deferred`, `delivered`, `partial`, `bounced`, or `failed`, keeping recipient-level state. External webhook payloads are versioned independently from Stalwart event schemas.
|
||||
|
||||
## Compatibility
|
||||
|
||||
`release/compatibility.json` is signed with Ed25519. The release public key is compiled into `mailctl`; upgrade refuses a modified signature, a mismatched MEOVV release, or a different Stalwart version/image digest. Contract fixtures and adapter tests should be updated before signing a new manifest.
|
||||
@@ -0,0 +1,40 @@
|
||||
# Operations runbook
|
||||
|
||||
## Delivery modes
|
||||
|
||||
Direct delivery is the default. Use it only when the host has a stable public IP, outbound TCP 25, correct PTR, and an IP range suitable for email. Relay mode sends through an authenticated TLS smart host and is the supported fallback. Changing mode does not require reinstalling; update the delivery configuration and run diagnostics before switching traffic.
|
||||
|
||||
## Backups and restore drills
|
||||
|
||||
`mailctl backup` stops the two data writers, archives every named volume and the host configuration/secrets, computes checksums, and starts the services again. Copy the resulting directory to storage that is encrypted, access-controlled, and separate from the mail host.
|
||||
|
||||
Run a restore drill for every release:
|
||||
|
||||
1. Prepare a clean host with the same MEOVV release.
|
||||
2. Copy the complete backup directory to it.
|
||||
3. Run `mailctl restore --from <directory> --yes`.
|
||||
4. Run `mailctl doctor` and inspect `/health/ready`.
|
||||
5. Verify administrator sign-in, mailbox counts, a historical attachment, REST status records, and DKIM output.
|
||||
6. Submit inbound, direct/relay outbound, and webhook test messages.
|
||||
|
||||
Restore checks every archive before replacing any volume and rejects cross-release restores.
|
||||
|
||||
## Upgrades
|
||||
|
||||
Only use a complete versioned release bundle. `mailctl upgrade` verifies the compatibility signature, creates a backup, pulls approved images, builds the MEOVV image, and recreates the services. Never edit the Stalwart tag or digest directly. If preflight or signature validation fails, do not force the upgrade.
|
||||
|
||||
## Lockout recovery
|
||||
|
||||
`mailctl reset-password` creates or installs a temporary recovery administrator and recreates Stalwart. Use it to enter Stalwart, change the permanent account credential, revoke suspect sessions, and verify normal sign-in. Then run `mailctl harden`, which removes the recovery environment value and recreates Stalwart and MEOVV. Leaving recovery access enabled is a critical finding.
|
||||
|
||||
## Incident checks
|
||||
|
||||
- Queue growth: check DNS, upstream response text, outbound port 25, relay authentication, and reputation.
|
||||
- Inbound failures: check public MX, TCP 25, Stalwart listeners, TLS, recipient existence, and bans.
|
||||
- OAuth loops: confirm the browser hostname exactly matches `MAIL_HOSTNAME` and `STALWART_PUBLIC_URL`.
|
||||
- Webhook retries: inspect DNS resolution, public HTTPS, response code, latency, and signature verification. Duplicates are expected after ambiguous failures.
|
||||
- Readiness failure: inspect the named database volumes and Stalwart HTTPS health before restarting repeatedly.
|
||||
|
||||
## Retention
|
||||
|
||||
Cleanup runs daily. Delivery metadata defaults to 30 days, webhook attempts to 7 days, and administrator audit events to 180 days. Retention changes affect future cleanup and should be documented in the organization's policy.
|
||||
@@ -0,0 +1,29 @@
|
||||
# Security model
|
||||
|
||||
## Primary controls
|
||||
|
||||
- Passwords and mailbox content stay in Stalwart.
|
||||
- OAuth authorization code with PKCE prevents the browser from retaining a reusable password or bearer token.
|
||||
- Access and refresh tokens are encrypted with AES-256-GCM and referenced by opaque HttpOnly session cookies.
|
||||
- Mutating browser routes reject cross-site Origin and Fetch Metadata requests; cookies are SameSite and Secure on HTTPS.
|
||||
- REST API keys are shown once, stored as SHA-256 digests, scoped, sender-bound, rate-limited, and individually revocable.
|
||||
- REST messages are limited to 25 MiB decoded and 100 recipients; header names are allowlisted and CR/LF injection is rejected.
|
||||
- Email HTML is sanitized, remote content is blocked by default, and attachment filenames are reduced to safe basenames.
|
||||
- Webhooks require public HTTPS and reject loopback, private, link-local, unspecified, and multicast resolutions.
|
||||
- External webhooks sign `{timestamp}.{raw_body}` with HMAC-SHA256 and retain event IDs across retries.
|
||||
- Caddy adds HSTS; the application adds CSP, anti-framing, MIME-sniffing, referrer, and permissions policies.
|
||||
- Only 25, 465, 587, and 993 are published for mail. POP3 and plaintext IMAP are absent.
|
||||
|
||||
## Deployment invariants
|
||||
|
||||
Before exposure, confirm that unauthenticated SMTP cannot relay to a third-party domain, sender authorization is enforced on submission, recovery administrator access is removed, and Stalwart's spam/phishing, SPF, DKIM, DMARC, TLS, abuse-ban, and rate-limit defaults remain enabled.
|
||||
|
||||
The internal Docker network is not a trust substitute. Stalwart delivery events use a separate shared HMAC secret. The Stalwart management API is not routed publicly by Caddy; administrators use the authenticated Go adapter.
|
||||
|
||||
## Audit and response
|
||||
|
||||
Administrator mutations write append-only application audit events. Production operators should additionally forward container logs to immutable external storage. Rotate an exposed API key or webhook secret rather than trying to recover it. Revoke active sessions and application passwords after an account incident.
|
||||
|
||||
## Required release review
|
||||
|
||||
Run open-relay, sender-spoofing, brute-force, CSRF, session-fixation, malicious HTML, attachment traversal, API-key leakage, and webhook SSRF tests for each supported architecture. Distribution also requires legal review of the Stalwart AGPL separation and corresponding-source offer.
|
||||
@@ -0,0 +1,41 @@
|
||||
import { defineConfig, globalIgnores } from "eslint/config";
|
||||
import eslint from "@eslint/js";
|
||||
import jsxA11y from "eslint-plugin-jsx-a11y";
|
||||
import react from "eslint-plugin-react";
|
||||
import reactHooks from "eslint-plugin-react-hooks";
|
||||
import globals from "globals";
|
||||
import tseslint from "typescript-eslint";
|
||||
|
||||
const eslintConfig = defineConfig([
|
||||
globalIgnores([
|
||||
".next/**",
|
||||
".vinext/**",
|
||||
".wrangler/**",
|
||||
".openai/**",
|
||||
"dist/**",
|
||||
"out/**",
|
||||
"web-dist/**",
|
||||
]),
|
||||
eslint.configs.recommended,
|
||||
...tseslint.configs.recommended,
|
||||
react.configs.flat.recommended,
|
||||
react.configs.flat["jsx-runtime"],
|
||||
reactHooks.configs.flat["recommended-latest"],
|
||||
jsxA11y.flatConfigs.recommended,
|
||||
{
|
||||
languageOptions: {
|
||||
globals: {
|
||||
...globals.browser,
|
||||
...globals.node,
|
||||
...globals.serviceworker,
|
||||
},
|
||||
},
|
||||
settings: {
|
||||
react: {
|
||||
version: "detect",
|
||||
},
|
||||
},
|
||||
},
|
||||
]);
|
||||
|
||||
export default eslintConfig;
|
||||
@@ -0,0 +1,18 @@
|
||||
module github.com/meovv-mail/meovv-mail
|
||||
|
||||
go 1.24.0
|
||||
|
||||
require modernc.org/sqlite v1.38.2
|
||||
|
||||
require (
|
||||
github.com/dustin/go-humanize v1.0.1 // indirect
|
||||
github.com/google/uuid v1.6.0 // indirect
|
||||
github.com/mattn/go-isatty v0.0.20 // indirect
|
||||
github.com/ncruces/go-strftime v0.1.9 // indirect
|
||||
github.com/remyoudompheng/bigfft v0.0.0-20230129092748-24d4a6f8daec // indirect
|
||||
golang.org/x/exp v0.0.0-20250620022241-b7579e27df2b // indirect
|
||||
golang.org/x/sys v0.34.0 // indirect
|
||||
modernc.org/libc v1.66.3 // indirect
|
||||
modernc.org/mathutil v1.7.1 // indirect
|
||||
modernc.org/memory v1.11.0 // indirect
|
||||
)
|
||||
@@ -0,0 +1,49 @@
|
||||
github.com/dustin/go-humanize v1.0.1 h1:GzkhY7T5VNhEkwH0PVJgjz+fX1rhBrR7pRT3mDkpeCY=
|
||||
github.com/dustin/go-humanize v1.0.1/go.mod h1:Mu1zIs6XwVuF/gI1OepvI0qD18qycQx+mFykh5fBlto=
|
||||
github.com/google/pprof v0.0.0-20250317173921-a4b03ec1a45e h1:ijClszYn+mADRFY17kjQEVQ1XRhq2/JR1M3sGqeJoxs=
|
||||
github.com/google/pprof v0.0.0-20250317173921-a4b03ec1a45e/go.mod h1:boTsfXsheKC2y+lKOCMpSfarhxDeIzfZG1jqGcPl3cA=
|
||||
github.com/google/uuid v1.6.0 h1:NIvaJDMOsjHA8n1jAhLSgzrAzy1Hgr+hNrb57e+94F0=
|
||||
github.com/google/uuid v1.6.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo=
|
||||
github.com/mattn/go-isatty v0.0.20 h1:xfD0iDuEKnDkl03q4limB+vH+GxLEtL/jb4xVJSWWEY=
|
||||
github.com/mattn/go-isatty v0.0.20/go.mod h1:W+V8PltTTMOvKvAeJH7IuucS94S2C6jfK/D7dTCTo3Y=
|
||||
github.com/ncruces/go-strftime v0.1.9 h1:bY0MQC28UADQmHmaF5dgpLmImcShSi2kHU9XLdhx/f4=
|
||||
github.com/ncruces/go-strftime v0.1.9/go.mod h1:Fwc5htZGVVkseilnfgOVb9mKy6w1naJmn9CehxcKcls=
|
||||
github.com/remyoudompheng/bigfft v0.0.0-20230129092748-24d4a6f8daec h1:W09IVJc94icq4NjY3clb7Lk8O1qJ8BdBEF8z0ibU0rE=
|
||||
github.com/remyoudompheng/bigfft v0.0.0-20230129092748-24d4a6f8daec/go.mod h1:qqbHyh8v60DhA7CoWK5oRCqLrMHRGoxYCSS9EjAz6Eo=
|
||||
golang.org/x/exp v0.0.0-20250620022241-b7579e27df2b h1:M2rDM6z3Fhozi9O7NWsxAkg/yqS/lQJ6PmkyIV3YP+o=
|
||||
golang.org/x/exp v0.0.0-20250620022241-b7579e27df2b/go.mod h1:3//PLf8L/X+8b4vuAfHzxeRUl04Adcb341+IGKfnqS8=
|
||||
golang.org/x/mod v0.25.0 h1:n7a+ZbQKQA/Ysbyb0/6IbB1H/X41mKgbhfv7AfG/44w=
|
||||
golang.org/x/mod v0.25.0/go.mod h1:IXM97Txy2VM4PJ3gI61r1YEk/gAj6zAHN3AdZt6S9Ww=
|
||||
golang.org/x/sync v0.15.0 h1:KWH3jNZsfyT6xfAfKiz6MRNmd46ByHDYaZ7KSkCtdW8=
|
||||
golang.org/x/sync v0.15.0/go.mod h1:1dzgHSNfp02xaA81J2MS99Qcpr2w7fw1gpm99rleRqA=
|
||||
golang.org/x/sys v0.6.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
|
||||
golang.org/x/sys v0.34.0 h1:H5Y5sJ2L2JRdyv7ROF1he/lPdvFsd0mJHFw2ThKHxLA=
|
||||
golang.org/x/sys v0.34.0/go.mod h1:BJP2sWEmIv4KK5OTEluFJCKSidICx8ciO85XgH3Ak8k=
|
||||
golang.org/x/tools v0.34.0 h1:qIpSLOxeCYGg9TrcJokLBG4KFA6d795g0xkBkiESGlo=
|
||||
golang.org/x/tools v0.34.0/go.mod h1:pAP9OwEaY1CAW3HOmg3hLZC5Z0CCmzjAF2UQMSqNARg=
|
||||
modernc.org/cc/v4 v4.26.2 h1:991HMkLjJzYBIfha6ECZdjrIYz2/1ayr+FL8GN+CNzM=
|
||||
modernc.org/cc/v4 v4.26.2/go.mod h1:uVtb5OGqUKpoLWhqwNQo/8LwvoiEBLvZXIQ/SmO6mL0=
|
||||
modernc.org/ccgo/v4 v4.28.0 h1:rjznn6WWehKq7dG4JtLRKxb52Ecv8OUGah8+Z/SfpNU=
|
||||
modernc.org/ccgo/v4 v4.28.0/go.mod h1:JygV3+9AV6SmPhDasu4JgquwU81XAKLd3OKTUDNOiKE=
|
||||
modernc.org/fileutil v1.3.8 h1:qtzNm7ED75pd1C7WgAGcK4edm4fvhtBsEiI/0NQ54YM=
|
||||
modernc.org/fileutil v1.3.8/go.mod h1:HxmghZSZVAz/LXcMNwZPA/DRrQZEVP9VX0V4LQGQFOc=
|
||||
modernc.org/gc/v2 v2.6.5 h1:nyqdV8q46KvTpZlsw66kWqwXRHdjIlJOhG6kxiV/9xI=
|
||||
modernc.org/gc/v2 v2.6.5/go.mod h1:YgIahr1ypgfe7chRuJi2gD7DBQiKSLMPgBQe9oIiito=
|
||||
modernc.org/goabi0 v0.2.0 h1:HvEowk7LxcPd0eq6mVOAEMai46V+i7Jrj13t4AzuNks=
|
||||
modernc.org/goabi0 v0.2.0/go.mod h1:CEFRnnJhKvWT1c1JTI3Avm+tgOWbkOu5oPA8eH8LnMI=
|
||||
modernc.org/libc v1.66.3 h1:cfCbjTUcdsKyyZZfEUKfoHcP3S0Wkvz3jgSzByEWVCQ=
|
||||
modernc.org/libc v1.66.3/go.mod h1:XD9zO8kt59cANKvHPXpx7yS2ELPheAey0vjIuZOhOU8=
|
||||
modernc.org/mathutil v1.7.1 h1:GCZVGXdaN8gTqB1Mf/usp1Y/hSqgI2vAGGP4jZMCxOU=
|
||||
modernc.org/mathutil v1.7.1/go.mod h1:4p5IwJITfppl0G4sUEDtCr4DthTaT47/N3aT6MhfgJg=
|
||||
modernc.org/memory v1.11.0 h1:o4QC8aMQzmcwCK3t3Ux/ZHmwFPzE6hf2Y5LbkRs+hbI=
|
||||
modernc.org/memory v1.11.0/go.mod h1:/JP4VbVC+K5sU2wZi9bHoq2MAkCnrt2r98UGeSK7Mjw=
|
||||
modernc.org/opt v0.1.4 h1:2kNGMRiUjrp4LcaPuLY2PzUfqM/w9N23quVwhKt5Qm8=
|
||||
modernc.org/opt v0.1.4/go.mod h1:03fq9lsNfvkYSfxrfUhZCWPk1lm4cq4N+Bh//bEtgns=
|
||||
modernc.org/sortutil v1.2.1 h1:+xyoGf15mM3NMlPDnFqrteY07klSFxLElE2PVuWIJ7w=
|
||||
modernc.org/sortutil v1.2.1/go.mod h1:7ZI3a3REbai7gzCLcotuw9AC4VZVpYMjDzETGsSMqJE=
|
||||
modernc.org/sqlite v1.38.2 h1:Aclu7+tgjgcQVShZqim41Bbw9Cho0y/7WzYptXqkEek=
|
||||
modernc.org/sqlite v1.38.2/go.mod h1:cPTJYSlgg3Sfg046yBShXENNtPrWrDX8bsbAQBzgQ5E=
|
||||
modernc.org/strutil v1.2.1 h1:UneZBkQA+DX2Rp35KcM69cSsNES9ly8mQWD71HKlOA0=
|
||||
modernc.org/strutil v1.2.1/go.mod h1:EHkiggD70koQxjVdSBM3JKM7k6L0FbGE5eymy9i3B9A=
|
||||
modernc.org/token v1.1.0 h1:Xl7Ap9dKaEs5kLoOQeQmPWevfnk/DM5qcLcYlA8ys6Y=
|
||||
modernc.org/token v1.1.0/go.mod h1:UGzOrNV1mAFSEB63lOFHIpNRUVMvYTc6yu1SMY/XTDM=
|
||||
@@ -0,0 +1,41 @@
|
||||
package app
|
||||
|
||||
import (
|
||||
"crypto/aes"
|
||||
"crypto/cipher"
|
||||
"crypto/rand"
|
||||
"encoding/base64"
|
||||
"fmt"
|
||||
"io"
|
||||
)
|
||||
|
||||
type TokenCipher struct{ aead cipher.AEAD }
|
||||
|
||||
func NewTokenCipher(key []byte) (TokenCipher, error) {
|
||||
block, err := aes.NewCipher(key)
|
||||
if err != nil {
|
||||
return TokenCipher{}, err
|
||||
}
|
||||
aead, err := cipher.NewGCM(block)
|
||||
return TokenCipher{aead: aead}, err
|
||||
}
|
||||
func (c TokenCipher) Encrypt(value string) ([]byte, error) {
|
||||
nonce := make([]byte, c.aead.NonceSize())
|
||||
if _, err := io.ReadFull(rand.Reader, nonce); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return c.aead.Seal(nonce, nonce, []byte(value), nil), nil
|
||||
}
|
||||
func (c TokenCipher) Decrypt(value []byte) (string, error) {
|
||||
if len(value) < c.aead.NonceSize() {
|
||||
return "", fmt.Errorf("invalid encrypted token")
|
||||
}
|
||||
nonce, ciphertext := value[:c.aead.NonceSize()], value[c.aead.NonceSize():]
|
||||
raw, err := c.aead.Open(nil, nonce, ciphertext, nil)
|
||||
return string(raw), err
|
||||
}
|
||||
func RandomID(prefix string) string {
|
||||
raw := make([]byte, 18)
|
||||
_, _ = rand.Read(raw)
|
||||
return prefix + base64.RawURLEncoding.EncodeToString(raw)
|
||||
}
|
||||
@@ -0,0 +1,25 @@
|
||||
package app
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestTokenCipherRoundTripAndRandomNonce(t *testing.T) {
|
||||
cipher, err := NewTokenCipher(bytes.Repeat([]byte{7}, 32))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
one, err := cipher.Encrypt("access-token")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
two, _ := cipher.Encrypt("access-token")
|
||||
if bytes.Equal(one, two) {
|
||||
t.Fatal("ciphertext reused a nonce")
|
||||
}
|
||||
plain, err := cipher.Decrypt(one)
|
||||
if err != nil || plain != "access-token" {
|
||||
t.Fatalf("round trip = %q, %v", plain, err)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,132 @@
|
||||
package config
|
||||
|
||||
import (
|
||||
"crypto/rand"
|
||||
"encoding/base64"
|
||||
"errors"
|
||||
"fmt"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strconv"
|
||||
"strings"
|
||||
"time"
|
||||
)
|
||||
|
||||
type Config struct {
|
||||
Addr string
|
||||
DataDir string
|
||||
PublicURL string
|
||||
StalwartURL string
|
||||
StalwartBootstrapURL string
|
||||
StalwartTLSInsecure bool
|
||||
StalwartRecoveryAdmin string
|
||||
SMTPAddress string
|
||||
SMTPTLSServerName string
|
||||
SMTPUsername string
|
||||
SMTPPassword string
|
||||
SessionKey []byte
|
||||
InternalWebhookSecret string
|
||||
BootstrapToken string
|
||||
MessageRetention time.Duration
|
||||
WebhookRetention time.Duration
|
||||
AuditRetention time.Duration
|
||||
MaxMessageBytes int64
|
||||
MaxRecipients int
|
||||
RateLimitPerMinute int
|
||||
}
|
||||
|
||||
func Load() (Config, error) {
|
||||
dataDir := value("MEOVV_DATA_DIR", "/var/lib/meovv-mail")
|
||||
cfg := Config{
|
||||
Addr: value("MEOVV_ADDR", ":8080"),
|
||||
DataDir: dataDir,
|
||||
PublicURL: strings.TrimRight(value("MEOVV_PUBLIC_URL", "http://localhost:8080"), "/"),
|
||||
StalwartURL: strings.TrimRight(value("STALWART_URL", "http://stalwart:8080"), "/"),
|
||||
StalwartBootstrapURL: strings.TrimRight(value("STALWART_BOOTSTRAP_URL", "http://stalwart:8080"), "/"),
|
||||
StalwartTLSInsecure: strings.EqualFold(value("STALWART_TLS_INSECURE", "false"), "true"),
|
||||
StalwartRecoveryAdmin: secret("STALWART_RECOVERY_ADMIN", "STALWART_RECOVERY_ADMIN_FILE"),
|
||||
SMTPAddress: value("STALWART_SMTP_ADDRESS", "stalwart:587"),
|
||||
SMTPTLSServerName: value("STALWART_TLS_SERVER_NAME", ""),
|
||||
SMTPUsername: os.Getenv("STALWART_SMTP_USERNAME"),
|
||||
SMTPPassword: secret("STALWART_SMTP_PASSWORD", "STALWART_SMTP_PASSWORD_FILE"),
|
||||
InternalWebhookSecret: secret("MEOVV_INTERNAL_WEBHOOK_SECRET", "MEOVV_INTERNAL_WEBHOOK_SECRET_FILE"),
|
||||
BootstrapToken: secret("MEOVV_BOOTSTRAP_TOKEN", "MEOVV_BOOTSTRAP_TOKEN_FILE"),
|
||||
MessageRetention: duration("MEOVV_MESSAGE_RETENTION", 30*24*time.Hour),
|
||||
WebhookRetention: duration("MEOVV_WEBHOOK_RETENTION", 7*24*time.Hour),
|
||||
AuditRetention: duration("MEOVV_AUDIT_RETENTION", 180*24*time.Hour),
|
||||
MaxMessageBytes: int64Value("MEOVV_MAX_MESSAGE_BYTES", 25*1024*1024),
|
||||
MaxRecipients: intValue("MEOVV_MAX_RECIPIENTS", 100),
|
||||
RateLimitPerMinute: intValue("MEOVV_RATE_LIMIT_PER_MINUTE", 60),
|
||||
}
|
||||
|
||||
sessionSecret := secret("MEOVV_SESSION_KEY", "MEOVV_SESSION_KEY_FILE")
|
||||
if sessionSecret == "" {
|
||||
if err := os.MkdirAll(dataDir, 0o700); err != nil {
|
||||
return Config{}, fmt.Errorf("create data directory: %w", err)
|
||||
}
|
||||
path := filepath.Join(dataDir, "session.key")
|
||||
contents, err := os.ReadFile(path)
|
||||
if errors.Is(err, os.ErrNotExist) {
|
||||
key := make([]byte, 32)
|
||||
if _, err = rand.Read(key); err != nil {
|
||||
return Config{}, fmt.Errorf("generate session key: %w", err)
|
||||
}
|
||||
sessionSecret = base64.RawURLEncoding.EncodeToString(key)
|
||||
if err = os.WriteFile(path, []byte(sessionSecret+"\n"), 0o600); err != nil {
|
||||
return Config{}, fmt.Errorf("write session key: %w", err)
|
||||
}
|
||||
} else if err != nil {
|
||||
return Config{}, fmt.Errorf("read session key: %w", err)
|
||||
} else {
|
||||
sessionSecret = strings.TrimSpace(string(contents))
|
||||
}
|
||||
}
|
||||
key, err := base64.RawURLEncoding.DecodeString(sessionSecret)
|
||||
if err != nil || len(key) != 32 {
|
||||
return Config{}, errors.New("MEOVV_SESSION_KEY must be a base64url encoded 32-byte key")
|
||||
}
|
||||
cfg.SessionKey = key
|
||||
return cfg, nil
|
||||
}
|
||||
|
||||
func value(name, fallback string) string {
|
||||
if v := strings.TrimSpace(os.Getenv(name)); v != "" {
|
||||
return v
|
||||
}
|
||||
return fallback
|
||||
}
|
||||
|
||||
func secret(valueName, fileName string) string {
|
||||
if v := strings.TrimSpace(os.Getenv(valueName)); v != "" {
|
||||
return v
|
||||
}
|
||||
if path := strings.TrimSpace(os.Getenv(fileName)); path != "" {
|
||||
if contents, err := os.ReadFile(path); err == nil {
|
||||
return strings.TrimSpace(string(contents))
|
||||
}
|
||||
}
|
||||
return ""
|
||||
}
|
||||
|
||||
func duration(name string, fallback time.Duration) time.Duration {
|
||||
if v := strings.TrimSpace(os.Getenv(name)); v != "" {
|
||||
if parsed, err := time.ParseDuration(v); err == nil {
|
||||
return parsed
|
||||
}
|
||||
}
|
||||
return fallback
|
||||
}
|
||||
|
||||
func intValue(name string, fallback int) int {
|
||||
if v, err := strconv.Atoi(strings.TrimSpace(os.Getenv(name))); err == nil && v > 0 {
|
||||
return v
|
||||
}
|
||||
return fallback
|
||||
}
|
||||
|
||||
func int64Value(name string, fallback int64) int64 {
|
||||
if v, err := strconv.ParseInt(strings.TrimSpace(os.Getenv(name)), 10, 64); err == nil && v > 0 {
|
||||
return v
|
||||
}
|
||||
return fallback
|
||||
}
|
||||
@@ -0,0 +1,886 @@
|
||||
package httpapi
|
||||
|
||||
import (
|
||||
"context"
|
||||
"crypto/hmac"
|
||||
"crypto/sha256"
|
||||
"encoding/base64"
|
||||
"encoding/hex"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"log/slog"
|
||||
"net/http"
|
||||
"net/mail"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strconv"
|
||||
"strings"
|
||||
"sync"
|
||||
"sync/atomic"
|
||||
"time"
|
||||
|
||||
"github.com/meovv-mail/meovv-mail/internal/app"
|
||||
"github.com/meovv-mail/meovv-mail/internal/config"
|
||||
"github.com/meovv-mail/meovv-mail/internal/mailer"
|
||||
"github.com/meovv-mail/meovv-mail/internal/stalwart"
|
||||
"github.com/meovv-mail/meovv-mail/internal/store"
|
||||
"github.com/meovv-mail/meovv-mail/internal/webhook"
|
||||
)
|
||||
|
||||
type Server struct {
|
||||
Config config.Config
|
||||
Store *store.Store
|
||||
Mailer mailer.Sender
|
||||
Stalwart *stalwart.Client
|
||||
Cipher app.TokenCipher
|
||||
Logger *slog.Logger
|
||||
StaticDir string
|
||||
started time.Time
|
||||
accepted atomic.Uint64
|
||||
failed atomic.Uint64
|
||||
limiter *rateLimiter
|
||||
}
|
||||
|
||||
func New(cfg config.Config, st *store.Store, sender mailer.Sender, client *stalwart.Client, cipher app.TokenCipher, logger *slog.Logger, staticDir string) *Server {
|
||||
return &Server{Config: cfg, Store: st, Mailer: sender, Stalwart: client, Cipher: cipher, Logger: logger, StaticDir: staticDir, started: time.Now(), limiter: newRateLimiter()}
|
||||
}
|
||||
|
||||
func (s *Server) Handler() http.Handler {
|
||||
mux := http.NewServeMux()
|
||||
mux.HandleFunc("GET /health/live", s.live)
|
||||
mux.HandleFunc("GET /health/ready", s.ready)
|
||||
mux.HandleFunc("GET /metrics", s.metrics)
|
||||
mux.HandleFunc("GET /api/setup/status", s.setupStatus)
|
||||
mux.HandleFunc("POST /api/setup/complete", s.setupComplete)
|
||||
mux.HandleFunc("POST /api/session/exchange", s.sessionExchange)
|
||||
mux.HandleFunc("GET /api/session", s.sessionStatus)
|
||||
mux.HandleFunc("POST /api/session/logout", s.logout)
|
||||
mux.HandleFunc("POST /api/mail/jmap", s.jmap)
|
||||
mux.HandleFunc("GET /api/mail/session", s.jmapSession)
|
||||
mux.HandleFunc("GET /api/mail/events", s.jmapEvents)
|
||||
mux.HandleFunc("GET /api/admin/overview", s.adminOverview)
|
||||
mux.HandleFunc("POST /api/admin/stalwart", s.adminStalwart)
|
||||
mux.HandleFunc("GET /api/admin/api-keys", s.listAPIKeys)
|
||||
mux.HandleFunc("POST /api/admin/api-keys", s.createAPIKey)
|
||||
mux.HandleFunc("DELETE /api/admin/api-keys/{id}", s.revokeAPIKey)
|
||||
mux.HandleFunc("GET /api/admin/webhooks", s.listWebhooks)
|
||||
mux.HandleFunc("POST /api/admin/webhooks", s.createWebhook)
|
||||
mux.HandleFunc("DELETE /api/admin/webhooks/{id}", s.deleteWebhook)
|
||||
mux.HandleFunc("POST /api/internal/stalwart/events", s.internalEvents)
|
||||
mux.HandleFunc("POST /api/v1/messages", s.authAPI("messages.send", s.sendMessage))
|
||||
mux.HandleFunc("GET /api/v1/messages", s.authAPI("messages.status", s.listMessages))
|
||||
mux.HandleFunc("GET /api/v1/messages/{id}", s.authAPI("messages.status", s.getMessage))
|
||||
mux.Handle("/", s.frontend())
|
||||
return s.security(s.csrf(mux))
|
||||
}
|
||||
|
||||
func (s *Server) csrf(next http.Handler) http.Handler {
|
||||
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
if r.Method == http.MethodGet || r.Method == http.MethodHead || r.Method == http.MethodOptions || strings.HasPrefix(r.URL.Path, "/api/v1/") || r.URL.Path == "/api/internal/stalwart/events" {
|
||||
next.ServeHTTP(w, r)
|
||||
return
|
||||
}
|
||||
origin := strings.TrimRight(r.Header.Get("Origin"), "/")
|
||||
if origin != "" && origin != s.Config.PublicURL {
|
||||
problem(w, http.StatusForbidden, "cross_site_request", "Cross-site state changes are not allowed.")
|
||||
return
|
||||
}
|
||||
if strings.EqualFold(r.Header.Get("Sec-Fetch-Site"), "cross-site") {
|
||||
problem(w, http.StatusForbidden, "cross_site_request", "Cross-site state changes are not allowed.")
|
||||
return
|
||||
}
|
||||
next.ServeHTTP(w, r)
|
||||
})
|
||||
}
|
||||
|
||||
func (s *Server) security(next http.Handler) http.Handler {
|
||||
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
w.Header().Set("X-Content-Type-Options", "nosniff")
|
||||
w.Header().Set("X-Frame-Options", "DENY")
|
||||
w.Header().Set("Referrer-Policy", "same-origin")
|
||||
w.Header().Set("Permissions-Policy", "camera=(), microphone=(), geolocation=()")
|
||||
w.Header().Set("Content-Security-Policy", "default-src 'self'; img-src 'self' data: blob:; style-src 'self' 'unsafe-inline'; script-src 'self'; connect-src 'self' wss:; frame-src 'none'; object-src 'none'; base-uri 'self'; form-action 'self'")
|
||||
next.ServeHTTP(w, r)
|
||||
})
|
||||
}
|
||||
|
||||
func (s *Server) live(w http.ResponseWriter, r *http.Request) {
|
||||
writeJSON(w, 200, map[string]any{"status": "ok", "uptime_seconds": int(time.Since(s.started).Seconds())})
|
||||
}
|
||||
func (s *Server) ready(w http.ResponseWriter, r *http.Request) {
|
||||
ctx, cancel := context.WithTimeout(r.Context(), 2*time.Second)
|
||||
defer cancel()
|
||||
checks := map[string]string{"database": "ok", "stalwart": "ok"}
|
||||
status := 200
|
||||
if err := s.Store.Ping(ctx); err != nil {
|
||||
checks["database"] = err.Error()
|
||||
status = 503
|
||||
}
|
||||
if err := s.Stalwart.Ready(ctx); err != nil {
|
||||
checks["stalwart"] = err.Error()
|
||||
status = 503
|
||||
}
|
||||
writeJSON(w, status, map[string]any{"status": map[bool]string{true: "ok", false: "degraded"}[status == 200], "checks": checks})
|
||||
}
|
||||
func (s *Server) metrics(w http.ResponseWriter, r *http.Request) {
|
||||
w.Header().Set("Content-Type", "text/plain; version=0.0.4")
|
||||
fmt.Fprintf(w, "# HELP meovv_messages_accepted_total Messages accepted by the REST API.\n# TYPE meovv_messages_accepted_total counter\nmeovv_messages_accepted_total %d\n# HELP meovv_messages_failed_total Message submissions that failed.\n# TYPE meovv_messages_failed_total counter\nmeovv_messages_failed_total %d\n", s.accepted.Load(), s.failed.Load())
|
||||
}
|
||||
|
||||
type setupRequest struct {
|
||||
Hostname string `json:"hostname"`
|
||||
PrimaryDomain string `json:"primary_domain"`
|
||||
AdminEmail string `json:"admin_email"`
|
||||
Organization string `json:"organization"`
|
||||
Accent string `json:"accent"`
|
||||
DeliveryMode string `json:"delivery_mode"`
|
||||
RelayHost string `json:"relay_host,omitempty"`
|
||||
}
|
||||
|
||||
func (s *Server) setupStatus(w http.ResponseWriter, r *http.Request) {
|
||||
var setup setupRequest
|
||||
err := s.Store.GetSetting(r.Context(), "installation", &setup)
|
||||
writeJSON(w, 200, map[string]any{"configured": err == nil, "installation": func() any {
|
||||
if err == nil {
|
||||
return setup
|
||||
}
|
||||
return nil
|
||||
}()})
|
||||
}
|
||||
func (s *Server) setupComplete(w http.ResponseWriter, r *http.Request) {
|
||||
if s.Config.BootstrapToken == "" || !hmac.Equal([]byte(r.Header.Get("X-Bootstrap-Token")), []byte(s.Config.BootstrapToken)) {
|
||||
problem(w, 401, "invalid_bootstrap_token", "The one-time bootstrap token is missing or invalid.")
|
||||
return
|
||||
}
|
||||
var in setupRequest
|
||||
if !decodeJSON(w, r, &in, 64<<10) {
|
||||
return
|
||||
}
|
||||
if !validHostname(in.Hostname) || !validDomain(in.PrimaryDomain) {
|
||||
problem(w, 422, "invalid_installation", "Hostname and primary domain must be valid DNS names.")
|
||||
return
|
||||
}
|
||||
if address, err := mail.ParseAddress(in.AdminEmail); err != nil || !strings.HasSuffix(strings.ToLower(address.Address), "@"+strings.ToLower(in.PrimaryDomain)) {
|
||||
problem(w, 422, "invalid_admin", "Administrator email must belong to the primary domain.")
|
||||
return
|
||||
}
|
||||
if in.DeliveryMode != "direct" && in.DeliveryMode != "relay" {
|
||||
problem(w, 422, "invalid_delivery_mode", "Delivery mode must be direct or relay.")
|
||||
return
|
||||
}
|
||||
bootstrapResult, err := s.Stalwart.Bootstrap(r.Context(), s.Config.StalwartBootstrapURL, s.Config.StalwartRecoveryAdmin, in.Hostname, in.PrimaryDomain)
|
||||
if err != nil {
|
||||
problem(w, 502, "mail_core_setup_failed", err.Error())
|
||||
return
|
||||
}
|
||||
if err := s.Store.SetSetting(r.Context(), "installation", in); err != nil {
|
||||
problem(w, 500, "storage_error", "Could not save the installation.")
|
||||
return
|
||||
}
|
||||
_ = s.Store.Audit(r.Context(), app.RandomID("aud_"), in.AdminEmail, "installation.completed", in.Hostname, in)
|
||||
writeJSON(w, 201, map[string]any{"configured": true, "next": "Save the one-time administrator result, restart Stalwart, verify permanent administrator sign-in, then run mailctl harden.", "mail_core_result": json.RawMessage(bootstrapResult), "dns_checks": []string{"A/AAAA", "MX", "PTR", "SPF", "DKIM", "DMARC", "TLS"}})
|
||||
}
|
||||
|
||||
func (s *Server) sessionExchange(w http.ResponseWriter, r *http.Request) {
|
||||
var in struct {
|
||||
ClientCode string `json:"client_code"`
|
||||
CodeVerifier string `json:"code_verifier"`
|
||||
Account string `json:"account"`
|
||||
ClientID string `json:"client_id"`
|
||||
RedirectURI string `json:"redirect_uri"`
|
||||
}
|
||||
if !decodeJSON(w, r, &in, 16<<10) {
|
||||
return
|
||||
}
|
||||
if in.ClientID == "" {
|
||||
in.ClientID = "meovv-web"
|
||||
}
|
||||
if in.RedirectURI == "" {
|
||||
in.RedirectURI = s.Config.PublicURL + "/auth/callback"
|
||||
}
|
||||
tokens, err := s.Stalwart.Exchange(r.Context(), in.ClientID, in.ClientCode, in.CodeVerifier, in.RedirectURI)
|
||||
if err != nil {
|
||||
problem(w, 401, "exchange_failed", err.Error())
|
||||
return
|
||||
}
|
||||
access, _ := s.Cipher.Encrypt(tokens.AccessToken)
|
||||
refresh, _ := s.Cipher.Encrypt(tokens.RefreshToken)
|
||||
now := time.Now()
|
||||
id := app.RandomID("ses_")
|
||||
expiry := now.Add(time.Duration(tokens.ExpiresIn) * time.Second)
|
||||
if expiry.Equal(now) {
|
||||
expiry = now.Add(time.Hour)
|
||||
}
|
||||
sessionExpiry := now.Add(30 * 24 * time.Hour)
|
||||
if err = s.Store.CreateSession(r.Context(), store.Session{ID: id, Account: in.Account, AccessToken: access, RefreshToken: refresh, ExpiresAt: expiry, SessionExpiresAt: sessionExpiry, CreatedAt: now, LastSeenAt: now}); err != nil {
|
||||
problem(w, 500, "session_failed", "Could not establish the session.")
|
||||
return
|
||||
}
|
||||
http.SetCookie(w, &http.Cookie{Name: "meovv_session", Value: id, Path: "/", HttpOnly: true, Secure: strings.HasPrefix(s.Config.PublicURL, "https://"), SameSite: http.SameSiteLaxMode, MaxAge: int(time.Until(sessionExpiry).Seconds())})
|
||||
writeJSON(w, 200, map[string]any{"authenticated": true, "account": in.Account})
|
||||
}
|
||||
func (s *Server) sessionStatus(w http.ResponseWriter, r *http.Request) {
|
||||
session, _, err := s.session(r)
|
||||
if err != nil {
|
||||
problem(w, 401, "authentication_required", "Sign in to continue.")
|
||||
return
|
||||
}
|
||||
writeJSON(w, 200, map[string]any{"authenticated": true, "account": session.Account})
|
||||
}
|
||||
func (s *Server) logout(w http.ResponseWriter, r *http.Request) {
|
||||
if cookie, err := r.Cookie("meovv_session"); err == nil {
|
||||
_ = s.Store.DeleteSession(r.Context(), cookie.Value)
|
||||
}
|
||||
http.SetCookie(w, &http.Cookie{Name: "meovv_session", Value: "", Path: "/", HttpOnly: true, Secure: strings.HasPrefix(s.Config.PublicURL, "https://"), SameSite: http.SameSiteLaxMode, MaxAge: -1})
|
||||
w.WriteHeader(204)
|
||||
}
|
||||
func (s *Server) session(r *http.Request) (store.Session, string, error) {
|
||||
cookie, err := r.Cookie("meovv_session")
|
||||
if err != nil {
|
||||
return store.Session{}, "", store.ErrNotFound
|
||||
}
|
||||
session, err := s.Store.GetSession(r.Context(), cookie.Value)
|
||||
if err != nil {
|
||||
return session, "", err
|
||||
}
|
||||
if time.Until(session.ExpiresAt) < time.Minute {
|
||||
refreshToken, decryptErr := s.Cipher.Decrypt(session.RefreshToken)
|
||||
if decryptErr != nil {
|
||||
return session, "", decryptErr
|
||||
}
|
||||
tokens, refreshErr := s.Stalwart.Refresh(r.Context(), "meovv-web", refreshToken)
|
||||
if refreshErr != nil {
|
||||
_ = s.Store.DeleteSession(r.Context(), session.ID)
|
||||
return session, "", refreshErr
|
||||
}
|
||||
access, encryptErr := s.Cipher.Encrypt(tokens.AccessToken)
|
||||
if encryptErr != nil {
|
||||
return session, "", encryptErr
|
||||
}
|
||||
if tokens.RefreshToken == "" {
|
||||
tokens.RefreshToken = refreshToken
|
||||
}
|
||||
refresh, encryptErr := s.Cipher.Encrypt(tokens.RefreshToken)
|
||||
if encryptErr != nil {
|
||||
return session, "", encryptErr
|
||||
}
|
||||
expires := time.Now().Add(time.Duration(tokens.ExpiresIn) * time.Second)
|
||||
if tokens.ExpiresIn <= 0 {
|
||||
expires = time.Now().Add(time.Hour)
|
||||
}
|
||||
if err = s.Store.UpdateSessionTokens(r.Context(), session.ID, access, refresh, expires); err != nil {
|
||||
return session, "", err
|
||||
}
|
||||
session.AccessToken = access
|
||||
session.RefreshToken = refresh
|
||||
session.ExpiresAt = expires
|
||||
}
|
||||
token, err := s.Cipher.Decrypt(session.AccessToken)
|
||||
return session, token, err
|
||||
}
|
||||
func (s *Server) jmap(w http.ResponseWriter, r *http.Request) {
|
||||
_, token, err := s.session(r)
|
||||
if err != nil {
|
||||
problem(w, 401, "authentication_required", "Sign in to access this mailbox.")
|
||||
return
|
||||
}
|
||||
raw, err := io.ReadAll(io.LimitReader(r.Body, 32<<20))
|
||||
if err != nil {
|
||||
problem(w, 400, "invalid_body", err.Error())
|
||||
return
|
||||
}
|
||||
status, headers, response, err := s.Stalwart.ProxyJMAP(r.Context(), token, raw)
|
||||
if err != nil {
|
||||
problem(w, 502, "mail_service_error", err.Error())
|
||||
return
|
||||
}
|
||||
if content := headers.Get("Content-Type"); content != "" {
|
||||
w.Header().Set("Content-Type", content)
|
||||
}
|
||||
w.WriteHeader(status)
|
||||
_, _ = w.Write(response)
|
||||
}
|
||||
func (s *Server) jmapSession(w http.ResponseWriter, r *http.Request) {
|
||||
_, token, err := s.session(r)
|
||||
if err != nil {
|
||||
problem(w, 401, "authentication_required", "Sign in to access this mailbox.")
|
||||
return
|
||||
}
|
||||
status, headers, response, err := s.Stalwart.JMAPSession(r.Context(), token)
|
||||
if err != nil {
|
||||
problem(w, 502, "mail_service_error", err.Error())
|
||||
return
|
||||
}
|
||||
if content := headers.Get("Content-Type"); content != "" {
|
||||
w.Header().Set("Content-Type", content)
|
||||
}
|
||||
w.WriteHeader(status)
|
||||
_, _ = w.Write(response)
|
||||
}
|
||||
func (s *Server) jmapEvents(w http.ResponseWriter, r *http.Request) {
|
||||
_, token, err := s.session(r)
|
||||
if err != nil {
|
||||
problem(w, 401, "authentication_required", "Sign in to access this mailbox.")
|
||||
return
|
||||
}
|
||||
response, err := s.Stalwart.EventStream(r.Context(), token)
|
||||
if err != nil {
|
||||
problem(w, 502, "mail_service_error", err.Error())
|
||||
return
|
||||
}
|
||||
defer response.Body.Close()
|
||||
if response.StatusCode/100 != 2 {
|
||||
body, _ := io.ReadAll(io.LimitReader(response.Body, 4096))
|
||||
problem(w, 502, "mail_service_error", strings.TrimSpace(string(body)))
|
||||
return
|
||||
}
|
||||
w.Header().Set("Content-Type", "text/event-stream")
|
||||
w.Header().Set("Cache-Control", "no-cache, no-transform")
|
||||
w.Header().Set("X-Accel-Buffering", "no")
|
||||
w.WriteHeader(200)
|
||||
flusher, _ := w.(http.Flusher)
|
||||
buffer := make([]byte, 16<<10)
|
||||
for {
|
||||
n, readErr := response.Body.Read(buffer)
|
||||
if n > 0 {
|
||||
if _, err = w.Write(buffer[:n]); err != nil {
|
||||
return
|
||||
}
|
||||
if flusher != nil {
|
||||
flusher.Flush()
|
||||
}
|
||||
}
|
||||
if readErr != nil {
|
||||
return
|
||||
}
|
||||
}
|
||||
}
|
||||
func (s *Server) adminOverview(w http.ResponseWriter, r *http.Request) {
|
||||
session, _, ok := s.requireAdmin(w, r)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
stats, err := s.Store.Stats(r.Context())
|
||||
if err != nil {
|
||||
problem(w, 500, "storage_error", err.Error())
|
||||
return
|
||||
}
|
||||
stats["account"] = session.Account
|
||||
stats["version"] = "0.1.0"
|
||||
stats["stalwart_version"] = "0.16.17"
|
||||
writeJSON(w, 200, stats)
|
||||
}
|
||||
|
||||
func (s *Server) requireAdmin(w http.ResponseWriter, r *http.Request) (store.Session, string, bool) {
|
||||
session, token, err := s.session(r)
|
||||
if err != nil {
|
||||
if os.Getenv("MEOVV_DEMO_MODE") == "1" {
|
||||
return store.Session{Account: "demo-admin"}, "", true
|
||||
}
|
||||
problem(w, 401, "authentication_required", "Administrator sign-in is required.")
|
||||
return store.Session{}, "", false
|
||||
}
|
||||
var installation setupRequest
|
||||
if err = s.Store.GetSetting(r.Context(), "installation", &installation); err == nil && !strings.EqualFold(session.Account, installation.AdminEmail) && !strings.EqualFold(session.Account, "admin") {
|
||||
problem(w, 403, "administrator_required", "This account is not the installation administrator.")
|
||||
return store.Session{}, "", false
|
||||
}
|
||||
return session, token, true
|
||||
}
|
||||
|
||||
func (s *Server) adminStalwart(w http.ResponseWriter, r *http.Request) {
|
||||
_, token, ok := s.requireAdmin(w, r)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
raw, err := io.ReadAll(io.LimitReader(r.Body, 4<<20))
|
||||
if err != nil {
|
||||
problem(w, 400, "invalid_body", err.Error())
|
||||
return
|
||||
}
|
||||
status, headers, response, err := s.Stalwart.ProxyManagement(r.Context(), token, raw)
|
||||
if err != nil {
|
||||
problem(w, 502, "mail_service_error", err.Error())
|
||||
return
|
||||
}
|
||||
if value := headers.Get("Content-Type"); value != "" {
|
||||
w.Header().Set("Content-Type", value)
|
||||
}
|
||||
w.WriteHeader(status)
|
||||
_, _ = w.Write(response)
|
||||
}
|
||||
|
||||
func (s *Server) listAPIKeys(w http.ResponseWriter, r *http.Request) {
|
||||
if _, _, ok := s.requireAdmin(w, r); !ok {
|
||||
return
|
||||
}
|
||||
keys, err := s.Store.ListAPIKeys(r.Context())
|
||||
if err != nil {
|
||||
problem(w, 500, "storage_error", err.Error())
|
||||
return
|
||||
}
|
||||
writeJSON(w, 200, map[string]any{"data": keys})
|
||||
}
|
||||
|
||||
func (s *Server) createAPIKey(w http.ResponseWriter, r *http.Request) {
|
||||
session, _, ok := s.requireAdmin(w, r)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
var in struct {
|
||||
Name string `json:"name"`
|
||||
Scopes []string `json:"scopes"`
|
||||
AllowedSenders []string `json:"allowed_senders"`
|
||||
RateLimit int `json:"rate_limit"`
|
||||
}
|
||||
if !decodeJSON(w, r, &in, 64<<10) {
|
||||
return
|
||||
}
|
||||
if strings.TrimSpace(in.Name) == "" || !validScopes(in.Scopes) || len(in.AllowedSenders) == 0 {
|
||||
problem(w, 422, "invalid_api_key", "Name, valid scopes, and at least one approved sender are required.")
|
||||
return
|
||||
}
|
||||
for _, sender := range in.AllowedSenders {
|
||||
if !validSenderPattern(sender) {
|
||||
problem(w, 422, "invalid_sender", "Approved senders must be complete addresses or domain wildcards such as *@example.com.")
|
||||
return
|
||||
}
|
||||
}
|
||||
if in.RateLimit <= 0 {
|
||||
in.RateLimit = s.Config.RateLimitPerMinute
|
||||
}
|
||||
secret := app.RandomID("meovv_")
|
||||
key := store.APIKey{ID: app.RandomID("key_"), Name: strings.TrimSpace(in.Name), Prefix: secret[:min(14, len(secret))], Scopes: in.Scopes, AllowedSenders: in.AllowedSenders, RateLimit: in.RateLimit, CreatedAt: time.Now().UTC()}
|
||||
if err := s.Store.CreateAPIKey(r.Context(), key, secret); err != nil {
|
||||
problem(w, 500, "storage_error", err.Error())
|
||||
return
|
||||
}
|
||||
_ = s.Store.Audit(r.Context(), app.RandomID("aud_"), session.Account, "api_key.created", key.ID, map[string]any{"name": key.Name, "scopes": key.Scopes})
|
||||
writeJSON(w, 201, map[string]any{"api_key": key, "secret": secret, "warning": "This secret is shown once and cannot be recovered."})
|
||||
}
|
||||
|
||||
func (s *Server) revokeAPIKey(w http.ResponseWriter, r *http.Request) {
|
||||
session, _, ok := s.requireAdmin(w, r)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
if err := s.Store.RevokeAPIKey(r.Context(), r.PathValue("id")); err != nil {
|
||||
if errors.Is(err, store.ErrNotFound) {
|
||||
problem(w, 404, "not_found", "API key not found.")
|
||||
} else {
|
||||
problem(w, 500, "storage_error", err.Error())
|
||||
}
|
||||
return
|
||||
}
|
||||
_ = s.Store.Audit(r.Context(), app.RandomID("aud_"), session.Account, "api_key.revoked", r.PathValue("id"), nil)
|
||||
w.WriteHeader(204)
|
||||
}
|
||||
|
||||
var allowedWebhookEvents = map[string]bool{"message.queued": true, "message.delivered": true, "message.deferred": true, "message.bounced": true, "message.failed": true}
|
||||
|
||||
func (s *Server) listWebhooks(w http.ResponseWriter, r *http.Request) {
|
||||
if _, _, ok := s.requireAdmin(w, r); !ok {
|
||||
return
|
||||
}
|
||||
items, err := s.Store.ListWebhookEndpoints(r.Context())
|
||||
if err != nil {
|
||||
problem(w, 500, "storage_error", err.Error())
|
||||
return
|
||||
}
|
||||
writeJSON(w, 200, map[string]any{"data": items})
|
||||
}
|
||||
|
||||
func (s *Server) createWebhook(w http.ResponseWriter, r *http.Request) {
|
||||
session, _, ok := s.requireAdmin(w, r)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
var in struct {
|
||||
Name string `json:"name"`
|
||||
URL string `json:"url"`
|
||||
Events []string `json:"events"`
|
||||
}
|
||||
if !decodeJSON(w, r, &in, 64<<10) {
|
||||
return
|
||||
}
|
||||
if strings.TrimSpace(in.Name) == "" || len(in.Events) == 0 {
|
||||
problem(w, 422, "invalid_webhook", "Name and at least one event are required.")
|
||||
return
|
||||
}
|
||||
for _, event := range in.Events {
|
||||
if !allowedWebhookEvents[event] {
|
||||
problem(w, 422, "invalid_event", "The webhook contains an unsupported event type.")
|
||||
return
|
||||
}
|
||||
}
|
||||
ctx, cancel := context.WithTimeout(r.Context(), 3*time.Second)
|
||||
defer cancel()
|
||||
if err := webhook.ValidatePublicURL(ctx, in.URL); err != nil {
|
||||
problem(w, 422, "unsafe_webhook_url", err.Error())
|
||||
return
|
||||
}
|
||||
rawSecret := app.RandomID("whsec_")
|
||||
encryptedSecret, err := s.Cipher.Encrypt(rawSecret)
|
||||
if err != nil {
|
||||
problem(w, 500, "secret_encryption_failed", "Could not protect the webhook signing secret.")
|
||||
return
|
||||
}
|
||||
endpoint := store.WebhookEndpoint{ID: app.RandomID("wh_"), Name: strings.TrimSpace(in.Name), URL: in.URL, Secret: base64.RawStdEncoding.EncodeToString(encryptedSecret), Events: in.Events, Enabled: true, CreatedAt: time.Now().UTC()}
|
||||
if err := s.Store.CreateWebhookEndpoint(r.Context(), endpoint); err != nil {
|
||||
problem(w, 500, "storage_error", err.Error())
|
||||
return
|
||||
}
|
||||
_ = s.Store.Audit(r.Context(), app.RandomID("aud_"), session.Account, "webhook.created", endpoint.ID, map[string]any{"url": endpoint.URL, "events": endpoint.Events})
|
||||
writeJSON(w, 201, map[string]any{"webhook": endpoint, "secret": rawSecret, "warning": "This signing secret is shown once."})
|
||||
}
|
||||
|
||||
func (s *Server) deleteWebhook(w http.ResponseWriter, r *http.Request) {
|
||||
session, _, ok := s.requireAdmin(w, r)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
if err := s.Store.DeleteWebhookEndpoint(r.Context(), r.PathValue("id")); err != nil {
|
||||
if errors.Is(err, store.ErrNotFound) {
|
||||
problem(w, 404, "not_found", "Webhook endpoint not found.")
|
||||
} else {
|
||||
problem(w, 500, "storage_error", err.Error())
|
||||
}
|
||||
return
|
||||
}
|
||||
_ = s.Store.Audit(r.Context(), app.RandomID("aud_"), session.Account, "webhook.deleted", r.PathValue("id"), nil)
|
||||
w.WriteHeader(204)
|
||||
}
|
||||
|
||||
func (s *Server) sendMessage(w http.ResponseWriter, r *http.Request, key store.APIKey) {
|
||||
var in struct {
|
||||
From string `json:"from"`
|
||||
To []string `json:"to"`
|
||||
CC []string `json:"cc"`
|
||||
BCC []string `json:"bcc"`
|
||||
ReplyTo string `json:"reply_to"`
|
||||
Subject string `json:"subject"`
|
||||
Text string `json:"text"`
|
||||
HTML string `json:"html"`
|
||||
Headers map[string]string `json:"headers"`
|
||||
Attachments []struct {
|
||||
Filename string `json:"filename"`
|
||||
ContentType string `json:"content_type"`
|
||||
Content string `json:"content_base64"`
|
||||
} `json:"attachments"`
|
||||
}
|
||||
if !decodeJSON(w, r, &in, s.Config.MaxMessageBytes*2) {
|
||||
return
|
||||
}
|
||||
if in.Text == "" && in.HTML == "" {
|
||||
problem(w, 422, "body_required", "A text or HTML body is required.")
|
||||
return
|
||||
}
|
||||
if !allowedSender(key, in.From) {
|
||||
problem(w, 403, "sender_not_allowed", "The API key is not allowed to use this sender.")
|
||||
return
|
||||
}
|
||||
if len(in.To)+len(in.CC)+len(in.BCC) > s.Config.MaxRecipients {
|
||||
problem(w, 422, "too_many_recipients", fmt.Sprintf("At most %d recipients are allowed.", s.Config.MaxRecipients))
|
||||
return
|
||||
}
|
||||
id := app.RandomID("msg_")
|
||||
headers := in.Headers
|
||||
if headers == nil {
|
||||
headers = map[string]string{}
|
||||
}
|
||||
headers["X-MEOVV-Message-ID"] = id
|
||||
attachments := make([]mailer.Attachment, len(in.Attachments))
|
||||
for i, a := range in.Attachments {
|
||||
attachments[i] = mailer.Attachment{Filename: a.Filename, ContentType: a.ContentType, ContentBase64: a.Content}
|
||||
}
|
||||
raw, recipients, err := mailer.Build(mailer.Message{From: in.From, To: in.To, CC: in.CC, BCC: in.BCC, ReplyTo: in.ReplyTo, Subject: in.Subject, Text: in.Text, HTML: in.HTML, Headers: headers, Attachments: attachments}, s.Config.MaxMessageBytes)
|
||||
if err != nil {
|
||||
problem(w, 422, "invalid_message", err.Error())
|
||||
return
|
||||
}
|
||||
now := time.Now().UTC()
|
||||
message := store.Message{ID: id, APIKeyID: key.ID, Sender: strings.ToLower(in.From), Subject: in.Subject, Status: "queued", SizeBytes: int64(len(raw)), SubmittedAt: now, UpdatedAt: now}
|
||||
for _, recipient := range recipients {
|
||||
message.Recipients = append(message.Recipients, store.Recipient{Address: recipient, Status: "queued"})
|
||||
}
|
||||
digest := sha256.Sum256(raw)
|
||||
existing, err := s.Store.InsertMessage(r.Context(), message, r.Header.Get("Idempotency-Key"), hex.EncodeToString(digest[:]))
|
||||
if err != nil {
|
||||
problem(w, 409, "idempotency_conflict", err.Error())
|
||||
return
|
||||
}
|
||||
if existing != "" {
|
||||
prior, err := s.Store.GetMessage(r.Context(), existing)
|
||||
if err != nil {
|
||||
problem(w, 500, "storage_error", err.Error())
|
||||
return
|
||||
}
|
||||
writeJSON(w, 202, receipt(prior))
|
||||
return
|
||||
}
|
||||
smtpID, err := s.Mailer.Send(r.Context(), in.From, recipients, raw)
|
||||
if err != nil {
|
||||
s.failed.Add(1)
|
||||
_ = s.Store.UpdateMessageStatus(r.Context(), id, "failed", err.Error(), "")
|
||||
problem(w, 502, "submission_failed", "The mail service did not accept this message.")
|
||||
return
|
||||
}
|
||||
s.accepted.Add(1)
|
||||
_ = s.Store.UpdateMessageStatus(r.Context(), id, "processing", "", smtpID)
|
||||
eventPayload, _ := json.Marshal(map[string]any{"id": app.RandomID("evt_"), "type": "message.queued", "created_at": now, "data": map[string]any{"message_id": id, "status": "queued"}})
|
||||
_ = s.Store.EnqueueEvent(r.Context(), app.RandomID("evt_"), "message.queued", eventPayload, now)
|
||||
w.Header().Set("Location", "/api/v1/messages/"+id)
|
||||
writeJSON(w, 202, map[string]any{"id": id, "status": "queued", "submitted_at": now})
|
||||
}
|
||||
func receipt(m store.Message) map[string]any {
|
||||
return map[string]any{"id": m.ID, "status": m.Status, "submitted_at": m.SubmittedAt}
|
||||
}
|
||||
func (s *Server) getMessage(w http.ResponseWriter, r *http.Request, key store.APIKey) {
|
||||
m, err := s.Store.GetMessage(r.Context(), r.PathValue("id"))
|
||||
if errors.Is(err, store.ErrNotFound) {
|
||||
problem(w, 404, "not_found", "Message not found.")
|
||||
return
|
||||
}
|
||||
if err != nil {
|
||||
problem(w, 500, "storage_error", err.Error())
|
||||
return
|
||||
}
|
||||
if m.APIKeyID != key.ID {
|
||||
problem(w, 404, "not_found", "Message not found.")
|
||||
return
|
||||
}
|
||||
writeJSON(w, 200, m)
|
||||
}
|
||||
func (s *Server) listMessages(w http.ResponseWriter, r *http.Request, key store.APIKey) {
|
||||
q := r.URL.Query()
|
||||
filter := store.MessageFilter{Status: q.Get("status"), Sender: q.Get("sender"), Recipient: q.Get("recipient"), Cursor: q.Get("cursor"), APIKeyID: key.ID}
|
||||
filter.Limit, _ = strconv.Atoi(q.Get("limit"))
|
||||
if v := q.Get("from"); v != "" {
|
||||
if t, err := time.Parse(time.RFC3339, v); err == nil {
|
||||
filter.From = &t
|
||||
}
|
||||
}
|
||||
if v := q.Get("to"); v != "" {
|
||||
if t, err := time.Parse(time.RFC3339, v); err == nil {
|
||||
filter.To = &t
|
||||
}
|
||||
}
|
||||
items, next, err := s.Store.ListMessages(r.Context(), filter)
|
||||
if err != nil {
|
||||
problem(w, 500, "storage_error", err.Error())
|
||||
return
|
||||
}
|
||||
writeJSON(w, 200, map[string]any{"data": items, "next_cursor": next})
|
||||
}
|
||||
|
||||
func (s *Server) internalEvents(w http.ResponseWriter, r *http.Request) {
|
||||
raw, err := io.ReadAll(io.LimitReader(r.Body, 2<<20))
|
||||
if err != nil {
|
||||
problem(w, 400, "invalid_body", err.Error())
|
||||
return
|
||||
}
|
||||
if s.Config.InternalWebhookSecret == "" || !verifyInternal(s.Config.InternalWebhookSecret, r.Header.Get("X-Signature"), raw) {
|
||||
problem(w, 401, "invalid_signature", "Invalid Stalwart webhook signature.")
|
||||
return
|
||||
}
|
||||
var envelope struct {
|
||||
Events []struct {
|
||||
ID, Type, CreatedAt string
|
||||
Data map[string]any
|
||||
} `json:"events"`
|
||||
}
|
||||
if err = json.Unmarshal(raw, &envelope); err != nil {
|
||||
problem(w, 400, "invalid_event", err.Error())
|
||||
return
|
||||
}
|
||||
for _, event := range envelope.Events {
|
||||
messageID := findString(event.Data, "message_id", "messageId", "queue_id", "queueId")
|
||||
recipient := findString(event.Data, "recipient", "to")
|
||||
status, external := normalizeEvent(event.Type)
|
||||
if messageID != "" && status != "" {
|
||||
if recipient != "" {
|
||||
_ = s.Store.UpdateRecipient(r.Context(), messageID, recipient, status, findString(event.Data, "response", "reason"), time.Now())
|
||||
} else {
|
||||
_ = s.Store.UpdateMessageStatus(r.Context(), messageID, status, findString(event.Data, "reason"), "")
|
||||
}
|
||||
}
|
||||
if external != "" {
|
||||
payload, _ := json.Marshal(map[string]any{"id": event.ID, "type": external, "created_at": event.CreatedAt, "data": map[string]any{"message_id": messageID, "recipient": recipient, "status": status}})
|
||||
_ = s.Store.EnqueueEvent(r.Context(), event.ID, external, payload, time.Now())
|
||||
}
|
||||
}
|
||||
w.WriteHeader(204)
|
||||
}
|
||||
|
||||
type apiHandler func(http.ResponseWriter, *http.Request, store.APIKey)
|
||||
|
||||
func (s *Server) authAPI(scope string, next apiHandler) http.HandlerFunc {
|
||||
return func(w http.ResponseWriter, r *http.Request) {
|
||||
value := strings.TrimSpace(strings.TrimPrefix(r.Header.Get("Authorization"), "Bearer "))
|
||||
if value == "" {
|
||||
problem(w, 401, "authentication_required", "Provide a bearer API key.")
|
||||
return
|
||||
}
|
||||
key, err := s.Store.AuthenticateAPIKey(r.Context(), value)
|
||||
if err != nil {
|
||||
problem(w, 401, "invalid_api_key", "The API key is invalid or revoked.")
|
||||
return
|
||||
}
|
||||
if !hasScope(key, scope) {
|
||||
problem(w, 403, "insufficient_scope", "The API key does not have the required scope.")
|
||||
return
|
||||
}
|
||||
limit := key.RateLimit
|
||||
if limit <= 0 {
|
||||
limit = s.Config.RateLimitPerMinute
|
||||
}
|
||||
if !s.limiter.Allow(key.ID, limit) {
|
||||
w.Header().Set("Retry-After", "60")
|
||||
problem(w, 429, "rate_limited", "API key rate limit exceeded.")
|
||||
return
|
||||
}
|
||||
next(w, r, key)
|
||||
}
|
||||
}
|
||||
|
||||
func (s *Server) frontend() http.Handler {
|
||||
files := http.FileServer(http.Dir(s.StaticDir))
|
||||
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
path := filepath.Join(s.StaticDir, filepath.Clean(r.URL.Path))
|
||||
if info, err := os.Stat(path); err == nil && !info.IsDir() {
|
||||
files.ServeHTTP(w, r)
|
||||
return
|
||||
}
|
||||
http.ServeFile(w, r, filepath.Join(s.StaticDir, "index.html"))
|
||||
})
|
||||
}
|
||||
|
||||
func decodeJSON(w http.ResponseWriter, r *http.Request, dst any, limit int64) bool {
|
||||
r.Body = http.MaxBytesReader(w, r.Body, limit)
|
||||
decoder := json.NewDecoder(r.Body)
|
||||
decoder.DisallowUnknownFields()
|
||||
if err := decoder.Decode(dst); err != nil {
|
||||
problem(w, 400, "invalid_json", err.Error())
|
||||
return false
|
||||
}
|
||||
return true
|
||||
}
|
||||
func writeJSON(w http.ResponseWriter, status int, value any) {
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
w.WriteHeader(status)
|
||||
_ = json.NewEncoder(w).Encode(value)
|
||||
}
|
||||
func problem(w http.ResponseWriter, status int, code, detail string) {
|
||||
w.Header().Set("Content-Type", "application/problem+json")
|
||||
writeJSON(w, status, map[string]any{"type": "https://docs.meovv.mail/problems/" + code, "title": strings.ReplaceAll(code, "_", " "), "status": status, "detail": detail, "code": code})
|
||||
}
|
||||
func validHostname(v string) bool { return validDomain(v) && strings.Contains(v, ".") }
|
||||
func validDomain(v string) bool {
|
||||
if len(v) < 3 || len(v) > 253 || strings.ContainsAny(v, " /:@") {
|
||||
return false
|
||||
}
|
||||
for _, part := range strings.Split(v, ".") {
|
||||
if part == "" || strings.HasPrefix(part, "-") || strings.HasSuffix(part, "-") {
|
||||
return false
|
||||
}
|
||||
}
|
||||
return true
|
||||
}
|
||||
func hasScope(k store.APIKey, scope string) bool {
|
||||
for _, s := range k.Scopes {
|
||||
if s == scope {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
func allowedSender(k store.APIKey, value string) bool {
|
||||
address, err := mail.ParseAddress(value)
|
||||
if err != nil {
|
||||
return false
|
||||
}
|
||||
for _, allowed := range k.AllowedSenders {
|
||||
if strings.EqualFold(allowed, address.Address) {
|
||||
return true
|
||||
}
|
||||
if strings.HasPrefix(allowed, "*@") && strings.HasSuffix(strings.ToLower(address.Address), strings.ToLower(allowed[1:])) {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
func validSenderPattern(value string) bool {
|
||||
if strings.HasPrefix(value, "*@") {
|
||||
return validDomain(strings.TrimPrefix(value, "*@"))
|
||||
}
|
||||
_, err := mail.ParseAddress(value)
|
||||
return err == nil
|
||||
}
|
||||
func validScopes(scopes []string) bool {
|
||||
if len(scopes) == 0 {
|
||||
return false
|
||||
}
|
||||
for _, scope := range scopes {
|
||||
if scope != "messages.send" && scope != "messages.status" {
|
||||
return false
|
||||
}
|
||||
}
|
||||
return true
|
||||
}
|
||||
func verifyInternal(secret, signature string, body []byte) bool {
|
||||
mac := hmac.New(sha256.New, []byte(secret))
|
||||
mac.Write(body)
|
||||
expected := base64.StdEncoding.EncodeToString(mac.Sum(nil))
|
||||
return hmac.Equal([]byte(expected), []byte(signature))
|
||||
}
|
||||
func normalizeEvent(event string) (string, string) {
|
||||
switch event {
|
||||
case "queue.queue-message", "queue.queue-message-authenticated":
|
||||
return "queued", "message.queued"
|
||||
case "delivery.delivered":
|
||||
return "delivered", "message.delivered"
|
||||
case "delivery.dsn-temp-fail", "queue.rescheduled":
|
||||
return "deferred", "message.deferred"
|
||||
case "delivery.dsn-perm-fail":
|
||||
return "bounced", "message.bounced"
|
||||
case "delivery.double-bounce":
|
||||
return "failed", "message.failed"
|
||||
}
|
||||
return "", ""
|
||||
}
|
||||
func findString(data map[string]any, keys ...string) string {
|
||||
for _, key := range keys {
|
||||
if v, ok := data[key].(string); ok {
|
||||
return v
|
||||
}
|
||||
}
|
||||
return ""
|
||||
}
|
||||
|
||||
type rateLimiter struct {
|
||||
mu sync.Mutex
|
||||
entries map[string]rateEntry
|
||||
}
|
||||
type rateEntry struct {
|
||||
minute int64
|
||||
count int
|
||||
}
|
||||
|
||||
func newRateLimiter() *rateLimiter { return &rateLimiter{entries: map[string]rateEntry{}} }
|
||||
func (l *rateLimiter) Allow(id string, limit int) bool {
|
||||
l.mu.Lock()
|
||||
defer l.mu.Unlock()
|
||||
minute := time.Now().Unix() / 60
|
||||
entry := l.entries[id]
|
||||
if entry.minute != minute {
|
||||
entry = rateEntry{minute: minute}
|
||||
}
|
||||
if entry.count >= limit {
|
||||
return false
|
||||
}
|
||||
entry.count++
|
||||
l.entries[id] = entry
|
||||
return true
|
||||
}
|
||||
@@ -0,0 +1,33 @@
|
||||
package httpapi
|
||||
|
||||
import (
|
||||
"testing"
|
||||
|
||||
"github.com/meovv-mail/meovv-mail/internal/store"
|
||||
)
|
||||
|
||||
func TestEventNormalization(t *testing.T) {
|
||||
tests := map[string][2]string{
|
||||
"queue.queue-message": {"queued", "message.queued"},
|
||||
"delivery.delivered": {"delivered", "message.delivered"},
|
||||
"delivery.dsn-temp-fail": {"deferred", "message.deferred"},
|
||||
"delivery.dsn-perm-fail": {"bounced", "message.bounced"},
|
||||
"delivery.double-bounce": {"failed", "message.failed"},
|
||||
}
|
||||
for event, expected := range tests {
|
||||
state, external := normalizeEvent(event)
|
||||
if state != expected[0] || external != expected[1] {
|
||||
t.Errorf("%s = %s/%s", event, state, external)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestScopesAndApprovedSender(t *testing.T) {
|
||||
key := store.APIKey{Scopes: []string{"messages.send"}, AllowedSenders: []string{"alerts@example.com", "*@internal.example.com"}}
|
||||
if !hasScope(key, "messages.send") || hasScope(key, "messages.status") {
|
||||
t.Fatal("scope evaluation failed")
|
||||
}
|
||||
if !allowedSender(key, "Alerts <alerts@example.com>") || !allowedSender(key, "robot@internal.example.com") || allowedSender(key, "attacker@example.net") {
|
||||
t.Fatal("sender identity evaluation failed")
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,150 @@
|
||||
package mailer
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"crypto/rand"
|
||||
"encoding/base64"
|
||||
"fmt"
|
||||
"mime"
|
||||
"net/mail"
|
||||
"net/textproto"
|
||||
"path/filepath"
|
||||
"regexp"
|
||||
"sort"
|
||||
"strings"
|
||||
"time"
|
||||
)
|
||||
|
||||
type Attachment struct{ Filename, ContentType, ContentBase64 string }
|
||||
type Message struct {
|
||||
From string
|
||||
To, CC, BCC []string
|
||||
ReplyTo, Subject, Text, HTML string
|
||||
Headers map[string]string
|
||||
Attachments []Attachment
|
||||
}
|
||||
|
||||
var allowedHeader = regexp.MustCompile(`(?i)^(X-[A-Za-z0-9-]{1,64}|List-Unsubscribe|List-Unsubscribe-Post)$`)
|
||||
|
||||
func Build(m Message, maxBytes int64) ([]byte, []string, error) {
|
||||
from, err := mail.ParseAddress(m.From)
|
||||
if err != nil {
|
||||
return nil, nil, fmt.Errorf("invalid from address: %w", err)
|
||||
}
|
||||
recipients := append(append(append([]string{}, m.To...), m.CC...), m.BCC...)
|
||||
if len(recipients) == 0 {
|
||||
return nil, nil, fmt.Errorf("at least one recipient is required")
|
||||
}
|
||||
for i, value := range recipients {
|
||||
address, err := mail.ParseAddress(value)
|
||||
if err != nil {
|
||||
return nil, nil, fmt.Errorf("invalid recipient %q", value)
|
||||
}
|
||||
recipients[i] = strings.ToLower(address.Address)
|
||||
}
|
||||
var out bytes.Buffer
|
||||
boundary := randomBoundary()
|
||||
bodyBoundary := randomBoundary()
|
||||
headers := textproto.MIMEHeader{}
|
||||
headers.Set("From", from.String())
|
||||
headers.Set("To", strings.Join(m.To, ", "))
|
||||
if len(m.CC) > 0 {
|
||||
headers.Set("Cc", strings.Join(m.CC, ", "))
|
||||
}
|
||||
if m.ReplyTo != "" {
|
||||
if _, err = mail.ParseAddress(m.ReplyTo); err != nil {
|
||||
return nil, nil, fmt.Errorf("invalid reply-to")
|
||||
}
|
||||
headers.Set("Reply-To", m.ReplyTo)
|
||||
}
|
||||
headers.Set("Subject", mime.QEncoding.Encode("utf-8", m.Subject))
|
||||
headers.Set("Date", time.Now().Format(time.RFC1123Z))
|
||||
headers.Set("MIME-Version", "1.0")
|
||||
headers.Set("Message-ID", fmt.Sprintf("<%s@meovv.local>", strings.ToLower(randomBoundary())))
|
||||
for k, v := range m.Headers {
|
||||
if !allowedHeader.MatchString(k) || strings.ContainsAny(k+v, "\r\n") {
|
||||
return nil, nil, fmt.Errorf("header %q is not allowed", k)
|
||||
}
|
||||
headers.Set(k, v)
|
||||
}
|
||||
withAttachments := len(m.Attachments) > 0
|
||||
decodedBytes := int64(len([]byte(m.Text)) + len([]byte(m.HTML)))
|
||||
if withAttachments {
|
||||
headers.Set("Content-Type", fmt.Sprintf(`multipart/mixed; boundary="%s"`, boundary))
|
||||
} else {
|
||||
headers.Set("Content-Type", fmt.Sprintf(`multipart/alternative; boundary="%s"`, bodyBoundary))
|
||||
}
|
||||
keys := make([]string, 0, len(headers))
|
||||
for k := range headers {
|
||||
keys = append(keys, k)
|
||||
}
|
||||
sort.Strings(keys)
|
||||
for _, k := range keys {
|
||||
fmt.Fprintf(&out, "%s: %s\r\n", k, headers.Get(k))
|
||||
}
|
||||
out.WriteString("\r\n")
|
||||
if withAttachments {
|
||||
fmt.Fprintf(&out, "--%s\r\nContent-Type: multipart/alternative; boundary=\"%s\"\r\n\r\n", boundary, bodyBoundary)
|
||||
}
|
||||
writeAlternative(&out, bodyBoundary, m.Text, m.HTML)
|
||||
if withAttachments {
|
||||
for _, a := range m.Attachments {
|
||||
filename := filepath.Base(strings.ReplaceAll(a.Filename, "\\", "/"))
|
||||
if filename == "." || filename == "" {
|
||||
return nil, nil, fmt.Errorf("attachment filename is required")
|
||||
}
|
||||
raw, err := base64.StdEncoding.DecodeString(a.ContentBase64)
|
||||
if err != nil {
|
||||
return nil, nil, fmt.Errorf("attachment %q is not valid base64", filename)
|
||||
}
|
||||
decodedBytes += int64(len(raw))
|
||||
if decodedBytes > maxBytes {
|
||||
return nil, nil, fmt.Errorf("decoded message exceeds %d bytes", maxBytes)
|
||||
}
|
||||
contentType := a.ContentType
|
||||
if contentType == "" {
|
||||
contentType = "application/octet-stream"
|
||||
}
|
||||
fmt.Fprintf(&out, "--%s\r\nContent-Type: %s; name=%q\r\nContent-Disposition: attachment; filename=%q\r\nContent-Transfer-Encoding: base64\r\n\r\n", boundary, contentType, filename, filename)
|
||||
writeBase64(&out, raw)
|
||||
out.WriteString("\r\n")
|
||||
}
|
||||
fmt.Fprintf(&out, "--%s--\r\n", boundary)
|
||||
}
|
||||
if decodedBytes > maxBytes {
|
||||
return nil, nil, fmt.Errorf("decoded message exceeds %d bytes", maxBytes)
|
||||
}
|
||||
return out.Bytes(), recipients, nil
|
||||
}
|
||||
|
||||
func writeAlternative(out *bytes.Buffer, boundary, text, html string) {
|
||||
if text == "" {
|
||||
text = stripHTML(html)
|
||||
}
|
||||
fmt.Fprintf(out, "--%s\r\nContent-Type: text/plain; charset=utf-8\r\nContent-Transfer-Encoding: base64\r\n\r\n", boundary)
|
||||
writeBase64(out, []byte(text))
|
||||
out.WriteString("\r\n")
|
||||
if html != "" {
|
||||
fmt.Fprintf(out, "--%s\r\nContent-Type: text/html; charset=utf-8\r\nContent-Transfer-Encoding: base64\r\n\r\n", boundary)
|
||||
writeBase64(out, []byte(html))
|
||||
out.WriteString("\r\n")
|
||||
}
|
||||
fmt.Fprintf(out, "--%s--\r\n", boundary)
|
||||
}
|
||||
func writeBase64(out *bytes.Buffer, data []byte) {
|
||||
encoded := base64.StdEncoding.EncodeToString(data)
|
||||
for len(encoded) > 76 {
|
||||
out.WriteString(encoded[:76])
|
||||
out.WriteString("\r\n")
|
||||
encoded = encoded[76:]
|
||||
}
|
||||
out.WriteString(encoded)
|
||||
}
|
||||
func randomBoundary() string {
|
||||
b := make([]byte, 18)
|
||||
_, _ = rand.Read(b)
|
||||
return base64.RawURLEncoding.EncodeToString(b)
|
||||
}
|
||||
func stripHTML(value string) string {
|
||||
return strings.TrimSpace(regexp.MustCompile(`<[^>]+>`).ReplaceAllString(value, " "))
|
||||
}
|
||||
@@ -0,0 +1,50 @@
|
||||
package mailer
|
||||
|
||||
import (
|
||||
"encoding/base64"
|
||||
"strings"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestBuildMIMEAndProtectAttachmentFilename(t *testing.T) {
|
||||
raw, recipients, err := Build(Message{
|
||||
From: "MEOVV <sender@example.com>",
|
||||
To: []string{"Person <PERSON@example.net>"},
|
||||
Subject: "سلام — status",
|
||||
Text: "Hello",
|
||||
HTML: "<p>Hello</p>",
|
||||
Headers: map[string]string{"X-Campaign-ID": "welcome"},
|
||||
Attachments: []Attachment{{Filename: "../../private/statement.pdf", ContentType: "application/pdf", ContentBase64: base64.StdEncoding.EncodeToString([]byte("content"))}},
|
||||
}, 25<<20)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if len(recipients) != 1 || recipients[0] != "person@example.net" {
|
||||
t.Fatalf("unexpected recipients: %#v", recipients)
|
||||
}
|
||||
message := string(raw)
|
||||
if strings.Contains(message, "../") || !strings.Contains(message, `filename="statement.pdf"`) {
|
||||
t.Fatalf("unsafe or missing filename in MIME:\n%s", message)
|
||||
}
|
||||
if strings.Contains(message, "Bcc:") {
|
||||
t.Fatal("Bcc header leaked into MIME")
|
||||
}
|
||||
}
|
||||
|
||||
func TestBuildRejectsHeaderInjectionAndDecodedLimit(t *testing.T) {
|
||||
_, _, err := Build(Message{From: "sender@example.com", To: []string{"to@example.net"}, Text: "hello", Headers: map[string]string{"X-Test": "ok\r\nBcc: stolen@example.net"}}, 1024)
|
||||
if err == nil {
|
||||
t.Fatal("expected injected header to be rejected")
|
||||
}
|
||||
_, _, err = Build(Message{From: "sender@example.com", To: []string{"to@example.net"}, Text: strings.Repeat("x", 1025)}, 1024)
|
||||
if err == nil || !strings.Contains(err.Error(), "decoded message") {
|
||||
t.Fatalf("expected decoded size limit, got %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestBuildRequiresRecipient(t *testing.T) {
|
||||
_, _, err := Build(Message{From: "sender@example.com", Text: "hello"}, 1024)
|
||||
if err == nil {
|
||||
t.Fatal("expected recipient validation error")
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,92 @@
|
||||
package mailer
|
||||
|
||||
import (
|
||||
"context"
|
||||
"crypto/tls"
|
||||
"fmt"
|
||||
"net"
|
||||
"net/smtp"
|
||||
"strings"
|
||||
)
|
||||
|
||||
type Sender interface {
|
||||
Send(context.Context, string, []string, []byte) (string, error)
|
||||
}
|
||||
|
||||
type SMTP struct {
|
||||
Address, Username, Password string
|
||||
TLSConfig *tls.Config
|
||||
}
|
||||
|
||||
func (s SMTP) Send(ctx context.Context, from string, to []string, raw []byte) (string, error) {
|
||||
host, _, err := net.SplitHostPort(s.Address)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
dialer := net.Dialer{}
|
||||
conn, err := dialer.DialContext(ctx, "tcp", s.Address)
|
||||
if err != nil {
|
||||
return "", fmt.Errorf("connect to submission service: %w", err)
|
||||
}
|
||||
defer conn.Close()
|
||||
c, err := smtp.NewClient(conn, host)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
defer c.Close()
|
||||
tlsConfig := s.TLSConfig
|
||||
if tlsConfig == nil {
|
||||
tlsConfig = &tls.Config{ServerName: host, MinVersion: tls.VersionTLS12}
|
||||
}
|
||||
if ok, _ := c.Extension("STARTTLS"); ok {
|
||||
if err = c.StartTLS(tlsConfig); err != nil {
|
||||
return "", fmt.Errorf("start TLS: %w", err)
|
||||
}
|
||||
} else {
|
||||
return "", fmt.Errorf("submission service did not offer STARTTLS")
|
||||
}
|
||||
if s.Username != "" {
|
||||
auth := smtp.PlainAuth("", s.Username, s.Password, host)
|
||||
if err = c.Auth(auth); err != nil {
|
||||
return "", fmt.Errorf("authenticate: %w", err)
|
||||
}
|
||||
}
|
||||
address, err := mailbox(from)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
if err = c.Mail(address); err != nil {
|
||||
return "", err
|
||||
}
|
||||
for _, recipient := range to {
|
||||
if err = c.Rcpt(recipient); err != nil {
|
||||
return "", err
|
||||
}
|
||||
}
|
||||
w, err := c.Data()
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
if _, err = w.Write(raw); err != nil {
|
||||
return "", err
|
||||
}
|
||||
if err = w.Close(); err != nil {
|
||||
return "", err
|
||||
}
|
||||
if err = c.Quit(); err != nil {
|
||||
return "", err
|
||||
}
|
||||
return "smtp-accepted", nil
|
||||
}
|
||||
|
||||
func mailbox(value string) (string, error) {
|
||||
start := strings.LastIndex(value, "<")
|
||||
end := strings.LastIndex(value, ">")
|
||||
if start >= 0 && end > start {
|
||||
return strings.TrimSpace(value[start+1 : end]), nil
|
||||
}
|
||||
if strings.Contains(value, "@") {
|
||||
return strings.TrimSpace(value), nil
|
||||
}
|
||||
return "", fmt.Errorf("invalid mailbox")
|
||||
}
|
||||
@@ -0,0 +1,154 @@
|
||||
package stalwart
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"crypto/tls"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"io"
|
||||
"net/http"
|
||||
"net/url"
|
||||
"strings"
|
||||
"time"
|
||||
)
|
||||
|
||||
type Client struct {
|
||||
BaseURL string
|
||||
HTTP *http.Client
|
||||
}
|
||||
|
||||
func New(base string, insecure bool) *Client {
|
||||
transport := http.DefaultTransport.(*http.Transport).Clone()
|
||||
transport.TLSClientConfig = &tls.Config{MinVersion: tls.VersionTLS12, InsecureSkipVerify: insecure} // Internal Docker TLS; public TLS terminates at Caddy.
|
||||
return &Client{BaseURL: strings.TrimRight(base, "/"), HTTP: &http.Client{Timeout: 15 * time.Second, Transport: transport}}
|
||||
}
|
||||
|
||||
func (c *Client) Bootstrap(ctx context.Context, bootstrapURL, recoveryAdmin, hostname, domain string) ([]byte, error) {
|
||||
parts := strings.SplitN(recoveryAdmin, ":", 2)
|
||||
if len(parts) != 2 || parts[0] == "" || parts[1] == "" {
|
||||
return nil, fmt.Errorf("Stalwart recovery administrator is not configured")
|
||||
}
|
||||
payload := map[string]any{
|
||||
"using": []string{"urn:ietf:params:jmap:core", "urn:stalwart:jmap"},
|
||||
"methodCalls": []any{[]any{"x:Bootstrap/set", map[string]any{"update": map[string]any{"singleton": map[string]any{
|
||||
"serverHostname": hostname, "defaultDomain": domain, "requestTlsCertificate": true, "generateDkimKeys": true,
|
||||
"dataStore": map[string]any{"@type": "RocksDb", "path": "/var/lib/stalwart/"},
|
||||
"blobStore": map[string]any{"@type": "Default"}, "searchStore": map[string]any{"@type": "Default"}, "inMemoryStore": map[string]any{"@type": "Default"},
|
||||
"directory": map[string]any{"@type": "Internal"}, "tracer": map[string]any{"@type": "Console"}, "dnsServer": map[string]any{"@type": "Manual"},
|
||||
}}}, "bootstrap"}},
|
||||
}
|
||||
raw, _ := json.Marshal(payload)
|
||||
req, _ := http.NewRequestWithContext(ctx, http.MethodPost, strings.TrimRight(bootstrapURL, "/")+"/api", bytes.NewReader(raw))
|
||||
req.SetBasicAuth(parts[0], parts[1])
|
||||
req.Header.Set("Content-Type", "application/json")
|
||||
resp, err := c.HTTP.Do(req)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("configure Stalwart: %w", err)
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
body, _ := io.ReadAll(io.LimitReader(resp.Body, 1<<20))
|
||||
if resp.StatusCode/100 != 2 {
|
||||
return nil, fmt.Errorf("configure Stalwart: %s: %s", resp.Status, strings.TrimSpace(string(body)))
|
||||
}
|
||||
if bytes.Contains(body, []byte(`"type":"error"`)) || bytes.Contains(body, []byte(`"notUpdated"`)) {
|
||||
return nil, fmt.Errorf("Stalwart rejected bootstrap configuration: %s", strings.TrimSpace(string(body)))
|
||||
}
|
||||
return body, nil
|
||||
}
|
||||
func (c *Client) Ready(ctx context.Context) error {
|
||||
req, _ := http.NewRequestWithContext(ctx, http.MethodGet, c.BaseURL+"/.well-known/jmap", nil)
|
||||
resp, err := c.HTTP.Do(req)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
if resp.StatusCode >= 500 {
|
||||
return fmt.Errorf("stalwart returned %s", resp.Status)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
type Tokens struct {
|
||||
AccessToken string `json:"access_token"`
|
||||
RefreshToken string `json:"refresh_token"`
|
||||
ExpiresIn int `json:"expires_in"`
|
||||
TokenType string `json:"token_type"`
|
||||
}
|
||||
|
||||
func (c *Client) Exchange(ctx context.Context, clientID, code, verifier, redirectURI string) (Tokens, error) {
|
||||
form := url.Values{"grant_type": {"authorization_code"}, "client_id": {clientID}, "code": {code}, "code_verifier": {verifier}, "redirect_uri": {redirectURI}}
|
||||
req, _ := http.NewRequestWithContext(ctx, http.MethodPost, c.BaseURL+"/auth/token", strings.NewReader(form.Encode()))
|
||||
req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
|
||||
resp, err := c.HTTP.Do(req)
|
||||
if err != nil {
|
||||
return Tokens{}, err
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
if resp.StatusCode/100 != 2 {
|
||||
body, _ := io.ReadAll(io.LimitReader(resp.Body, 4096))
|
||||
return Tokens{}, fmt.Errorf("token exchange: %s: %s", resp.Status, strings.TrimSpace(string(body)))
|
||||
}
|
||||
var out Tokens
|
||||
err = json.NewDecoder(resp.Body).Decode(&out)
|
||||
return out, err
|
||||
}
|
||||
func (c *Client) Refresh(ctx context.Context, clientID, refreshToken string) (Tokens, error) {
|
||||
form := url.Values{"grant_type": {"refresh_token"}, "client_id": {clientID}, "refresh_token": {refreshToken}}
|
||||
req, _ := http.NewRequestWithContext(ctx, http.MethodPost, c.BaseURL+"/auth/token", strings.NewReader(form.Encode()))
|
||||
req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
|
||||
resp, err := c.HTTP.Do(req)
|
||||
if err != nil {
|
||||
return Tokens{}, err
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
if resp.StatusCode/100 != 2 {
|
||||
body, _ := io.ReadAll(io.LimitReader(resp.Body, 4096))
|
||||
return Tokens{}, fmt.Errorf("token refresh: %s: %s", resp.Status, strings.TrimSpace(string(body)))
|
||||
}
|
||||
var out Tokens
|
||||
err = json.NewDecoder(resp.Body).Decode(&out)
|
||||
return out, err
|
||||
}
|
||||
func (c *Client) ProxyJMAP(ctx context.Context, token string, body []byte) (int, http.Header, []byte, error) {
|
||||
return c.proxy(ctx, token, "/jmap", body)
|
||||
}
|
||||
|
||||
// ProxyManagement keeps Stalwart's pre-1.0 management schema behind the MEOVV
|
||||
// adapter. The browser never receives an administrator token or direct access
|
||||
// to Stalwart's management endpoint.
|
||||
func (c *Client) ProxyManagement(ctx context.Context, token string, body []byte) (int, http.Header, []byte, error) {
|
||||
return c.proxy(ctx, token, "/api", body)
|
||||
}
|
||||
|
||||
func (c *Client) JMAPSession(ctx context.Context, token string) (int, http.Header, []byte, error) {
|
||||
req, _ := http.NewRequestWithContext(ctx, http.MethodGet, c.BaseURL+"/.well-known/jmap", nil)
|
||||
req.Header.Set("Authorization", "Bearer "+token)
|
||||
resp, err := c.HTTP.Do(req)
|
||||
if err != nil {
|
||||
return 0, nil, nil, err
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
raw, err := io.ReadAll(io.LimitReader(resp.Body, 4<<20))
|
||||
return resp.StatusCode, resp.Header, raw, err
|
||||
}
|
||||
|
||||
func (c *Client) EventStream(ctx context.Context, token string) (*http.Response, error) {
|
||||
req, _ := http.NewRequestWithContext(ctx, http.MethodGet, c.BaseURL+"/jmap/eventsource/?types=Email,Mailbox&closeafter=45&ping=15", nil)
|
||||
req.Header.Set("Authorization", "Bearer "+token)
|
||||
client := &http.Client{Transport: c.HTTP.Transport}
|
||||
return client.Do(req)
|
||||
}
|
||||
|
||||
func (c *Client) proxy(ctx context.Context, token, path string, body []byte) (int, http.Header, []byte, error) {
|
||||
req, _ := http.NewRequestWithContext(ctx, http.MethodPost, c.BaseURL+path, bytes.NewReader(body))
|
||||
req.Header.Set("Authorization", "Bearer "+token)
|
||||
req.Header.Set("Content-Type", "application/json")
|
||||
resp, err := c.HTTP.Do(req)
|
||||
if err != nil {
|
||||
return 0, nil, nil, err
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
raw, err := io.ReadAll(io.LimitReader(resp.Body, 32<<20))
|
||||
return resp.StatusCode, resp.Header, raw, err
|
||||
}
|
||||
@@ -0,0 +1,623 @@
|
||||
package store
|
||||
|
||||
import (
|
||||
"context"
|
||||
"crypto/sha256"
|
||||
"database/sql"
|
||||
"encoding/hex"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
_ "modernc.org/sqlite"
|
||||
)
|
||||
|
||||
var ErrNotFound = errors.New("not found")
|
||||
|
||||
type Store struct{ db *sql.DB }
|
||||
|
||||
type APIKey struct {
|
||||
ID string `json:"id"`
|
||||
Name string `json:"name"`
|
||||
Prefix string `json:"prefix"`
|
||||
Scopes []string `json:"scopes"`
|
||||
AllowedSenders []string `json:"allowed_senders"`
|
||||
RateLimit int `json:"rate_limit"`
|
||||
CreatedAt time.Time `json:"created_at"`
|
||||
LastUsedAt *time.Time `json:"last_used_at,omitempty"`
|
||||
}
|
||||
|
||||
type Recipient struct {
|
||||
Address string `json:"address"`
|
||||
Status string `json:"status"`
|
||||
LastResponse string `json:"last_response,omitempty"`
|
||||
LastAttemptAt *time.Time `json:"last_attempt_at,omitempty"`
|
||||
}
|
||||
|
||||
type Message struct {
|
||||
ID string `json:"id"`
|
||||
APIKeyID string `json:"api_key_id,omitempty"`
|
||||
Sender string `json:"sender"`
|
||||
Subject string `json:"subject"`
|
||||
Status string `json:"status"`
|
||||
SizeBytes int64 `json:"size_bytes"`
|
||||
SubmittedAt time.Time `json:"submitted_at"`
|
||||
UpdatedAt time.Time `json:"updated_at"`
|
||||
StalwartID string `json:"stalwart_id,omitempty"`
|
||||
FailureReason string `json:"failure_reason,omitempty"`
|
||||
Recipients []Recipient `json:"recipients"`
|
||||
}
|
||||
|
||||
type MessageFilter struct {
|
||||
Status, Sender, Recipient, Cursor, APIKeyID string
|
||||
From, To *time.Time
|
||||
Limit int
|
||||
}
|
||||
|
||||
type WebhookEndpoint struct {
|
||||
ID string `json:"id"`
|
||||
Name string `json:"name"`
|
||||
URL string `json:"url"`
|
||||
Secret string `json:"-"`
|
||||
Events []string `json:"events"`
|
||||
Enabled bool `json:"enabled"`
|
||||
CreatedAt time.Time `json:"created_at"`
|
||||
}
|
||||
|
||||
type WebhookDelivery struct {
|
||||
ID, EndpointID, EventID, EventType string
|
||||
Payload []byte
|
||||
Attempt int
|
||||
NextAttemptAt, CreatedAt time.Time
|
||||
}
|
||||
|
||||
type Session struct {
|
||||
ID, Account string
|
||||
AccessToken, RefreshToken []byte
|
||||
ExpiresAt, SessionExpiresAt, CreatedAt, LastSeenAt time.Time
|
||||
}
|
||||
|
||||
func Open(path string) (*Store, error) {
|
||||
db, err := sql.Open("sqlite", path)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
db.SetMaxOpenConns(1)
|
||||
if _, err = db.Exec(`PRAGMA journal_mode=WAL; PRAGMA foreign_keys=ON; PRAGMA busy_timeout=5000;`); err != nil {
|
||||
db.Close()
|
||||
return nil, err
|
||||
}
|
||||
s := &Store{db: db}
|
||||
if err = s.migrate(context.Background()); err != nil {
|
||||
db.Close()
|
||||
return nil, err
|
||||
}
|
||||
return s, nil
|
||||
}
|
||||
|
||||
func (s *Store) Close() error { return s.db.Close() }
|
||||
func (s *Store) Ping(ctx context.Context) error { return s.db.PingContext(ctx) }
|
||||
|
||||
func (s *Store) migrate(ctx context.Context) error {
|
||||
statements := []string{
|
||||
`CREATE TABLE IF NOT EXISTS settings (key TEXT PRIMARY KEY, value TEXT NOT NULL, updated_at TEXT NOT NULL)`,
|
||||
`CREATE TABLE IF NOT EXISTS api_keys (id TEXT PRIMARY KEY, name TEXT NOT NULL, prefix TEXT NOT NULL, digest TEXT NOT NULL UNIQUE, scopes TEXT NOT NULL, allowed_senders TEXT NOT NULL, rate_limit INTEGER NOT NULL, created_at TEXT NOT NULL, last_used_at TEXT, revoked_at TEXT)`,
|
||||
`CREATE TABLE IF NOT EXISTS messages (id TEXT PRIMARY KEY, api_key_id TEXT, sender TEXT NOT NULL, subject TEXT NOT NULL, status TEXT NOT NULL, size_bytes INTEGER NOT NULL, submitted_at TEXT NOT NULL, updated_at TEXT NOT NULL, stalwart_id TEXT NOT NULL DEFAULT '', failure_reason TEXT NOT NULL DEFAULT '', FOREIGN KEY(api_key_id) REFERENCES api_keys(id))`,
|
||||
`CREATE TABLE IF NOT EXISTS message_recipients (message_id TEXT NOT NULL, address TEXT NOT NULL, status TEXT NOT NULL, last_response TEXT NOT NULL DEFAULT '', last_attempt_at TEXT, PRIMARY KEY(message_id,address), FOREIGN KEY(message_id) REFERENCES messages(id) ON DELETE CASCADE)`,
|
||||
`CREATE TABLE IF NOT EXISTS idempotency_keys (api_key_id TEXT NOT NULL, token TEXT NOT NULL, message_id TEXT NOT NULL, request_digest TEXT NOT NULL, expires_at TEXT NOT NULL, PRIMARY KEY(api_key_id,token), FOREIGN KEY(message_id) REFERENCES messages(id) ON DELETE CASCADE)`,
|
||||
`CREATE TABLE IF NOT EXISTS webhook_endpoints (id TEXT PRIMARY KEY, name TEXT NOT NULL, url TEXT NOT NULL, secret TEXT NOT NULL, events TEXT NOT NULL, enabled INTEGER NOT NULL DEFAULT 1, created_at TEXT NOT NULL)`,
|
||||
`CREATE TABLE IF NOT EXISTS webhook_deliveries (id TEXT PRIMARY KEY, endpoint_id TEXT NOT NULL, event_id TEXT NOT NULL, event_type TEXT NOT NULL, payload BLOB NOT NULL, attempt INTEGER NOT NULL DEFAULT 0, next_attempt_at TEXT NOT NULL, delivered_at TEXT, last_error TEXT NOT NULL DEFAULT '', created_at TEXT NOT NULL, FOREIGN KEY(endpoint_id) REFERENCES webhook_endpoints(id) ON DELETE CASCADE)`,
|
||||
`CREATE TABLE IF NOT EXISTS audit_events (id TEXT PRIMARY KEY, actor TEXT NOT NULL, action TEXT NOT NULL, target TEXT NOT NULL, detail TEXT NOT NULL, created_at TEXT NOT NULL)`,
|
||||
`CREATE TABLE IF NOT EXISTS sessions (id TEXT PRIMARY KEY, account TEXT NOT NULL, access_token BLOB NOT NULL, refresh_token BLOB NOT NULL, expires_at TEXT NOT NULL, session_expires_at TEXT NOT NULL, created_at TEXT NOT NULL, last_seen_at TEXT NOT NULL)`,
|
||||
`CREATE INDEX IF NOT EXISTS idx_messages_submitted ON messages(submitted_at DESC)`,
|
||||
`CREATE INDEX IF NOT EXISTS idx_messages_status_submitted ON messages(status, submitted_at DESC)`,
|
||||
`CREATE INDEX IF NOT EXISTS idx_recipients_address ON message_recipients(address, message_id)`,
|
||||
`CREATE INDEX IF NOT EXISTS idx_webhook_due ON webhook_deliveries(next_attempt_at) WHERE delivered_at IS NULL`,
|
||||
}
|
||||
tx, err := s.db.BeginTx(ctx, nil)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer tx.Rollback()
|
||||
for _, stmt := range statements {
|
||||
if _, err = tx.ExecContext(ctx, stmt); err != nil {
|
||||
return fmt.Errorf("migration: %w", err)
|
||||
}
|
||||
}
|
||||
if err = ensureSessionExpiryColumn(ctx, tx); err != nil {
|
||||
return err
|
||||
}
|
||||
if _, err = tx.ExecContext(ctx, `PRAGMA optimize`); err != nil {
|
||||
return err
|
||||
}
|
||||
return tx.Commit()
|
||||
}
|
||||
|
||||
func ensureSessionExpiryColumn(ctx context.Context, tx *sql.Tx) error {
|
||||
rows, err := tx.QueryContext(ctx, `PRAGMA table_info(sessions)`)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
found := false
|
||||
for rows.Next() {
|
||||
var cid, notNull, primaryKey int
|
||||
var name, columnType string
|
||||
var defaultValue any
|
||||
if err = rows.Scan(&cid, &name, &columnType, ¬Null, &defaultValue, &primaryKey); err != nil {
|
||||
rows.Close()
|
||||
return err
|
||||
}
|
||||
if name == "session_expires_at" {
|
||||
found = true
|
||||
}
|
||||
}
|
||||
if err = rows.Close(); err != nil {
|
||||
return err
|
||||
}
|
||||
if found {
|
||||
return nil
|
||||
}
|
||||
if _, err = tx.ExecContext(ctx, `ALTER TABLE sessions ADD COLUMN session_expires_at TEXT`); err != nil {
|
||||
return err
|
||||
}
|
||||
_, err = tx.ExecContext(ctx, `UPDATE sessions SET session_expires_at=expires_at WHERE session_expires_at IS NULL`)
|
||||
return err
|
||||
}
|
||||
|
||||
func DigestSecret(secret string) string {
|
||||
sum := sha256.Sum256([]byte(secret))
|
||||
return hex.EncodeToString(sum[:])
|
||||
}
|
||||
|
||||
func (s *Store) CreateAPIKey(ctx context.Context, key APIKey, secret string) error {
|
||||
scopes, _ := json.Marshal(key.Scopes)
|
||||
senders, _ := json.Marshal(key.AllowedSenders)
|
||||
_, err := s.db.ExecContext(ctx, `INSERT INTO api_keys(id,name,prefix,digest,scopes,allowed_senders,rate_limit,created_at) VALUES(?,?,?,?,?,?,?,?)`, key.ID, key.Name, key.Prefix, DigestSecret(secret), string(scopes), string(senders), key.RateLimit, key.CreatedAt.UTC().Format(time.RFC3339Nano))
|
||||
return err
|
||||
}
|
||||
|
||||
func (s *Store) AuthenticateAPIKey(ctx context.Context, secret string) (APIKey, error) {
|
||||
var k APIKey
|
||||
var scopes, senders, created string
|
||||
var last sql.NullString
|
||||
err := s.db.QueryRowContext(ctx, `SELECT id,name,prefix,scopes,allowed_senders,rate_limit,created_at,last_used_at FROM api_keys WHERE digest=? AND revoked_at IS NULL`, DigestSecret(secret)).Scan(&k.ID, &k.Name, &k.Prefix, &scopes, &senders, &k.RateLimit, &created, &last)
|
||||
if errors.Is(err, sql.ErrNoRows) {
|
||||
return k, ErrNotFound
|
||||
}
|
||||
if err != nil {
|
||||
return k, err
|
||||
}
|
||||
_ = json.Unmarshal([]byte(scopes), &k.Scopes)
|
||||
_ = json.Unmarshal([]byte(senders), &k.AllowedSenders)
|
||||
k.CreatedAt, _ = time.Parse(time.RFC3339Nano, created)
|
||||
if last.Valid {
|
||||
t, _ := time.Parse(time.RFC3339Nano, last.String)
|
||||
k.LastUsedAt = &t
|
||||
}
|
||||
_, _ = s.db.ExecContext(ctx, `UPDATE api_keys SET last_used_at=? WHERE id=?`, time.Now().UTC().Format(time.RFC3339Nano), k.ID)
|
||||
return k, nil
|
||||
}
|
||||
|
||||
func (s *Store) ListAPIKeys(ctx context.Context) ([]APIKey, error) {
|
||||
rows, err := s.db.QueryContext(ctx, `SELECT id,name,prefix,scopes,allowed_senders,rate_limit,created_at,last_used_at FROM api_keys WHERE revoked_at IS NULL ORDER BY created_at DESC`)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer rows.Close()
|
||||
var out []APIKey
|
||||
for rows.Next() {
|
||||
var key APIKey
|
||||
var scopes, senders, created string
|
||||
var last sql.NullString
|
||||
if err = rows.Scan(&key.ID, &key.Name, &key.Prefix, &scopes, &senders, &key.RateLimit, &created, &last); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
_ = json.Unmarshal([]byte(scopes), &key.Scopes)
|
||||
_ = json.Unmarshal([]byte(senders), &key.AllowedSenders)
|
||||
key.CreatedAt, _ = time.Parse(time.RFC3339Nano, created)
|
||||
if last.Valid {
|
||||
t, _ := time.Parse(time.RFC3339Nano, last.String)
|
||||
key.LastUsedAt = &t
|
||||
}
|
||||
out = append(out, key)
|
||||
}
|
||||
return out, rows.Err()
|
||||
}
|
||||
|
||||
func (s *Store) RevokeAPIKey(ctx context.Context, id string) error {
|
||||
result, err := s.db.ExecContext(ctx, `UPDATE api_keys SET revoked_at=? WHERE id=? AND revoked_at IS NULL`, time.Now().UTC().Format(time.RFC3339Nano), id)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if affected, _ := result.RowsAffected(); affected == 0 {
|
||||
return ErrNotFound
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (s *Store) InsertMessage(ctx context.Context, m Message, idemToken, requestDigest string) (existing string, err error) {
|
||||
tx, err := s.db.BeginTx(ctx, nil)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
defer tx.Rollback()
|
||||
if idemToken != "" {
|
||||
var priorID, priorDigest string
|
||||
err = tx.QueryRowContext(ctx, `SELECT message_id,request_digest FROM idempotency_keys WHERE api_key_id=? AND token=? AND expires_at>?`, m.APIKeyID, idemToken, time.Now().UTC().Format(time.RFC3339Nano)).Scan(&priorID, &priorDigest)
|
||||
if err == nil {
|
||||
if priorDigest != requestDigest {
|
||||
return "", fmt.Errorf("idempotency key reused with a different request")
|
||||
}
|
||||
return priorID, nil
|
||||
}
|
||||
if !errors.Is(err, sql.ErrNoRows) {
|
||||
return "", err
|
||||
}
|
||||
}
|
||||
_, err = tx.ExecContext(ctx, `INSERT INTO messages(id,api_key_id,sender,subject,status,size_bytes,submitted_at,updated_at) VALUES(?,?,?,?,?,?,?,?)`, m.ID, m.APIKeyID, m.Sender, m.Subject, m.Status, m.SizeBytes, m.SubmittedAt.UTC().Format(time.RFC3339Nano), m.UpdatedAt.UTC().Format(time.RFC3339Nano))
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
for _, r := range m.Recipients {
|
||||
if _, err = tx.ExecContext(ctx, `INSERT INTO message_recipients(message_id,address,status) VALUES(?,?,?)`, m.ID, strings.ToLower(r.Address), r.Status); err != nil {
|
||||
return "", err
|
||||
}
|
||||
}
|
||||
if idemToken != "" {
|
||||
_, err = tx.ExecContext(ctx, `INSERT INTO idempotency_keys(api_key_id,token,message_id,request_digest,expires_at) VALUES(?,?,?,?,?)`, m.APIKeyID, idemToken, m.ID, requestDigest, time.Now().Add(24*time.Hour).UTC().Format(time.RFC3339Nano))
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
}
|
||||
return "", tx.Commit()
|
||||
}
|
||||
|
||||
func (s *Store) UpdateMessageStatus(ctx context.Context, id, status, reason, stalwartID string) error {
|
||||
_, err := s.db.ExecContext(ctx, `UPDATE messages SET status=?,failure_reason=?,stalwart_id=CASE WHEN ?='' THEN stalwart_id ELSE ? END,updated_at=? WHERE id=?`, status, reason, stalwartID, stalwartID, time.Now().UTC().Format(time.RFC3339Nano), id)
|
||||
return err
|
||||
}
|
||||
|
||||
func (s *Store) UpdateRecipient(ctx context.Context, id, address, status, response string, at time.Time) error {
|
||||
_, err := s.db.ExecContext(ctx, `UPDATE message_recipients SET status=?,last_response=?,last_attempt_at=? WHERE message_id=? AND address=?`, status, response, at.UTC().Format(time.RFC3339Nano), id, strings.ToLower(address))
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
return s.recalculate(ctx, id)
|
||||
}
|
||||
|
||||
func (s *Store) recalculate(ctx context.Context, id string) error {
|
||||
rows, err := s.db.QueryContext(ctx, `SELECT status,COUNT(*) FROM message_recipients WHERE message_id=? GROUP BY status`, id)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer rows.Close()
|
||||
counts := map[string]int{}
|
||||
total := 0
|
||||
for rows.Next() {
|
||||
var status string
|
||||
var n int
|
||||
if err = rows.Scan(&status, &n); err != nil {
|
||||
return err
|
||||
}
|
||||
counts[status] = n
|
||||
total += n
|
||||
}
|
||||
status := "processing"
|
||||
switch {
|
||||
case total > 0 && counts["delivered"] == total:
|
||||
status = "delivered"
|
||||
case counts["delivered"] > 0 && (counts["bounced"]+counts["failed"] > 0):
|
||||
status = "partial"
|
||||
case total > 0 && counts["bounced"] == total:
|
||||
status = "bounced"
|
||||
case total > 0 && counts["failed"] == total:
|
||||
status = "failed"
|
||||
case counts["deferred"] > 0:
|
||||
status = "deferred"
|
||||
case counts["queued"] == total:
|
||||
status = "queued"
|
||||
}
|
||||
return s.UpdateMessageStatus(ctx, id, status, "", "")
|
||||
}
|
||||
|
||||
func (s *Store) GetMessage(ctx context.Context, id string) (Message, error) {
|
||||
var m Message
|
||||
var submitted, updated string
|
||||
err := s.db.QueryRowContext(ctx, `SELECT id,COALESCE(api_key_id,''),sender,subject,status,size_bytes,submitted_at,updated_at,stalwart_id,failure_reason FROM messages WHERE id=?`, id).Scan(&m.ID, &m.APIKeyID, &m.Sender, &m.Subject, &m.Status, &m.SizeBytes, &submitted, &updated, &m.StalwartID, &m.FailureReason)
|
||||
if errors.Is(err, sql.ErrNoRows) {
|
||||
return m, ErrNotFound
|
||||
}
|
||||
if err != nil {
|
||||
return m, err
|
||||
}
|
||||
m.SubmittedAt, _ = time.Parse(time.RFC3339Nano, submitted)
|
||||
m.UpdatedAt, _ = time.Parse(time.RFC3339Nano, updated)
|
||||
rows, err := s.db.QueryContext(ctx, `SELECT address,status,last_response,last_attempt_at FROM message_recipients WHERE message_id=? ORDER BY address`, id)
|
||||
if err != nil {
|
||||
return m, err
|
||||
}
|
||||
defer rows.Close()
|
||||
for rows.Next() {
|
||||
var r Recipient
|
||||
var at sql.NullString
|
||||
if err = rows.Scan(&r.Address, &r.Status, &r.LastResponse, &at); err != nil {
|
||||
return m, err
|
||||
}
|
||||
if at.Valid {
|
||||
t, _ := time.Parse(time.RFC3339Nano, at.String)
|
||||
r.LastAttemptAt = &t
|
||||
}
|
||||
m.Recipients = append(m.Recipients, r)
|
||||
}
|
||||
return m, rows.Err()
|
||||
}
|
||||
|
||||
func (s *Store) ListMessages(ctx context.Context, f MessageFilter) ([]Message, string, error) {
|
||||
if f.Limit <= 0 || f.Limit > 100 {
|
||||
f.Limit = 25
|
||||
}
|
||||
args := []any{}
|
||||
where := []string{"1=1"}
|
||||
if f.APIKeyID != "" {
|
||||
where = append(where, "m.api_key_id=?")
|
||||
args = append(args, f.APIKeyID)
|
||||
}
|
||||
if f.Status != "" {
|
||||
where = append(where, "m.status=?")
|
||||
args = append(args, f.Status)
|
||||
}
|
||||
if f.Sender != "" {
|
||||
where = append(where, "m.sender=?")
|
||||
args = append(args, strings.ToLower(f.Sender))
|
||||
}
|
||||
if f.Recipient != "" {
|
||||
where = append(where, "EXISTS(SELECT 1 FROM message_recipients mr WHERE mr.message_id=m.id AND mr.address=?)")
|
||||
args = append(args, strings.ToLower(f.Recipient))
|
||||
}
|
||||
if f.From != nil {
|
||||
where = append(where, "m.submitted_at>=?")
|
||||
args = append(args, f.From.UTC().Format(time.RFC3339Nano))
|
||||
}
|
||||
if f.To != nil {
|
||||
where = append(where, "m.submitted_at<=?")
|
||||
args = append(args, f.To.UTC().Format(time.RFC3339Nano))
|
||||
}
|
||||
if f.Cursor != "" {
|
||||
where = append(where, "m.submitted_at<?")
|
||||
args = append(args, f.Cursor)
|
||||
}
|
||||
args = append(args, f.Limit+1)
|
||||
rows, err := s.db.QueryContext(ctx, `SELECT m.id FROM messages m WHERE `+strings.Join(where, " AND ")+` ORDER BY m.submitted_at DESC LIMIT ?`, args...)
|
||||
if err != nil {
|
||||
return nil, "", err
|
||||
}
|
||||
defer rows.Close()
|
||||
ids := []string{}
|
||||
for rows.Next() {
|
||||
var id string
|
||||
if err = rows.Scan(&id); err != nil {
|
||||
return nil, "", err
|
||||
}
|
||||
ids = append(ids, id)
|
||||
}
|
||||
next := ""
|
||||
if len(ids) > f.Limit {
|
||||
last, err := s.GetMessage(ctx, ids[f.Limit-1])
|
||||
if err == nil {
|
||||
next = last.SubmittedAt.UTC().Format(time.RFC3339Nano)
|
||||
}
|
||||
ids = ids[:f.Limit]
|
||||
}
|
||||
out := make([]Message, 0, len(ids))
|
||||
for _, id := range ids {
|
||||
m, err := s.GetMessage(ctx, id)
|
||||
if err != nil {
|
||||
return nil, "", err
|
||||
}
|
||||
out = append(out, m)
|
||||
}
|
||||
return out, next, nil
|
||||
}
|
||||
|
||||
func (s *Store) SetSetting(ctx context.Context, key string, value any) error {
|
||||
raw, err := json.Marshal(value)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
_, err = s.db.ExecContext(ctx, `INSERT INTO settings(key,value,updated_at) VALUES(?,?,?) ON CONFLICT(key) DO UPDATE SET value=excluded.value,updated_at=excluded.updated_at`, key, string(raw), time.Now().UTC().Format(time.RFC3339Nano))
|
||||
return err
|
||||
}
|
||||
func (s *Store) GetSetting(ctx context.Context, key string, dst any) error {
|
||||
var raw string
|
||||
err := s.db.QueryRowContext(ctx, `SELECT value FROM settings WHERE key=?`, key).Scan(&raw)
|
||||
if errors.Is(err, sql.ErrNoRows) {
|
||||
return ErrNotFound
|
||||
}
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
return json.Unmarshal([]byte(raw), dst)
|
||||
}
|
||||
|
||||
func (s *Store) EnqueueEvent(ctx context.Context, eventID, eventType string, payload []byte, now time.Time) error {
|
||||
rows, err := s.db.QueryContext(ctx, `SELECT id FROM webhook_endpoints WHERE enabled=1 AND EXISTS(SELECT 1 FROM json_each(events) WHERE value=?)`, eventType)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
var endpointIDs []string
|
||||
for rows.Next() {
|
||||
var endpointID string
|
||||
if err = rows.Scan(&endpointID); err != nil {
|
||||
rows.Close()
|
||||
return err
|
||||
}
|
||||
endpointIDs = append(endpointIDs, endpointID)
|
||||
}
|
||||
if err = rows.Err(); err != nil {
|
||||
rows.Close()
|
||||
return err
|
||||
}
|
||||
if err = rows.Close(); err != nil {
|
||||
return err
|
||||
}
|
||||
for _, endpointID := range endpointIDs {
|
||||
id := eventID + "_" + endpointID
|
||||
if _, err = s.db.ExecContext(ctx, `INSERT OR IGNORE INTO webhook_deliveries(id,endpoint_id,event_id,event_type,payload,next_attempt_at,created_at) VALUES(?,?,?,?,?,?,?)`, id, endpointID, eventID, eventType, payload, now.UTC().Format(time.RFC3339Nano), now.UTC().Format(time.RFC3339Nano)); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
func (s *Store) DueWebhooks(ctx context.Context, now time.Time, limit int) ([]WebhookDelivery, error) {
|
||||
rows, err := s.db.QueryContext(ctx, `SELECT id,endpoint_id,event_id,event_type,payload,attempt,next_attempt_at,created_at FROM webhook_deliveries WHERE delivered_at IS NULL AND next_attempt_at<=? ORDER BY next_attempt_at LIMIT ?`, now.UTC().Format(time.RFC3339Nano), limit)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer rows.Close()
|
||||
var out []WebhookDelivery
|
||||
for rows.Next() {
|
||||
var d WebhookDelivery
|
||||
var next, created string
|
||||
if err = rows.Scan(&d.ID, &d.EndpointID, &d.EventID, &d.EventType, &d.Payload, &d.Attempt, &next, &created); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
d.NextAttemptAt, _ = time.Parse(time.RFC3339Nano, next)
|
||||
d.CreatedAt, _ = time.Parse(time.RFC3339Nano, created)
|
||||
out = append(out, d)
|
||||
}
|
||||
return out, rows.Err()
|
||||
}
|
||||
func (s *Store) GetWebhookEndpoint(ctx context.Context, id string) (WebhookEndpoint, error) {
|
||||
var e WebhookEndpoint
|
||||
var events, created string
|
||||
var enabled int
|
||||
err := s.db.QueryRowContext(ctx, `SELECT id,name,url,secret,events,enabled,created_at FROM webhook_endpoints WHERE id=?`, id).Scan(&e.ID, &e.Name, &e.URL, &e.Secret, &events, &enabled, &created)
|
||||
if errors.Is(err, sql.ErrNoRows) {
|
||||
return e, ErrNotFound
|
||||
}
|
||||
_ = json.Unmarshal([]byte(events), &e.Events)
|
||||
e.Enabled = enabled == 1
|
||||
e.CreatedAt, _ = time.Parse(time.RFC3339Nano, created)
|
||||
return e, err
|
||||
}
|
||||
|
||||
func (s *Store) CreateWebhookEndpoint(ctx context.Context, endpoint WebhookEndpoint) error {
|
||||
events, _ := json.Marshal(endpoint.Events)
|
||||
_, err := s.db.ExecContext(ctx, `INSERT INTO webhook_endpoints(id,name,url,secret,events,enabled,created_at) VALUES(?,?,?,?,?,?,?)`, endpoint.ID, endpoint.Name, endpoint.URL, endpoint.Secret, string(events), boolInt(endpoint.Enabled), endpoint.CreatedAt.UTC().Format(time.RFC3339Nano))
|
||||
return err
|
||||
}
|
||||
|
||||
func (s *Store) ListWebhookEndpoints(ctx context.Context) ([]WebhookEndpoint, error) {
|
||||
rows, err := s.db.QueryContext(ctx, `SELECT id,name,url,events,enabled,created_at FROM webhook_endpoints ORDER BY created_at DESC`)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer rows.Close()
|
||||
var out []WebhookEndpoint
|
||||
for rows.Next() {
|
||||
var endpoint WebhookEndpoint
|
||||
var events, created string
|
||||
var enabled int
|
||||
if err = rows.Scan(&endpoint.ID, &endpoint.Name, &endpoint.URL, &events, &enabled, &created); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
_ = json.Unmarshal([]byte(events), &endpoint.Events)
|
||||
endpoint.Enabled = enabled == 1
|
||||
endpoint.CreatedAt, _ = time.Parse(time.RFC3339Nano, created)
|
||||
out = append(out, endpoint)
|
||||
}
|
||||
return out, rows.Err()
|
||||
}
|
||||
|
||||
func (s *Store) DeleteWebhookEndpoint(ctx context.Context, id string) error {
|
||||
result, err := s.db.ExecContext(ctx, `DELETE FROM webhook_endpoints WHERE id=?`, id)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if affected, _ := result.RowsAffected(); affected == 0 {
|
||||
return ErrNotFound
|
||||
}
|
||||
return nil
|
||||
}
|
||||
func (s *Store) CompleteWebhook(ctx context.Context, id string, delivered bool, next time.Time, lastErr string) error {
|
||||
if delivered {
|
||||
_, err := s.db.ExecContext(ctx, `UPDATE webhook_deliveries SET attempt=attempt+1,delivered_at=?,last_error='' WHERE id=?`, time.Now().UTC().Format(time.RFC3339Nano), id)
|
||||
return err
|
||||
}
|
||||
_, err := s.db.ExecContext(ctx, `UPDATE webhook_deliveries SET attempt=attempt+1,next_attempt_at=?,last_error=? WHERE id=?`, next.UTC().Format(time.RFC3339Nano), lastErr, id)
|
||||
return err
|
||||
}
|
||||
|
||||
func (s *Store) Stats(ctx context.Context) (map[string]any, error) {
|
||||
out := map[string]any{}
|
||||
for key, query := range map[string]string{"messages_24h": `SELECT COUNT(*) FROM messages WHERE submitted_at>=datetime('now','-1 day')`, "queued": `SELECT COUNT(*) FROM messages WHERE status IN ('queued','processing','deferred')`, "failed_webhooks": `SELECT COUNT(*) FROM webhook_deliveries WHERE delivered_at IS NULL AND attempt>0`, "api_keys": `SELECT COUNT(*) FROM api_keys WHERE revoked_at IS NULL`} {
|
||||
var n int
|
||||
if err := s.db.QueryRowContext(ctx, query).Scan(&n); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
out[key] = n
|
||||
}
|
||||
return out, nil
|
||||
}
|
||||
|
||||
func (s *Store) Cleanup(ctx context.Context, messageBefore, webhookBefore, auditBefore time.Time) error {
|
||||
tx, err := s.db.BeginTx(ctx, nil)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer tx.Rollback()
|
||||
for _, q := range []struct {
|
||||
sql string
|
||||
arg time.Time
|
||||
}{{`DELETE FROM messages WHERE submitted_at<?`, messageBefore}, {`DELETE FROM webhook_deliveries WHERE created_at<?`, webhookBefore}, {`DELETE FROM audit_events WHERE created_at<?`, auditBefore}, {`DELETE FROM idempotency_keys WHERE expires_at<?`, time.Now()}, {`DELETE FROM sessions WHERE session_expires_at<?`, time.Now()}} {
|
||||
if _, err = tx.ExecContext(ctx, q.sql, q.arg.UTC().Format(time.RFC3339Nano)); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
return tx.Commit()
|
||||
}
|
||||
|
||||
func (s *Store) CreateSession(ctx context.Context, v Session) error {
|
||||
_, err := s.db.ExecContext(ctx, `INSERT INTO sessions(id,account,access_token,refresh_token,expires_at,session_expires_at,created_at,last_seen_at) VALUES(?,?,?,?,?,?,?,?)`, v.ID, v.Account, v.AccessToken, v.RefreshToken, v.ExpiresAt.UTC().Format(time.RFC3339Nano), v.SessionExpiresAt.UTC().Format(time.RFC3339Nano), v.CreatedAt.UTC().Format(time.RFC3339Nano), v.LastSeenAt.UTC().Format(time.RFC3339Nano))
|
||||
return err
|
||||
}
|
||||
func (s *Store) GetSession(ctx context.Context, id string) (Session, error) {
|
||||
var v Session
|
||||
var expires, sessionExpires, created, seen string
|
||||
err := s.db.QueryRowContext(ctx, `SELECT id,account,access_token,refresh_token,expires_at,session_expires_at,created_at,last_seen_at FROM sessions WHERE id=? AND session_expires_at>?`, id, time.Now().UTC().Format(time.RFC3339Nano)).Scan(&v.ID, &v.Account, &v.AccessToken, &v.RefreshToken, &expires, &sessionExpires, &created, &seen)
|
||||
if errors.Is(err, sql.ErrNoRows) {
|
||||
return v, ErrNotFound
|
||||
}
|
||||
if err != nil {
|
||||
return v, err
|
||||
}
|
||||
v.ExpiresAt, _ = time.Parse(time.RFC3339Nano, expires)
|
||||
v.SessionExpiresAt, _ = time.Parse(time.RFC3339Nano, sessionExpires)
|
||||
v.CreatedAt, _ = time.Parse(time.RFC3339Nano, created)
|
||||
v.LastSeenAt, _ = time.Parse(time.RFC3339Nano, seen)
|
||||
_, _ = s.db.ExecContext(ctx, `UPDATE sessions SET last_seen_at=? WHERE id=?`, time.Now().UTC().Format(time.RFC3339Nano), id)
|
||||
return v, nil
|
||||
}
|
||||
func (s *Store) UpdateSessionTokens(ctx context.Context, id string, access, refresh []byte, expiresAt time.Time) error {
|
||||
_, err := s.db.ExecContext(ctx, `UPDATE sessions SET access_token=?,refresh_token=?,expires_at=?,last_seen_at=? WHERE id=?`, access, refresh, expiresAt.UTC().Format(time.RFC3339Nano), time.Now().UTC().Format(time.RFC3339Nano), id)
|
||||
return err
|
||||
}
|
||||
func (s *Store) DeleteSession(ctx context.Context, id string) error {
|
||||
_, err := s.db.ExecContext(ctx, `DELETE FROM sessions WHERE id=?`, id)
|
||||
return err
|
||||
}
|
||||
|
||||
func (s *Store) Audit(ctx context.Context, id, actor, action, target string, detail any) error {
|
||||
raw, _ := json.Marshal(detail)
|
||||
_, err := s.db.ExecContext(ctx, `INSERT INTO audit_events(id,actor,action,target,detail,created_at) VALUES(?,?,?,?,?,?)`, id, actor, action, target, string(raw), time.Now().UTC().Format(time.RFC3339Nano))
|
||||
return err
|
||||
}
|
||||
|
||||
func boolInt(value bool) int {
|
||||
if value {
|
||||
return 1
|
||||
}
|
||||
return 0
|
||||
}
|
||||
@@ -0,0 +1,90 @@
|
||||
package store
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"path/filepath"
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
func testStore(t *testing.T) *Store {
|
||||
t.Helper()
|
||||
db, err := Open(filepath.Join(t.TempDir(), "test.sqlite"))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
t.Cleanup(func() { _ = db.Close() })
|
||||
return db
|
||||
}
|
||||
|
||||
func TestAPIKeyHashingListingAndRevocation(t *testing.T) {
|
||||
ctx := context.Background()
|
||||
db := testStore(t)
|
||||
key := APIKey{ID: "key_1", Name: "Production", Prefix: "meovv_abc", Scopes: []string{"messages.send"}, AllowedSenders: []string{"*@example.com"}, RateLimit: 60, CreatedAt: time.Now()}
|
||||
if err := db.CreateAPIKey(ctx, key, "meovv_secret"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
got, err := db.AuthenticateAPIKey(ctx, "meovv_secret")
|
||||
if err != nil || got.ID != key.ID || len(got.Scopes) != 1 {
|
||||
t.Fatalf("authenticate = %#v, %v", got, err)
|
||||
}
|
||||
keys, err := db.ListAPIKeys(ctx)
|
||||
if err != nil || len(keys) != 1 {
|
||||
t.Fatalf("list = %#v, %v", keys, err)
|
||||
}
|
||||
if err = db.RevokeAPIKey(ctx, key.ID); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err = db.AuthenticateAPIKey(ctx, "meovv_secret"); !errors.Is(err, ErrNotFound) {
|
||||
t.Fatalf("revoked key authenticated: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestIdempotencyAndRecipientStateRollup(t *testing.T) {
|
||||
ctx := context.Background()
|
||||
db := testStore(t)
|
||||
now := time.Now().UTC()
|
||||
key := APIKey{ID: "key_1", Name: "test", Prefix: "meovv_test", Scopes: []string{"messages.send"}, AllowedSenders: []string{"sender@example.com"}, RateLimit: 60, CreatedAt: now}
|
||||
if err := db.CreateAPIKey(ctx, key, "secret"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
message := Message{ID: "msg_1", APIKeyID: key.ID, Sender: "sender@example.com", Subject: "test", Status: "queued", SubmittedAt: now, UpdatedAt: now, Recipients: []Recipient{{Address: "a@example.net", Status: "queued"}, {Address: "b@example.net", Status: "queued"}}}
|
||||
if prior, err := db.InsertMessage(ctx, message, "retry-token", "digest-a"); err != nil || prior != "" {
|
||||
t.Fatalf("insert = %q, %v", prior, err)
|
||||
}
|
||||
duplicate := message
|
||||
duplicate.ID = "msg_2"
|
||||
if prior, err := db.InsertMessage(ctx, duplicate, "retry-token", "digest-a"); err != nil || prior != "msg_1" {
|
||||
t.Fatalf("replay = %q, %v", prior, err)
|
||||
}
|
||||
if _, err := db.InsertMessage(ctx, duplicate, "retry-token", "digest-b"); err == nil {
|
||||
t.Fatal("expected conflicting idempotency digest")
|
||||
}
|
||||
if err := db.UpdateRecipient(ctx, "msg_1", "a@example.net", "delivered", "250 ok", now); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := db.UpdateRecipient(ctx, "msg_1", "b@example.net", "bounced", "550 no", now); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
got, err := db.GetMessage(ctx, "msg_1")
|
||||
if err != nil || got.Status != "partial" {
|
||||
t.Fatalf("status = %q, %v", got.Status, err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestWebhookEndpointLifecycle(t *testing.T) {
|
||||
ctx := context.Background()
|
||||
db := testStore(t)
|
||||
endpoint := WebhookEndpoint{ID: "wh_1", Name: "Billing", URL: "https://example.com/hook", Secret: "secret", Events: []string{"message.delivered"}, Enabled: true, CreatedAt: time.Now()}
|
||||
if err := db.CreateWebhookEndpoint(ctx, endpoint); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
items, err := db.ListWebhookEndpoints(ctx)
|
||||
if err != nil || len(items) != 1 || items[0].Secret != "" {
|
||||
t.Fatalf("list = %#v, %v", items, err)
|
||||
}
|
||||
if err = db.DeleteWebhookEndpoint(ctx, endpoint.ID); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,139 @@
|
||||
package webhook
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"crypto/hmac"
|
||||
"crypto/sha256"
|
||||
"encoding/base64"
|
||||
"encoding/hex"
|
||||
"fmt"
|
||||
"io"
|
||||
"math"
|
||||
"net"
|
||||
"net/http"
|
||||
"net/url"
|
||||
"strconv"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/meovv-mail/meovv-mail/internal/app"
|
||||
"github.com/meovv-mail/meovv-mail/internal/store"
|
||||
)
|
||||
|
||||
type Dispatcher struct {
|
||||
Store *store.Store
|
||||
Cipher app.TokenCipher
|
||||
HTTP *http.Client
|
||||
Now func() time.Time
|
||||
}
|
||||
|
||||
func New(s *store.Store, cipher app.TokenCipher) *Dispatcher {
|
||||
return &Dispatcher{Store: s, Cipher: cipher, HTTP: &http.Client{Timeout: 10 * time.Second}, Now: time.Now}
|
||||
}
|
||||
|
||||
func Signature(secret string, timestamp int64, body []byte) string {
|
||||
mac := hmac.New(sha256.New, []byte(secret))
|
||||
fmt.Fprintf(mac, "%d.", timestamp)
|
||||
mac.Write(body)
|
||||
return hex.EncodeToString(mac.Sum(nil))
|
||||
}
|
||||
func Verify(secret, signature, timestamp string, body []byte, maxSkew time.Duration) bool {
|
||||
unix, err := strconv.ParseInt(timestamp, 10, 64)
|
||||
if err != nil || time.Since(time.Unix(unix, 0)) > maxSkew || time.Until(time.Unix(unix, 0)) > maxSkew {
|
||||
return false
|
||||
}
|
||||
expected := Signature(secret, unix, body)
|
||||
return hmac.Equal([]byte(expected), []byte(strings.ToLower(signature)))
|
||||
}
|
||||
|
||||
func (d *Dispatcher) Run(ctx context.Context) {
|
||||
ticker := time.NewTicker(time.Second)
|
||||
defer ticker.Stop()
|
||||
for {
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
return
|
||||
case <-ticker.C:
|
||||
d.DispatchOnce(ctx)
|
||||
}
|
||||
}
|
||||
}
|
||||
func (d *Dispatcher) DispatchOnce(ctx context.Context) {
|
||||
items, err := d.Store.DueWebhooks(ctx, d.Now(), 25)
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
for _, item := range items {
|
||||
d.dispatch(ctx, item)
|
||||
}
|
||||
}
|
||||
func (d *Dispatcher) dispatch(ctx context.Context, item store.WebhookDelivery) {
|
||||
endpoint, err := d.Store.GetWebhookEndpoint(ctx, item.EndpointID)
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
if err = ValidatePublicURL(ctx, endpoint.URL); err != nil {
|
||||
d.fail(ctx, item, err)
|
||||
return
|
||||
}
|
||||
secretBytes, err := base64.RawStdEncoding.DecodeString(endpoint.Secret)
|
||||
if err != nil {
|
||||
d.fail(ctx, item, fmt.Errorf("decode webhook secret: %w", err))
|
||||
return
|
||||
}
|
||||
secret, err := d.Cipher.Decrypt(secretBytes)
|
||||
if err != nil {
|
||||
d.fail(ctx, item, fmt.Errorf("decrypt webhook secret: %w", err))
|
||||
return
|
||||
}
|
||||
timestamp := d.Now().Unix()
|
||||
req, err := http.NewRequestWithContext(ctx, http.MethodPost, endpoint.URL, bytes.NewReader(item.Payload))
|
||||
if err != nil {
|
||||
d.fail(ctx, item, err)
|
||||
return
|
||||
}
|
||||
req.Header.Set("Content-Type", "application/json")
|
||||
req.Header.Set("User-Agent", "MEOVV-Mail-Webhooks/1.0")
|
||||
req.Header.Set("X-MEOVV-Event-ID", item.EventID)
|
||||
req.Header.Set("X-MEOVV-Event", item.EventType)
|
||||
req.Header.Set("X-MEOVV-Timestamp", strconv.FormatInt(timestamp, 10))
|
||||
req.Header.Set("X-MEOVV-Signature", "v1="+Signature(secret, timestamp, item.Payload))
|
||||
resp, err := d.HTTP.Do(req)
|
||||
if err == nil {
|
||||
io.Copy(io.Discard, io.LimitReader(resp.Body, 4096))
|
||||
resp.Body.Close()
|
||||
if resp.StatusCode >= 200 && resp.StatusCode < 300 {
|
||||
_ = d.Store.CompleteWebhook(ctx, item.ID, true, time.Time{}, "")
|
||||
return
|
||||
}
|
||||
err = fmt.Errorf("endpoint returned %s", resp.Status)
|
||||
}
|
||||
d.fail(ctx, item, err)
|
||||
}
|
||||
func (d *Dispatcher) fail(ctx context.Context, item store.WebhookDelivery, err error) {
|
||||
age := d.Now().Sub(item.CreatedAt)
|
||||
if age >= 24*time.Hour {
|
||||
_ = d.Store.CompleteWebhook(ctx, item.ID, false, d.Now().Add(365*24*time.Hour), "retry window expired: "+err.Error())
|
||||
return
|
||||
}
|
||||
delay := time.Duration(math.Min(3600, math.Pow(2, float64(item.Attempt))*15)) * time.Second
|
||||
_ = d.Store.CompleteWebhook(ctx, item.ID, false, d.Now().Add(delay), err.Error())
|
||||
}
|
||||
|
||||
func ValidatePublicURL(ctx context.Context, raw string) error {
|
||||
parsed, err := url.Parse(raw)
|
||||
if err != nil || parsed.Scheme != "https" || parsed.Hostname() == "" {
|
||||
return fmt.Errorf("webhook URL must be public HTTPS")
|
||||
}
|
||||
ips, err := net.DefaultResolver.LookupIP(ctx, "ip", parsed.Hostname())
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
for _, ip := range ips {
|
||||
if ip.IsLoopback() || ip.IsPrivate() || ip.IsLinkLocalUnicast() || ip.IsUnspecified() || ip.IsMulticast() {
|
||||
return fmt.Errorf("webhook URL resolves to a non-public address")
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
@@ -0,0 +1,67 @@
|
||||
package webhook
|
||||
|
||||
import (
|
||||
"context"
|
||||
"path/filepath"
|
||||
"strconv"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/meovv-mail/meovv-mail/internal/store"
|
||||
)
|
||||
|
||||
func TestSignatureAndVerification(t *testing.T) {
|
||||
body := []byte(`{"id":"evt_1"}`)
|
||||
timestamp := time.Now().Unix()
|
||||
signature := Signature("secret", timestamp, body)
|
||||
if !Verify("secret", signature, fmtInt(timestamp), body, 5*time.Minute) {
|
||||
t.Fatal("valid signature was rejected")
|
||||
}
|
||||
if Verify("wrong", signature, fmtInt(timestamp), body, 5*time.Minute) {
|
||||
t.Fatal("wrong secret was accepted")
|
||||
}
|
||||
}
|
||||
|
||||
func TestRetryScheduleStartsAtFifteenSeconds(t *testing.T) {
|
||||
ctx := context.Background()
|
||||
db, err := store.Open(filepath.Join(t.TempDir(), "test.sqlite"))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer db.Close()
|
||||
now := time.Date(2026, 8, 12, 10, 0, 0, 0, time.UTC)
|
||||
endpoint := store.WebhookEndpoint{ID: "wh_1", Name: "test", URL: "https://example.com", Secret: "secret", Events: []string{"message.failed"}, Enabled: true, CreatedAt: now}
|
||||
if err = db.CreateWebhookEndpoint(ctx, endpoint); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err = db.EnqueueEvent(ctx, "evt_1", "message.failed", []byte(`{}`), now); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
items, err := db.DueWebhooks(ctx, now, 10)
|
||||
if err != nil || len(items) != 1 {
|
||||
t.Fatalf("due = %#v, %v", items, err)
|
||||
}
|
||||
dispatcher := &Dispatcher{Store: db, Now: func() time.Time { return now }}
|
||||
dispatcher.fail(ctx, items[0], context.DeadlineExceeded)
|
||||
if due, _ := db.DueWebhooks(ctx, now.Add(14*time.Second), 10); len(due) != 0 {
|
||||
t.Fatal("delivery retried too early")
|
||||
}
|
||||
if due, _ := db.DueWebhooks(ctx, now.Add(15*time.Second), 10); len(due) != 1 {
|
||||
t.Fatal("delivery was not scheduled after 15 seconds")
|
||||
}
|
||||
}
|
||||
|
||||
func TestRejectsPrivateWebhookTargets(t *testing.T) {
|
||||
ctx, cancel := context.WithTimeout(context.Background(), time.Second)
|
||||
defer cancel()
|
||||
if err := ValidatePublicURL(ctx, "http://example.com/hook"); err == nil {
|
||||
t.Fatal("plain HTTP was accepted")
|
||||
}
|
||||
if err := ValidatePublicURL(ctx, "https://127.0.0.1/hook"); err == nil {
|
||||
t.Fatal("loopback target was accepted")
|
||||
}
|
||||
}
|
||||
|
||||
func fmtInt(value int64) string {
|
||||
return strconv.FormatInt(value, 10)
|
||||
}
|
||||
Generated
+5615
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,42 @@
|
||||
{
|
||||
"name": "meovv-mail-web",
|
||||
"version": "0.1.0",
|
||||
"private": true,
|
||||
"description": "Web interface for the MEOVV Mail self-hosted email appliance",
|
||||
"license": "UNLICENSED",
|
||||
"engines": {
|
||||
"node": ">=22.13.0"
|
||||
},
|
||||
"scripts": {
|
||||
"dev": "vite --config vite.frontend.config.ts",
|
||||
"build": "vite build --config vite.frontend.config.ts",
|
||||
"build:web": "npm run build",
|
||||
"start": "vite preview --config vite.frontend.config.ts",
|
||||
"test": "npm run build && node --test tests/rendered-html.test.mjs",
|
||||
"lint": "eslint .",
|
||||
"typecheck": "tsc --noEmit",
|
||||
"check": "npm run lint && npm run typecheck && npm test"
|
||||
},
|
||||
"dependencies": {
|
||||
"dompurify": "^3.4.13",
|
||||
"lucide-react": "^1.31.0",
|
||||
"react": "19.2.6",
|
||||
"react-dom": "19.2.6"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@eslint/js": "9.39.4",
|
||||
"@types/node": "22.19.19",
|
||||
"@types/react": "19.2.14",
|
||||
"@types/react-dom": "19.2.3",
|
||||
"@vitejs/plugin-react": "6.0.2",
|
||||
"eslint": "9.39.4",
|
||||
"eslint-plugin-jsx-a11y": "6.10.2",
|
||||
"eslint-plugin-react": "7.37.5",
|
||||
"eslint-plugin-react-hooks": "7.1.1",
|
||||
"globals": "16.4.0",
|
||||
"typescript": "5.9.3",
|
||||
"typescript-eslint": "8.59.3",
|
||||
"vite": "8.2.1"
|
||||
},
|
||||
"type": "module"
|
||||
}
|
||||
@@ -0,0 +1,14 @@
|
||||
{
|
||||
"schema": 1,
|
||||
"issued_at": "2026-08-12T00:00:00Z",
|
||||
"meovv_version": "0.1.0",
|
||||
"stalwart": {
|
||||
"version": "0.16.17",
|
||||
"image": "stalwartlabs/stalwart:v0.16.17",
|
||||
"digest": "sha256:a8108e19bd927e172d4d8c128907b8dfc93fd180ae8ee07dccdd42cb97eb9dfa"
|
||||
},
|
||||
"platforms": [
|
||||
"linux/amd64",
|
||||
"linux/arm64"
|
||||
]
|
||||
}
|
||||
@@ -0,0 +1,3 @@
|
||||
algorithm: Ed25519
|
||||
encoding: base64-raw
|
||||
public-key: LcI9Tk7sfc6//uMsUiubzg+PY+HCJOZGPV1RVN+JJKs
|
||||
@@ -0,0 +1 @@
|
||||
5DNpgn6TEgGYon4y8ECX5KyP+q3I1xx362//XUipSm8IsQ8dImQ86wBCL3ANzIxwbOPv58gBavxSslLVfd6MBQ
|
||||
@@ -0,0 +1,36 @@
|
||||
import assert from "node:assert/strict";
|
||||
import { access, readFile, readdir } from "node:fs/promises";
|
||||
import test from "node:test";
|
||||
|
||||
test("builds the standalone MEOVV application shell", async () => {
|
||||
const html = await readFile(new URL("../web-dist/index.html", import.meta.url), "utf8");
|
||||
assert.match(html, /<title>MEOVV Mail — Private email, beautifully run<\/title>/i);
|
||||
assert.match(html, /<div id="root"><\/div>/);
|
||||
assert.match(html, /meovv-mail-social\.png/);
|
||||
assert.doesNotMatch(html, /cloudflare|vinext-starter/i);
|
||||
const assets = await readdir(new URL("../web-dist/assets", import.meta.url));
|
||||
assert.ok(assets.some((file) => file.endsWith(".js")));
|
||||
assert.ok(assets.some((file) => file.endsWith(".css")));
|
||||
});
|
||||
|
||||
test("includes production auth, JMAP, sanitization, and responsive UI paths", async () => {
|
||||
const [page, css, openapi, standalone] = await Promise.all([
|
||||
readFile(new URL("../app/page.tsx", import.meta.url), "utf8"),
|
||||
readFile(new URL("../app/globals.css", import.meta.url), "utf8"),
|
||||
readFile(new URL("../api/openapi.yaml", import.meta.url), "utf8"),
|
||||
readFile(new URL("../web-dist/index.html", import.meta.url), "utf8"),
|
||||
]);
|
||||
assert.match(page, /crypto\.subtle\.digest\("SHA-256"/);
|
||||
assert.match(page, /fetch\("\/api\/auth"/);
|
||||
assert.match(page, /fetch\("\/api\/mail\/jmap"/);
|
||||
assert.match(page, /new EventSource\("\/api\/mail\/events"\)/);
|
||||
assert.match(page, /DOMPurify\.sanitize/);
|
||||
assert.match(page, /Remote images are blocked/);
|
||||
assert.match(css, /@media \(max-width: 720px\)/);
|
||||
assert.match(css, /prefers-reduced-motion: reduce/);
|
||||
assert.doesNotMatch(css, /linear-gradient|radial-gradient/);
|
||||
assert.match(openapi, /openapi: 3\.1\.0/);
|
||||
assert.match(openapi, /Idempotency-Key/);
|
||||
assert.match(standalone, /<div id="root"><\/div>/);
|
||||
await access(new URL("../web-dist/assets", import.meta.url));
|
||||
});
|
||||
@@ -0,0 +1,22 @@
|
||||
{
|
||||
"compilerOptions": {
|
||||
"target": "ES2017",
|
||||
"lib": ["dom", "dom.iterable", "esnext"],
|
||||
"allowJs": false,
|
||||
"skipLibCheck": true,
|
||||
"strict": true,
|
||||
"noEmit": true,
|
||||
"esModuleInterop": true,
|
||||
"module": "esnext",
|
||||
"moduleResolution": "bundler",
|
||||
"resolveJsonModule": true,
|
||||
"isolatedModules": true,
|
||||
"jsx": "react-jsx",
|
||||
"incremental": false,
|
||||
"paths": {
|
||||
"@/*": ["./*"]
|
||||
}
|
||||
},
|
||||
"include": ["app/**/*.ts", "app/**/*.tsx", "web/**/*.ts", "web/**/*.tsx", "vite.frontend.config.ts"],
|
||||
"exclude": ["node_modules", "web-dist"]
|
||||
}
|
||||
@@ -0,0 +1,12 @@
|
||||
import react from "@vitejs/plugin-react";
|
||||
import { defineConfig } from "vite";
|
||||
|
||||
export default defineConfig({
|
||||
root: "web",
|
||||
plugins: [react()],
|
||||
build: {
|
||||
outDir: "../web-dist",
|
||||
emptyOutDir: true,
|
||||
sourcemap: false,
|
||||
},
|
||||
});
|
||||
@@ -0,0 +1,20 @@
|
||||
<!doctype html>
|
||||
<html lang="en">
|
||||
<head>
|
||||
<meta charset="UTF-8" />
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
|
||||
<meta name="theme-color" content="#6756e8" />
|
||||
<meta name="description" content="A polished, secure email service that runs on infrastructure you control." />
|
||||
<meta property="og:title" content="MEOVV Mail — Private email, beautifully run" />
|
||||
<meta property="og:description" content="A polished, secure email service that runs on infrastructure you control." />
|
||||
<meta property="og:type" content="website" />
|
||||
<meta property="og:image" content="/meovv-mail-social.png" />
|
||||
<meta name="twitter:card" content="summary_large_image" />
|
||||
<link rel="icon" href="/favicon.svg" />
|
||||
<title>MEOVV Mail — Private email, beautifully run</title>
|
||||
</head>
|
||||
<body>
|
||||
<div id="root"></div>
|
||||
<script type="module" src="/main.tsx"></script>
|
||||
</body>
|
||||
</html>
|
||||
@@ -0,0 +1,6 @@
|
||||
import { StrictMode } from "react";
|
||||
import { createRoot } from "react-dom/client";
|
||||
import Home from "../app/page";
|
||||
import "../app/globals.css";
|
||||
|
||||
createRoot(document.getElementById("root")!).render(<StrictMode><Home /></StrictMode>);
|
||||
@@ -0,0 +1 @@
|
||||
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 64 64"><rect width="64" height="64" rx="17" fill="#6756e8"/><path d="M15 21.5 31.3 34a1.2 1.2 0 0 0 1.4 0L49 21.5M17 18h30a4 4 0 0 1 4 4v21a4 4 0 0 1-4 4H17a4 4 0 0 1-4-4V22a4 4 0 0 1 4-4Z" fill="none" stroke="#fff" stroke-width="4" stroke-linecap="round" stroke-linejoin="round"/></svg>
|
||||
|
After Width: | Height: | Size: 341 B |
Binary file not shown.
|
After Width: | Height: | Size: 767 KiB |
Reference in new issue
Block a user