diff --git a/.changeset/selfhost-smtp.md b/.changeset/selfhost-smtp.md new file mode 100644 index 00000000..0b00ed67 --- /dev/null +++ b/.changeset/selfhost-smtp.md @@ -0,0 +1,11 @@ +--- +"@cloudhal/cli": minor +--- + +The self-host image mails invites and password resets (#291). Set `CLOUDHAL_SMTP_URL` (or `CLOUDHAL_SMTP_URL_FILE`) and `CLOUDHAL_MAIL_FROM`, and the generated workerd config gets an `smtp` Worker behind the admin Worker's `EMAIL` binding, the binding used on Cloudflare. +- It connects with STARTTLS (`smtp://`) or implicit TLS (`smtps://`) only. +- Retries are bounded. +- Its logs carry no message bodies and no credentials. +- `CLOUDHAL_SMTP_CA_FILE` adds certificates to trust. + +The compose file gains a `mail` profile (Mailpit), and the Helm chart gains `mail.*` values. diff --git a/.github/workflows/docker.yml b/.github/workflows/docker.yml index 559803b3..0aefe2da 100644 --- a/.github/workflows/docker.yml +++ b/.github/workflows/docker.yml @@ -11,7 +11,8 @@ name: Docker image # (compose.yml's SeaweedFS, the image's own `secrets`, the first site and owner, a publish live # on the next request, a restart, the Node-volume guard, a second instance taking over while the # first stops), scripts/failover-smoke.ts (three instances, one killed with SIGKILL while a release -# is due, then graceful handoffs under load; #290) and Trivy, which fails the job on a CRITICAL +# is due, then graceful handoffs under load; #290), scripts/mail-smoke.ts (an invite and a reset +# through Mailpit with STARTTLS and AUTH; #291) and Trivy, which fails the job on a CRITICAL # vulnerability with a fix; # - `smoke-arm64` runs the same smoke test on the arm64 image, on GitHub's native arm64 runner; # - `tag` adds the release tags to the very digest that passed, with `imagetools create`, writes @@ -52,6 +53,7 @@ on: - ".github/workflows/docker.yml" - "scripts/docker-smoke.ts" - "scripts/failover-smoke.ts" + - "scripts/mail-smoke.ts" - "scripts/pack-packages.ts" - "scripts/selfhost-edge-bundle.ts" - "packages/cli/src/selfhost/**" @@ -111,11 +113,17 @@ jobs: } > "$RUNNER_TEMP/compose.env" docker compose -f deploy/docker/compose.yml --env-file "$RUNNER_TEMP/compose.env" config --quiet docker compose -f deploy/docker/compose.yml --env-file "$RUNNER_TEMP/compose.env" --profile caddy config --quiet + docker compose -f deploy/docker/compose.yml --env-file "$RUNNER_TEMP/compose.env" --profile mail config --quiet - name: Lint the Helm chart run: | helm lint deploy/helm/cloudhal helm lint deploy/helm/cloudhal --set replicaCount=3 --set baseUrl=https://studio.example.com --set ingress.enabled=true helm template t deploy/helm/cloudhal --set httpRoute.enabled=true --set baseUrl=https://studio.example.com --set 'httpRoute.parentRefs[0].name=gw' > /dev/null + helm template t deploy/helm/cloudhal --set mail.smtpUrlSecret.name=smtp --set mail.from=cloudhal@example.com --set mail.caConfigMap.name=ca \ + | grep -q 'CLOUDHAL_SMTP_CA_FILE' || { echo "::error::the chart's mail values render no CLOUDHAL_SMTP_CA_FILE"; exit 1; } + if helm template t deploy/helm/cloudhal --set mail.smtpUrlSecret.name=smtp > /dev/null 2>&1; then + echo "::error::mail.smtpUrlSecret without mail.from must fail"; exit 1 + fi - name: The kustomize base matches the chart run: scripts/kustomize-base.sh --check # The stores the recipes offer, against what workerd's cluster and R2 binding need @@ -251,6 +259,11 @@ jobs: - name: Cluster failover test timeout-minutes: 20 run: node scripts/failover-smoke.ts --image cloudhal:ci + # Mail (#291): Mailpit requiring STARTTLS and AUTH; an invite and a password reset arrive, and + # the log names each send without the password or a token. CI only, like the failover test. + - name: Mail smoke test (Mailpit) + timeout-minutes: 10 + run: node scripts/mail-smoke.ts --image cloudhal:ci - name: Trivy scan timeout-minutes: 15 uses: aquasecurity/trivy-action@ed142fd0673e97e23eac54620cfb913e5ce36c25 # v0.36.0 diff --git a/AGENTS.md b/AGENTS.md index a169893b..c3b6c63f 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -33,7 +33,7 @@ node scripts/release-bundle.ts build|verify … # RFC-0046 release bundle: det - `packages/core-ts` — `SiteGraphStore` (CAS on `rev`, snapshots, diff, publish, rollback). Behavioural suite in `src/testing.ts` runs on sqlite and Miniflare D1. `./local` opens the offline store; `seedStarterSite` seeds a demo. `./surfaces` is RFC-0020's generative UI: the catalog (primitives + block types), eval-free surface checks, bindings, repairs, JSON Patch (`patchPage`), `catalogPrompt`; `./interop` converts A2UI v0.9 and json-render to and from surfaces; `./design` is RFC-0021's DESIGN.md lint and guidance. `./fields` is RFC-0041's typed custom fields (definition and value checks, `resolveFields`, `formatFieldValue`, the agents' JSON Schema, the conversion table); `src/fields-operations/` runs rename/retype/localize/remove. `search.ts` is RFC-0019's FTS5 site search (index written with the publish batch; articles, pages, terms and authors, RFC-0029); `search-provider.ts` is RFC-0029's `SearchProvider` (`fts5`, `memory`, `withFallback`), set with `SiteGraphStoreOptions.search`; `search-ai.ts` is the experimental Cloudflare AI Search provider (`hybridProvider`, `searchProviderFromEnv`, `cloudhal.json` `search`, docs/guides/search.md). - `packages/schedules` — RFC-0008: time model (only `temporal-polyfill/implementation`, `now` injected, never `Temporal.Now`), RRULE subset, release model (`rl1:`), automation/run state, taint and budgets, `runDue`; `./sql` is `SqlScheduleStore`, `./engine` the Temporal-free part core-ts and the site Worker use. Worker-safe; conformance suites in `src/testing.ts` on sqlite and Miniflare D1. - `packages/astro-renderer` — `GraphSource` (live/snapshot), `cloudhal()` integration (virtual config + dev route-cache watcher), `.astro` section components (`Surface.astro` for RFC-0020 surfaces; `./surfaces` renders them, `./kit` has the table of contents and reading time; `./fields` and `EntryFields.astro` render typed field values, RFC-0041). `./status-page` is RFC-0043's status pages (`statusPage(state, input) → Response`, served by the Site Worker entry before Astro and by `cloudhal dev` at `/__cloudhal/status/`; the optional `statusPage` theme hook; the catalog in `src/status-strings/` where only `en.ts` is hand-edited and the other languages come from `pnpm i18n:import`). Routes live in starters, not here. -- `packages/cli` — the `cloudhal` CLI (`init`, `dev`, `studio`, `mcp`, `deploy`, `push`, `pull`, `export`, `import`, …; every command is in `src/cli/help.ts`, which `cloudhal --help` prints and the docs site's CLI reference is generated from); TS bin run by Node 24 type stripping. `src/cli.ts` parses flags and dispatches through `COMMANDS`, built from `src/cli/commands-{local,remote,content,ops,site}.ts` (a new command is one handler plus one line in `src/cli/help.ts`). `src/archive/` is RFC-0039's `.cloudhal` container (tar, gzip, manifest, limits), read and written by `src/commands/export.ts` and `import*.ts` (`archive-bundle.ts`, `archive-reassemble.ts`); the starter demo archive `test/fixtures/site-archives/starter-blog.cloudhal` is written by `pnpm demo:archive`, and `pnpm check` fails when it is stale. E2E test spawns the bin (Astro disables dev middleware under `VITEST`). Cloudflare tests run both Workers on workerd via wrangler's `createTestHarness`; test files run serially (shared starter caches). `src/commands/deploy/release/` is RFC-0046 §11b's `deploy --release`: the signed key and yank lists (`trust.ts`, the yank memory in `~/.cloudhal/release-trust.json`), the release lookup and download, the theme check against the CLI's starter (`theme-check.ts`; recheck its build-input list on every Astro or Vite major), the build keys of `src/config-build-keys.ts`, extraction and the `no_bundle` wrangler configs; tests use `@cloudhal/release-verify`'s synthetic bundle (`test/fixtures/release-deploy.ts`), never the network. `src/selfhost/` is RFC-0047's self-host image on workerd (`cloudhal selfhost fetch|check|config|secrets|start`): the settings (`_FILE` secrets), the generated Cap'n Proto config (Durable Object `uniqueKey`s are constants, never change them), the bundle check, the Node-volume guard and the first site; `deploy/docker/workerd/` pins workerd (an npm lockfile Dependabot bumps weekly, ADR-0047; never the Miniflare pin), `scripts/docker-smoke.ts` runs it on SeaweedFS. +- `packages/cli` — the `cloudhal` CLI (`init`, `dev`, `studio`, `mcp`, `deploy`, `push`, `pull`, `export`, `import`, …; every command is in `src/cli/help.ts`, which `cloudhal --help` prints and the docs site's CLI reference is generated from); TS bin run by Node 24 type stripping. `src/cli.ts` parses flags and dispatches through `COMMANDS`, built from `src/cli/commands-{local,remote,content,ops,site}.ts` (a new command is one handler plus one line in `src/cli/help.ts`). `src/archive/` is RFC-0039's `.cloudhal` container (tar, gzip, manifest, limits), read and written by `src/commands/export.ts` and `import*.ts` (`archive-bundle.ts`, `archive-reassemble.ts`); the starter demo archive `test/fixtures/site-archives/starter-blog.cloudhal` is written by `pnpm demo:archive`, and `pnpm check` fails when it is stale. E2E test spawns the bin (Astro disables dev middleware under `VITEST`). Cloudflare tests run both Workers on workerd via wrangler's `createTestHarness`; test files run serially (shared starter caches). `src/commands/deploy/release/` is RFC-0046 §11b's `deploy --release`: the signed key and yank lists (`trust.ts`, the yank memory in `~/.cloudhal/release-trust.json`), the release lookup and download, the theme check against the CLI's starter (`theme-check.ts`; recheck its build-input list on every Astro or Vite major), the build keys of `src/config-build-keys.ts`, extraction and the `no_bundle` wrangler configs; tests use `@cloudhal/release-verify`'s synthetic bundle (`test/fixtures/release-deploy.ts`), never the network. `src/selfhost/` is RFC-0047's self-host image on workerd (`cloudhal selfhost fetch|check|config|secrets|start`): the settings (`_FILE` secrets), the generated Cap'n Proto config (Durable Object `uniqueKey`s are constants, never change them), the bundle check, the Node-volume guard, the first site and the SMTP sender behind `EMAIL` (`smtp-*.ts`, #291: STARTTLS or TLS only; `smtp-client.ts` has no imports because the config embeds it as a Worker module); `deploy/docker/workerd/` pins workerd (an npm lockfile Dependabot bumps weekly, ADR-0047; never the Miniflare pin), `scripts/docker-smoke.ts` runs it on SeaweedFS. - `packages/cloudflare` — the admin Worker (`createAdminWorker`); `./playground` is RFC-0036's playground Worker (`createPlaygroundWorker`, the `PlaygroundSite` Durable Object, signed session cookies). Generated entries must import `@cloudhal/cloudflare/workerd-prelude` first (ADR-0012). - `packages/agent-runtime` / `packages/mcp-server` — policy, skills, audit; MCP tools and transports (ADR-0011). `@cloudhal/mcp-server/render` is RFC-0021's `render_page` core: a small DevTools client, the in-page checks and limits; the CLI drives local Chrome with it (`render-chrome.ts`), the admin Worker Browser Rendering (`browser-render.ts`). - `starters/blog` — the theme boundary: `src/pages/[...path].astro`, `src/layouts`, `src/theme.ts`. diff --git a/deploy/docker/.env.example b/deploy/docker/.env.example index 8be84f40..d37ea3c8 100644 --- a/deploy/docker/.env.example +++ b/deploy/docker/.env.example @@ -36,5 +36,17 @@ # uploads after a day. #CLOUDHAL_S3_LIFECYCLE=on +# Mail: invites and password resets by email. Off unless CLOUDHAL_SMTP_URL is set (or +# CLOUDHAL_SMTP_URL_FILE names a file holding it). smtp:// is STARTTLS (port 587 by default), +# smtps:// TLS from the start (465); a server without STARTTLS is refused, never used unencrypted. +# CLOUDHAL_MAIL_FROM is the one sender address; CLOUDHAL_SMTP_CA_FILE adds certificates to trust. +#CLOUDHAL_SMTP_URL=smtp://user:password@smtp.example.com:587 +#CLOUDHAL_MAIL_FROM=cloudhal@example.com +#CLOUDHAL_MAIL_FROM_NAME=Cloudhal +#CLOUDHAL_SMTP_CA_FILE= +# The mail profile (Mailpit, http://127.0.0.1:8025) instead: `docker compose --profile mail up -d`. +#CLOUDHAL_SMTP_URL=smtp://cloudhal:mailpit@mailpit:1025 +#CLOUDHAL_SMTP_CA_FILE=/run/cloudhal-mail/cert.pem + # Traces of every Worker invocation to an OTLP/HTTP collector. #OTEL_EXPORTER_OTLP_ENDPOINT=http://otel-collector:4318 diff --git a/deploy/docker/README.md b/deploy/docker/README.md index c1e1763a..069e2228 100644 --- a/deploy/docker/README.md +++ b/deploy/docker/README.md @@ -14,7 +14,9 @@ The official self-host image, `ghcr.io/cloudhal-dev/cloudhal`, built from each r 3. checks the bundle; 4. writes the workerd config and runs workerd, passing one SIGTERM on; 5. creates the site under `CLOUDHAL_SITE_ID`. -- **`compose.yml`, `.env.example`, `Caddyfile`:** Cloudhal with SeaweedFS and a one-shot that creates the bucket. With the `caddy` profile, Caddy proxies both hosts with TLS and sets `CF-Connecting-IP`. +- **`compose.yml`, `.env.example`, `Caddyfile`:** Cloudhal with SeaweedFS and a one-shot that creates the bucket. + - With the `caddy` profile, Caddy proxies both hosts with TLS and sets `CF-Connecting-IP`. + - With the `mail` profile, Mailpit catches every message at http://127.0.0.1:8025. It requires STARTTLS, with a certificate the `mail-tls` one-shot makes once. Build a release: @@ -30,4 +32,4 @@ node scripts/pack-packages.ts deploy/docker/tarballs && pnpm --filter @cloudhal/ `node scripts/docker-smoke.ts --image cloudhal:local` runs what CI runs after every build (`.github/workflows/docker.yml`); `--platform linux/arm64` runs the other architecture where Docker can. -`scripts/failover-smoke.ts` is the cluster failover test (#290): three instances, one killed with SIGKILL while a release is due, then graceful handoffs under load. It runs in CI only and refuses to start anywhere else. +`scripts/failover-smoke.ts` is the cluster failover test (#290): three instances, one killed with SIGKILL while a release is due, then graceful handoffs under load. It runs in CI only and refuses to start anywhere else. So does `scripts/mail-smoke.ts` (#291), which sends an invite and a password reset through Mailpit with STARTTLS and AUTH required. diff --git a/deploy/docker/compose.yml b/deploy/docker/compose.yml index 4936b60e..6fac14fd 100644 --- a/deploy/docker/compose.yml +++ b/deploy/docker/compose.yml @@ -5,6 +5,8 @@ # docker compose up -d Studio on http://localhost:8787, the site on :8788 # docker compose --profile caddy up -d + Caddy with automatic TLS for CLOUDHAL_BASE_URL # (Studio) and CLOUDHAL_SITE_URL (the site) +# docker compose --profile mail up -d + Mailpit, which catches every mail Cloudhal sends +# (http://127.0.0.1:8025; see the mailpit service) # Every instance of an installation needs the same .env; this file runs one instance (the cluster # of one). More instances: deploy/swarm or deploy/helm. x-store: &store @@ -50,8 +52,17 @@ services: CLOUDHAL_SITE_NAME: ${CLOUDHAL_SITE_NAME:-My site} CLOUDHAL_AUTOMATIONS: ${CLOUDHAL_AUTOMATIONS:-} OTEL_EXPORTER_OTLP_ENDPOINT: ${OTEL_EXPORTER_OTLP_ENDPOINT:-} + # Mail (invites, password resets): off unless CLOUDHAL_SMTP_URL is set. smtp:// is STARTTLS, + # smtps:// TLS from the start; there is no unencrypted mode. CLOUDHAL_SMTP_CA_FILE adds + # certificates to trust (the mail profile's, a private relay's). + CLOUDHAL_SMTP_URL: ${CLOUDHAL_SMTP_URL:-} + CLOUDHAL_SMTP_CA_FILE: ${CLOUDHAL_SMTP_CA_FILE:-} + CLOUDHAL_MAIL_FROM: ${CLOUDHAL_MAIL_FROM:-} + CLOUDHAL_MAIL_FROM_NAME: ${CLOUDHAL_MAIL_FROM_NAME:-} volumes: - cloudhal-data:/data + # The mail profile's certificate (empty without the profile). + - mail-tls:/run/cloudhal-mail:ro read_only: true tmpfs: - /tmp @@ -109,6 +120,42 @@ services: - caddy-data:/data - caddy-config:/config + # The mail profile: Mailpit catches every message at http://127.0.0.1:8025 and sends nothing on. + # It requires STARTTLS, with a certificate mail-tls makes once. Set in .env (.env.example): + # CLOUDHAL_SMTP_URL=smtp://cloudhal:mailpit@mailpit:1025 + # CLOUDHAL_SMTP_CA_FILE=/run/cloudhal-mail/cert.pem + # CLOUDHAL_MAIL_FROM=cloudhal@example.com + mail-tls: + profiles: [mail] + image: alpine/openssl:3.5.9@sha256:b5d60ce9b9a318fa4efda9b0cd2111fa1e536342072885e8e2ce37c40f653ed9 + entrypoint: ["/bin/sh", "-c"] + command: + - | + [ -s /tls/cert.pem ] && exit 0 + openssl req -x509 -newkey ec -pkeyopt ec_paramgen_curve:P-256 -nodes -days 3650 \ + -subj /CN=mailpit -addext subjectAltName=DNS:mailpit \ + -keyout /tls/key.pem -out /tls/cert.pem && chmod 644 /tls/key.pem /tls/cert.pem + volumes: + - mail-tls:/tls + + mailpit: + profiles: [mail] + image: axllent/mailpit:v1.34.0@sha256:23a2ef85bc50853ab3093645d1d64679afd8887e89da5e48a88940c172591a4e + restart: unless-stopped + depends_on: + mail-tls: + condition: service_completed_successfully + environment: + MP_SMTP_TLS_CERT: /tls/cert.pem + MP_SMTP_TLS_KEY: /tls/key.pem + MP_SMTP_REQUIRE_STARTTLS: "true" + # Any user and password: it is a catcher, not a relay. + MP_SMTP_AUTH_ACCEPT_ANY: "true" + ports: + - "127.0.0.1:${MAILPIT_PORT:-8025}:8025" + volumes: + - mail-tls:/tls:ro + volumes: # Each instance's Durable Object files (they replicate through the store) and the v2 marker. cloudhal-data: @@ -118,3 +165,4 @@ volumes: name: ${CLOUDHAL_STORE_VOLUME:-cloudhal-store} caddy-data: caddy-config: + mail-tls: diff --git a/deploy/helm/cloudhal/README.md b/deploy/helm/cloudhal/README.md index 0170832b..58299dd9 100644 --- a/deploy/helm/cloudhal/README.md +++ b/deploy/helm/cloudhal/README.md @@ -54,6 +54,23 @@ helm install cloudhal deploy/helm/cloudhal --set store.enabled=false \ The store must enforce conditional writes. That covers AWS S3, GCS's XML API, R2 and RustFS, but not MinIO's archived community edition or Garage. Give the bucket a lifecycle rule that aborts incomplete multipart uploads. +## Mail + +Invites and password resets go by email once the chart knows an SMTP server. Keep its URL in a Secret of your own, then name it and the sender address: + +```bash +kubectl create secret generic cloudhal-smtp --from-literal=CLOUDHAL_SMTP_URL='smtp://user:password@smtp.example.com:587' +``` + +```bash +helm upgrade cloudhal deploy/helm/cloudhal --reuse-values \ + --set mail.smtpUrlSecret.name=cloudhal-smtp --set mail.from=cloudhal@example.com +``` + +- `smtp://` means STARTTLS, and a server that does not offer it is refused. `smtps://` means TLS from the first byte. There is no unencrypted mode. +- For a relay whose certificate no browser trusts, put its CA in a ConfigMap and set `mail.caConfigMap.name` (key `ca.pem` by default). +- The pods connect to the server themselves. Under an egress NetworkPolicy of your own, allow its port. + ## Upgrades ```bash diff --git a/deploy/helm/cloudhal/templates/statefulset.yaml b/deploy/helm/cloudhal/templates/statefulset.yaml index c0537a15..2bc56724 100644 --- a/deploy/helm/cloudhal/templates/statefulset.yaml +++ b/deploy/helm/cloudhal/templates/statefulset.yaml @@ -72,6 +72,23 @@ spec: - name: OTEL_EXPORTER_OTLP_ENDPOINT value: {{ . | quote }} {{- end }} + {{- with .Values.mail.smtpUrlSecret.name }} + - name: CLOUDHAL_SMTP_URL + valueFrom: + secretKeyRef: + name: {{ . | quote }} + key: {{ $.Values.mail.smtpUrlSecret.key | quote }} + - name: CLOUDHAL_MAIL_FROM + value: {{ required "mail.from is required with mail.smtpUrlSecret.name" $.Values.mail.from | quote }} + {{- with $.Values.mail.fromName }} + - name: CLOUDHAL_MAIL_FROM_NAME + value: {{ . | quote }} + {{- end }} + {{- if $.Values.mail.caConfigMap.name }} + - name: CLOUDHAL_SMTP_CA_FILE + value: "/etc/cloudhal/smtp-ca/{{ $.Values.mail.caConfigMap.key }}" + {{- end }} + {{- end }} {{- with .Values.extraEnv }} {{- toYaml . | nindent 12 }} {{- end }} @@ -109,11 +126,21 @@ spec: mountPath: /data - name: tmp mountPath: /tmp + {{- if and .Values.mail.smtpUrlSecret.name .Values.mail.caConfigMap.name }} + - name: smtp-ca + mountPath: /etc/cloudhal/smtp-ca + readOnly: true + {{- end }} volumes: - name: tmp emptyDir: medium: Memory sizeLimit: 16Mi + {{- if and .Values.mail.smtpUrlSecret.name .Values.mail.caConfigMap.name }} + - name: smtp-ca + configMap: + name: {{ .Values.mail.caConfigMap.name | quote }} + {{- end }} {{- if not .Values.persistence.enabled }} - name: data emptyDir: {} diff --git a/deploy/helm/cloudhal/values.yaml b/deploy/helm/cloudhal/values.yaml index 0c0a6bd1..500d7ebe 100644 --- a/deploy/helm/cloudhal/values.yaml +++ b/deploy/helm/cloudhal/values.yaml @@ -87,6 +87,22 @@ otel: # http://otel-collector.observability:4318 endpoint: "" +# Mail (invites and password resets by email): off unless smtpUrlSecret.name is set. The URL is +# smtp://user:password@host:587 (STARTTLS) or smtps://user:password@host:465 (TLS from the start); +# a server without STARTTLS is refused. Keep it in a Secret of your own: +# kubectl create secret generic cloudhal-smtp --from-literal=CLOUDHAL_SMTP_URL='smtp://…' +mail: + # The one sender address (required with smtpUrlSecret). + from: "" + fromName: "" + smtpUrlSecret: + name: "" + key: CLOUDHAL_SMTP_URL + # A ConfigMap with PEM certificates to trust besides the browser CAs (a private relay). + caConfigMap: + name: "" + key: ca.pem + # Extra environment for the Cloudhal container (CLOUDHAL_AUTOMATIONS, …). extraEnv: [] diff --git a/deploy/swarm/README.md b/deploy/swarm/README.md index 763e726b..f6b03497 100644 --- a/deploy/swarm/README.md +++ b/deploy/swarm/README.md @@ -36,4 +36,11 @@ - **Peer traffic** (port 7000) travels on the stack's own overlay, `10.231.0.0/24`, which is `encrypted`. Each task advertises its address there (`CLOUDHAL_CLUSTER_ADVERTISE=auto:10.231.0.0/24`). If that subnet is taken in your swarm, change it in both places. - **Working copies:** each task's `/data` is a volume named `cloudhal-data-` on the node it runs on. It holds only working copies; the store holds the installation, so back up the `cloudhal-store` volume (guide, "Backup and restore"). - **TLS:** put a TLS proxy or load balancer in front of ports 8787 and 8788. It must append the client's address to `X-Forwarded-For`. Then set `CLOUDHAL_BASE_URL` and `CLOUDHAL_BEHIND_PROXY=1` when you deploy. The routing mesh hides the client's address, so without a proxy rate limits share one bucket per path. +- **Mail:** keep the SMTP URL as a Docker secret, not in the stack's environment: + + ```bash + printf '%s' 'smtp://user:password@smtp.example.com:587' | docker secret create cloudhal_smtp_url - + ``` + + Then add `cloudhal_smtp_url` to the `cloudhal` service's `secrets` and to the file's `secrets:` list (`external: true`), and set `CLOUDHAL_SMTP_URL_FILE: /run/secrets/cloudhal_smtp_url` and `CLOUDHAL_MAIL_FROM` in its `environment`. `smtp://` is STARTTLS and `smtps://` TLS from the start; a server without STARTTLS is refused. Without the secret, mail stays off. - **External store:** to use an external S3 store, set `CLOUDHAL_S3_ENDPOINT` and the bucket, put its keys in the two `cloudhal_aws_*` secrets, and remove the `seaweedfs` service. diff --git a/docs/guides/self-host.md b/docs/guides/self-host.md index 7f8a44fa..1a53bc84 100644 --- a/docs/guides/self-host.md +++ b/docs/guides/self-host.md @@ -50,7 +50,7 @@ Run it once per installation and keep the file. Every instance needs the same va - The first start runs the database migrations and creates the installation's site, named after `CLOUDHAL_SITE_NAME`, from the blog starter. Nothing is published yet, so the site answers the "coming soon" page with 503 until the first publish. - The log (`docker compose logs cloudhal`) prints the setup link, `http://localhost:8787/login#setup=`. Put the value of `CLOUDHAL_SETUP_TOKEN` from `.env` in place of the placeholder, open the link and create the Owner account. Without the token, sign-up is refused, so nobody who reaches the port first can claim the installation. -After that, sign-up closes and everyone else joins by invite. Invites and password resets are links that Studio's Team page makes and you pass on yourself (see [limits](#limits)). +After that, sign-up closes and everyone else joins by invite. Without a mail server, invites and password resets are links that Studio's Team page makes and you pass on yourself. With one, Studio mails them ([mail](#mail)). Agents connect to the MCP endpoint at `/mcp` with an agent key made in Studio, or through OAuth ([connect an agent](../agents/clients.md)). @@ -108,6 +108,9 @@ location / { | `CLOUDHAL_BASE_URL`, `CLOUDHAL_BEHIND_PROXY` | As above. | | `CLOUDHAL_SITE_NAME` | The name of the site the first start creates. | | `CLOUDHAL_AUTOMATIONS` | `off` turns scheduled automations off. | +| `CLOUDHAL_SMTP_URL` | The SMTP server for invites and password resets ([mail](#mail)): `smtp://user:password@host:587` (STARTTLS) or `smtps://…:465`. `_FILE` works too. Unset, mail is off. | +| `CLOUDHAL_MAIL_FROM`, `CLOUDHAL_MAIL_FROM_NAME` | The one sender address mail goes out from, and its display name. The address is required with `CLOUDHAL_SMTP_URL`. | +| `CLOUDHAL_SMTP_CA_FILE` | PEM certificates to trust besides the browser CAs, for a relay with a private CA. | | `OTEL_EXPORTER_OTLP_ENDPOINT` | Traces of every Worker invocation to an OTLP/HTTP collector. | | `CLOUDHAL_BIND`, `CLOUDHAL_PORT`, `CLOUDHAL_SITE_PORT` | Compose only: the host address and ports for Studio (8787) and the site (8788). | @@ -166,6 +169,34 @@ The cluster runs on workerd's experimental cluster mode, so treat several instan `scripts/swarm-smoke.sh` and `scripts/helm-smoke.sh` (kind) run both recipes in CI with every image. Each smoke test covers a publish that is live on the next request and a rolling update while the site is polled. +## Mail + +Set `CLOUDHAL_SMTP_URL` and `CLOUDHAL_MAIL_FROM`, and Studio mails invites and password-reset links. Without them it makes links you pass on yourself, as before. + +```bash +CLOUDHAL_SMTP_URL=smtp://user:password@smtp.example.com:587 +CLOUDHAL_MAIL_FROM=cloudhal@example.com +``` + +- **Encrypted only.** `smtp://` means STARTTLS: a server that does not offer it is refused before anything is sent, credentials included. `smtps://` means TLS from the first byte. Certificates are checked against the browser CAs, plus those in `CLOUDHAL_SMTP_CA_FILE`. +- **Bounded.** Each reply has 10 s and each attempt 20 s. A refused connection, a timeout or a 4xx answer is tried twice more, after 1 s and 3 s. A 5xx answer (bad credentials, an unknown recipient) is final, and Studio shows its code. +- **Logs** carry one line per attempt: the recipient's domain, the server and the outcome. They never carry the message, its links or the credentials. +- **The sender** is a small Worker in the image, behind the same `EMAIL` binding the admin Worker uses on Cloudflare. It may send only from `CLOUDHAL_MAIL_FROM`, and it is the only Worker that opens connections of its own. + +**Trying it out:** the compose file's `mail` profile runs [Mailpit](https://mailpit.axllent.org), which catches every message and sends nothing on. Its web UI is at http://127.0.0.1:8025. Add these to `.env`: + +```bash +CLOUDHAL_SMTP_URL=smtp://cloudhal:mailpit@mailpit:1025 +CLOUDHAL_SMTP_CA_FILE=/run/cloudhal-mail/cert.pem +CLOUDHAL_MAIL_FROM=cloudhal@example.com +``` + +```bash +docker compose --profile mail up -d +``` + +CI sends an invite and a password reset through Mailpit with every image, with STARTTLS and SMTP AUTH required ([`scripts/mail-smoke.ts`](https://github.com/cloudhal-dev/cloudhal/blob/main/scripts/mail-smoke.ts)). + ## Upgrades The image carries the same version as the npm packages and the release bundle. Tags are `X.Y.Z`, `X.Y` and `latest`; in production, pin `X.Y` (`CLOUDHAL_TAG=0.11`). @@ -214,7 +245,6 @@ For one site rather than the installation, `cloudhal export` writes a portable ` ## Limits -- **Mail.** There is no mail sender yet. Invites and password resets are links made on Studio's Team page and passed on by hand. An SMTP sender is the next step (RFC-0047 §6). - **`render_page`** (the agents' screenshot tool) needs a browser, which the image does not carry, so the tool reports itself unavailable. A Chrome sidecar is planned. - **One site** per installation for now (RFC-0047 decision 2). - **No edge cache.** Every page renders on request. Put a CDN in front if you need one. A shared cache with purge on publish is a later step. diff --git a/docs/rfcs/0047-self-host-on-workerd.md b/docs/rfcs/0047-self-host-on-workerd.md index 0262cdaf..d4bc35fb 100644 --- a/docs/rfcs/0047-self-host-on-workerd.md +++ b/docs/rfcs/0047-self-host-on-workerd.md @@ -143,7 +143,7 @@ The site Worker needs the site's id in its config (`CLOUDHAL_SITE_ID`). Open que | edge cache (`cache: true`) | not used: the site Worker reports "no edge cache in this runtime" and sends `no-store` semantics | a CDN or the proxy in front may cache. The shared Cache API is a later, measured step (open question 3) | | `ANALYTICS` analytics engine, `ANALYTICS_SQL` | absent (optional bindings) | analytics off on self-host for now | | `ANALYTICS_RL`, `COMMENTS_RL` ratelimit | `/workerd/ratelimit.js` | counts are per process, not per cluster; acceptable for these soft limits | -| `EMAIL` send_email | **new:** an SMTP sender Worker (`CLOUDHAL_SMTP_URL`) behind the same binding | follow-up PR, removes the "no mail" limit | +| `EMAIL` send_email | **new:** an SMTP sender Worker (`CLOUDHAL_SMTP_URL`) behind the same binding | *Done (#291):* the `smtp` Worker's default entrypoint has the binding's `send` (JS RPC), over STARTTLS or implicit TLS only, through its own `smtp-network` | | `BROWSER` | **new:** optional Chrome sidecar over CDP | follow-up PR, removes the "no `render_page`" limit | | `AI` | REST with `CLOUDHAL_AI_TOKEN`, as today | unchanged | diff --git a/packages/cli/src/selfhost/settings.ts b/packages/cli/src/selfhost/settings.ts index f70b3d55..38628fdd 100644 --- a/packages/cli/src/selfhost/settings.ts +++ b/packages/cli/src/selfhost/settings.ts @@ -7,6 +7,7 @@ */ import { readFileSync } from "node:fs"; import { resolveAdvertise } from "./advertise.ts"; +import { type MailSettings, readMailSettings } from "./smtp-settings.ts"; /** The manifest's secrets (RFC-0046 `bindingTemplates.*.secrets`) the image requires. */ export const REQUIRED_SECRETS = [ @@ -49,6 +50,8 @@ export interface SelfhostSettings { readonly otlp: string | undefined; /** Optional admin vars passed through when set (`CLOUDHAL_AUTOMATIONS`, …). */ readonly adminVars: Readonly>; + /** The SMTP sender behind `EMAIL` (#291), when `CLOUDHAL_SMTP_URL` is set. */ + readonly mail: MailSettings | undefined; } export type Env = Readonly>; @@ -70,6 +73,7 @@ export function resolveSecretFiles( ...STORE_SECRETS, "CLOUDHAL_CLUSTER_KEY", "CLOUDHAL_SITE_ID", + "CLOUDHAL_SMTP_URL", ]) { const file = env[`${name}_FILE`]; if (file === undefined || file === "") continue; @@ -124,8 +128,12 @@ function problems(env: Env): string[] { } /** The settings, or one error listing every problem. `env` has its `_FILE`s resolved. */ -export function readSettings(env: Env): SelfhostSettings { +export function readSettings( + env: Env, + read: (file: string) => string = (f) => readFileSync(f, "utf8"), +): SelfhostSettings { const found = problems(env); + const mail = readMailSettings(env, found, read); if (found.length > 0) throw new Error(`the self-host settings are incomplete:\n - ${found.join("\n - ")}`); const prefix = (env.CLOUDHAL_S3_PREFIX ?? "").replace(/^\/+/, ""); @@ -155,5 +163,6 @@ export function readSettings(env: Env): SelfhostSettings { }, otlp: env.OTEL_EXPORTER_OTLP_ENDPOINT ? hostPort(env.OTEL_EXPORTER_OTLP_ENDPOINT) : undefined, adminVars, + mail, }; } diff --git a/packages/cli/src/selfhost/smtp-client.ts b/packages/cli/src/selfhost/smtp-client.ts new file mode 100644 index 00000000..db520bdf --- /dev/null +++ b/packages/cli/src/selfhost/smtp-client.ts @@ -0,0 +1,443 @@ +/** + * #291: the SMTP client behind the self-host image's `EMAIL` binding (RFC-0047 §6). The admin + * Worker calls `env.EMAIL.send({ to, from, subject, text, html?, headers? })`, the structured send + * of Cloudflare's `send_email` binding. On self-host, `EMAIL` is a service binding to the SMTP + * sender Worker (`smtp-service.ts`), whose `send` runs `sendMail` here. + * + * - **Encrypted only.** `smtp://` means STARTTLS: a server that does not offer it is refused before + * anything else is sent, credentials included. `smtps://` means TLS from the first byte. There is + * no plain mode. + * - **Bounded.** Each reply has a deadline, and so does each attempt. A connection failure, a + * timeout or a 4xx reply is retried after each of `delaysMs`; a 5xx reply is final. + * - **Logs carry no bodies and no credentials.** One line per attempt: the recipient's domain, the + * server, the outcome, and the first line of the server's reply when it refused. + * + * Self-contained on purpose: no imports, so the config can embed this file as a Worker module + * (compiled `.js` in the image, type-stripped `.ts` from a checkout) and tests can import it. + */ + +export interface SmtpTarget { + host: string; + port: number; + /** `starttls` for `smtp://`, `implicit` for `smtps://`. */ + tls: "starttls" | "implicit"; + user?: string; + pass?: string; +} + +/** The structured message of the `send_email` binding (`@cloudhal/cloudflare`'s `mail.ts`). */ +export interface StructuredMail { + to: string; + from: { email: string; name?: string }; + subject: string; + text: string; + html?: string; + headers?: Record; +} + +/** The part of a `cloudflare:sockets` Socket the client uses. */ +export interface SmtpSocket { + readable: ReadableStream; + writable: WritableStream; + close(): unknown; + startTls(): SmtpSocket; +} + +export type SmtpConnect = ( + address: { hostname: string; port: number }, + options: { secureTransport: "on" | "starttls"; allowHalfOpen: boolean }, +) => SmtpSocket; + +export interface SendMailOptions { + /** `CLOUDHAL_SMTP_URL`. */ + url: string; + /** `CLOUDHAL_MAIL_FROM`: the one sender address allowed. */ + from: string; + /** The name this client gives in `EHLO`. */ + helo: string; + connect: SmtpConnect; + log?: (line: string) => void; + sleep?: (ms: number) => Promise; + /** Waits before the 2nd, 3rd, … attempt. */ + delaysMs?: readonly number[]; + replyTimeoutMs?: number; + attemptTimeoutMs?: number; +} + +export const DEFAULT_DELAYS_MS: readonly number[] = [1000, 3000]; +const REPLY_TIMEOUT_MS = 10_000; +const ATTEMPT_TIMEOUT_MS = 20_000; +const MAX_LINE = 4096; +const MAX_REPLY_LINES = 100; + +/** A failed send. `code` matches `MailError`'s `E_…` format; `transient` sends are retried. */ +export class SmtpError extends Error { + code: string; + transient: boolean; + constructor(code: string, message: string, transient: boolean) { + super(`${code}: ${message}`); + this.name = "SmtpError"; + this.code = code; + this.transient = transient; + } +} + +/** `smtp://user:password@host:587` (STARTTLS) or `smtps://…@host:465` (implicit TLS). */ +export function parseSmtpUrl(raw: string): SmtpTarget { + let url: URL; + try { + url = new URL(raw.trim()); + } catch { + // never the value: it may hold a password + throw new Error( + "CLOUDHAL_SMTP_URL is not a URL: smtp://user:password@host:587 (STARTTLS) or smtps://user:password@host:465", + ); + } + const tls = url.protocol === "smtp:" ? "starttls" : url.protocol === "smtps:" ? "implicit" : ""; + if (tls === "") + throw new Error( + "CLOUDHAL_SMTP_URL: the scheme is smtp:// (STARTTLS) or smtps:// (implicit TLS); there is no unencrypted mode", + ); + const host = url.hostname.startsWith("[") ? url.hostname.slice(1, -1) : url.hostname; + if (host === "") throw new Error("CLOUDHAL_SMTP_URL has no host"); + if ((url.pathname !== "" && url.pathname !== "/") || url.search !== "" || url.hash !== "") + throw new Error("CLOUDHAL_SMTP_URL takes no path, query or fragment"); + const port = url.port === "" ? (tls === "starttls" ? 587 : 465) : Number(url.port); + const user = decodeURIComponent(url.username); + const pass = decodeURIComponent(url.password); + if (pass !== "" && user === "") throw new Error("CLOUDHAL_SMTP_URL has a password but no user"); + return { host, port, tls, ...(user !== "" ? { user, pass } : {}) }; +} + +/** A plain `local@domain`: no whitespace, line breaks, `<`, `>` or `"`, at most 254 characters. */ +export function plainAddress(value: unknown): value is string { + if (typeof value !== "string" || value.length > 254) return false; + for (const c of value) if (c <= " " || c === "<" || c === ">" || c === '"') return false; + const at = value.indexOf("@"); + if (at < 1 || value.indexOf("@", at + 1) !== -1) return false; + return value.slice(at + 2, -1).includes("."); +} + +const encoder = new TextEncoder(); + +function base64(text: string): string { + let binary = ""; + for (const byte of encoder.encode(text)) binary += String.fromCharCode(byte); + return btoa(binary); +} + +function wrap(b64: string): string { + const lines: string[] = []; + for (let i = 0; i < b64.length; i += 76) lines.push(b64.slice(i, i + 76)); + return lines.join("\r\n"); +} + +const oneLine = (s: string) => + s + .split("") + .map((c) => (c === "\r" || c === "\n" || c === "\t" ? " " : c)) + .join("") + .trim(); + +/** RFC 2047: printable ASCII as is, anything else as UTF-8 encoded words of at most 76 bytes. */ +export function encodeHeader(value: string): string { + const v = oneLine(value); + let ascii = true; + for (const c of v) if (c < " " || c > "~") ascii = false; + if (ascii) return v; + const chars = Array.from(v); + const words: string[] = []; + for (let i = 0; i < chars.length; i += 12) + words.push(`=?UTF-8?B?${base64(chars.slice(i, i + 12).join(""))}?=`); + return words.join("\r\n "); +} + +function fromHeader(email: string, name: string | undefined): string { + const n = name === undefined ? "" : oneLine(name); + if (n === "") return `<${email}>`; + const encoded = encodeHeader(n); + const quoted = encoded === n ? `"${n.split("\\").join("\\\\").split('"').join('\\"')}"` : encoded; + return `${quoted} <${email}>`; +} + +const RESERVED = new Set([ + "from", + "to", + "cc", + "bcc", + "subject", + "date", + "message-id", + "mime-version", + "content-type", + "content-transfer-encoding", +]); + +function extraHeaders(headers: Record | undefined): string[] { + const out: string[] = []; + for (const [name, value] of Object.entries(headers ?? {})) { + if (RESERVED.has(name.toLowerCase()) || typeof value !== "string") continue; + let ok = name.length > 0 && name.length <= 64; + for (const c of name) + if ( + !((c >= "A" && c <= "Z") || (c >= "a" && c <= "z") || (c >= "0" && c <= "9") || c === "-") + ) + ok = false; + if (ok) out.push(`${name}: ${encodeHeader(value)}`); + } + return out; +} + +const part = (type: string, text: string) => + `Content-Type: ${type}; charset=utf-8\r\nContent-Transfer-Encoding: base64\r\n\r\n${wrap(base64(text))}`; + +/** The RFC 5322 message, CRLF line ends, before dot-stuffing. */ +export function buildMessage( + mail: StructuredMail, + opts: { messageId: string; date: Date; boundary: string }, +): string { + const head = [ + `From: ${fromHeader(mail.from.email, mail.from.name)}`, + `To: <${mail.to}>`, + `Subject: ${encodeHeader(mail.subject)}`, + `Date: ${opts.date.toUTCString()}`, + `Message-ID: ${opts.messageId}`, + "MIME-Version: 1.0", + ...extraHeaders(mail.headers), + ]; + if (!mail.html) return `${head.join("\r\n")}\r\n${part("text/plain", mail.text)}\r\n`; + const b = opts.boundary; + return `${head.join("\r\n")}\r\nContent-Type: multipart/alternative; boundary="${b}"\r\n\r\n--${b}\r\n${part("text/plain", mail.text)}\r\n--${b}\r\n${part("text/html", mail.html)}\r\n--${b}--\r\n`; +} + +/** RFC 5321 §4.5.2: a line that starts with "." gets one more. */ +export function dotStuff(message: string): string { + return message + .split("\r\n") + .map((l) => (l.startsWith(".") ? `.${l}` : l)) + .join("\r\n"); +} + +interface Reply { + code: number; + lines: string[]; +} + +/** One SMTP conversation on one socket, every read bounded. */ +class Conversation { + #socket: SmtpSocket; + #reader: ReadableStreamDefaultReader; + #writer: WritableStreamDefaultWriter; + #decoder = new TextDecoder(); + #buffer = ""; + #timeout: number; + + constructor(socket: SmtpSocket, timeout: number) { + this.#socket = socket; + this.#reader = socket.readable.getReader(); + this.#writer = socket.writable.getWriter(); + this.#timeout = timeout; + } + + async #line(): Promise { + for (;;) { + const end = this.#buffer.indexOf("\n"); + if (end !== -1) { + const line = this.#buffer.slice(0, end); + this.#buffer = this.#buffer.slice(end + 1); + return line.endsWith("\r") ? line.slice(0, -1) : line; + } + if (this.#buffer.length > MAX_LINE) + throw new SmtpError("E_SMTP_PROTOCOL", "the server sent an overlong line", true); + const { value, done } = await this.#reader.read(); + if (done) throw new SmtpError("E_SMTP_CONNECT", "the server closed the connection", true); + this.#buffer += this.#decoder.decode(value, { stream: true }); + } + } + + async #reply(): Promise { + const lines: string[] = []; + for (;;) { + const line = await this.#line(); + const code = Number(line.slice(0, 3)); + if ( + !/^\d{3}$/.test(line.slice(0, 3)) || + (line.length > 3 && line[3] !== " " && line[3] !== "-") + ) + throw new SmtpError("E_SMTP_PROTOCOL", "the server's reply is not SMTP", true); + lines.push(line.slice(4)); + if (line[3] !== "-") return { code, lines }; + if (lines.length >= MAX_REPLY_LINES) + throw new SmtpError("E_SMTP_PROTOCOL", "the server's reply is too long", true); + } + } + + /** The next reply within the deadline; `ok` lists the codes that continue the conversation. */ + async expect(step: string, ok: readonly number[]): Promise { + let timer: ReturnType | undefined; + const deadline = new Promise((_, reject) => { + timer = setTimeout( + () => reject(new SmtpError("E_SMTP_TIMEOUT", `no reply to ${step} in time`, true)), + this.#timeout, + ); + }); + try { + const reply = await Promise.race([this.#reply(), deadline]); + if (ok.includes(reply.code)) return reply; + const said = oneLine(reply.lines[0] ?? "").slice(0, 160); + if (reply.code >= 400 && reply.code < 500) + throw new SmtpError("E_SMTP_TEMPORARY", `${step}: ${reply.code} ${said}`, true); + const code = step === "AUTH" ? "E_SMTP_AUTH" : "E_SMTP_REJECTED"; + throw new SmtpError(code, `${step}: ${reply.code} ${said}`, false); + } finally { + clearTimeout(timer); + } + } + + async send(line: string): Promise { + await this.#writer.write(encoder.encode(`${line}\r\n`)); + } + + async sendRaw(data: string): Promise { + await this.#writer.write(encoder.encode(data)); + } + + /** STARTTLS: the same connection, encrypted; reads and writes go through the new socket. */ + upgrade(): void { + this.#reader.releaseLock(); + this.#writer.releaseLock(); + this.#socket = this.#socket.startTls(); + this.#reader = this.#socket.readable.getReader(); + this.#writer = this.#socket.writable.getWriter(); + this.#buffer = ""; + } + + close(): void { + try { + this.#socket.close(); + } catch { + // already closed + } + } +} + +const capabilities = (reply: Reply) => reply.lines.slice(1).map((l) => l.toUpperCase()); + +async function transaction( + target: SmtpTarget, + mail: StructuredMail, + opts: SendMailOptions, + data: string, +): Promise { + const socket = opts.connect( + { hostname: target.host, port: target.port }, + { secureTransport: target.tls === "implicit" ? "on" : "starttls", allowHalfOpen: false }, + ); + const c = new Conversation(socket, opts.replyTimeoutMs ?? REPLY_TIMEOUT_MS); + try { + await c.expect("the greeting", [220]); + await c.send(`EHLO ${opts.helo}`); + let caps = capabilities(await c.expect("EHLO", [250])); + if (target.tls === "starttls") { + if (!caps.some((l) => l === "STARTTLS" || l.startsWith("STARTTLS "))) + throw new SmtpError( + "E_SMTP_TLS_UNAVAILABLE", + "the server does not offer STARTTLS, and Cloudhal never sends over an unencrypted connection", + false, + ); + await c.send("STARTTLS"); + await c.expect("STARTTLS", [220]); + c.upgrade(); + await c.send(`EHLO ${opts.helo}`); + caps = capabilities(await c.expect("EHLO", [250])); + } + if (target.user !== undefined) { + const auth = caps.find((l) => l.startsWith("AUTH ") || l.startsWith("AUTH=")); + const mechanisms = (auth ?? "").slice(5).split(" "); + if (mechanisms.includes("PLAIN")) { + await c.send(`AUTH PLAIN ${base64(`\u0000${target.user}\u0000${target.pass ?? ""}`)}`); + await c.expect("AUTH", [235]); + } else if (mechanisms.includes("LOGIN")) { + await c.send("AUTH LOGIN"); + await c.expect("AUTH", [334]); + await c.send(base64(target.user)); + await c.expect("AUTH", [334]); + await c.send(base64(target.pass ?? "")); + await c.expect("AUTH", [235]); + } else + throw new SmtpError("E_SMTP_AUTH", "the server offers neither AUTH PLAIN nor LOGIN", false); + } + await c.send(`MAIL FROM:<${mail.from.email}>`); + await c.expect("MAIL FROM", [250]); + await c.send(`RCPT TO:<${mail.to}>`); + await c.expect("RCPT TO", [250, 251]); + await c.send("DATA"); + await c.expect("DATA", [354]); + await c.sendRaw(`${dotStuff(data)}.\r\n`); + await c.expect("the message", [250]); + await c.send("QUIT"); + await c.expect("QUIT", [221]).catch(() => undefined); + } finally { + c.close(); + } +} + +function bounded(work: Promise, ms: number): Promise { + let timer: ReturnType | undefined; + const deadline = new Promise((_, reject) => { + timer = setTimeout( + () => reject(new SmtpError("E_SMTP_TIMEOUT", `the attempt took longer than ${ms} ms`, true)), + ms, + ); + }); + return Promise.race([work, deadline]).finally(() => clearTimeout(timer)); +} + +function asSmtpError(e: unknown): SmtpError { + if (e instanceof SmtpError) return e; + // connection refused, DNS, TLS handshake: the runtime's own error, which names no secret + const message = e instanceof Error ? e.message : String(e); + return new SmtpError("E_SMTP_CONNECT", oneLine(message).slice(0, 160), true); +} + +/** Sends `mail` through the server of `opts.url`; resolves with its Message-ID. */ +export async function sendMail( + mail: StructuredMail, + opts: SendMailOptions, +): Promise<{ messageId: string }> { + const target = parseSmtpUrl(opts.url); + if (!plainAddress(mail?.to)) + throw new SmtpError("E_SMTP_ADDRESS", "the recipient is not a plain address", false); + if (!plainAddress(mail.from?.email) || mail.from.email.toLowerCase() !== opts.from.toLowerCase()) + throw new SmtpError("E_SMTP_SENDER", "only CLOUDHAL_MAIL_FROM may send", false); + const domain = mail.from.email.slice(mail.from.email.indexOf("@") + 1); + const messageId = `<${crypto.randomUUID()}@${domain}>`; + const data = buildMessage( + { ...mail, subject: mail.subject ?? "", text: mail.text ?? "" }, + { messageId, date: new Date(), boundary: `cloudhal-${crypto.randomUUID()}` }, + ); + const log = opts.log ?? (() => undefined); + const sleep = opts.sleep ?? ((ms: number) => new Promise((r) => setTimeout(r, ms))); + const delays = opts.delaysMs ?? DEFAULT_DELAYS_MS; + const rcpt = `…@${mail.to.slice(mail.to.indexOf("@") + 1)}`; + const via = `${target.host}:${target.port} (${target.tls === "implicit" ? "TLS" : "STARTTLS"})`; + for (let attempt = 1; ; attempt++) { + const started = Date.now(); + try { + await bounded( + transaction(target, mail, opts, data), + opts.attemptTimeoutMs ?? ATTEMPT_TIMEOUT_MS, + ); + log(`smtp: sent to ${rcpt} via ${via}, attempt ${attempt}, ${Date.now() - started} ms`); + return { messageId }; + } catch (e) { + const err = asSmtpError(e); + const wait = err.transient ? delays[attempt - 1] : undefined; + log( + `smtp: attempt ${attempt} to ${rcpt} via ${via} failed: ${err.message}${wait === undefined ? "" : `; retrying in ${wait} ms`}`, + ); + if (wait === undefined) throw err; + await sleep(wait); + } + } +} diff --git a/packages/cli/src/selfhost/smtp-service.ts b/packages/cli/src/selfhost/smtp-service.ts new file mode 100644 index 00000000..c8d4f447 --- /dev/null +++ b/packages/cli/src/selfhost/smtp-service.ts @@ -0,0 +1,78 @@ +/** + * #291: the SMTP sender Worker of the generated workerd config, behind the admin Worker's `EMAIL` + * binding (RFC-0047 §6). Present only when `CLOUDHAL_SMTP_URL` is set; without it there is no + * `EMAIL` binding and the admin Worker reports mail as unavailable, as before. + * + * - `smtp` is a Worker whose default entrypoint has the binding's `send(message)` (JS RPC). Its + * modules are the wrapper below and `smtp-client.ts`, embedded as `smtp-client.js`. + * - Its URL (with any credentials) reaches it only through `fromEnvironment` (RFC-0047 §2, + * invariant 3); the config holds the sender address, the EHLO name and the CA to trust. + * - Its sockets go through `smtp-network`, its `globalOutbound`: public and private addresses (a + * relay on the LAN, the compose file's Mailpit), with TLS that trusts the browser CAs and + * `CLOUDHAL_SMTP_CA_FILE`'s certificates. No other Worker uses that network. + */ +import { readFileSync } from "node:fs"; +import { stripTypeScriptTypes } from "node:module"; +import path from "node:path"; +import type { SelfhostSettings } from "./settings.ts"; + +/** The compatibility date of the image's own small Workers (front, smtp). */ +const DATE = "2026-11-01"; + +/** Indented, so no line of it reads as an import of this file (the entry-imports test). */ +export const SMTP_WORKER_SOURCE = ` + import { WorkerEntrypoint } from "cloudflare:workers"; + import { connect } from "cloudflare:sockets"; + import { sendMail } from "./smtp-client.js"; + export default class SmtpSender extends WorkerEntrypoint { + send(message) { + return sendMail(message, { + url: this.env.SMTP_URL, + from: this.env.MAIL_FROM, + helo: this.env.HELO, + connect, + log: (line) => console.log(line), + }); + } + } +`; + +/** `smtp-client.ts` as a Worker module: the compiled `.js` in the image, stripped `.ts` here. */ +export function smtpClientSource(): string { + const here = (file: string) => path.join(import.meta.dirname, file); + try { + return readFileSync(here("smtp-client.js"), "utf8"); + } catch { + const ts = readFileSync(here("smtp-client.ts"), "utf8"); + return stripTypeScriptTypes(ts); + } +} + +const q = (s: string) => JSON.stringify(s); + +/** The `EMAIL` binding and the sender vars of the admin Worker, when mail is on. */ +export function smtpAdminBindings(s: SelfhostSettings): string[] { + if (!s.mail) return []; + return [ + `(name = "EMAIL", service = "smtp")`, + `(name = "CLOUDHAL_MAIL_FROM", text = ${q(s.mail.from)})`, + ...(s.mail.fromName + ? [`(name = "CLOUDHAL_MAIL_FROM_NAME", text = ${q(s.mail.fromName)})`] + : []), + ]; +} + +/** The `smtp` Worker and its network, when mail is on. */ +export function smtpServices( + s: SelfhostSettings, + client: () => string = smtpClientSource, +): string[] { + if (!s.mail) return []; + const trusted = s.mail.caCertificates.length + ? `, trustedCertificates = [${s.mail.caCertificates.map(q).join(", ")}]` + : ""; + return [ + `(name = "smtp-network", network = (allow = ["public", "private"], tlsOptions = (trustBrowserCas = true${trusted})))`, + `(name = "smtp", worker = (compatibilityDate = ${q(DATE)}, modules = [(name = "smtp.js", esModule = ${q(SMTP_WORKER_SOURCE)}), (name = "smtp-client.js", esModule = ${q(client())})], globalOutbound = "smtp-network", bindings = [(name = "SMTP_URL", fromEnvironment = "CLOUDHAL_SMTP_URL"), (name = "MAIL_FROM", text = ${q(s.mail.from)}), (name = "HELO", text = ${q(s.mail.helo)})]))`, + ]; +} diff --git a/packages/cli/src/selfhost/smtp-settings.ts b/packages/cli/src/selfhost/smtp-settings.ts new file mode 100644 index 00000000..ffd84114 --- /dev/null +++ b/packages/cli/src/selfhost/smtp-settings.ts @@ -0,0 +1,83 @@ +/** + * #291: the mail settings of the self-host image. Mail is on only when `CLOUDHAL_SMTP_URL` (or + * `CLOUDHAL_SMTP_URL_FILE`) is set; then `CLOUDHAL_MAIL_FROM` must be a plain address. The URL is + * checked here, at start, and never printed: it may carry a password. + * + * - `CLOUDHAL_SMTP_URL`: `smtp://user:password@host:587` (STARTTLS) or `smtps://…@host:465`. + * - `CLOUDHAL_MAIL_FROM`, `CLOUDHAL_MAIL_FROM_NAME`: the sender, as on Cloudflare. + * - `CLOUDHAL_SMTP_CA_FILE`: PEM certificates to trust besides the browser CAs (a private relay, the + * compose file's Mailpit). + */ +import { parseSmtpUrl, plainAddress } from "./smtp-client.ts"; + +export interface MailSettings { + readonly from: string; + readonly fromName: string | undefined; + /** The name the sender gives in `EHLO`: the Studio host, else `cloudhal`. */ + readonly helo: string; + /** Each PEM certificate of `CLOUDHAL_SMTP_CA_FILE`. */ + readonly caCertificates: readonly string[]; +} + +type Env = Readonly>; + +const BEGIN = "-----BEGIN CERTIFICATE-----"; +const END = "-----END CERTIFICATE-----"; + +/** Every certificate block of a PEM file, found with `indexOf` (no pattern over file content). */ +export function pemCertificates(text: string): string[] { + const out: string[] = []; + for (let at = text.indexOf(BEGIN); at !== -1; at = text.indexOf(BEGIN, at + 1)) { + const end = text.indexOf(END, at); + if (end === -1) break; + out.push(`${text.slice(at, end + END.length)}\n`); + } + return out; +} + +function heloName(baseUrl: string | undefined): string { + try { + if (baseUrl) return new URL(baseUrl).hostname || "cloudhal"; + } catch { + // reported by the settings' own check + } + return "cloudhal"; +} + +/** The mail settings, or `undefined` when mail is off; `problems` collects what is wrong. */ +export function readMailSettings( + env: Env, + problems: string[], + read: (file: string) => string, +): MailSettings | undefined { + const url = env.CLOUDHAL_SMTP_URL?.trim(); + if (!url) return undefined; + try { + parseSmtpUrl(url); + } catch (e) { + problems.push((e as Error).message); + } + const from = env.CLOUDHAL_MAIL_FROM?.trim() ?? ""; + if (!plainAddress(from)) + problems.push( + "CLOUDHAL_SMTP_URL needs CLOUDHAL_MAIL_FROM, a plain address (cloudhal@example.com)", + ); + let caCertificates: string[] = []; + const caFile = env.CLOUDHAL_SMTP_CA_FILE; + if (caFile) { + try { + caCertificates = pemCertificates(read(caFile)); + if (caCertificates.length === 0) + problems.push(`CLOUDHAL_SMTP_CA_FILE: ${caFile} holds no PEM certificate`); + } catch (e) { + problems.push(`CLOUDHAL_SMTP_CA_FILE: cannot read ${caFile} (${(e as Error).message})`); + } + } + const name = env.CLOUDHAL_MAIL_FROM_NAME?.trim(); + return { + from, + fromName: name ? name : undefined, + helo: heloName(env.CLOUDHAL_BASE_URL), + caCertificates, + }; +} diff --git a/packages/cli/src/selfhost/workerd-config.ts b/packages/cli/src/selfhost/workerd-config.ts index 2f335770..4ac3cf14 100644 --- a/packages/cli/src/selfhost/workerd-config.ts +++ b/packages/cli/src/selfhost/workerd-config.ts @@ -11,6 +11,7 @@ import path from "node:path"; import type { ReleaseManifest } from "@cloudhal/release-verify"; import { FRONT_WORKER_SOURCE } from "./front-worker.ts"; import type { SelfhostSettings } from "./settings.ts"; +import { smtpAdminBindings, smtpServices } from "./smtp-service.ts"; /** The compatibility date of workerd's own bundled Workers (D1, R2, cron). */ const BUILTIN_DATE = "2026-11-01"; @@ -142,6 +143,7 @@ export function workerdConfig(input: ConfigInput): string { text("CLOUDHAL_SCHEDULER", "cron"), siteId, ...Object.entries(s.adminVars).map(([k, v]) => text(k, v)), + ...smtpAdminBindings(s), ], }); const site = worker(input, "site", { @@ -161,6 +163,7 @@ export function workerdConfig(input: ConfigInput): string { assets(input, "admin"), front("site", s), front("admin", s), + ...smtpServices(s), ...(s.otlp ? [`(name = "otlp", external = (address = ${q(s.otlp)}, http = ()))`] : []), ].map((x) => x.replaceAll("{DATA}", s.dataDir)); const bucket = `s3://${s.s3.bucket}/${s.s3.prefix}cluster`; diff --git a/packages/cli/test/selfhost-smtp.test.ts b/packages/cli/test/selfhost-smtp.test.ts new file mode 100644 index 00000000..16a7623d --- /dev/null +++ b/packages/cli/test/selfhost-smtp.test.ts @@ -0,0 +1,362 @@ +/** + * #291: the SMTP sender behind the self-host image's `EMAIL` binding. The client runs against a + * scripted server here; the image's Worker against Mailpit in scripts/mail-smoke.ts (CI). + */ +import { describe, expect, it } from "vitest"; +import { secretsEnv } from "../src/selfhost/secrets.ts"; +import { readSettings } from "../src/selfhost/settings.ts"; +import { + buildMessage, + dotStuff, + encodeHeader, + parseSmtpUrl, + type SmtpConnect, + type SmtpSocket, + type StructuredMail, + sendMail, +} from "../src/selfhost/smtp-client.ts"; +import { + SMTP_WORKER_SOURCE, + smtpAdminBindings, + smtpClientSource, + smtpServices, +} from "../src/selfhost/smtp-service.ts"; +import { pemCertificates } from "../src/selfhost/smtp-settings.ts"; + +const enc = new TextEncoder(); +const dec = new TextDecoder(); + +interface Script { + starttls?: boolean; + auth?: "PLAIN" | "LOGIN" | "none"; + /** Replies by command for the first `times` connections, e.g. `{ RCPT: "451 4.3.0 busy" }`. */ + fail?: Record; + times?: number; + password?: string; +} + +/** A scripted SMTP server; every connection is recorded. */ +function server(script: Script = {}) { + const seen = { connections: 0, commands: [] as string[], tls: [] as boolean[], data: "" }; + const connect: SmtpConnect = (address, options) => { + seen.connections++; + const conn = seen.connections; + const failing = conn <= (script.times ?? 1) ? (script.fail ?? {}) : {}; + let loginStep = 0; + const make = (tls: boolean, greet: boolean): SmtpSocket => { + let ctl!: ReadableStreamDefaultController; + const readable = new ReadableStream({ + start(c) { + ctl = c; + }, + }); + const say = (s: string) => ctl.enqueue(enc.encode(`${s}\r\n`)); + let buf = ""; + let inData = false; + const reply = (verb: string, normal: string) => say(failing[verb] ?? normal); + const writable = new WritableStream({ + write(chunk) { + buf += dec.decode(chunk); + for (;;) { + if (inData) { + const end = buf.indexOf("\r\n.\r\n"); + if (end === -1) return; + seen.data = buf.slice(0, end + 2); + buf = buf.slice(end + 5); + inData = false; + reply("MESSAGE", "250 2.0.0 queued"); + continue; + } + const nl = buf.indexOf("\r\n"); + if (nl === -1) return; + const line = buf.slice(0, nl); + buf = buf.slice(nl + 2); + seen.commands.push(line); + seen.tls.push(tls); + const verb = line.split(" ")[0]?.split(":")[0]?.toUpperCase() ?? ""; + if (loginStep === 1) { + loginStep = 2; + say("334 UGFzc3dvcmQ6"); + } else if (loginStep === 2) { + loginStep = 0; + reply("AUTH", "235 ok"); + } else if (verb === "EHLO") { + const auth = script.auth === "none" ? [] : [`AUTH ${script.auth ?? "PLAIN LOGIN"}`]; + const caps = [ + "fake.example", + ...(!tls && script.starttls !== false ? ["STARTTLS"] : []), + ...auth, + ]; + for (const [i, c] of caps.entries()) + say(`250${i === caps.length - 1 ? " " : "-"}${c}`); + } else if (verb === "STARTTLS") say("220 go ahead"); + else if (verb === "AUTH" && line.startsWith("AUTH LOGIN")) { + loginStep = 1; + say("334 VXNlcm5hbWU6"); + } else if (verb === "AUTH") reply("AUTH", "235 2.7.0 ok"); + else if (verb === "MAIL") reply("MAIL", "250 ok"); + else if (verb === "RCPT") reply("RCPT", "250 ok"); + else if (verb === "DATA") { + reply("DATA", "354 go"); + if (!failing.DATA) inData = true; + } else if (verb === "QUIT") say("221 bye"); + else say("500 what"); + } + }, + }); + if (greet) say("220 fake.example ESMTP"); + return { + readable, + writable, + close() {}, + startTls: () => make(true, false), + }; + }; + expect(address).toEqual({ hostname: "mail.example.com", port: 587 }); + return make(options.secureTransport === "on", true); + }; + return { connect, seen }; +} + +const MAIL: StructuredMail = { + to: "ada@example.org", + from: { email: "cloudhal@example.com", name: "Cloudhal Studio" }, + subject: "You're invited", + text: "Open https://studio.example.com/invite#chinv_SECRET\n.\nThanks", + headers: { "Auto-Submitted": "auto-generated" }, +}; +const opts = (connect: SmtpConnect, log: string[] = []) => ({ + url: "smtp://cloudhal:s3cret-pw@mail.example.com", + from: "cloudhal@example.com", + helo: "studio.example.com", + connect, + log: (l: string) => log.push(l), + sleep: async () => {}, + delaysMs: [0, 0], +}); + +describe("SMTP URL", () => { + it("is STARTTLS or implicit TLS, never plain, and never echoes the URL", () => { + expect(parseSmtpUrl("smtp://u%40x:p%3Aw@mail.example.com")).toEqual({ + host: "mail.example.com", + port: 587, + tls: "starttls", + user: "u@x", + pass: "p:w", + }); + expect(parseSmtpUrl("smtps://relay:2465")).toEqual({ + host: "relay", + port: 2465, + tls: "implicit", + }); + expect(() => parseSmtpUrl("http://u:topsecret@mail")).toThrow(/no unencrypted mode/); + expect(() => parseSmtpUrl("smtp://u:topsecret@mail/x")).toThrow(/no path/); + expect(() => parseSmtpUrl("smtp://:topsecret@mail")).toThrow(/no user/); + for (const bad of ["http://u:topsecret@mail", "nope topsecret", "smtp://:topsecret@mail"]) + expect(() => parseSmtpUrl(bad)).toThrow(expect.not.stringContaining("topsecret") as never); + }); +}); + +describe("SMTP message", () => { + it("encodes headers, base64 bodies and dot-stuffs", () => { + expect(encodeHeader("Plain subject")).toBe("Plain subject"); + expect(encodeHeader("Davet: Güler\r\nBcc: x@y")).toMatch(/^=\?UTF-8\?B\?/); + expect(encodeHeader("Davet: Güler\r\nBcc: x@y")).not.toContain("\nBcc"); + const m = buildMessage( + { ...MAIL, html: "

hi

" }, + { messageId: "", date: new Date(0), boundary: "B" }, + ); + expect(m).toContain('From: "Cloudhal Studio" \r\n'); + expect(m).toContain("To: \r\n"); + expect(m).toContain("Auto-Submitted: auto-generated\r\n"); + expect(m).toContain('Content-Type: multipart/alternative; boundary="B"'); + expect(m).not.toContain("chinv_SECRET"); // base64, so no line of the text is a raw line + expect(dotStuff("a\r\n.b\r\n..c")).toBe("a\r\n..b\r\n...c"); + }); +}); + +describe("SMTP sending", () => { + it("upgrades with STARTTLS before AUTH, sends the message, logs no body or password", async () => { + const { connect, seen } = server(); + const log: string[] = []; + const { messageId } = await sendMail(MAIL, opts(connect, log)); + expect(messageId).toMatch(/^<[0-9a-f-]{36}@example\.com>$/); + const verbs = seen.commands.map((c) => c.split(/[ :]/)[0]); + expect(verbs).toEqual(["EHLO", "STARTTLS", "EHLO", "AUTH", "MAIL", "RCPT", "DATA", "QUIT"]); + const auth = seen.commands.findIndex((c) => c.startsWith("AUTH")); + expect(seen.tls[auth]).toBe(true); + expect(seen.tls[0]).toBe(false); + expect(Buffer.from(seen.commands[auth]?.slice(11) ?? "", "base64").toString()).toBe( + "\0cloudhal\0s3cret-pw", + ); + expect(seen.commands).toContain("MAIL FROM:"); + expect(seen.data).toContain(`Message-ID: ${messageId}`); + const text = Buffer.from( + seen.data.split("\r\n\r\n")[1]?.replaceAll("\r\n", "") ?? "", + "base64", + ).toString(); + expect(text).toBe(MAIL.text); + expect(log).toEqual([ + expect.stringMatching( + /^smtp: sent to …@example\.org via mail\.example\.com:587 \(STARTTLS\), attempt 1/, + ), + ]); + expect(log.join()).not.toMatch(/s3cret|chinv_|ada@/); + }); + + it("uses AUTH LOGIN when PLAIN is not offered", async () => { + const { connect, seen } = server({ auth: "LOGIN" }); + await sendMail(MAIL, opts(connect)); + expect(seen.commands).toContain("AUTH LOGIN"); + expect(seen.commands).toContain(Buffer.from("s3cret-pw").toString("base64")); + }); + + it("refuses a server without STARTTLS before sending anything else, and does not retry", async () => { + const { connect, seen } = server({ starttls: false }); + const log: string[] = []; + await expect(sendMail(MAIL, opts(connect, log))).rejects.toMatchObject({ + code: "E_SMTP_TLS_UNAVAILABLE", + }); + expect(seen.commands).toEqual(["EHLO studio.example.com"]); + expect(seen.connections).toBe(1); + expect(log.join()).not.toContain("s3cret"); + }); + + it("retries a 4xx reply, bounded, and never a 5xx one", async () => { + const busy = server({ fail: { RCPT: "451 4.3.0 try later" }, times: 2 }); + const log: string[] = []; + await sendMail(MAIL, opts(busy.connect, log)); + expect(busy.seen.connections).toBe(3); + expect(log[0]).toMatch(/attempt 1 .* failed: E_SMTP_TEMPORARY: RCPT TO: 451 .*retrying/); + expect(log[2]).toMatch(/sent .* attempt 3/); + + const down = server({ fail: { MAIL: "421 4.3.2 closing" }, times: 9 }); + await expect(sendMail(MAIL, opts(down.connect))).rejects.toMatchObject({ + code: "E_SMTP_TEMPORARY", + }); + expect(down.seen.connections).toBe(3); + + const denied = server({ fail: { AUTH: "535 5.7.8 bad credentials" } }); + await expect(sendMail(MAIL, opts(denied.connect))).rejects.toMatchObject({ + code: "E_SMTP_AUTH", + }); + expect(denied.seen.connections).toBe(1); + + const rejected = server({ fail: { RCPT: "550 5.1.1 no such user" } }); + await expect(sendMail(MAIL, opts(rejected.connect))).rejects.toMatchObject({ + code: "E_SMTP_REJECTED", + }); + expect(rejected.seen.connections).toBe(1); + }); + + it("retries a connection error and times out a silent server", async () => { + let n = 0; + const flaky: SmtpConnect = (a, o) => { + n++; + if (n === 1) throw new Error("connection refused"); + return server().connect(a, o); + }; + await sendMail(MAIL, opts(flaky)); + expect(n).toBe(2); + const silent: SmtpConnect = () => ({ + readable: new ReadableStream(), + writable: new WritableStream(), + close() {}, + startTls() { + throw new Error("no"); + }, + }); + await expect( + sendMail(MAIL, { ...opts(silent), replyTimeoutMs: 20, delaysMs: [] }), + ).rejects.toMatchObject({ code: "E_SMTP_TIMEOUT" }); + }); + + it("sends only from CLOUDHAL_MAIL_FROM, to a plain address", async () => { + const { connect, seen } = server(); + await expect( + sendMail({ ...MAIL, from: { email: "ceo@example.com" } }, opts(connect)), + ).rejects.toMatchObject({ code: "E_SMTP_SENDER" }); + await expect( + sendMail({ ...MAIL, to: "a@example.org>\r\nRCPT TO: = { + ...Object.fromEntries( + secretsEnv() + .split("\n") + .filter((l) => l && !l.startsWith("#")) + .map((l) => [l.slice(0, l.indexOf("=")), l.slice(l.indexOf("=") + 1)]), + ), + CLOUDHAL_S3_ENDPOINT: "http://seaweedfs:8333", + CLOUDHAL_S3_BUCKET: "cloudhal", +}; +const PEM = "-----BEGIN CERTIFICATE-----\nMIIB\n-----END CERTIFICATE-----"; + +describe("SMTP settings and config", () => { + it("is off without CLOUDHAL_SMTP_URL and checks the rest when it is set", () => { + expect(readSettings(ENV).mail).toBeUndefined(); + expect(smtpServices(readSettings(ENV))).toEqual([]); + expect(() => readSettings({ ...ENV, CLOUDHAL_SMTP_URL: "smtp://u:topsecret@mail" })).toThrow( + /CLOUDHAL_MAIL_FROM/, + ); + expect(() => + readSettings({ + ...ENV, + CLOUDHAL_SMTP_URL: "plain://u:topsecret@mail", + CLOUDHAL_MAIL_FROM: "a@b.co", + }), + ).toThrow(expect.not.stringContaining("topsecret") as never); + const s = readSettings( + { + ...ENV, + CLOUDHAL_SMTP_URL: "smtp://u:topsecret@mailpit:1025", + CLOUDHAL_MAIL_FROM: "cloudhal@example.com", + CLOUDHAL_MAIL_FROM_NAME: "Studio", + CLOUDHAL_SMTP_CA_FILE: "/certs/ca.pem", + CLOUDHAL_BASE_URL: "https://studio.example.com", + }, + () => `${PEM}\n${PEM}\n`, + ); + expect(s.mail).toEqual({ + from: "cloudhal@example.com", + fromName: "Studio", + helo: "studio.example.com", + caCertificates: [`${PEM}\n`, `${PEM}\n`], + }); + expect(smtpAdminBindings(s)).toEqual([ + '(name = "EMAIL", service = "smtp")', + '(name = "CLOUDHAL_MAIL_FROM", text = "cloudhal@example.com")', + '(name = "CLOUDHAL_MAIL_FROM_NAME", text = "Studio")', + ]); + const [network, worker] = smtpServices(s, () => "export const x = 1;"); + expect(network).toContain('allow = ["public", "private"]'); + expect(network).toContain("trustBrowserCas = true, trustedCertificates = ["); + expect(worker).toContain('globalOutbound = "smtp-network"'); + expect(worker).toContain('(name = "SMTP_URL", fromEnvironment = "CLOUDHAL_SMTP_URL")'); + expect(worker).not.toContain("topsecret"); + expect(() => + readSettings( + { + ...ENV, + CLOUDHAL_SMTP_URL: "smtps://m", + CLOUDHAL_MAIL_FROM: "a@b.co", + CLOUDHAL_SMTP_CA_FILE: "/x", + }, + () => "not a pem", + ), + ).toThrow(/holds no PEM certificate/); + expect(pemCertificates("junk")).toEqual([]); + }); + + it("embeds a client module with no imports, and a wrapper that imports only it", () => { + const src = smtpClientSource(); + expect(src).toContain("export async function sendMail"); + expect(src).not.toMatch(/^\s*import\s/m); + expect(src).not.toMatch(/\binterface\s+SmtpTarget\b/); + const imports = [...SMTP_WORKER_SOURCE.matchAll(/from "([^"]+)"/g)].map((m) => m[1]); + expect(imports).toEqual(["cloudflare:workers", "cloudflare:sockets", "./smtp-client.js"]); + }); +}); diff --git a/scripts/mail-smoke.ts b/scripts/mail-smoke.ts new file mode 100644 index 00000000..74af3b5c --- /dev/null +++ b/scripts/mail-smoke.ts @@ -0,0 +1,287 @@ +/** + * The SMTP sender behind the image's `EMAIL` binding, end to end (#291). CI only: + * .github/workflows/docker.yml runs it on the candidate image, and it refuses to start outside + * GitHub Actions. + * + * 1. Mailpit with a certificate made here, requiring STARTTLS and SMTP AUTH, so a message that + * arrives went encrypted and authenticated. SeaweedFS and one instance, which trusts the + * certificate through CLOUDHAL_SMTP_CA_FILE. + * 2. Studio reports email delivery. The first owner invites someone with `delivery: "email"`, and + * the invite arrives with its link. A password reset asked for by email arrives too. + * 3. The instance's log names each send, but neither the SMTP password nor any link's token. + * + * node scripts/mail-smoke.ts --image [--port ] + */ +import { execFile } from "node:child_process"; +import { randomBytes } from "node:crypto"; +import { chmodSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs"; +import os from "node:os"; +import path from "node:path"; +import { fileURLToPath } from "node:url"; +import { promisify } from "node:util"; + +if (process.env.GITHUB_ACTIONS !== "true") { + console.error("mail-smoke runs in CI only (.github/workflows/docker.yml), never locally"); + process.exit(2); +} + +const arg = (name: string): string | undefined => { + const i = process.argv.indexOf(`--${name}`); + return i === -1 ? undefined : process.argv[i + 1]; +}; +const image = arg("image") ?? "cloudhal:ci"; +const port = Number(arg("port") ?? 38787); +const id = `cloudhal-mail-${process.pid}`; +const names = { store: `${id}-store`, mailpit: `${id}-mailpit`, cloudhal: `${id}-cloudhal` }; +// 127.0.0.1, never localhost (#306) +const studio = `http://127.0.0.1:${port}`; +const mailpitApi = `http://127.0.0.1:${port + 2}`; +const compose = readFileSync( + path.resolve(path.dirname(fileURLToPath(import.meta.url)), "../deploy/docker/compose.yml"), + "utf8", +); +const pinned = (repo: string) => { + const at = compose.indexOf(`image: ${repo}:`); + if (at === -1) throw new Error(`compose.yml names no ${repo} image`); + return compose.slice(at + 7, compose.indexOf("\n", at)).trim(); +}; +const STORE_IMAGE = pinned("chrislusf/seaweedfs"); +const MAILPIT_IMAGE = pinned("axllent/mailpit"); + +const run = promisify(execFile); +async function docker(args: string[], timeout = 120_000): Promise { + const { stdout } = await run("docker", args, { encoding: "utf8", timeout, maxBuffer: 64 << 20 }); + return stdout.trim(); +} +async function dockerLogs(name: string): Promise { + const { stdout, stderr } = await run("docker", ["logs", "--timestamps", name], { + encoding: "utf8", + timeout: 30_000, + maxBuffer: 64 << 20, + }); + return `${stdout}${stderr}`; +} +const sleep = (ms: number) => new Promise((r) => setTimeout(r, ms)); +const step = (text: string) => console.log(`✓ ${text}`); +function expect(ok: boolean, what: string, detail?: unknown): void { + if (!ok) throw new Error(`${what}${detail === undefined ? "" : `: ${JSON.stringify(detail)}`}`); +} + +const work = mkdtempSync(path.join(os.tmpdir(), "cloudhal-mail-")); +const tls = path.join(work, "tls"); +function envFile(name: string, env: Record): string { + const file = path.join(work, `${name}.env`); + writeFileSync( + file, + Object.entries(env) + .map(([k, v]) => `${k}=${v}\n`) + .join(""), + { mode: 0o600 }, + ); + return file; +} + +interface Res { + status: number; + text: string; + body: unknown; + headers: Headers; +} +async function req(url: string, init: RequestInit = {}): Promise { + try { + const res = await fetch(url, { ...init, signal: AbortSignal.timeout(30_000) }); + const text = await res.text(); + let body: unknown = text; + try { + body = JSON.parse(text); + } catch { + // not JSON + } + return { status: res.status, text, body, headers: res.headers }; + } catch (e) { + const err = e as { name?: string; cause?: { code?: string } }; + const text = err.cause?.code ?? err.name ?? String(e); + return { status: 0, text, body: text, headers: new Headers() }; + } +} +async function until(what: string, seconds: number, check: () => Promise) { + const deadline = Date.now() + seconds * 1000; + while (Date.now() < deadline) { + const v = await check().catch(() => undefined); + if (v !== undefined) return v; + await sleep(1000); + } + throw new Error(`${what} within ${seconds} s`); +} + +/** A self-signed certificate for `mailpit`, readable by Mailpit's and Cloudhal's users. */ +async function certificate(): Promise { + await run("mkdir", ["-p", tls]); + await run( + "openssl", + [ + ...["req", "-x509", "-newkey", "ec", "-pkeyopt", "ec_paramgen_curve:P-256", "-nodes"], + ...["-days", "2", "-subj", "/CN=mailpit", "-addext", "subjectAltName=DNS:mailpit"], + ...["-keyout", path.join(tls, "key.pem"), "-out", path.join(tls, "cert.pem")], + ], + { timeout: 30_000 }, + ); + chmodSync(tls, 0o755); + for (const f of ["key.pem", "cert.pem"]) chmodSync(path.join(tls, f), 0o644); +} + +const smtpPassword = randomBytes(18).toString("hex"); + +async function start(env: Record): Promise { + await docker(["network", "create", id]); + const s3 = JSON.stringify({ + identities: [ + { + name: "cloudhal", + credentials: [{ accessKey: env.AWS_ACCESS_KEY_ID, secretKey: env.AWS_SECRET_ACCESS_KEY }], + actions: ["Admin", "Read", "Write", "List", "Tagging"], + }, + ], + }); + await docker([ + ...["run", "-d", "--name", names.store, "--network", id, "--network-alias", "seaweedfs"], + ...["--env-file", envFile("store", { S3_CONFIG: s3 }), "--entrypoint", "/bin/sh"], + STORE_IMAGE, + "-c", + 'printf "%s" "$S3_CONFIG" > /tmp/s3.json && exec weed server -dir=/data -s3 -s3.config=/tmp/s3.json -master.volumeSizeLimitMB=256', + ]); + const mailpit = envFile("mailpit", { + MP_SMTP_TLS_CERT: "/tls/cert.pem", + MP_SMTP_TLS_KEY: "/tls/key.pem", + MP_SMTP_REQUIRE_STARTTLS: "true", + MP_SMTP_AUTH: `cloudhal:${smtpPassword}`, + }); + await docker([ + ...["run", "-d", "--name", names.mailpit, "--network", id, "--network-alias", "mailpit"], + ...["--env-file", mailpit, "-v", `${tls}:/tls:ro`, "-p", `127.0.0.1:${port + 2}:8025`], + MAILPIT_IMAGE, + ]); + const cloudhal = envFile("cloudhal", { + ...env, + CLOUDHAL_S3_ENDPOINT: "http://seaweedfs:8333", + CLOUDHAL_S3_BUCKET: "cloudhal", + CLOUDHAL_CLUSTER_ADVERTISE: `${names.cloudhal}:7000`, + CLOUDHAL_SITE_NAME: "Mail Site", + CLOUDHAL_BASE_URL: studio, + CLOUDHAL_SMTP_URL: `smtp://cloudhal:${smtpPassword}@mailpit:1025`, + CLOUDHAL_SMTP_CA_FILE: "/run/cloudhal-mail/cert.pem", + CLOUDHAL_MAIL_FROM: "cloudhal@example.com", + CLOUDHAL_MAIL_FROM_NAME: "Cloudhal Smoke", + }); + await docker([ + ...["run", "-d", "--name", names.cloudhal, "--network", id, "--read-only", "--tmpfs", "/tmp"], + ...["--cap-drop", "ALL", "--security-opt", "no-new-privileges:true"], + ...["-v", `${tls}:/run/cloudhal-mail:ro`, "--env-file", cloudhal], + ...["-p", `127.0.0.1:${port}:8787`, "-p", `127.0.0.1:${port + 1}:8788`], + image, + ]); +} + +interface MailpitMessage { + ID: string; + To: { Address: string }[]; + Subject: string; +} +/** The message Mailpit holds for `to`, with its plain text. */ +function arrives(to: string): Promise<{ subject: string; text: string }> { + return until(`no message to ${to} arrived`, 60, async () => { + const list = await req(`${mailpitApi}/api/v1/messages`); + const found = ((list.body as { messages?: MailpitMessage[] }).messages ?? []).find((m) => + m.To.some((t) => t.Address === to), + ); + if (!found) return undefined; + const full = await req(`${mailpitApi}/api/v1/message/${found.ID}`); + return { subject: found.Subject, text: String((full.body as { Text?: string }).Text ?? "") }; + }); +} + +async function main(env: Record): Promise { + await certificate(); + await start(env); + const admin = { authorization: `Bearer ${env.CLOUDHAL_DEPLOY_TOKEN}` }; + await until("the instance did not create its site", 180, async () => { + const r = await req(`${studio}/api/admin/sites`, { headers: admin }); + const sites = (r.body as { sites?: { id: string }[] }).sites ?? []; + return sites.some((s) => s.id === env.CLOUDHAL_SITE_ID) ? true : undefined; + }); + step("Mailpit (STARTTLS and AUTH required) and an instance with CLOUDHAL_SMTP_URL are up"); + + const json = { origin: studio, "content-type": "application/json" }; + const signUp = await req(`${studio}/api/auth/sign-up/email`, { + method: "POST", + headers: { ...json, "x-cloudhal-setup-token": env.CLOUDHAL_SETUP_TOKEN as string }, + body: JSON.stringify({ + name: "Mail Owner", + email: "owner@example.com", + password: "mail-smoke-password", + }), + }); + expect(signUp.status === 200, "sign-up of the first owner", signUp.body); + const cookie = + signUp.headers + .getSetCookie() + .map((c) => c.split(";")[0] as string) + .find((c) => c.includes("better-auth.session_token=")) ?? ""; + const instance = await req(`${studio}/api/instance`, { headers: { cookie } }); + const delivery = (instance.body as { invites?: { delivery?: string[] } }).invites?.delivery; + expect(delivery?.includes("email") === true, "Studio reports email delivery", instance.body); + step("Studio reports invites by email"); + + const invite = await req(`${studio}/api/invites`, { + method: "POST", + headers: { ...json, cookie }, + body: JSON.stringify({ email: "invitee@example.org", role: "editor", delivery: "email" }), + }); + expect(invite.status === 201, "the invite by email", invite.body); + const invited = await arrives("invitee@example.org"); + expect(invited.text.includes("/invite#chinv_"), "the invite carries its link", invited.subject); + step(`the invite arrived through STARTTLS and AUTH ("${invited.subject}")`); + + const reset = await req(`${studio}/api/password-reset/request`, { + method: "POST", + headers: json, + body: JSON.stringify({ email: "owner@example.com" }), + }); + expect(reset.status === 202, "the password reset request", reset.body); + const resetMail = await arrives("owner@example.com"); + expect(resetMail.text.length > 0, "the reset mail has a text"); + step(`a password reset asked for by email arrived ("${resetMail.subject}")`); + + const logs = await dockerLogs(names.cloudhal); + const sent = logs.split("\n").filter((l) => l.includes("smtp: sent to")); + expect(sent.length >= 2, "the log names each send", sent); + expect(!logs.includes(smtpPassword), "the log holds no SMTP password"); + expect(!logs.includes("chinv_"), "the log holds no invite token"); + step("the log names both sends and holds neither the password nor a token"); + console.log("\nMail smoke test passed."); +} + +const env = Object.fromEntries( + (await docker(["run", "--rm", image, "secrets"])) + .split("\n") + .filter((l) => l.includes("=") && !l.startsWith("#")) + .map((l) => [l.slice(0, l.indexOf("=")), l.slice(l.indexOf("=") + 1)]), +) as Record; +try { + await main(env); +} catch (e) { + console.error(`\n✗ ${e instanceof Error ? e.message : String(e)}`); + for (const name of Object.values(names)) { + const text = await dockerLogs(name).catch((d: Error) => `error: ${d.message}`); + // the SMTP password is this run's own, but never print it anyway + console.error( + `--- ${name} logs\n${text.split(smtpPassword).join("").slice(-12_000)}`, + ); + } + process.exitCode = 1; +} finally { + for (const name of Object.values(names)) + await docker(["rm", "-f", "-v", name], 60_000).catch(() => undefined); + await docker(["network", "rm", id], 30_000).catch(() => undefined); + rmSync(work, { recursive: true, force: true }); +}