Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion docs/de/operator/configuration.md
Original file line number Diff line number Diff line change
Expand Up @@ -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 <no-reply@localhost>` | Absenderadresse und -name |

## Login-Anbieter
Expand Down
2 changes: 1 addition & 1 deletion docs/de/operator/firebase.md
Original file line number Diff line number Diff line change
Expand Up @@ -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://<projekt>-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` |
Expand Down
4 changes: 4 additions & 0 deletions docs/de/operator/mail.md
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,10 @@ MAIL_FROM="Wayfare <no-reply@photos.example.com>"

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
Expand Down
2 changes: 1 addition & 1 deletion docs/en/operator/configuration.md
Original file line number Diff line number Diff line change
Expand Up @@ -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 <no-reply@localhost>` | Sender address and name |

## Login providers
Expand Down
2 changes: 1 addition & 1 deletion docs/en/operator/firebase.md
Original file line number Diff line number Diff line change
Expand Up @@ -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://<project>-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 |
Expand Down
4 changes: 4 additions & 0 deletions docs/en/operator/mail.md
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,10 @@ MAIL_FROM="Wayfare <no-reply@photos.example.com>"

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
Expand Down
58 changes: 53 additions & 5 deletions scripts/firebase-bootstrap.sh
Original file line number Diff line number Diff line change
Expand Up @@ -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}$ ]]; }
Expand Down Expand Up @@ -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() {
Expand Down Expand Up @@ -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):"
Expand Down Expand Up @@ -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
Expand Down
14 changes: 13 additions & 1 deletion scripts/test/bootstrap-dry-run.sh
Original file line number Diff line number Diff line change
Expand Up @@ -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 <dev@example.com>"' 'WAYFARE_BASE_URL=https://wayfare--wayfare-demo.europe-west4.hosted.app' ;;
'MAIL_FROM="Wayfare <dev@example.com>"' '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 ;;
Expand Down Expand Up @@ -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
Expand Down
8 changes: 7 additions & 1 deletion src/server/adapters/mail/smtp.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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<typeof nodemailer.createTransport>;
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) {
Expand Down
17 changes: 16 additions & 1 deletion src/server/config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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"),
Expand All @@ -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 <no-reply@localhost>"),

AUTH_GOOGLE_ID: optStr,
Expand Down
35 changes: 27 additions & 8 deletions src/server/container.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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<Container> };
const g = globalThis as unknown as { __wayfareContainer?: Promise<Container>; __wayfareMailer?: Promise<Mailer> };

async function build(): Promise<Container> {
const cfg = config();
Expand All @@ -42,19 +42,38 @@ async function build(): Promise<Container> {
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<Mailer> {
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<Container> {
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<Mailer> {
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();
17 changes: 16 additions & 1 deletion tests/config/config.test.ts
Original file line number Diff line number Diff line change
@@ -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", () => {
Expand Down Expand Up @@ -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);
});
});
Loading