import "server-only"; import { randomBytes } from "node:crypto"; import { mkdir, writeFile } from "node:fs/promises"; import path from "node:path"; import nodemailer from "nodemailer"; import type { PoolClient } from "pg"; import { withHousehold } from "./db"; import { unseal } from "./vault"; // Mails verschicken (26.11.40): je Haushalt ein SMTP-Zugang, Standard Resend // (smtp.resend.com, 465, Benutzer „resend“, Passwort = API-Schlüssel). Der // Schlüssel liegt nur verschlüsselt in household_mail (lib/vault.ts). // Nur für die Tests: MAIL_TEST_DIR schreibt jede Mail als JSON statt zu senden. export const RESEND = { host: "smtp.resend.com", port: 465, secure: true, username: "resend" } as const; export type MailSettings = { host: string; port: number; secure: boolean; username: string; passwordEnc: Buffer | null; fromAddress: string; fromName: string | null; }; export type Mail = { to: string; subject: string; text: string; html: string }; export class MailNotConfigured extends Error { constructor() { super("notConfigured"); } } export async function loadMail(client: PoolClient): Promise { const { rows } = await client.query( `select host, port, secure, username, password_enc as "passwordEnc", from_address as "fromAddress", from_name as "fromName" from household_mail`, ); return rows[0] ?? null; } /** Schickt eine Mail über den Zugang des Haushalts. Wirft MailNotConfigured oder den SMTP-Fehler. */ export async function sendMail(householdId: string, mail: Mail): Promise { const settings = await withHousehold(householdId, loadMail); if (!settings?.passwordEnc) throw new MailNotConfigured(); // Kein Anführungszeichen, kein Zeilenumbruch: nichts, was einen Kopf der Mail aufbrechen könnte. const display = settings.fromName?.replace(/["\\\x00-\x1f\x7f]/g, "").trim(); const from = display ? `"${display}" <${settings.fromAddress}>` : settings.fromAddress; const dir = process.env.MAIL_TEST_DIR; if (dir) { await mkdir(dir, { recursive: true }); const name = `${Date.now()}-${randomBytes(4).toString("hex")}.json`; await writeFile(path.join(dir, name), JSON.stringify({ from, ...mail }), { mode: 0o600 }); return; } const transport = nodemailer.createTransport({ host: settings.host, port: settings.port, secure: settings.secure, auth: { user: settings.username, pass: await unseal(settings.passwordEnc) }, connectionTimeout: 10_000, greetingTimeout: 10_000, socketTimeout: 20_000, }); await transport.sendMail({ from, to: mail.to, subject: mail.subject, text: mail.text, html: mail.html }); } const escape = (s: string) => s.replace(/[&<>"']/g, (c) => ({ "&": "&", "<": "<", ">": ">", '"': """, "'": "'" })[c]!); /** Eine schlichte Mail: Satz, Knopf, Hinweis. Keine Bilder von außen, kein Tracking. */ export function buttonMail(p: { to: string; subject: string; lead: string; button: string; url: string; note: string }): Mail { const text = `${p.lead}\n\n${p.url}\n\n${p.note}\n\n— foodplanhero`; const html = `

foodplanhero

${escape(p.lead)}

${escape(p.button)}

${escape(p.note)}

`; return { to: p.to, subject: p.subject, text, html }; } /** * Mails zur Runde (26.11.53): Kopf in Koralle, große Frist-Box, Knopf, kurze Liste, * Fuß mit Abmelde-Link. Nur Inline-Stile, keine Bilder von außen, kein Tracking — * die Gerichtsfotos sind privat und bleiben auf der Box. */ export function roundMail(p: { to: string; subject: string; preheader: string; eyebrow: string; title: string; lead: string; box?: { big: string; small: string } | null; points?: string[]; listTitle?: string; list?: { title: string; meta: string }[]; button: string; url: string; footer: string; unsubscribe: { label: string; url: string }; }): Mail { const lines = [ p.title, "", p.lead, ...(p.box ? ["", `${p.box.big} — ${p.box.small}`] : []), ...(p.points?.length ? ["", ...p.points.map((x) => `• ${x}`)] : []), ...(p.list?.length ? ["", p.listTitle ?? "", ...p.list.map((x) => `• ${x.title}${x.meta ? ` (${x.meta})` : ""}`)] : []), "", `${p.button}: ${p.url}`, "", p.footer, `${p.unsubscribe.label}: ${p.unsubscribe.url}`, ]; const box = p.box ? `

${escape(p.box.big)}

${escape(p.box.small)}

` : ""; const points = p.points?.length ? `` : ""; const list = p.list?.length ? `

${escape(p.listTitle ?? "")}

${p.list .map( (x) => ``, ) .join("")}
${escape(x.title)}${escape(x.meta)}
` : ""; const html = ` ${escape(p.preheader)}

${escape(p.eyebrow)}

${escape(p.title)}

${escape(p.lead)}

${box}${points}${list}

${escape(p.button)}

${escape(p.footer)}
${escape(p.unsubscribe.label)}

`; return { to: p.to, subject: p.subject, text: lines.join("\n"), html }; }