Email for professionals and teams
Send the password reset email in the language the user chose (#136)
Can K.9a3bb6a248c2
diff --git a/public/locales/tr.json b/public/locales/tr.jsonindex 2db82cd..0f29ff3 100644--- a/public/locales/tr.json+++ b/public/locales/tr.json@@ -760,6 +760,10 @@"auth.forgot.description": "Oturum açtığınız adresi girin. Hesaptaki kurtarma e-postasına bir sıfırlama bağlantısı göndereceğiz.","auth.sending": "Gönderiliyor...","auth.sendReset": "Sıfırlama bağlantısı gönder",+ "auth.resetMail.subject": "{appName} parolanızı sıfırlayın",+ "auth.resetMail.intro": "Biri {appName} üzerindeki {email} hesabının parolasını sıfırlamak istedi.",+ "auth.resetMail.instructions": "Yeni bir parola seçmek için bu bağlantıyı {minutes} dakika içinde açın:",+ "auth.resetMail.ignore": "Bu istek size ait değilse bu iletiyi yok sayabilirsiniz; parolanız olduğu gibi kalır.","auth.reset.mismatch": "Parolalar eşleşmiyor","auth.reset.failed": "Parola sıfırlanamadı","auth.reset.linkMissing": "Sıfırlama bağlantısı eksik",diff --git a/src/app/api/auth/password-reset/request/route.ts b/src/app/api/auth/password-reset/request/route.tsindex 5b8dba9..7082124 100644--- a/src/app/api/auth/password-reset/request/route.ts+++ b/src/app/api/auth/password-reset/request/route.ts@@ -6,6 +6,7 @@ import { verifyTurnstileToken } from "@/lib/auth/turnstile";import { readJsonBody } from "@/lib/http/request";import { RequestBodyTooLargeError } from "@/lib/http/errors";import { requestPasswordReset } from "@/lib/auth/password-reset";+import { getServerTranslator } from "@/lib/i18n/server";/*** Always answers 200 once the input is well-formed, whether or not the@@ -33,7 +34,7 @@ export async function POST(request: Request) {const origin = env.APP_URL?.trim() || new URL(request.url).origin;try {- await requestPasswordReset(env, parsed.data.email, origin);+ await requestPasswordReset(env, parsed.data.email, origin, await getServerTranslator());} catch (error) {// Delivery problems are logged, never surfaced: the answer stays uniform.console.error("Password reset request failed", error);diff --git a/src/lib/auth/password-reset-utils.ts b/src/lib/auth/password-reset-utils.tsindex aaa7a51..280813e 100644--- a/src/lib/auth/password-reset-utils.ts+++ b/src/lib/auth/password-reset-utils.ts@@ -1,3 +1,24 @@+import type { Translator } from "@/lib/i18n/utils";+export function escapeHtml(value: string): string {return value.replace(/&/g, "&").replace(/</g, "<").replace(/>/g, ">").replace(/"/g, """);}++export function buildPasswordResetEmail(+ t: Translator,+ { email, appName, link, minutes }: { email: string; appName: string; link: string; minutes: number },+): { subject: string; text: string; html: string } {+ const ignore = t("auth.resetMail.ignore");+ return {+ subject: t("auth.resetMail.subject", { appName }),+ text: [+ t("auth.resetMail.intro", { email, appName }),+ "",+ t("auth.resetMail.instructions", { minutes }),+ link,+ "",+ ignore,+ ].join("\n"),+ html: `<p>${t("auth.resetMail.intro", { email: `<b>${escapeHtml(email)}</b>`, appName: escapeHtml(appName) })}</p><p>${escapeHtml(t("auth.resetMail.instructions", { minutes }))}</p><p><a href="${escapeHtml(link)}">${escapeHtml(link)}</a></p><p>${escapeHtml(ignore)}</p>`,+ };+}diff --git a/src/lib/auth/password-reset.ts b/src/lib/auth/password-reset.tsindex 3164de9..59fa374 100644--- a/src/lib/auth/password-reset.ts+++ b/src/lib/auth/password-reset.ts@@ -7,7 +7,8 @@ import { deleteUserSessions, hashSessionToken } from "@/lib/auth/session";import { getBranding } from "@/lib/branding/service";import { sendSystemEmail } from "@/lib/email/system-mail";import { createAuditLog } from "@/lib/mailboxes/audit";-import { escapeHtml } from "@/lib/auth/password-reset-utils";+import { buildPasswordResetEmail } from "@/lib/auth/password-reset-utils";+import type { Translator } from "@/lib/i18n/utils";const TOKEN_MINUTES = 30;@@ -16,7 +17,7 @@ const TOKEN_MINUTES = 30;* the account exists or has one: the caller always answers the same way, so* the form cannot be used to probe for addresses.*/-export async function requestPasswordReset(env: CloudflareEnv, email: string, origin: string): Promise<void> {+export async function requestPasswordReset(env: CloudflareEnv, email: string, origin: string, t: Translator): Promise<void> {const db = getDb(env);const [user] = await db.select().from(users).where(eq(users.email, email.trim().toLowerCase())).limit(1);if (!user || user.disabled || !user.resetEmail) return;@@ -33,16 +34,7 @@ export async function requestPasswordReset(env: CloudflareEnv, email: string, orconst { appName } = await getBranding(env);const sent = await sendSystemEmail(env, {to: user.resetEmail,- subject: `Reset your ${appName} password`,- text: [- `Someone asked to reset the password for ${user.email} on ${appName}.`,- "",- `Open this link within ${TOKEN_MINUTES} minutes to choose a new password:`,- link,- "",- "If that was not you, you can ignore this message; the password stays as it is.",- ].join("\n"),- html: `<p>Someone asked to reset the password for <b>${escapeHtml(user.email)}</b> on ${escapeHtml(appName)}.</p><p>Open this link within ${TOKEN_MINUTES} minutes to choose a new password:</p><p><a href="${escapeHtml(link)}">${escapeHtml(link)}</a></p><p>If that was not you, you can ignore this message; the password stays as it is.</p>`,+ ...buildPasswordResetEmail(t, { email: user.email, appName, link, minutes: TOKEN_MINUTES }),});if (!sent) console.warn("Password reset requested but no domain can send mail; link not delivered");}diff --git a/src/lib/i18n/en.json b/src/lib/i18n/en.jsonindex c2ab972..08b2d84 100644--- a/src/lib/i18n/en.json+++ b/src/lib/i18n/en.json@@ -769,6 +769,10 @@"auth.forgot.description": "Enter the address you sign in with. We will send a reset link to the recovery email on the account.","auth.sending": "Sending...","auth.sendReset": "Send reset link",+ "auth.resetMail.subject": "Reset your {appName} password",+ "auth.resetMail.intro": "Someone asked to reset the password for {email} on {appName}.",+ "auth.resetMail.instructions": "Open this link within {minutes} minutes to choose a new password:",+ "auth.resetMail.ignore": "If that was not you, you can ignore this message; the password stays as it is.","auth.reset.mismatch": "Passwords do not match","auth.reset.failed": "Could not reset the password","auth.reset.linkMissing": "Reset link missing",diff --git a/tests/password-reset-email.test.mjs b/tests/password-reset-email.test.mjsnew file mode 100644index 0000000..63ae006--- /dev/null+++ b/tests/password-reset-email.test.mjs@@ -0,0 +1,71 @@+import assert from "node:assert/strict";+import { mkdtempSync, readFileSync, rmSync } from "node:fs";+import { dirname, join } from "node:path";+import test from "node:test";+import { fileURLToPath, pathToFileURL } from "node:url";+import { build } from "esbuild";++const root = join(dirname(fileURLToPath(import.meta.url)), "..");+const bundleDirectory = mkdtempSync(join(root, "node_modules", "mailflare-reset-bundle-"));+await build({+ stdin: {+ contents: `+ export { buildPasswordResetEmail } from "./src/lib/auth/password-reset-utils.ts";+ export { createTranslator } from "./src/lib/i18n/utils.ts";+ `,+ resolveDir: root,+ sourcefile: "reset-test-entry.ts",+ },+ outfile: join(bundleDirectory, "entry.mjs"),+ bundle: true,+ platform: "node",+ format: "esm",+ target: "node24",+ tsconfig: join(root, "tsconfig.json"),+ packages: "external",+ loader: { ".json": "json" },+ logLevel: "silent",+});+const { buildPasswordResetEmail, createTranslator } = await import(pathToFileURL(join(bundleDirectory, "entry.mjs")).href);+rmSync(bundleDirectory, { recursive: true, force: true });++const turkish = JSON.parse(readFileSync(join(root, "public", "locales", "tr.json"), "utf8"));+const input = { email: "[email protected]", appName: "Posta", link: "https://mail.example.com/reset-password?token=abc&x=1", minutes: 30 };++test("the reset mail is in English by default", () => {+ const mail = buildPasswordResetEmail(createTranslator("en"), input);+ assert.equal(mail.subject, "Reset your Posta password");+ assert.match(mail.text, /Someone asked to reset the password for [email protected] on Posta\./);+ assert.match(mail.text, /within 30 minutes/);+ assert.match(mail.text, /If that was not you/);+});++test("the reset mail follows the chosen language", () => {+ const mail = buildPasswordResetEmail(createTranslator("tr", turkish), input);+ assert.equal(mail.subject, "Posta parolanızı sıfırlayın");+ assert.match(mail.text, /30 dakika içinde/);+ assert.match(mail.text, /parolanız olduğu gibi kalır/);+ assert.ok(!/Someone asked|If that was not you/.test(mail.text + mail.html));+});++test("the link is never translated or altered", () => {+ for (const t of [createTranslator("en"), createTranslator("tr", turkish)]) {+ const mail = buildPasswordResetEmail(t, input);+ assert.ok(mail.text.includes(input.link));+ assert.ok(mail.html.includes("https://mail.example.com/reset-password?token=abc&x=1"));+ }+});++test("addresses and names are escaped in the HTML part only", () => {+ const mail = buildPasswordResetEmail(createTranslator("en"), { ...input, email: "a<b>@example.com", appName: "R&D <Mail>" });+ assert.ok(mail.html.includes("<b>a<b>@example.com</b>"));+ assert.ok(mail.html.includes("R&D <Mail>"));+ assert.ok(!mail.html.includes("<Mail>"));+ assert.ok(mail.text.includes("a<b>@example.com"));+ assert.ok(mail.text.includes("R&D <Mail>"));+});++test("a language without the new strings falls back to English", () => {+ const mail = buildPasswordResetEmail(createTranslator("de", {}), input);+ assert.equal(mail.subject, "Reset your Posta password");+});