v4: every email is rendered by its template in api/mail/ on one layout that takes the instance's style, and sent one way — the welcome email was built and sent inside the register route and the reset link in its service, each writing Markdown, running marked, and calling a nodemailer wrapper whose cc, bcc, replyTo and send result nothing used. Now api/mail/ holds one template per email (welcome.ts, password-reset.ts) on layout.ts's EmailKit, which draws each block with inline styles in a style from styles.ts: the six site styles' palettes, copied from src/themes/, and what makes each recognisable in a mail client (Brutalist's hard border and shadow, GeoCities' ridge and rainbow rules, Times' underlined ink links, Kanagawa's colored quotes, dates and wordmark, Melange's spice bar). On the "auto" scheme the light palette is inlined and the dark one swapped in by a prefers-color-scheme block; a chosen scheme sends only its own. User-written text is escaped where it lands. strings.ts holds every email's words in English and French. GERBEUR_EMAIL_LOCALE picks the language and GERBEUR_DEFAULT_STYLE the instance's style, which the welcome and reset emails are drawn in; GERBEUR_WELCOME_EMAIL_BODY still replaces the welcome's Markdown, whose blocks now take the style too. email-service sends a rendered email with its recipient and headers, refuses to load when GERBEUR_SMTPS_URL is set without GERBEUR_FROM_EMAIL (sends used to fail one by one), and takes a test transport, through which the tests now read what was sent. The welcome send moves to user-service's sendWelcomeEmail. The style and scheme names move to shared/theme.ts, which the server now needs. README, mod.ts and .env.example describe mail/ and the new variables, and drop the "notifications, invites" email that never existed. 221 backend tests pass (new: the layout's schemes, styles and escaping, both templates, the welcome on sign-up, a reset link from the email that works), and deno check, deno lint, doc:lint, deno fmt, tsc and eslint are clean.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
@@ -1,121 +1,76 @@
|
||||
/**
|
||||
* Sends mail through the SMTP server of {@link SMTPS_URL}, which may be unset.
|
||||
* Its two callers, the welcome email at sign-up and the password reset link,
|
||||
* check {@link isEmailEnabled} first and don't wait for delivery.
|
||||
* Sends the site's email through the SMTP server of {@link SMTPS_URL}, which
|
||||
* may be unset. The welcome email, the password reset link and the digests go
|
||||
* through it, each rendered first by its module in `api/mail/`. They check
|
||||
* {@link isEmailEnabled} before rendering.
|
||||
*
|
||||
* Importing this module throws when {@link SMTPS_URL} is set without
|
||||
* {@link FROM_EMAIL}, so a misconfigured server doesn't start rather than fail
|
||||
* at its first send.
|
||||
*
|
||||
* @module
|
||||
*/
|
||||
|
||||
import nodemailer, { type SendMailOptions, type Transporter } from "nodemailer";
|
||||
import nodemailer from "nodemailer";
|
||||
|
||||
import { SMTPS_URL } from "../config.ts";
|
||||
import { FROM_EMAIL, SMTPS_URL } from "../config.ts";
|
||||
import type { RenderedEmail } from "../mail/layout.ts";
|
||||
|
||||
/**
|
||||
* One address, a comma-separated list of them, or an array, as nodemailer
|
||||
* takes them.
|
||||
*/
|
||||
export type EmailRecipient = string | string[];
|
||||
|
||||
/**
|
||||
* Passed to {@link sendEmail}. It needs a recipient, a subject, and a text or
|
||||
* HTML body; the callers send the same Markdown as both, rendered for `html`.
|
||||
*/
|
||||
export interface EmailMessage {
|
||||
from: string;
|
||||
to: EmailRecipient;
|
||||
subject: string;
|
||||
text?: string;
|
||||
html?: string;
|
||||
cc?: EmailRecipient;
|
||||
bcc?: EmailRecipient;
|
||||
replyTo?: string;
|
||||
if (SMTPS_URL && !FROM_EMAIL) {
|
||||
throw new Error(
|
||||
"GERBEUR_FROM_EMAIL environment variable is required when GERBEUR_SMTPS_URL is set.",
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Returned by {@link sendEmail} once the SMTP server has taken the message.
|
||||
* No caller reads it yet.
|
||||
* Passed to {@link sendEmail}: a rendered email, its recipient, and the
|
||||
* headers some emails add (the digests' `List-Unsubscribe`).
|
||||
*/
|
||||
export interface EmailSendResult {
|
||||
messageId: string;
|
||||
accepted: string[];
|
||||
rejected: string[];
|
||||
export interface OutgoingEmail extends RenderedEmail {
|
||||
to: string;
|
||||
headers?: Record<string, string>;
|
||||
}
|
||||
|
||||
let transporter: Transporter | null = null;
|
||||
/**
|
||||
* Hands a message to a mail server. nodemailer's SMTP transport is one, and
|
||||
* the tests put a recording one in its place with {@link setEmailTransport}.
|
||||
*/
|
||||
export interface EmailTransport {
|
||||
sendMail(message: OutgoingEmail & { from: string }): Promise<unknown>;
|
||||
}
|
||||
|
||||
let transport: EmailTransport | null = SMTPS_URL
|
||||
? nodemailer.createTransport(SMTPS_URL)
|
||||
: null;
|
||||
|
||||
/**
|
||||
* Checks whether an SMTP server is configured. Without one, sign-up sends no
|
||||
* welcome email and a password reset request does nothing.
|
||||
* Checks whether email can be sent. Without an SMTP server, sign-up sends no
|
||||
* welcome email, a password reset request does nothing, and no digest goes
|
||||
* out.
|
||||
*/
|
||||
export function isEmailEnabled(): boolean {
|
||||
return SMTPS_URL.length > 0;
|
||||
}
|
||||
|
||||
/** Flattens the recipient forms nodemailer takes and returns into addresses. */
|
||||
function normalizeRecipients(
|
||||
recipient: string | readonly (string | { address?: string })[] | undefined,
|
||||
): string[] {
|
||||
if (!recipient) return [];
|
||||
if (typeof recipient === "string") {
|
||||
return recipient.split(",").map((s) => s.trim()).filter(Boolean);
|
||||
}
|
||||
return recipient.flatMap((entry) =>
|
||||
typeof entry === "string" ? entry.trim() : (entry.address?.trim() ?? "")
|
||||
).filter(Boolean);
|
||||
}
|
||||
|
||||
function getTransporter(): Transporter {
|
||||
if (!isEmailEnabled()) {
|
||||
throw new Error(
|
||||
"GERBEUR_SMTPS_URL environment variable is required to send emails.",
|
||||
);
|
||||
}
|
||||
|
||||
if (!transporter) {
|
||||
transporter = nodemailer.createTransport(SMTPS_URL);
|
||||
}
|
||||
|
||||
return transporter;
|
||||
return transport !== null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Sends `message` and resolves once the SMTP server has accepted it. The
|
||||
* transport is created on the first send.
|
||||
*
|
||||
* @throws {Error} When email is disabled, the message lacks a recipient,
|
||||
* subject or body, or the server refuses it.
|
||||
* Replaces the transport, so that email is enabled and every message goes to
|
||||
* `next`; null disables email again. The tests use it to read what was sent.
|
||||
*/
|
||||
export async function sendEmail(
|
||||
message: EmailMessage,
|
||||
): Promise<EmailSendResult> {
|
||||
if (normalizeRecipients(message.to).length === 0) {
|
||||
throw new Error("Email recipient is required.");
|
||||
}
|
||||
|
||||
if (!message.subject.trim()) {
|
||||
throw new Error("Email subject is required.");
|
||||
}
|
||||
|
||||
if (!message.text?.trim() && !message.html?.trim()) {
|
||||
throw new Error("Email body is required (text and/or html).");
|
||||
}
|
||||
|
||||
const options: SendMailOptions = {
|
||||
from: message.from,
|
||||
to: message.to,
|
||||
cc: message.cc,
|
||||
bcc: message.bcc,
|
||||
subject: message.subject,
|
||||
text: message.text,
|
||||
html: message.html,
|
||||
replyTo: message.replyTo,
|
||||
};
|
||||
|
||||
const info = await getTransporter().sendMail(options);
|
||||
|
||||
return {
|
||||
messageId: info.messageId,
|
||||
accepted: normalizeRecipients(info.accepted),
|
||||
rejected: normalizeRecipients(info.rejected),
|
||||
};
|
||||
export function setEmailTransport(next: EmailTransport | null): void {
|
||||
transport = next;
|
||||
}
|
||||
|
||||
/**
|
||||
* Sends `email` from {@link FROM_EMAIL} and resolves once the SMTP server has
|
||||
* accepted it. The welcome and reset emails don't wait for it: a slow server
|
||||
* mustn't hold up the request.
|
||||
*
|
||||
* @throws {Error} When email is disabled, or when the server refuses the
|
||||
* message or can't be reached.
|
||||
*/
|
||||
export async function sendEmail(email: OutgoingEmail): Promise<void> {
|
||||
if (!transport) {
|
||||
throw new Error("Email is disabled: GERBEUR_SMTPS_URL is unset.");
|
||||
}
|
||||
await transport.sendMail({ ...email, from: FROM_EMAIL });
|
||||
}
|
||||
|
||||
@@ -16,9 +16,9 @@ import {
|
||||
} from "../lib/jwt.ts";
|
||||
import { getUserByEmail, updateUser } from "./user-service.ts";
|
||||
import { isEmailEnabled, sendEmail } from "./email-service.ts";
|
||||
import { FROM_EMAIL, FRONTEND_URL, OG_SITE_NAME } from "../config.ts";
|
||||
import { FRONTEND_URL } from "../config.ts";
|
||||
import { VALIDATION } from "../../shared/validation.ts";
|
||||
import { marked } from "marked";
|
||||
import { renderPasswordResetEmail } from "../mail/password-reset.ts";
|
||||
import { type RateLimit, takeToken } from "../lib/rate-limit.ts";
|
||||
|
||||
/** Must match the `1h` that `createPasswordResetToken` signs into the token. */
|
||||
@@ -56,15 +56,9 @@ export async function requestPasswordReset(email: string): Promise<void> {
|
||||
const resetUrl = `${FRONTEND_URL}/reset-password?token=${
|
||||
encodeURIComponent(token)
|
||||
}`;
|
||||
const body =
|
||||
`# Reset your ${OG_SITE_NAME} password\n\nHi **${user.username}**,\n\nClick the link below to set a new password. It expires in ${RESET_TOKEN_TTL_HOURS} hour.\n\n[Reset password](${resetUrl})\n\nIf you did not request this, ignore this email.`;
|
||||
|
||||
sendEmail({
|
||||
from: FROM_EMAIL,
|
||||
to: user.email,
|
||||
subject: `Reset your ${OG_SITE_NAME} password`,
|
||||
text: body,
|
||||
html: await marked(body),
|
||||
...renderPasswordResetEmail(user.username, resetUrl, RESET_TOKEN_TTL_HOURS),
|
||||
}).catch((err) =>
|
||||
console.error("[password-reset] failed to send email:", err)
|
||||
);
|
||||
|
||||
@@ -30,6 +30,8 @@ import { hashPassword } from "../lib/password.ts";
|
||||
import { linkAttachments } from "./attachment-service.ts";
|
||||
import { LIKE, likePattern } from "../lib/like.ts";
|
||||
import { parseRows } from "../model/rows.ts";
|
||||
import { isEmailEnabled, sendEmail } from "./email-service.ts";
|
||||
import { renderWelcomeEmail } from "../mail/welcome.ts";
|
||||
|
||||
/** Selects full `UserRow`s from `users u`, with the inviter's name joined. */
|
||||
const USER_SELECT =
|
||||
@@ -94,6 +96,17 @@ export async function createUser(
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Emails `user` the welcome message, if email is configured. The register
|
||||
* route calls it once the account exists, and doesn't wait: a slow or failing
|
||||
* SMTP server mustn't hold up the sign-up, so a failure is only logged.
|
||||
*/
|
||||
export function sendWelcomeEmail(user: User): void {
|
||||
if (!isEmailEnabled()) return;
|
||||
sendEmail({ to: user.email, ...renderWelcomeEmail(user.username) })
|
||||
.catch((err) => console.error("[register] welcome email failed:", err));
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns user `userId`, with their hash and email.
|
||||
*
|
||||
|
||||
Reference in New Issue
Block a user