feat: add email verification and dark mode

This commit is contained in:
JetSprow
2026-04-29 10:55:20 +10:00
parent 2a50d789dd
commit 5215850bac
32 changed files with 1244 additions and 61 deletions

View File

@@ -0,0 +1,131 @@
interface EmailTemplateInput {
siteName: string;
title: string;
intro: string;
actionLabel: string;
actionUrl: string;
note?: string;
closing?: string;
}
function escapeHtml(value: string) {
return value
.replaceAll("&", "&")
.replaceAll("<", "&lt;")
.replaceAll(">", "&gt;")
.replaceAll('"', "&quot;");
}
export function renderActionEmail({
siteName,
title,
intro,
actionLabel,
actionUrl,
note,
closing = "如果这不是你的操作,可以忽略这封邮件。",
}: EmailTemplateInput) {
const safeSiteName = escapeHtml(siteName);
const safeTitle = escapeHtml(title);
const safeIntro = escapeHtml(intro);
const safeActionLabel = escapeHtml(actionLabel);
const safeActionUrl = escapeHtml(actionUrl);
const safeNote = note ? escapeHtml(note) : "";
const safeClosing = escapeHtml(closing);
const text = [
`${siteName} - ${title}`,
intro,
`${actionLabel}: ${actionUrl}`,
note,
closing,
].filter(Boolean).join("\n\n");
const html = `<!doctype html>
<html lang="zh-CN">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<title>${safeTitle}</title>
</head>
<body style="margin:0;background:#f6f3ed;color:#24211c;font-family:-apple-system,BlinkMacSystemFont,'Segoe UI','PingFang SC','Microsoft YaHei',sans-serif;">
<div style="display:none;max-height:0;overflow:hidden;opacity:0;">${safeIntro}</div>
<table role="presentation" width="100%" cellspacing="0" cellpadding="0" style="background:#f6f3ed;padding:32px 16px;">
<tr>
<td align="center">
<table role="presentation" width="100%" cellspacing="0" cellpadding="0" style="max-width:560px;background:#fffefa;border:1px solid #e8e1d4;border-radius:18px;overflow:hidden;box-shadow:0 14px 40px rgba(58,48,31,.08);">
<tr>
<td style="padding:28px 28px 18px;border-bottom:1px solid #eee7da;">
<div style="display:inline-flex;align-items:center;gap:10px;">
<span style="display:inline-block;width:34px;height:34px;line-height:34px;text-align:center;border-radius:10px;background:#15957f;color:#fff;font-weight:700;">S</span>
<span style="font-size:14px;color:#746b5e;font-weight:600;">${safeSiteName}</span>
</div>
<h1 style="margin:22px 0 0;font-size:24px;line-height:1.25;letter-spacing:-.02em;color:#24211c;">${safeTitle}</h1>
</td>
</tr>
<tr>
<td style="padding:26px 28px 28px;">
<p style="margin:0;font-size:15px;line-height:1.8;color:#4b453b;">${safeIntro}</p>
<div style="margin:26px 0 24px;">
<a href="${safeActionUrl}" style="display:inline-block;border-radius:12px;background:#15957f;color:#ffffff;text-decoration:none;font-size:14px;font-weight:700;padding:12px 18px;">${safeActionLabel}</a>
</div>
<p style="margin:0 0 18px;font-size:12px;line-height:1.8;color:#8a8172;">如果按钮无法打开,请复制下面的链接到浏览器:</p>
<p style="margin:0;word-break:break-all;border-radius:12px;background:#f3efe7;padding:12px;font-size:12px;line-height:1.6;color:#5f574b;">${safeActionUrl}</p>
${safeNote ? `<p style="margin:18px 0 0;font-size:13px;line-height:1.7;color:#746b5e;">${safeNote}</p>` : ""}
<p style="margin:22px 0 0;font-size:12px;line-height:1.7;color:#9b9285;">${safeClosing}</p>
</td>
</tr>
</table>
</td>
</tr>
</table>
</body>
</html>`;
return { html, text };
}
export function renderRegistrationEmail(siteName: string, actionUrl: string) {
return renderActionEmail({
siteName,
title: "验证你的邮箱",
intro: "欢迎来到 J-Board。点击下方按钮完成邮箱验证验证后即可使用你的账户。",
actionLabel: "完成邮箱验证",
actionUrl,
note: "链接 30 分钟内有效。为了账户安全,请不要转发这封邮件。",
});
}
export function renderPasswordResetEmail(siteName: string, actionUrl: string) {
return renderActionEmail({
siteName,
title: "重设账户密码",
intro: "我们收到了你的密码重设请求。点击下方按钮设置一个新密码。",
actionLabel: "重设密码",
actionUrl,
note: "链接 20 分钟内有效。如果不是你本人发起,请忽略这封邮件。",
});
}
export function renderEmailChangeEmail(siteName: string, actionUrl: string) {
return renderActionEmail({
siteName,
title: "确认新的登录邮箱",
intro: "你正在把 J-Board 账户绑定到这个邮箱。点击下方按钮确认变更。",
actionLabel: "确认邮箱变更",
actionUrl,
note: "链接 30 分钟内有效。确认后,新邮箱会成为你的登录邮箱。",
});
}
export function renderSmtpTestEmail(siteName: string) {
return renderActionEmail({
siteName,
title: "SMTP 测试邮件",
intro: "这是一封来自 J-Board 的测试邮件。收到它说明当前 SMTP 配置可以正常发信。",
actionLabel: "返回 J-Board",
actionUrl: "https://github.com/JetSprow/J-Board",
note: "你可以回到后台继续配置邮箱验证、密码找回和账户邮箱变更流程。",
closing: "测试完成后,无需回复这封邮件。",
});
}

