diff --git a/docs/de/operator/configuration.md b/docs/de/operator/configuration.md index 8081459..2474f20 100644 --- a/docs/de/operator/configuration.md +++ b/docs/de/operator/configuration.md @@ -41,7 +41,7 @@ Boolesche Werte akzeptieren `true`, `false`, `1`, `0`. Ein leerer Wert bedeutet | Schlüssel | Standard | Beschreibung | |---|---|---| -| `SMTP_URL` | *(leer)* | **Secret.** z. B. `smtps://user:pass@smtp.example.com:465`. Leer = Mails (inkl. Magic Links) werden ins Server-Log geschrieben | +| `SMTP_URL` | *(leer)* | **Secret.** z. B. `smtps://user:pass@smtp.example.com:465`. Leer = Mails (inkl. Magic Links) werden ins Server-Log geschrieben. Wird beim Start geprüft: Eine fehlerhafte URL stoppt die App mit einer klaren Meldung (ohne das Passwort auszugeben) | | `MAIL_FROM` | `Wayfare ` | Absenderadresse und -name | ## Login-Anbieter diff --git a/docs/de/operator/firebase.md b/docs/de/operator/firebase.md index 3c5beb7..852b5eb 100644 --- a/docs/de/operator/firebase.md +++ b/docs/de/operator/firebase.md @@ -35,7 +35,7 @@ Das Skript ist idempotent: Es prüft, was schon existiert, und legt nur Fehlende | 5 APIs | Aktiviert die nötigen APIs (Firebase, App Hosting, Cloud Build, Cloud Run, Artifact Registry, Secret Manager, Firestore, Storage, Scheduler, …) und fügt dem Projekt Firebase hinzu | | 6 Regionen | App-Hosting-Region (`europe-west4`, `us-central1` oder `asia-east1`) und Firestore-Standort | | 7 Daten | Firestore-Datenbank (Native-Modus) und ein **privater** Bucket `gs://-wayfare-media` (Uniform Access, Public-Access-Prevention) | -| 8 Konfiguration | Baut das Secret `WAYFARE_ENV`: Admin-E-Mail(s), Absenderadresse, optional SMTP, Login-Anbieter, Google-Foto-Import, eigene Domain. Erzeugt `WAYFARE_SECRET` und `CRON_SECRET` einmalig und **hält sie bei erneuten Läufen stabil** | +| 8 Konfiguration | Baut das Secret `WAYFARE_ENV`: Admin-E-Mail(s), Absenderadresse, optional SMTP (geführt: Host, Port, Benutzer, Passwort – die URL wird korrekt kodiert zusammengesetzt; eine gespeicherte fehlerhafte `SMTP_URL` wird erkannt), Login-Anbieter, Google-Foto-Import, eigene Domain. Erzeugt `WAYFARE_SECRET` und `CRON_SECRET` einmalig und **hält sie bei erneuten Läufen stabil** | | 9 Backend | Legt das App-Hosting-Backend `wayfare` an, erlaubt ihm das Lesen des Secrets und gibt seinem Dienstkonto `roles/datastore.user` (Projekt) und `roles/storage.objectAdmin` (Bucket) | | 10 Deploy | `firebase deploy` von Firestore-Regeln/-Indizes und Backend aus dem Klon | | 11 Messen | Wartet auf `/api/health`, misst dann, wie viele Proxys vor der App sitzen (siehe unten), und korrigiert bei Bedarf `WAYFARE_TRUSTED_PROXIES` | diff --git a/docs/de/operator/mail.md b/docs/de/operator/mail.md index b37a761..75b5155 100644 --- a/docs/de/operator/mail.md +++ b/docs/de/operator/mail.md @@ -11,6 +11,10 @@ MAIL_FROM="Wayfare " Nutze `smtps://` (implizites TLS, Port 465) oder `smtp://…:587` mit STARTTLS. Sonderzeichen im Passwort müssen URL-kodiert werden (`@` → `%40`). Jeder Anbieter funktioniert (Mailgun, Postmark, Brevo, eigener Server, Gmail mit App-Passwort …). +**Gmail:** `SMTP_URL=smtps://du%40gmail.com:APP-PASSWORT@smtp.gmail.com:465` – Host ist `smtp.gmail.com`, nicht `gmail.com`. Das [App-Passwort](https://myaccount.google.com/apppasswords) braucht die Bestätigung in zwei Schritten und wird ohne Leerzeichen eingetragen; `MAIL_FROM` sollte dieselbe Adresse sein. + +Eine fehlerhafte `SMTP_URL` (z. B. ohne Host) stoppt Wayfare beim Start mit einer Fehlermeldung, statt erst beim Versand aufzufallen. + Sorge dafür, dass die Absenderdomain zustellbar ist: Richte **SPF**, **DKIM** und **DMARC** für die Domain in `MAIL_FROM` ein, sonst landen Magic Links im Spam. ## Ohne SMTP diff --git a/docs/en/operator/configuration.md b/docs/en/operator/configuration.md index 8bcd525..fb239e3 100644 --- a/docs/en/operator/configuration.md +++ b/docs/en/operator/configuration.md @@ -41,7 +41,7 @@ Booleans accept `true`, `false`, `1`, `0`. An empty value means "use the default | Key | Default | Description | |---|---|---| -| `SMTP_URL` | *(empty)* | **Secret.** e.g. `smtps://user:pass@smtp.example.com:465`. Empty = mails (incl. magic links) are written to the server log | +| `SMTP_URL` | *(empty)* | **Secret.** e.g. `smtps://user:pass@smtp.example.com:465`. Empty = mails (incl. magic links) are written to the server log. Validated at startup: a malformed URL stops the app with a clear message (without printing the password) | | `MAIL_FROM` | `Wayfare ` | Sender address and name | ## Login providers diff --git a/docs/en/operator/firebase.md b/docs/en/operator/firebase.md index fab3447..c6f3a58 100644 --- a/docs/en/operator/firebase.md +++ b/docs/en/operator/firebase.md @@ -35,7 +35,7 @@ The script is idempotent: it checks what already exists and only creates what is | 5 APIs | Enables the required APIs (Firebase, App Hosting, Cloud Build, Cloud Run, Artifact Registry, Secret Manager, Firestore, Storage, Scheduler, …) and adds Firebase to the project | | 6 Regions | App Hosting region (`europe-west4`, `us-central1` or `asia-east1`) and Firestore location | | 7 Data | Firestore database (native mode) and a **private** bucket `gs://-wayfare-media` (uniform access, public access prevention) | -| 8 Configuration | Builds the `WAYFARE_ENV` secret: admin e-mail(s), sender address, optional SMTP, optional login providers, optional Google photo import, optional custom domain. Generates `WAYFARE_SECRET` and `CRON_SECRET` once and **keeps them stable** on re-runs | +| 8 Configuration | Builds the `WAYFARE_ENV` secret: admin e-mail(s), sender address, optional SMTP (guided: host, port, user, password – the URL is assembled and encoded for you; a stored malformed `SMTP_URL` is detected), optional login providers, optional Google photo import, optional custom domain. Generates `WAYFARE_SECRET` and `CRON_SECRET` once and **keeps them stable** on re-runs | | 9 Backend | Creates the App Hosting backend `wayfare`, lets it read the secret, grants its service account `roles/datastore.user` (project) and `roles/storage.objectAdmin` (bucket) | | 10 Deploy | `firebase deploy` of Firestore rules/indexes and the backend from the clone | | 11 Measure | Waits for `/api/health`, then measures how many proxies sit in front of the app (see below) and corrects `WAYFARE_TRUSTED_PROXIES` if needed | diff --git a/docs/en/operator/mail.md b/docs/en/operator/mail.md index 3ab268a..3d52343 100644 --- a/docs/en/operator/mail.md +++ b/docs/en/operator/mail.md @@ -11,6 +11,10 @@ MAIL_FROM="Wayfare " Use `smtps://` (implicit TLS, port 465) or `smtp://…:587` with STARTTLS. URL-encode special characters in the password (`@` → `%40`). Any provider works (Mailgun, Postmark, Brevo, your own server, Gmail with an app password …). +**Gmail:** `SMTP_URL=smtps://you%40gmail.com:APP-PASSWORD@smtp.gmail.com:465` – the host is `smtp.gmail.com`, not `gmail.com`. The [app password](https://myaccount.google.com/apppasswords) requires 2-step verification and is entered without spaces; `MAIL_FROM` should be the same address. + +A malformed `SMTP_URL` (e.g. without a host) stops Wayfare at startup with an error message instead of surfacing only when a mail is sent. + Make the sender domain deliverable: configure **SPF**, **DKIM** and **DMARC** for the domain in `MAIL_FROM`, or magic links will end up in spam. ## Without SMTP diff --git a/scripts/firebase-bootstrap.sh b/scripts/firebase-bootstrap.sh index b2e929a..883e9f8 100755 --- a/scripts/firebase-bootstrap.sh +++ b/scripts/firebase-bootstrap.sh @@ -147,7 +147,13 @@ v_email_list() { # one or more, comma separated } v_project_id() { [[ $1 =~ ^[a-z][a-z0-9-]{4,28}[a-z0-9]$ ]]; } v_https_url_opt() { [ -z "$1" ] || [[ $1 =~ ^https://[A-Za-z0-9.-]+(:[0-9]+)?(/[^[:space:]]*)?$ ]]; } -v_smtp_opt() { [ -z "$1" ] || [[ $1 =~ ^smtps?://[^[:space:]]+$ ]]; } +# Same rule as isValidSmtpUrl() in src/server/config.ts (the app refuses to start with a malformed SMTP_URL). +v_smtp_opt() { + [ -z "$1" ] && return 0 + node -e 'try{const u=new URL(process.argv[1]);process.exit((u.protocol==="smtp:"||u.protocol==="smtps:")&&/^(localhost|[0-9.]+|([A-Za-z0-9-]+\.)+[A-Za-z]{2,})$/.test(u.hostname)?0:1)}catch{process.exit(1)}' "$1" +} +v_hostname() { [[ $1 =~ ^([A-Za-z0-9-]+\.)+[A-Za-z]{2,}$ ]]; } +v_port() { [[ $1 =~ ^[0-9]{2,5}$ ]] && [ "$1" -le 65535 ]; } v_nonempty() { [ -n "$1" ]; } v_mail_from() { [[ $1 == *@* ]]; } v_timezone() { [[ $1 =~ ^[A-Za-z_]+(/[A-Za-z0-9_+-]+){0,2}$ ]]; } @@ -580,6 +586,36 @@ step_data() { state_save } +smtp_part() { # smtp_part host|port|user -> component of the current SMTP_URL (user decoded) + node -e 'try{const u=new URL(process.argv[1]);const p={host:u.hostname,port:u.port||(u.protocol==="smtps:"?"465":"587"),user:decodeURIComponent(u.username)};console.log(p[process.argv[2]]||"")}catch{}' "$(env_get SMTP_URL)" "$1" +} + +# Asks for host / port / user in the clear and only the password hidden, then builds a correctly +# URL-encoded SMTP_URL (a hand-typed URL with hidden input is too easy to get wrong). +smtp_setup() { + local host port user pass url cur_host="" cur_port="" cur_user="" + if env_has SMTP_URL && v_smtp_opt "$(env_get SMTP_URL)"; then + cur_host=$(smtp_part host); cur_port=$(smtp_part port); cur_user=$(smtp_part user) + fi + note "Gmail: host smtp.gmail.com, port 465, user = your Gmail address, password = an app password" + note " (https://myaccount.google.com/apppasswords, needs 2-step verification). MAIL_FROM should be that address." + while true; do + ask host "SMTP host (e.g. smtp.gmail.com):" "$cur_host" v_hostname + ask port "SMTP port (465 = TLS, 587 = STARTTLS):" "${cur_port:-465}" v_port + ask user "SMTP user name (often the full e-mail address):" "${cur_user:-$(env_get WAYFARE_ADMIN_EMAILS | cut -d, -f1)}" v_nonempty + ask_secret pass "SMTP password:" v_nonempty + [ "$host" = smtp.gmail.com ] && pass=${pass// /} # app passwords are displayed in groups of four + url=$(node -e 'const [h,p,u,pw]=process.argv.slice(1);console.log(`${p==="465"?"smtps":"smtp"}://${encodeURIComponent(u)}:${encodeURIComponent(pw)}@${h}:${p}`)' "$host" "$port" "$user" "$pass") + SECRET_MASKS+=("$url" "$(node -e 'console.log(encodeURIComponent(process.argv[1]))' "$pass")") + if v_smtp_opt "$url"; then + env_set SMTP_URL "$url" + ok "SMTP_URL set (host $host, port $port, user $user)." + return 0 + fi + warn "Could not build a valid SMTP URL from these values, please try again." + done +} + default_base_url() { printf 'https://%s--%s.%s.hosted.app' "$BACKEND" "$PROJECT_ID" "$REGION"; } step_config() { @@ -634,10 +670,11 @@ step_config() { BASE_URL=$(env_get WAYFARE_BASE_URL) note "SMTP is needed for magic-link sign-in and notifications in production (without it mails are only logged)." - note "Format: smtps://user:password@smtp.example.com:465" - local smtp - ask_secret smtp "SMTP_URL (empty = keep ${E[SMTP_URL]+current/}none):" v_smtp_opt - [ -n "$smtp" ] && env_set SMTP_URL "$smtp" + if env_has SMTP_URL && v_smtp_opt "$(env_get SMTP_URL)"; then + if ask_yn "SMTP is configured (host: $(smtp_part host)). Change it?" n; then smtp_setup; fi + elif ask_yn "Configure SMTP now?" n; then + smtp_setup + fi if ask_yn "Enable Google sign-in?" n; then info "Create an OAuth client (type: Web application):" @@ -689,6 +726,17 @@ step_config() { fi [ "$WANT_PHOTO_IMPORT" = yes ] && env_set GOOGLE_APP_ID "$PROJECT_NUMBER" + # A malformed SMTP_URL stops the app at startup - never store one. + if env_has SMTP_URL && ! v_smtp_opt "$(env_get SMTP_URL)"; then + warn "The stored SMTP_URL is malformed (expected smtps://user:password@smtp.example.com:465)." + if [ "$ASSUME_YES" != 1 ] && ask_yn "Re-enter the SMTP settings now? (no = remove SMTP_URL)" y; then + smtp_setup + else + env_set SMTP_URL "" + warn "SMTP_URL removed - mails are only logged until you run this script with --reconfigure." + fi + fi + echo info "Configuration to be stored (secrets masked):" env_summary diff --git a/scripts/test/bootstrap-dry-run.sh b/scripts/test/bootstrap-dry-run.sh index dba162b..4621777 100755 --- a/scripts/test/bootstrap-dry-run.sh +++ b/scripts/test/bootstrap-dry-run.sh @@ -34,7 +34,9 @@ case "$a" in resume || exit 1 printf '%s\n' 'WAYFARE_SECRET=SEKRET-do-not-leak-0123456789-0123456789-abcdef' 'CRON_SECRET=CRON-do-not-leak-0123456789' \ 'FIREBASE_STORAGE_BUCKET=wayfare-demo-wayfare-media' 'WAYFARE_TRUSTED_PROXIES=2' 'WAYFARE_ADMIN_EMAILS=dev@example.com' \ - 'MAIL_FROM="Wayfare "' 'WAYFARE_BASE_URL=https://wayfare--wayfare-demo.europe-west4.hosted.app' ;; + 'MAIL_FROM="Wayfare "' 'WAYFARE_BASE_URL=https://wayfare--wayfare-demo.europe-west4.hosted.app' + [ "${STUB_BAD_SMTP:-0}" = 1 ] && echo 'SMTP_URL=smtps://dev%40example.com:BADPASS-do-not-leak@://example.com' + true ;; "iam service-accounts describe"*) resume && echo "x@y" || exit 1 ;; "iam service-accounts list"*) echo "firebase-app-hosting-compute@wayfare-demo.iam.gserviceaccount.com" ;; "iam workload-identity-pools describe"*|"iam workload-identity-pools providers describe"*) resume && echo name || exit 1 ;; @@ -136,6 +138,16 @@ check "backends:create not called" 'backends:create' "$OUT" -v m=$(mutating_calls) [ -z "$m" ] && echo " ok: no mutating call executed" || { echo " FAIL: mutating calls executed:"; echo "$m"; fail=1; } +# ------------------------------------------------------------------ B2: stored SMTP_URL is malformed (would stop the app) +mkdir -p "$work/home-badsmtp/.config/wayfare" +cp "$work/home-resume/.config/wayfare/bootstrap.env" "$work/home-badsmtp/.config/wayfare/" +scenario badsmtp 1 STUB_BAD_SMTP=1 -- --dry-run --yes +[ "$RC" = 0 ] || { echo " FAIL: exit code $RC"; tail -20 "$OUT"; fail=1; } +check "malformed SMTP_URL detected" 'stored SMTP_URL is malformed' "$OUT" +check "malformed SMTP_URL removed (--yes)" 'SMTP_URL removed' "$OUT" +check "new secret version written" 'secrets versions add WAYFARE_ENV' "$OUT" +check "SMTP password never printed" 'BADPASS-do-not-leak' "$OUT" -v + # ------------------------------------------------------------------ C: billing link fails (real run against stubs, no cloud, no network) mkdir -p "$work/home-billing-fail/.config/wayfare" "$work/bf-clone" git -C "$work/bf-clone" init -q diff --git a/src/server/adapters/mail/smtp.ts b/src/server/adapters/mail/smtp.ts index 1624a3c..535c522 100644 --- a/src/server/adapters/mail/smtp.ts +++ b/src/server/adapters/mail/smtp.ts @@ -4,7 +4,13 @@ import type { Mailer } from "../../ports/mailer"; /** SMTP mailer (nodemailer). `url` e.g. smtp://user:pass@host:587 or smtps://user:pass@host:465. */ export function createSmtpMailer(url: string, from: string): Mailer { - const transport = nodemailer.createTransport(url); + let transport: ReturnType; + try { + transport = nodemailer.createTransport(url); + } catch { + // Never let the URL (it contains the SMTP password) reach logs or error pages. + throw new Error("Invalid SMTP_URL - expected smtps://user:password@smtp.example.com:465"); + } return { kind: "smtp", async send(msg) { diff --git a/src/server/config.ts b/src/server/config.ts index 87a3e69..1eb75e1 100644 --- a/src/server/config.ts +++ b/src/server/config.ts @@ -18,6 +18,21 @@ const optStr = z .optional() .transform((v) => (v && v.trim() !== "" ? v.trim() : undefined)); +/** smtp(s)://[user[:password]@]host[:port] — validated at startup so a typo fails loudly (without echoing the secret). */ +export function isValidSmtpUrl(v: string): boolean { + try { + const u = new URL(v); + if (u.protocol !== "smtp:" && u.protocol !== "smtps:") return false; + return /^(localhost|[0-9.]+|([A-Za-z0-9-]+\.)+[A-Za-z]{2,})$/.test(u.hostname); + } catch { + return false; + } +} + +const smtpUrl = optStr.refine((v) => v === undefined || isValidSmtpUrl(v), { + message: "SMTP_URL must look like smtps://user:password@smtp.example.com:465 (URL-encode special characters, e.g. @ as %40)", +}); + const schema = z.object({ WAYFARE_RUNTIME: z.enum(["selfhost", "firebase"]).default("selfhost"), WAYFARE_BASE_URL: z.string().url().default("http://localhost:3000"), @@ -42,7 +57,7 @@ const schema = z.object({ /** Optional service-account JSON (stringified). Without it, Application Default Credentials are used. */ FIREBASE_SERVICE_ACCOUNT: optStr, - SMTP_URL: optStr, + SMTP_URL: smtpUrl, MAIL_FROM: z.string().default("Wayfare "), AUTH_GOOGLE_ID: optStr, diff --git a/src/server/container.ts b/src/server/container.ts index 13deb71..747022a 100644 --- a/src/server/container.ts +++ b/src/server/container.ts @@ -18,9 +18,9 @@ import type { Mailer } from "./ports/mailer"; * loaded in a self-hosted deployment and vice versa. */ -type Container = { db: DocumentStore; blobs: BlobStorage; mailer: Mailer }; +type Container = { db: DocumentStore; blobs: BlobStorage }; -const g = globalThis as unknown as { __wayfareContainer?: Promise }; +const g = globalThis as unknown as { __wayfareContainer?: Promise; __wayfareMailer?: Promise }; async function build(): Promise { const cfg = config(); @@ -42,19 +42,38 @@ async function build(): Promise { blobs = (await import("./adapters/storage/local")).createLocalStorage(`${cfg.DATA_DIR}/blobs`); } - const mailer: Mailer = cfg.SMTP_URL + return { db, blobs }; +} + +/** The mailer is built separately: a broken mail setup must not take the database down with it. */ +async function buildMailer(): Promise { + const cfg = config(); + return cfg.SMTP_URL ? (await import("./adapters/mail/smtp")).createSmtpMailer(cfg.SMTP_URL, cfg.MAIL_FROM) : (await import("./adapters/mail/console")).createConsoleMailer(); - - return { db, blobs, mailer }; } -/** Process-wide singleton (survives Next.js dev HMR via globalThis). */ +/** Process-wide singleton (survives Next.js dev HMR via globalThis). A failed build is not cached. */ export function container(): Promise { - if (!g.__wayfareContainer) g.__wayfareContainer = build(); + if (!g.__wayfareContainer) { + g.__wayfareContainer = build().catch((e) => { + g.__wayfareContainer = undefined; + throw e; + }); + } return g.__wayfareContainer; } +function mailer(): Promise { + if (!g.__wayfareMailer) { + g.__wayfareMailer = buildMailer().catch((e) => { + g.__wayfareMailer = undefined; + throw e; + }); + } + return g.__wayfareMailer; +} + export const getDb = async () => (await container()).db; export const getBlobs = async () => (await container()).blobs; -export const getMailer = async () => (await container()).mailer; +export const getMailer = () => mailer(); diff --git a/tests/config/config.test.ts b/tests/config/config.test.ts index 0247239..2e685b3 100644 --- a/tests/config/config.test.ts +++ b/tests/config/config.test.ts @@ -1,5 +1,5 @@ import { describe, expect, it } from "vitest"; -import { effectiveEnv, parseDotenv } from "@/server/config"; +import { effectiveEnv, isValidSmtpUrl, parseDotenv } from "@/server/config"; describe("parseDotenv", () => { it("parses comments, quotes, export prefix and escapes", () => { @@ -44,3 +44,18 @@ describe("effectiveEnv", () => { expect(effectiveEnv({} as unknown as NodeJS.ProcessEnv).FIREBASE_PROJECT_ID).toBeUndefined(); }); }); + +describe("isValidSmtpUrl", () => { + it("accepts well-formed smtp/smtps URLs", () => { + expect(isValidSmtpUrl("smtps://me%40gmail.com:app-pass@smtp.gmail.com:465")).toBe(true); + expect(isValidSmtpUrl("smtp://user:pass@mail.example.org:587")).toBe(true); + expect(isValidSmtpUrl("smtp://localhost:1025")).toBe(true); + }); + + it("rejects malformed URLs", () => { + expect(isValidSmtpUrl("smtps://me%40gmail.com:pass@://gmail.com")).toBe(false); // real-world typo + expect(isValidSmtpUrl("https://smtp.example.com")).toBe(false); + expect(isValidSmtpUrl("smtp.gmail.com")).toBe(false); + expect(isValidSmtpUrl("smtps://user:pass@gmail")).toBe(false); + }); +});