285
src/services/email.ts Normal file
View File

@@ -0,0 +1,285 @@
import crypto from "crypto";
import nodemailer from "nodemailer";
import type { AppConfig, EmailToken, EmailTokenPurpose, Prisma } from "@prisma/client";
import { prisma, type DbClient } from "@/lib/prisma";
import { decrypt } from "@/lib/crypto";
import { getAppConfig } from "@/services/app-config";
import {
renderEmailChangeEmail,
renderPasswordResetEmail,
renderRegistrationEmail,
renderSmtpTestEmail,
} from "@/services/email-templates";
import { getSiteBaseUrl } from "@/services/site-url";
const TOKEN_BYTES = 32;
const REGISTRATION_TTL_MINUTES = 30;
const EMAIL_CHANGE_TTL_MINUTES = 30;
const PASSWORD_RESET_TTL_MINUTES = 20;
type EmailPurpose = EmailTokenPurpose;
type MailContent = {
subject: string;
html: string;
text: string;
};
export function normalizeEmailAddress(email: string) {
return email.trim().toLowerCase();
}
function hashToken(token: string) {
return crypto.createHash("sha256").update(token).digest("hex");
}
function addMinutes(minutes: number) {
return new Date(Date.now() + minutes * 60 * 1000);
}
function tokenTtl(purpose: EmailPurpose) {
if (purpose === "PASSWORD_RESET") return PASSWORD_RESET_TTL_MINUTES;
if (purpose === "EMAIL_CHANGE") return EMAIL_CHANGE_TTL_MINUTES;
return REGISTRATION_TTL_MINUTES;
}
function smtpPassword(config: AppConfig) {
if (!config.smtpPassword) return undefined;
try {
return decrypt(config.smtpPassword);
} catch {
return config.smtpPassword;
}
}
export function isSmtpConfigured(config: AppConfig) {
return Boolean(
config.smtpEnabled &&
config.smtpHost &&
config.smtpPort &&
config.smtpFromEmail,
);
}
function assertSmtpConfigured(config: AppConfig) {
if (!isSmtpConfigured(config)) {
throw new Error("邮件服务尚未配置,请联系管理员");
}
}
async function sendMail(config: AppConfig, to: string, content: MailContent) {
assertSmtpConfigured(config);
const user = config.smtpUser?.trim() || undefined;
const pass = smtpPassword(config);
const transporter = nodemailer.createTransport({
host: config.smtpHost!,
port: config.smtpPort,
secure: config.smtpSecure,
auth: user ? { user, pass } : undefined,
});
await transporter.sendMail({
from: {
name: config.smtpFromName || config.siteName,
address: config.smtpFromEmail!,
},
to,
subject: content.subject,
html: content.html,
text: content.text,
});
}
async function createEmailToken(input: {
email: string;
purpose: EmailPurpose;
userId?: string | null;
db?: DbClient;
}) {
const db = input.db ?? prisma;
const email = normalizeEmailAddress(input.email);
const token = crypto.randomBytes(TOKEN_BYTES).toString("hex");
const now = new Date();
await db.emailToken.updateMany({
where: {
email,
purpose: input.purpose,
userId: input.userId ?? null,
consumedAt: null,
},
data: { consumedAt: now },
});
await db.emailToken.create({
data: {
email,
userId: input.userId ?? null,
purpose: input.purpose,
tokenHash: hashToken(token),
expiresAt: addMinutes(tokenTtl(input.purpose)),
},
});
return token;
}
async function buildActionUrl(pathname: string, token: string, options: { headers?: Headers; requestUrl?: string } = {}) {
const baseUrl = await getSiteBaseUrl({
headers: options.headers,
requestUrl: options.requestUrl,
allowRequestFallback: true,
});
if (!baseUrl) {
throw new Error("请先在系统设置中填写站点域名");
}
const url = new URL(pathname, baseUrl);
url.searchParams.set("token", token);
return url.toString();
}
export async function sendRegistrationVerificationEmail(input: {
userId: string;
email: string;
headers?: Headers;
requestUrl?: string;
}) {
const config = await getAppConfig();
const token = await createEmailToken({
userId: input.userId,
email: input.email,
purpose: "REGISTRATION_VERIFY",
});
const url = await buildActionUrl("/verify-email", token, input);
const template = renderRegistrationEmail(config.siteName, url);
await sendMail(config, input.email, {
subject: `验证你的 ${config.siteName} 邮箱`,
...template,
});
}
export async function sendPasswordResetEmail(input: {
userId: string;
email: string;
headers?: Headers;
requestUrl?: string;
}) {
const config = await getAppConfig();
const token = await createEmailToken({
userId: input.userId,
email: input.email,
purpose: "PASSWORD_RESET",
});
const url = await buildActionUrl("/reset-password", token, input);
const template = renderPasswordResetEmail(config.siteName, url);
await sendMail(config, input.email, {
subject: `${config.siteName} 密码重设`,
...template,
});
}
export async function sendEmailChangeConfirmation(input: {
userId: string;
email: string;
headers?: Headers;
requestUrl?: string;
}) {
const config = await getAppConfig();
const token = await createEmailToken({
userId: input.userId,
email: input.email,
purpose: "EMAIL_CHANGE",
});
const url = await buildActionUrl("/verify-email", token, input);
const template = renderEmailChangeEmail(config.siteName, url);
await sendMail(config, input.email, {
subject: `${config.siteName} 邮箱变更确认`,
...template,
});
}
export async function sendSmtpTestEmail(to: string) {
const config = await getAppConfig();
const template = renderSmtpTestEmail(config.siteName);
await sendMail(config, normalizeEmailAddress(to), {
subject: `${config.siteName} SMTP 测试`,
...template,
});
}
export async function consumeEmailToken(token: string, purpose?: EmailPurpose) {
const tokenHash = hashToken(token.trim());
const record = await prisma.emailToken.findUnique({ where: { tokenHash } });
if (!record || record.consumedAt || record.expiresAt <= new Date()) {
return null;
}
if (purpose && record.purpose !== purpose) {
return null;
}
const result = await prisma.emailToken.updateMany({
where: {
id: record.id,
consumedAt: null,
expiresAt: { gt: new Date() },
...(purpose ? { purpose } : {}),
},
data: { consumedAt: new Date() },
});
return result.count === 1 ? record : null;
}
export async function verifyEmailToken(token: string) {
const record = await consumeEmailToken(token);
if (!record) return { ok: false as const, message: "验证链接无效或已过期" };
if (record.purpose === "REGISTRATION_VERIFY") {
if (!record.userId) return { ok: false as const, message: "验证链接缺少账户信息" };
await prisma.user.update({
where: { id: record.userId },
data: { emailVerifiedAt: new Date() },
});
return { ok: true as const, message: "邮箱验证完成,现在可以登录账户。" };
}
if (record.purpose === "EMAIL_CHANGE") {
if (!record.userId) return { ok: false as const, message: "验证链接缺少账户信息" };
try {
await prisma.user.update({
where: { id: record.userId },
data: {
email: record.email,
emailVerifiedAt: new Date(),
},
});
} catch (error) {
if ((error as { code?: string }).code === "P2002") {
return { ok: false as const, message: "这个邮箱已经被其他账户使用" };
}
throw error;
}
return { ok: true as const, message: "邮箱变更已确认,之后请使用新邮箱登录。" };
}
return { ok: false as const, message: "这个链接不能用于邮箱验证" };
}
export async function consumePasswordResetToken(token: string) {
const record = await consumeEmailToken(token, "PASSWORD_RESET");
if (!record?.userId) {
throw new Error("重设链接无效或已过期");
}
return record as EmailToken & { userId: string };
}
export async function deleteEmailTokens(where: Prisma.EmailTokenWhereInput, db: DbClient = prisma) {
await db.emailToken.deleteMany({ where });
}