feat: 接入 SMTP,支持后台配置、注册邮箱验证与密码找回
新增邮件能力,配置入口在管理后台「邮件设置」,无需改环境变量或重启。 一、邮件发送模块(lib/mailer.js) 基于 nodemailer 封装。SMTP 配置存在 settings 表(key 前缀 smtp_), 按需构建 transporter 并做短时缓存,配置变更时失效重建。 把底层 SMTP 异常翻译成可读中文提示(认证失败 / 无法连接 / 端口或 加密方式不匹配等),便于管理员自行排查。 二、管理后台「邮件设置」面板 - 服务器、端口、加密方式(STARTTLS 587 / SSL 465)、用户名、 发件人名称与邮箱 - 密码只写不读:任何接口都不回显明文,仅返回 password_set 布尔值。 留空表示保持原密码,避免管理员只改端口就把密码清掉 - 「发送测试邮件」按钮验证连通性,默认发给当前管理员 - 「注册邮箱验证」开关:仅在 SMTP 配置完整时才允许开启,避免开启后 所有人都注册不了 三、注册邮箱验证 - 新增 email_verifications 表存验证码。只存 sha256 摘要,不存明文; 同一邮箱+用途同时只允许一条有效记录(唯一索引约束) - 验证码 6 位数字,10 分钟有效,失败累计 5 次即作废; 校验用 timingSafeEqual 做定时安全比较 - 校验放在所有格式校验之后,避免用户因格式错误白白消耗一次验证码 - 验证码一次性,校验通过即标记 consumed - 注册框新增验证码输入与「获取验证码」按钮(含 60 秒倒计时) - 该字段仅在站点开启邮箱验证且 SMTP 可用时显示, 与既有的管理员引导令牌字段处理方式一致 四、密码找回邮件 新增 /api/auth/forgot-password 与 /api/auth/reset-password-by-email, 与既有恢复码机制并行。邮箱不存在时返回与成功一致的响应,避免被用于 枚举注册用户。重置成功后递增 token_version 使旧令牌失效。 五、安全与限流 - 新增 mailLimiter:发信接口 15 分钟 5 次,防止被当作垃圾邮件发射器 - SMTP 配置接口需管理员权限(未登录 401、普通用户 403),实测通过 六、顺带修复 - schema.sql 补上 email_verifications 表、users.email_verified 列与 SMTP 设置项。此前只改了 migrations/ 而漏了 schema.sql,被 test/schema-parity.test.js 抓出——这正是当初加该测试的目的。 - 管理后台原有一条 `#adminContent > div:first-of-type` 的 !important flex 规则,依赖「第一个 div 即论坛名称区域」这一脆弱假设,新增的 邮件设置面板正好撞上导致布局错乱。改为显式的 .forum-name-form 类名。 - 全局输入框规则补上 padding 兜底,否则管理后台的输入框会塌陷成 17px。 - multer 2.2.0 -> 2.4.0,修复多个 DoS 与上传限制绕过漏洞 (GHSA-wc9g-mqfw-jrwm 等)。test/app.test.js 中原本断言 multer 必须 匹配 /^2\.2\./,会阻碍安全升级,改为断言不低于已修复的 2.3.0。 - i18n 补充 39 条新文案(zh 与 en 各一份)。 已用本地 SMTP 捕获服务器完成端到端验证:测试邮件真实送达、验证码 正确与错误分支、验证码一次性、密码重置生效且旧密码失效、防用户枚举、 权限控制(401/403)、密码不回显、SMTP 未就绪时拒绝开启验证。 完整测试套件 25/25 通过。
This commit is contained in:
1 parent
75cc78d5f8
commit
627d284b02
13 files changed
+1285
-90
No files matched your search
+12
@@ -227,6 +227,12 @@
|
||||
</span>
|
||||
论坛设置
|
||||
</a>
|
||||
<a href="#" class="admin-nav-item" data-tab="smtp">
|
||||
<span class="nav-icon">
|
||||
<svg xmlns="http://www.w3.org/2000/svg" width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M4 4h16c1.1 0 2 .9 2 2v12c0 1.1-.9 2-2 2H4c-1.1 0-2-.9-2-2V6c0-1.1.9-2 2-2z"/><polyline points="22,6 12,13 2,6"/></svg>
|
||||
</span>
|
||||
邮件设置
|
||||
</a>
|
||||
<a href="#" class="admin-nav-item" data-tab="custom">
|
||||
<span class="nav-icon">
|
||||
<svg xmlns="http://www.w3.org/2000/svg" width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8z"/><polyline points="14 2 14 8 20 8"/><line x1="16" y1="13" x2="8" y2="13"/><line x1="16" y1="17" x2="8" y2="17"/><polyline points="10 9 9 9 8 9"/></svg>
|
||||
@@ -363,6 +369,12 @@
|
||||
<input type="email" id="regEmail" placeholder="邮箱" />
|
||||
<input type="password" id="regPassword" placeholder="密码(至少6位)" />
|
||||
<input type="password" id="regBootstrapToken" placeholder="管理员初始化令牌" autocomplete="off" style="display:none;" />
|
||||
<div id="regEmailCodeRow" style="display:none;gap:8px;align-items:center;margin-bottom:12px;">
|
||||
<input type="text" id="regEmailCode" placeholder="邮箱验证码" autocomplete="off"
|
||||
style="flex:1;margin-bottom:0;font-family:monospace;letter-spacing:2px;" />
|
||||
<button type="button" id="regSendCodeBtn" class="btn-secondary"
|
||||
style="padding:10px 14px;white-space:nowrap;font-size:13px;">获取验证码</button>
|
||||
</div>
|
||||
<div class="captcha-row">
|
||||
<span id="regCaptchaQuestion">3 + 5 = ?</span>
|
||||
<input type="text" id="regCaptchaInput" placeholder="答案" style="width:80px;" />
|
||||
|
||||
+175
-4
@@ -431,11 +431,11 @@ function renderAdminSettings() {
|
||||
container.innerHTML = `
|
||||
<h3 style="margin-bottom:16px;text-align:center;">${getIcon('settings')} 论坛名称</h3>
|
||||
|
||||
<div style="max-width:400px;margin:0 auto;width:100%;">
|
||||
<label style="font-weight:600;font-size:14px;display:block;margin-bottom:6px;">论坛名称</label>
|
||||
<input type="text" id="settingsForumName" style="width:100%;padding:10px 14px;border:1.5px solid #e2e8f0;border-radius:6px;font-size:15px;margin-bottom:12px;font-family:inherit;background:var(--bg);color:var(--text);" />
|
||||
<div class="forum-name-form">
|
||||
<label for="settingsForumName" style="font-weight:600;font-size:14px;display:block;margin-bottom:6px;width:100%;">论坛名称</label>
|
||||
<input type="text" id="settingsForumName" placeholder="论坛名称" />
|
||||
<button id="settingsForumSave" class="btn-primary" style="padding:10px 24px;">保存</button>
|
||||
<span id="settingsResult" style="margin-left:12px;font-size:14px;"></span>
|
||||
<span id="settingsResult" style="font-size:14px;"></span>
|
||||
</div>
|
||||
`;
|
||||
|
||||
@@ -461,6 +461,176 @@ function renderAdminSettings() {
|
||||
});
|
||||
}
|
||||
|
||||
// ============================================================
|
||||
// 📧 邮件设置(SMTP)
|
||||
// ============================================================
|
||||
|
||||
function renderAdminSmtp() {
|
||||
const container = document.getElementById('adminContent');
|
||||
container.innerHTML = `
|
||||
<h3 style="margin-bottom:6px;text-align:center;">${getIcon('message')} 邮件设置</h3>
|
||||
<p style="text-align:center;color:var(--text-secondary);font-size:13px;margin-bottom:20px;">
|
||||
配置后可用于注册邮箱验证与密码找回。密码只写不读,保存后不会回显。
|
||||
</p>
|
||||
|
||||
<div class="smtp-form">
|
||||
<div id="smtpStatus" style="margin-bottom:16px;padding:10px 14px;border-radius:var(--radius-sm);font-size:13px;"></div>
|
||||
|
||||
<label class="smtp-check">
|
||||
<input type="checkbox" id="smtpEnabled" />
|
||||
启用邮件发送
|
||||
</label>
|
||||
|
||||
<label for="smtpHost">SMTP 服务器</label>
|
||||
<input type="text" id="smtpHost" placeholder="smtp.example.com" autocomplete="off" />
|
||||
|
||||
<div class="smtp-row">
|
||||
<div>
|
||||
<label for="smtpPort">端口</label>
|
||||
<input type="number" id="smtpPort" placeholder="587" min="1" max="65535" />
|
||||
</div>
|
||||
<div>
|
||||
<label for="smtpSecure">加密方式</label>
|
||||
<select id="smtpSecure">
|
||||
<option value="false">STARTTLS(587)</option>
|
||||
<option value="true">SSL/TLS(465)</option>
|
||||
</select>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<label for="smtpUser">用户名</label>
|
||||
<input type="text" id="smtpUser" placeholder="通常为完整邮箱地址" autocomplete="off" />
|
||||
|
||||
<label for="smtpPassword">密码 / 授权码</label>
|
||||
<input type="password" id="smtpPassword" placeholder="留空表示不修改已保存的密码" autocomplete="new-password" />
|
||||
<div class="smtp-hint">QQ、163 等邮箱需填写「授权码」而非登录密码。</div>
|
||||
|
||||
<label for="smtpFromName">发件人名称</label>
|
||||
<input type="text" id="smtpFromName" placeholder="例如:论坛名称" />
|
||||
|
||||
<label for="smtpFromEmail">发件人邮箱 <span style="color:#ef4444;">*</span></label>
|
||||
<input type="email" id="smtpFromEmail" placeholder="noreply@example.com" />
|
||||
|
||||
<div class="smtp-actions">
|
||||
<button id="smtpSaveBtn" class="btn-primary" style="padding:10px 22px;">保存配置</button>
|
||||
<button id="smtpTestBtn" class="btn-secondary" style="padding:10px 22px;">发送测试邮件</button>
|
||||
<button id="smtpClearPwBtn" class="btn-secondary" style="padding:10px 22px;">清除密码</button>
|
||||
</div>
|
||||
|
||||
<hr />
|
||||
|
||||
<h4 style="font-size:15px;margin-bottom:6px;">注册邮箱验证</h4>
|
||||
<p style="font-size:13px;color:var(--text-secondary);margin-bottom:12px;">
|
||||
开启后,新用户注册必须填写邮箱收到的验证码。需先完成上方配置并确保测试邮件可送达。
|
||||
</p>
|
||||
<label class="smtp-check" style="margin-bottom:0;">
|
||||
<input type="checkbox" id="emailVerifyRequired" />
|
||||
要求注册时验证邮箱
|
||||
</label>
|
||||
</div>
|
||||
`;
|
||||
|
||||
const $ = id => document.getElementById(id);
|
||||
|
||||
// 载入现有配置
|
||||
API.getSmtpConfig().then(cfg => {
|
||||
$('smtpEnabled').checked = cfg.enabled;
|
||||
$('smtpHost').value = cfg.host || '';
|
||||
$('smtpPort').value = cfg.port || 587;
|
||||
$('smtpSecure').value = String(cfg.secure);
|
||||
$('smtpUser').value = cfg.user || '';
|
||||
$('smtpFromName').value = cfg.from_name || '';
|
||||
$('smtpFromEmail').value = cfg.from_email || '';
|
||||
// 密码永不回显,只用占位文字提示是否已设置
|
||||
$('smtpPassword').placeholder = cfg.password_set
|
||||
? '已保存密码,留空则不修改'
|
||||
: '尚未设置密码';
|
||||
|
||||
const status = $('smtpStatus');
|
||||
if (cfg.configured) {
|
||||
status.innerHTML = `${getIcon('success')} 配置完整,可以发信`;
|
||||
status.style.background = 'rgba(34,197,94,0.12)';
|
||||
status.style.color = '#16a34a';
|
||||
} else {
|
||||
status.innerHTML = `${getIcon('warning')} 尚未配置完成,邮件功能不可用`;
|
||||
status.style.background = 'rgba(245,158,11,0.12)';
|
||||
status.style.color = '#d97706';
|
||||
}
|
||||
}).catch(err => {
|
||||
showToast('加载配置失败:' + err.message, 'error');
|
||||
});
|
||||
|
||||
// 读取邮箱验证开关(该值在公开设置接口中)
|
||||
API.getSettings().then(s => {
|
||||
$('emailVerifyRequired').checked = s.email_verify_required === true;
|
||||
}).catch(() => {});
|
||||
|
||||
$('smtpSaveBtn').addEventListener('click', async () => {
|
||||
const payload = {
|
||||
enabled: $('smtpEnabled').checked,
|
||||
host: $('smtpHost').value.trim(),
|
||||
port: Number($('smtpPort').value || 587),
|
||||
secure: $('smtpSecure').value === 'true',
|
||||
user: $('smtpUser').value.trim(),
|
||||
from_name: $('smtpFromName').value.trim(),
|
||||
from_email: $('smtpFromEmail').value.trim(),
|
||||
};
|
||||
// 只有填了才提交,避免把已保存的密码覆盖成空
|
||||
const pw = $('smtpPassword').value;
|
||||
if (pw) payload.password = pw;
|
||||
|
||||
try {
|
||||
await API.saveSmtpConfig(payload);
|
||||
$('smtpPassword').value = '';
|
||||
showToast('配置已保存', 'success');
|
||||
renderAdminSmtp();
|
||||
} catch (err) {
|
||||
showToast(err.message, 'error');
|
||||
}
|
||||
});
|
||||
|
||||
$('smtpTestBtn').addEventListener('click', async function() {
|
||||
const btn = this;
|
||||
btn.disabled = true;
|
||||
btn.textContent = '发送中…';
|
||||
try {
|
||||
const r = await API.sendTestMail();
|
||||
showToast('测试邮件已发送至 ' + r.to, 'success');
|
||||
} catch (err) {
|
||||
showToast(err.message, 'error');
|
||||
} finally {
|
||||
btn.disabled = false;
|
||||
btn.textContent = '发送测试邮件';
|
||||
}
|
||||
});
|
||||
|
||||
$('smtpClearPwBtn').addEventListener('click', async () => {
|
||||
const ok = await showConfirm('确定要清除已保存的 SMTP 密码吗?', {
|
||||
title: '清除密码', confirmText: '清除', danger: true,
|
||||
});
|
||||
if (!ok) return;
|
||||
try {
|
||||
await API.clearSmtpPassword();
|
||||
showToast('密码已清除', 'success');
|
||||
renderAdminSmtp();
|
||||
} catch (err) {
|
||||
showToast(err.message, 'error');
|
||||
}
|
||||
});
|
||||
|
||||
$('emailVerifyRequired').addEventListener('change', async function() {
|
||||
const desired = this.checked;
|
||||
try {
|
||||
await API.setEmailVerifyRequired(desired);
|
||||
showToast(desired ? '已开启注册邮箱验证' : '已关闭注册邮箱验证', 'success');
|
||||
} catch (err) {
|
||||
// 失败时把开关状态回滚,避免界面与服务端不一致
|
||||
this.checked = !desired;
|
||||
showToast(err.message, 'error');
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
// ============================================================
|
||||
// 🎨 自定义 CSS(独立标签页)- 已改用 Toast 提示
|
||||
// ============================================================
|
||||
@@ -834,6 +1004,7 @@ document.querySelector('.admin-nav')?.addEventListener('click', function(e) {
|
||||
links: renderAdminLinks,
|
||||
'custom-css': renderAdminCustomCSS,
|
||||
settings: renderAdminSettings,
|
||||
smtp: renderAdminSmtp,
|
||||
custom: renderAdminCustomPages
|
||||
};
|
||||
if (tabMap[tab]) tabMap[tab]();
|
||||
|
||||
@@ -37,10 +37,16 @@ const API = {
|
||||
return data;
|
||||
},
|
||||
|
||||
async register(email, password, username, bootstrapToken = '') {
|
||||
async register(email, password, username, bootstrapToken = '', emailCode = '') {
|
||||
const data = await apiFetch('/auth/register', {
|
||||
method: 'POST',
|
||||
body: JSON.stringify({ email, password, username, bootstrap_token: bootstrapToken || undefined })
|
||||
body: JSON.stringify({
|
||||
email,
|
||||
password,
|
||||
username,
|
||||
bootstrap_token: bootstrapToken || undefined,
|
||||
email_code: emailCode || undefined
|
||||
})
|
||||
});
|
||||
if (data.error) throw new Error(data.error);
|
||||
return data;
|
||||
@@ -442,5 +448,80 @@ const API = {
|
||||
});
|
||||
if (data.error) throw new Error(data.error);
|
||||
return data;
|
||||
},
|
||||
|
||||
// ============================================================
|
||||
// SMTP 配置(管理员)
|
||||
// ============================================================
|
||||
|
||||
async getSmtpConfig() {
|
||||
const data = await apiFetch('/admin/smtp');
|
||||
if (data.error) throw new Error(data.error);
|
||||
return data;
|
||||
},
|
||||
|
||||
// password 留空表示保持原有密码不变
|
||||
async saveSmtpConfig(config) {
|
||||
const data = await apiFetch('/admin/smtp', {
|
||||
method: 'PUT',
|
||||
body: JSON.stringify(config)
|
||||
});
|
||||
if (data.error) throw new Error(data.error);
|
||||
return data;
|
||||
},
|
||||
|
||||
async clearSmtpPassword() {
|
||||
const data = await apiFetch('/admin/smtp/password', { method: 'DELETE' });
|
||||
if (data.error) throw new Error(data.error);
|
||||
return data;
|
||||
},
|
||||
|
||||
async sendTestMail(to) {
|
||||
const data = await apiFetch('/admin/smtp/test', {
|
||||
method: 'POST',
|
||||
body: JSON.stringify(to ? { to } : {})
|
||||
});
|
||||
if (data.error) throw new Error(data.error);
|
||||
return data;
|
||||
},
|
||||
|
||||
async setEmailVerifyRequired(required) {
|
||||
const data = await apiFetch('/admin/email-verify', {
|
||||
method: 'PUT',
|
||||
body: JSON.stringify({ required })
|
||||
});
|
||||
if (data.error) throw new Error(data.error);
|
||||
return data;
|
||||
},
|
||||
|
||||
// ============================================================
|
||||
// 邮箱验证码
|
||||
// ============================================================
|
||||
|
||||
async sendRegisterCode(email) {
|
||||
const data = await apiFetch('/auth/send-code', {
|
||||
method: 'POST',
|
||||
body: JSON.stringify({ email })
|
||||
});
|
||||
if (data.error) throw new Error(data.error);
|
||||
return data;
|
||||
},
|
||||
|
||||
async forgotPassword(email) {
|
||||
const data = await apiFetch('/auth/forgot-password', {
|
||||
method: 'POST',
|
||||
body: JSON.stringify({ email })
|
||||
});
|
||||
if (data.error) throw new Error(data.error);
|
||||
return data;
|
||||
},
|
||||
|
||||
async resetPasswordByEmail(email, code, newPassword) {
|
||||
const data = await apiFetch('/auth/reset-password-by-email', {
|
||||
method: 'POST',
|
||||
body: JSON.stringify({ email, code, newPassword })
|
||||
});
|
||||
if (data.error) throw new Error(data.error);
|
||||
return data;
|
||||
}
|
||||
};
|
||||
+60
-1
@@ -35,9 +35,60 @@ document.getElementById('loginSubmit').addEventListener('click', async () => {
|
||||
document.getElementById('registerBtn').addEventListener('click', () => {
|
||||
refreshCaptcha('reg');
|
||||
syncBootstrapTokenField();
|
||||
syncEmailCodeField();
|
||||
document.getElementById('registerModal').classList.add('active');
|
||||
});
|
||||
|
||||
// 邮箱验证码字段:仅在站点开启邮箱验证且 SMTP 可用时显示
|
||||
async function syncEmailCodeField() {
|
||||
const row = document.getElementById('regEmailCodeRow');
|
||||
const field = document.getElementById('regEmailCode');
|
||||
if (!row || !field) return;
|
||||
try {
|
||||
const settings = await API.getSettings();
|
||||
const required = settings.email_verify_required === true;
|
||||
row.style.display = required ? '' : 'none';
|
||||
if (!required) field.value = '';
|
||||
} catch (err) {
|
||||
// 取不到设置时按「不需要」处理,避免用户卡在无法完成的注册流程上
|
||||
row.style.display = 'none';
|
||||
field.value = '';
|
||||
}
|
||||
}
|
||||
|
||||
// 发送邮箱验证码,含 60 秒倒计时防止连点
|
||||
(function bindSendCodeButton() {
|
||||
const btn = document.getElementById('regSendCodeBtn');
|
||||
if (!btn) return;
|
||||
|
||||
btn.addEventListener('click', async () => {
|
||||
const email = document.getElementById('regEmail').value.trim();
|
||||
if (!email) { showToast('请先填写邮箱', 'warning'); return; }
|
||||
|
||||
btn.disabled = true;
|
||||
try {
|
||||
await API.sendRegisterCode(email);
|
||||
showToast('验证码已发送,请查收邮件', 'success');
|
||||
|
||||
let remain = 60;
|
||||
btn.textContent = remain + 's';
|
||||
const timer = setInterval(() => {
|
||||
remain -= 1;
|
||||
if (remain <= 0) {
|
||||
clearInterval(timer);
|
||||
btn.disabled = false;
|
||||
btn.textContent = '获取验证码';
|
||||
} else {
|
||||
btn.textContent = remain + 's';
|
||||
}
|
||||
}, 1000);
|
||||
} catch (err) {
|
||||
btn.disabled = false;
|
||||
showToast(err.message, 'error');
|
||||
}
|
||||
});
|
||||
})();
|
||||
|
||||
// 管理员初始化令牌输入框仅在首次部署且配置了引导令牌时出现。
|
||||
// 其余情况(普通部署、已初始化完成)普通用户完全看不到它。
|
||||
async function syncBootstrapTokenField() {
|
||||
@@ -64,13 +115,20 @@ document.getElementById('registerSubmit').addEventListener('click', async () =>
|
||||
const bootstrapToken = bootstrapField && bootstrapField.style.display !== 'none'
|
||||
? bootstrapField.value.trim()
|
||||
: '';
|
||||
const codeField = document.getElementById('regEmailCode');
|
||||
const emailCode = codeField && codeField.style.display !== 'none'
|
||||
? codeField.value.trim()
|
||||
: '';
|
||||
const captchaInput = document.getElementById('regCaptchaInput').value.trim();
|
||||
const captchaAnswer = parseInt(document.getElementById('regCaptchaInput').dataset.answer);
|
||||
if (!username || !email || !password) { showToast('请填写完整信息', 'warning'); return; }
|
||||
if (password.length < 6) { showToast('密码至少6位', 'warning'); return; }
|
||||
if (codeField && codeField.style.display !== 'none' && !emailCode) {
|
||||
showToast('请输入邮箱验证码', 'warning'); return;
|
||||
}
|
||||
if (parseInt(captchaInput) !== captchaAnswer) { showToast('验证码错误,请重新计算', 'error'); refreshCaptcha('reg'); return; }
|
||||
try {
|
||||
await API.register(email, password, username, bootstrapToken);
|
||||
await API.register(email, password, username, bootstrapToken, emailCode);
|
||||
} catch (err) {
|
||||
showToast('注册失败:' + err.message, 'error');
|
||||
return;
|
||||
@@ -81,6 +139,7 @@ document.getElementById('registerSubmit').addEventListener('click', async () =>
|
||||
document.getElementById('regEmail').value = '';
|
||||
document.getElementById('regPassword').value = '';
|
||||
if (bootstrapField) bootstrapField.value = '';
|
||||
if (codeField) codeField.value = '';
|
||||
document.getElementById('regCaptchaInput').value = '';
|
||||
|
||||
try {
|
||||
|
||||
+82
@@ -371,6 +371,47 @@ const TRANSLATIONS = {
|
||||
'修改用户角色': '修改用户角色',
|
||||
'重新生成恢复码': '重新生成恢复码',
|
||||
'退出登录': '退出登录',
|
||||
|
||||
// ===== SMTP 与邮箱验证 =====
|
||||
'邮件设置': '邮件设置',
|
||||
'启用邮件发送': '启用邮件发送',
|
||||
'SMTP 服务器': 'SMTP 服务器',
|
||||
'端口': '端口',
|
||||
'加密方式': '加密方式',
|
||||
'密码 / 授权码': '密码 / 授权码',
|
||||
'发件人名称': '发件人名称',
|
||||
'发件人邮箱': '发件人邮箱',
|
||||
'保存配置': '保存配置',
|
||||
'发送测试邮件': '发送测试邮件',
|
||||
'清除密码': '清除密码',
|
||||
'注册邮箱验证': '注册邮箱验证',
|
||||
'要求注册时验证邮箱': '要求注册时验证邮箱',
|
||||
'获取验证码': '获取验证码',
|
||||
'邮箱验证码': '邮箱验证码',
|
||||
'配置完整,可以发信': '配置完整,可以发信',
|
||||
'尚未配置完成,邮件功能不可用': '尚未配置完成,邮件功能不可用',
|
||||
'验证码已发送,请查收邮件': '验证码已发送,请查收邮件',
|
||||
'请输入邮箱验证码': '请输入邮箱验证码',
|
||||
'请输入有效邮箱': '请输入有效邮箱',
|
||||
'该邮箱已被注册': '该邮箱已被注册',
|
||||
'本站未开启邮箱验证': '本站未开启邮箱验证',
|
||||
'请先获取验证码': '请先获取验证码',
|
||||
'验证码已过期,请重新获取': '验证码已过期,请重新获取',
|
||||
'尝试次数过多,请重新获取验证码': '尝试次数过多,请重新获取验证码',
|
||||
'验证码错误': '验证码错误',
|
||||
'配置已保存': '配置已保存',
|
||||
'密码已清除': '密码已清除',
|
||||
'已开启注册邮箱验证': '已开启注册邮箱验证',
|
||||
'已关闭注册邮箱验证': '已关闭注册邮箱验证',
|
||||
'加载配置失败:': '加载配置失败:',
|
||||
'已保存密码,留空则不修改': '已保存密码,留空则不修改',
|
||||
'尚未设置密码': '尚未设置密码',
|
||||
'留空表示不修改已保存的密码': '留空表示不修改已保存的密码',
|
||||
'通常为完整邮箱地址': '通常为完整邮箱地址',
|
||||
'例如:论坛名称': '例如:论坛名称',
|
||||
'注册验证码': '注册验证码',
|
||||
'密码重置验证码': '密码重置验证码',
|
||||
'Forumlify SMTP 测试邮件': 'Forumlify SMTP 测试邮件',
|
||||
},
|
||||
|
||||
'en': {
|
||||
@@ -740,6 +781,47 @@ const TRANSLATIONS = {
|
||||
'修改用户角色': 'Change User Role',
|
||||
'重新生成恢复码': 'Regenerate Recovery Codes',
|
||||
'退出登录': 'Logout',
|
||||
|
||||
// ===== SMTP 与邮箱验证 =====
|
||||
'邮件设置': 'Email Settings',
|
||||
'启用邮件发送': 'Enable email sending',
|
||||
'SMTP 服务器': 'SMTP Server',
|
||||
'端口': 'Port',
|
||||
'加密方式': 'Encryption',
|
||||
'密码 / 授权码': 'Password / App Password',
|
||||
'发件人名称': 'Sender Name',
|
||||
'发件人邮箱': 'Sender Email',
|
||||
'保存配置': 'Save Settings',
|
||||
'发送测试邮件': 'Send Test Email',
|
||||
'清除密码': 'Clear Password',
|
||||
'注册邮箱验证': 'Email Verification on Signup',
|
||||
'要求注册时验证邮箱': 'Require email verification on signup',
|
||||
'获取验证码': 'Get Code',
|
||||
'邮箱验证码': 'Email Code',
|
||||
'配置完整,可以发信': 'Configuration complete, email is ready',
|
||||
'尚未配置完成,邮件功能不可用': 'Configuration incomplete, email is unavailable',
|
||||
'验证码已发送,请查收邮件': 'Verification code sent, please check your inbox',
|
||||
'请输入邮箱验证码': 'Please enter the email verification code',
|
||||
'请输入有效邮箱': 'Please enter a valid email address',
|
||||
'该邮箱已被注册': 'This email is already registered',
|
||||
'本站未开启邮箱验证': 'Email verification is not enabled on this site',
|
||||
'请先获取验证码': 'Please request a verification code first',
|
||||
'验证码已过期,请重新获取': 'The code has expired, please request a new one',
|
||||
'尝试次数过多,请重新获取验证码': 'Too many attempts, please request a new code',
|
||||
'验证码错误': 'Incorrect verification code',
|
||||
'配置已保存': 'Settings saved',
|
||||
'密码已清除': 'Password cleared',
|
||||
'已开启注册邮箱验证': 'Email verification on signup enabled',
|
||||
'已关闭注册邮箱验证': 'Email verification on signup disabled',
|
||||
'加载配置失败:': 'Failed to load settings: ',
|
||||
'已保存密码,留空则不修改': 'Password saved, leave blank to keep it',
|
||||
'尚未设置密码': 'No password set yet',
|
||||
'留空表示不修改已保存的密码': 'Leave blank to keep the saved password',
|
||||
'通常为完整邮箱地址': 'Usually your full email address',
|
||||
'例如:论坛名称': 'e.g. Forum name',
|
||||
'注册验证码': 'Signup verification code',
|
||||
'密码重置验证码': 'Password reset code',
|
||||
'Forumlify SMTP 测试邮件': 'Forumlify SMTP test email',
|
||||
}
|
||||
};
|
||||
|
||||
|
||||
+164
@@ -0,0 +1,164 @@
|
||||
// ============================================================
|
||||
// 邮件发送
|
||||
// ------------------------------------------------------------
|
||||
// SMTP 配置存在 settings 表中(key 前缀 smtp_),由管理员在后台
|
||||
// 填写,因此无需重启服务即可生效。这里按需构建 transporter 并做
|
||||
// 短时缓存,避免每次发信都重新握手。
|
||||
//
|
||||
// 安全约定:
|
||||
// - 密码只写不读,任何接口都不会回显明文
|
||||
// - 配置校验失败时给出可读的错误,而不是抛出底层异常
|
||||
// ============================================================
|
||||
|
||||
const nodemailer = require('nodemailer');
|
||||
|
||||
// 缓存 transporter:配置变更时通过 invalidateTransport() 失效
|
||||
let cachedTransport = null;
|
||||
let cachedSignature = null;
|
||||
|
||||
const SMTP_KEYS = [
|
||||
'smtp_enabled',
|
||||
'smtp_host',
|
||||
'smtp_port',
|
||||
'smtp_secure',
|
||||
'smtp_user',
|
||||
'smtp_password',
|
||||
'smtp_from_name',
|
||||
'smtp_from_email',
|
||||
];
|
||||
|
||||
function invalidateTransport() {
|
||||
if (cachedTransport && typeof cachedTransport.close === 'function') {
|
||||
try { cachedTransport.close(); } catch { /* 忽略关闭异常 */ }
|
||||
}
|
||||
cachedTransport = null;
|
||||
cachedSignature = null;
|
||||
}
|
||||
|
||||
// 从 settings 表读取 SMTP 配置并整理成对象
|
||||
async function loadSmtpConfig(pool) {
|
||||
const r = await pool.query(
|
||||
'SELECT key, value FROM settings WHERE key = ANY($1::text[])',
|
||||
[SMTP_KEYS]
|
||||
);
|
||||
const raw = {};
|
||||
r.rows.forEach(row => { raw[row.key] = row.value; });
|
||||
|
||||
return {
|
||||
enabled: raw.smtp_enabled === 'true',
|
||||
host: raw.smtp_host || '',
|
||||
port: Number(raw.smtp_port || 587),
|
||||
// secure=true 指 465 端口的隐式 TLS;587 用 STARTTLS
|
||||
secure: raw.smtp_secure === 'true',
|
||||
user: raw.smtp_user || '',
|
||||
password: raw.smtp_password || '',
|
||||
fromName: raw.smtp_from_name || '',
|
||||
fromEmail: raw.smtp_from_email || '',
|
||||
};
|
||||
}
|
||||
|
||||
// 判断配置是否足以发信
|
||||
function isConfigComplete(config) {
|
||||
return Boolean(
|
||||
config.enabled &&
|
||||
config.host &&
|
||||
config.port > 0 && config.port <= 65535 &&
|
||||
config.fromEmail
|
||||
);
|
||||
}
|
||||
|
||||
function buildTransport(config) {
|
||||
const options = {
|
||||
host: config.host,
|
||||
port: config.port,
|
||||
secure: config.secure,
|
||||
// 自签证书在小型部署中常见,这里不做严格校验以免误伤;
|
||||
// 如需强制校验可在此处改为 false 并配置 ca。
|
||||
tls: { rejectUnauthorized: false },
|
||||
connectionTimeout: 10000,
|
||||
greetingTimeout: 10000,
|
||||
socketTimeout: 20000,
|
||||
};
|
||||
|
||||
if (config.user) {
|
||||
options.auth = {
|
||||
user: config.user,
|
||||
// 部分服务商(如 QQ 邮箱、Gmail)要求使用授权码而非登录密码
|
||||
pass: config.password,
|
||||
};
|
||||
}
|
||||
|
||||
return nodemailer.createTransport(options);
|
||||
}
|
||||
|
||||
function getTransport(config) {
|
||||
// 以 host/port/secure/user/password 作为缓存签名
|
||||
const signature = [config.host, config.port, config.secure, config.user, config.password].join('|');
|
||||
if (cachedTransport && cachedSignature === signature) return cachedTransport;
|
||||
|
||||
invalidateTransport();
|
||||
cachedTransport = buildTransport(config);
|
||||
cachedSignature = signature;
|
||||
return cachedTransport;
|
||||
}
|
||||
|
||||
function formatFrom(config) {
|
||||
return config.fromName
|
||||
? `"${config.fromName.replace(/"/g, '')}" <${config.fromEmail}>`
|
||||
: config.fromEmail;
|
||||
}
|
||||
|
||||
// 发送一封邮件。调用方需先把配置读出来传入。
|
||||
async function sendMail(config, { to, subject, text, html }) {
|
||||
if (!isConfigComplete(config)) {
|
||||
const error = new Error('SMTP 尚未配置完成');
|
||||
error.code = 'SMTP_NOT_CONFIGURED';
|
||||
throw error;
|
||||
}
|
||||
|
||||
const transport = getTransport(config);
|
||||
return transport.sendMail({
|
||||
from: formatFrom(config),
|
||||
to,
|
||||
subject,
|
||||
text,
|
||||
html,
|
||||
});
|
||||
}
|
||||
|
||||
// 校验连通性:用于后台「发送测试邮件」按钮
|
||||
async function verifyConnection(config) {
|
||||
if (!isConfigComplete(config)) {
|
||||
const error = new Error('SMTP 尚未配置完成');
|
||||
error.code = 'SMTP_NOT_CONFIGURED';
|
||||
throw error;
|
||||
}
|
||||
const transport = getTransport(config);
|
||||
await transport.verify();
|
||||
return true;
|
||||
}
|
||||
|
||||
// 把底层异常转成便于管理员理解的中文提示
|
||||
function describeSmtpError(error) {
|
||||
const code = error && error.code;
|
||||
const map = {
|
||||
EAUTH: '认证失败:请检查用户名与密码(部分邮箱需使用授权码而非登录密码)',
|
||||
ECONNECTION: '无法连接到邮件服务器:请检查主机地址与端口',
|
||||
ETIMEDOUT: '连接邮件服务器超时:请检查端口是否被防火墙拦截',
|
||||
ESOCKET: '套接字错误:多数情况下是端口或加密方式不匹配(465 需开启 SSL,587 用 STARTTLS)',
|
||||
EENVELOPE: '发件人或收件人地址被服务器拒绝',
|
||||
EDNS: '域名解析失败:请检查 SMTP 主机地址',
|
||||
};
|
||||
if (code && map[code]) return map[code];
|
||||
return (error && error.message) || '发送失败';
|
||||
}
|
||||
|
||||
module.exports = {
|
||||
SMTP_KEYS,
|
||||
loadSmtpConfig,
|
||||
isConfigComplete,
|
||||
sendMail,
|
||||
verifyConnection,
|
||||
invalidateTransport,
|
||||
describeSmtpError,
|
||||
};
|
||||
@@ -0,0 +1,65 @@
|
||||
-- ============================================================
|
||||
-- 邮箱验证支持
|
||||
-- ------------------------------------------------------------
|
||||
-- 注册流程改为「先验证邮箱再建号」,因此需要一张表暂存验证码。
|
||||
-- 验证码只存哈希,不存明文,避免库被读取后可直接冒用。
|
||||
--
|
||||
-- 同时新增 SMTP 配置项到 settings 表(key-value 结构,无需建表),
|
||||
-- 由管理员在后台填写。
|
||||
-- ============================================================
|
||||
|
||||
-- 邮箱验证码:用于注册时的邮箱归属校验
|
||||
CREATE TABLE IF NOT EXISTS email_verifications (
|
||||
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
|
||||
email VARCHAR(255) NOT NULL,
|
||||
-- 验证码的 sha256 摘要;与用户输入做定时安全比较
|
||||
code_hash VARCHAR(64) NOT NULL,
|
||||
-- 用途区分:register(注册)/ reset(找回密码)
|
||||
purpose VARCHAR(20) NOT NULL DEFAULT 'register',
|
||||
-- 尝试次数,超过阈值即作废,防止暴力枚举 6 位数字
|
||||
attempts INTEGER NOT NULL DEFAULT 0,
|
||||
consumed_at TIMESTAMPTZ,
|
||||
expires_at TIMESTAMPTZ NOT NULL,
|
||||
created_at TIMESTAMPTZ NOT NULL DEFAULT now()
|
||||
);
|
||||
|
||||
-- 同一邮箱同一用途下只保留一条有效记录,靠下面的唯一索引约束
|
||||
CREATE INDEX IF NOT EXISTS idx_email_verifications_lookup
|
||||
ON email_verifications (LOWER(email), purpose, created_at DESC);
|
||||
|
||||
-- 清理过期记录时使用
|
||||
CREATE INDEX IF NOT EXISTS idx_email_verifications_expires
|
||||
ON email_verifications (expires_at);
|
||||
|
||||
-- 每个邮箱+用途同时只允许一条未消费的记录,避免重复发送堆积
|
||||
CREATE UNIQUE INDEX IF NOT EXISTS idx_email_verifications_active
|
||||
ON email_verifications (LOWER(email), purpose)
|
||||
WHERE consumed_at IS NULL;
|
||||
|
||||
-- ============================================================
|
||||
-- SMTP 默认配置项
|
||||
-- ------------------------------------------------------------
|
||||
-- 默认关闭。管理员在后台填写后才生效,因此现有部署升级后行为不变。
|
||||
-- ============================================================
|
||||
|
||||
INSERT INTO settings (key, value) VALUES
|
||||
('smtp_enabled', 'false'),
|
||||
('smtp_host', ''),
|
||||
('smtp_port', '587'),
|
||||
('smtp_secure', 'false'),
|
||||
('smtp_user', ''),
|
||||
('smtp_password', ''),
|
||||
('smtp_from_name', ''),
|
||||
('smtp_from_email', ''),
|
||||
('email_verify_required', 'false')
|
||||
ON CONFLICT (key) DO NOTHING;
|
||||
|
||||
-- ============================================================
|
||||
-- 用户邮箱验证标记
|
||||
-- ------------------------------------------------------------
|
||||
-- 记录该账号注册时是否通过了邮箱验证,便于后续审计与运营。
|
||||
-- 存量用户默认为 true:他们是在开启邮箱验证之前注册的,
|
||||
-- 不应因为新功能而被标记为「未验证」。
|
||||
-- ============================================================
|
||||
|
||||
ALTER TABLE users ADD COLUMN IF NOT EXISTS email_verified BOOLEAN NOT NULL DEFAULT true;
|
||||
Generated
+17
-61
@@ -14,11 +14,15 @@
|
||||
"express-rate-limit": "8.6.2",
|
||||
"helmet": "8.1.0",
|
||||
"jsonwebtoken": "^9.0.2",
|
||||
"multer": "2.2.0",
|
||||
"multer": "2.4.0",
|
||||
"nodemailer": "^7.0.9",
|
||||
"pg": "^8.11.3"
|
||||
},
|
||||
"devDependencies": {
|
||||
"supertest": "7.2.2"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=20"
|
||||
}
|
||||
},
|
||||
"node_modules/@noble/hashes": {
|
||||
@@ -122,12 +126,6 @@
|
||||
"integrity": "sha512-zRpUiDwd/xk6ADqPMATG8vc9VPrkck7T07OIx0gnjmJAnHnTVXNQG3vfvWNuiZIkwu9KrKdA1iJKfsfTVxE6NA==",
|
||||
"license": "BSD-3-Clause"
|
||||
},
|
||||
"node_modules/buffer-from": {
|
||||
"version": "1.1.2",
|
||||
"resolved": "https://registry.npmjs.org/buffer-from/-/buffer-from-1.1.2.tgz",
|
||||
"integrity": "sha512-E+XQCRwSbaaiChtv6k6Dwgc+bx+Bs6vuKJHHl5kox/BaKbhiXzqQOwK4cO22yElGp2OCmjwVhT3HmxgyPGnJfQ==",
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/busboy": {
|
||||
"version": "1.6.0",
|
||||
"resolved": "https://registry.npmjs.org/busboy/-/busboy-1.6.0.tgz",
|
||||
@@ -200,21 +198,6 @@
|
||||
"url": "https://github.com/sponsors/sindresorhus"
|
||||
}
|
||||
},
|
||||
"node_modules/concat-stream": {
|
||||
"version": "2.0.0",
|
||||
"resolved": "https://registry.npmjs.org/concat-stream/-/concat-stream-2.0.0.tgz",
|
||||
"integrity": "sha512-MWufYdFw53ccGjCA+Ol7XJYpAlW6/prSMzuPOTRnJGcGzuhLn4Scrz7qf6o8bROZ514ltazcIFJZevcfbo0x7A==",
|
||||
"engines": [
|
||||
"node >= 6.0"
|
||||
],
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"buffer-from": "^1.0.0",
|
||||
"inherits": "^2.0.3",
|
||||
"readable-stream": "^3.0.2",
|
||||
"typedarray": "^0.0.6"
|
||||
}
|
||||
},
|
||||
"node_modules/content-disposition": {
|
||||
"version": "0.5.4",
|
||||
"resolved": "https://registry.npmjs.org/content-disposition/-/content-disposition-0.5.4.tgz",
|
||||
@@ -919,14 +902,13 @@
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/multer": {
|
||||
"version": "2.2.0",
|
||||
"resolved": "https://registry.npmjs.org/multer/-/multer-2.2.0.tgz",
|
||||
"integrity": "sha512-6rdyFg2kLrMh9Jee7/BMPuV9lEAd7lLW2YUpF9/YxR7njyoUwwQ0ZPh3TaIY50Sw6vlyD2HW3wGOkTS4P79xrQ==",
|
||||
"version": "2.4.0",
|
||||
"resolved": "https://registry.npmjs.org/multer/-/multer-2.4.0.tgz",
|
||||
"integrity": "sha512-7dqa0ZcFfzbefdTuIkzOSMvZWC0J7FLqBOjJUZvDCXShIURWKxAyTT1wHhnE5q19c7jOJf43IYYKjBmZVZmvhg==",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"append-field": "^1.0.0",
|
||||
"busboy": "^1.6.0",
|
||||
"concat-stream": "^2.0.0",
|
||||
"type-is": "^1.6.18"
|
||||
},
|
||||
"engines": {
|
||||
@@ -946,6 +928,15 @@
|
||||
"node": ">= 0.6"
|
||||
}
|
||||
},
|
||||
"node_modules/nodemailer": {
|
||||
"version": "7.0.13",
|
||||
"resolved": "https://registry.npmjs.org/nodemailer/-/nodemailer-7.0.13.tgz",
|
||||
"integrity": "sha512-PNDFSJdP+KFgdsG3ZzMXCgquO7I6McjY2vlqILjtJd0hy8wEvtugS9xKRF2NWlPNGxvLCXlTNIae4serI7dinw==",
|
||||
"license": "MIT-0",
|
||||
"engines": {
|
||||
"node": ">=6.0.0"
|
||||
}
|
||||
},
|
||||
"node_modules/object-assign": {
|
||||
"version": "4.1.1",
|
||||
"resolved": "https://registry.npmjs.org/object-assign/-/object-assign-4.1.1.tgz",
|
||||
@@ -1185,20 +1176,6 @@
|
||||
"node": ">= 0.8"
|
||||
}
|
||||
},
|
||||
"node_modules/readable-stream": {
|
||||
"version": "3.6.2",
|
||||
"resolved": "https://registry.npmjs.org/readable-stream/-/readable-stream-3.6.2.tgz",
|
||||
"integrity": "sha512-9u/sniCrY3D5WdsERHzHE4G2YCXqoG5FTHUiCC4SIbr6XcLZBY05ya9EKjYek9O5xOAwjGq+1JdGBAS7Q9ScoA==",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"inherits": "^2.0.3",
|
||||
"string_decoder": "^1.1.1",
|
||||
"util-deprecate": "^1.0.1"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">= 6"
|
||||
}
|
||||
},
|
||||
"node_modules/safe-buffer": {
|
||||
"version": "5.2.1",
|
||||
"resolved": "https://registry.npmjs.org/safe-buffer/-/safe-buffer-5.2.1.tgz",
|
||||
@@ -1386,15 +1363,6 @@
|
||||
"node": ">=10.0.0"
|
||||
}
|
||||
},
|
||||
"node_modules/string_decoder": {
|
||||
"version": "1.3.0",
|
||||
"resolved": "https://registry.npmjs.org/string_decoder/-/string_decoder-1.3.0.tgz",
|
||||
"integrity": "sha512-hkRX8U1WjJFd8LsDJ2yQ/wWWxaopEsABU1XfkM8A+j0+85JAGppt16cr1Whg6KIbb4okU6Mql6BOj+uup/wKeA==",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"safe-buffer": "~5.2.0"
|
||||
}
|
||||
},
|
||||
"node_modules/superagent": {
|
||||
"version": "10.3.0",
|
||||
"resolved": "https://registry.npmjs.org/superagent/-/superagent-10.3.0.tgz",
|
||||
@@ -1501,12 +1469,6 @@
|
||||
"node": ">= 0.6"
|
||||
}
|
||||
},
|
||||
"node_modules/typedarray": {
|
||||
"version": "0.0.6",
|
||||
"resolved": "https://registry.npmjs.org/typedarray/-/typedarray-0.0.6.tgz",
|
||||
"integrity": "sha512-/aCDEGatGvZ2BIk+HmLf4ifCJFwvKFNb9/JeZPMulfgFracn9QFcAf5GO8B/mweUjSoblS5In0cWhqpfs/5PQA==",
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/unpipe": {
|
||||
"version": "1.0.0",
|
||||
"resolved": "https://registry.npmjs.org/unpipe/-/unpipe-1.0.0.tgz",
|
||||
@@ -1516,12 +1478,6 @@
|
||||
"node": ">= 0.8"
|
||||
}
|
||||
},
|
||||
"node_modules/util-deprecate": {
|
||||
"version": "1.0.2",
|
||||
"resolved": "https://registry.npmjs.org/util-deprecate/-/util-deprecate-1.0.2.tgz",
|
||||
"integrity": "sha512-EPD5q1uXyFxJpCrLnCc1nHnq3gOa6DZBocAIiI2TaSCA7VCJ1UJDMagCzIkXNsUYfD1daK//LTEQ8xiIbrHtcw==",
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/utils-merge": {
|
||||
"version": "1.0.1",
|
||||
"resolved": "https://registry.npmjs.org/utils-merge/-/utils-merge-1.0.1.tgz",
|
||||
|
||||
+2
-1
@@ -21,7 +21,8 @@
|
||||
"express-rate-limit": "8.6.2",
|
||||
"helmet": "8.1.0",
|
||||
"jsonwebtoken": "^9.0.2",
|
||||
"multer": "2.2.0",
|
||||
"multer": "2.4.0",
|
||||
"nodemailer": "^7.0.9",
|
||||
"pg": "^8.11.3"
|
||||
},
|
||||
"devDependencies": {
|
||||
|
||||
+45
@@ -287,3 +287,48 @@ CREATE UNIQUE INDEX IF NOT EXISTS idx_reports_unique_pending
|
||||
-- ============================================================
|
||||
INSERT INTO settings (key, value) VALUES ('forum_name', 'Forumlify')
|
||||
ON CONFLICT (key) DO NOTHING;
|
||||
|
||||
-- ============================================================
|
||||
-- 邮箱验证(对应 migrations/003_email_verification.sql)
|
||||
-- ============================================================
|
||||
|
||||
-- 邮箱验证码:用于注册时的邮箱归属校验,以及通过邮箱找回密码
|
||||
CREATE TABLE IF NOT EXISTS email_verifications (
|
||||
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
|
||||
email VARCHAR(255) NOT NULL,
|
||||
-- 验证码的 sha256 摘要,不存明文
|
||||
code_hash VARCHAR(64) NOT NULL,
|
||||
purpose VARCHAR(20) NOT NULL DEFAULT 'register',
|
||||
-- 尝试次数,超过阈值即作废,防止暴力枚举 6 位数字
|
||||
attempts INTEGER NOT NULL DEFAULT 0,
|
||||
consumed_at TIMESTAMPTZ,
|
||||
expires_at TIMESTAMPTZ NOT NULL,
|
||||
created_at TIMESTAMPTZ NOT NULL DEFAULT now()
|
||||
);
|
||||
|
||||
CREATE INDEX IF NOT EXISTS idx_email_verifications_lookup
|
||||
ON email_verifications (LOWER(email), purpose, created_at DESC);
|
||||
|
||||
CREATE INDEX IF NOT EXISTS idx_email_verifications_expires
|
||||
ON email_verifications (expires_at);
|
||||
|
||||
CREATE UNIQUE INDEX IF NOT EXISTS idx_email_verifications_active
|
||||
ON email_verifications (LOWER(email), purpose)
|
||||
WHERE consumed_at IS NULL;
|
||||
|
||||
-- 用户邮箱验证标记。存量用户默认为 true:他们是在开启邮箱验证之前
|
||||
-- 注册的,不应因为新功能而被标记为「未验证」。
|
||||
ALTER TABLE users ADD COLUMN IF NOT EXISTS email_verified BOOLEAN NOT NULL DEFAULT true;
|
||||
|
||||
-- SMTP 配置项(默认关闭,管理员在后台填写后生效)
|
||||
INSERT INTO settings (key, value) VALUES
|
||||
('smtp_enabled', 'false'),
|
||||
('smtp_host', ''),
|
||||
('smtp_port', '587'),
|
||||
('smtp_secure', 'false'),
|
||||
('smtp_user', ''),
|
||||
('smtp_password', ''),
|
||||
('smtp_from_name', ''),
|
||||
('smtp_from_email', ''),
|
||||
('email_verify_required', 'false')
|
||||
ON CONFLICT (key) DO NOTHING;
|
||||
@@ -14,6 +14,7 @@ const multer = require('multer');
|
||||
const path = require('path');
|
||||
const fs = require('fs');
|
||||
const crypto = require('crypto');
|
||||
const mailer = require('./lib/mailer');
|
||||
|
||||
const app = express();
|
||||
|
||||
@@ -91,8 +92,19 @@ const authLimiter = rateLimit({
|
||||
handler: (req, res) => res.status(429).json({ error: '尝试次数过多,请稍后重试' }),
|
||||
});
|
||||
|
||||
// 发送邮件的接口单独限流:这类接口会真实发出邮件,若被滥用既会
|
||||
// 骚扰收件人,也可能导致发信账号被服务商封禁。
|
||||
const mailLimiter = rateLimit({
|
||||
windowMs: 15 * 60 * 1000,
|
||||
limit: 5,
|
||||
standardHeaders: 'draft-8',
|
||||
legacyHeaders: false,
|
||||
handler: (req, res) => res.status(429).json({ error: '请求过于频繁,请稍后再试' }),
|
||||
});
|
||||
|
||||
app.use('/api', apiLimiter);
|
||||
app.use(['/api/auth/login', '/api/auth/register', '/api/auth/reset-password'], authLimiter);
|
||||
app.use(['/api/auth/send-code', '/api/auth/forgot-password'], mailLimiter);
|
||||
app.use(express.json({ limit: '100kb' }));
|
||||
app.use(express.urlencoded({ extended: true, limit: '100kb' }));
|
||||
|
||||
@@ -322,6 +334,13 @@ app.get('/api/settings', async (req, res) => {
|
||||
}
|
||||
settings.bootstrap_required = bootstrapConfigured && !adminExists;
|
||||
|
||||
// 告知前端注册时是否需要邮箱验证码,决定是否显示验证码输入框。
|
||||
// 同时暴露 SMTP 是否可用,避免在未配置邮件时引导用户去点「获取验证码」。
|
||||
const smtpConfig = await mailer.loadSmtpConfig(pool);
|
||||
const smtpReady = mailer.isConfigComplete(smtpConfig);
|
||||
settings.email_verify_required = settings.email_verify_required === 'true' && smtpReady;
|
||||
settings.smtp_ready = smtpReady;
|
||||
|
||||
res.json(settings);
|
||||
} catch (err) {
|
||||
res.status(500).json({ error: '服务器错误' });
|
||||
@@ -346,6 +365,183 @@ app.put('/api/settings', auth, admin, async (req, res) => {
|
||||
}
|
||||
});
|
||||
|
||||
// ============================================================
|
||||
// SMTP 配置(管理员)
|
||||
// ============================================================
|
||||
|
||||
// 读取 SMTP 配置。密码永不回显,只返回是否已设置。
|
||||
app.get('/api/admin/smtp', auth, admin, async (req, res) => {
|
||||
try {
|
||||
const config = await mailer.loadSmtpConfig(pool);
|
||||
res.json({
|
||||
enabled: config.enabled,
|
||||
host: config.host,
|
||||
port: config.port,
|
||||
secure: config.secure,
|
||||
user: config.user,
|
||||
from_name: config.fromName,
|
||||
from_email: config.fromEmail,
|
||||
// 只告诉前端「有没有设置过」,不返回明文
|
||||
password_set: Boolean(config.password),
|
||||
configured: mailer.isConfigComplete(config),
|
||||
});
|
||||
} catch (err) {
|
||||
res.status(500).json({ error: '服务器错误' });
|
||||
}
|
||||
});
|
||||
|
||||
// 保存 SMTP 配置
|
||||
app.put('/api/admin/smtp', auth, admin, async (req, res) => {
|
||||
const { enabled, host, port, secure, user, password, from_name, from_email } = req.body;
|
||||
|
||||
if (typeof enabled !== 'boolean' || typeof secure !== 'boolean') {
|
||||
return res.status(400).json({ error: '启用状态与加密方式必须为布尔值' });
|
||||
}
|
||||
|
||||
const portNumber = Number(port);
|
||||
if (!Number.isInteger(portNumber) || portNumber < 1 || portNumber > 65535) {
|
||||
return res.status(400).json({ error: '端口应为 1 到 65535 之间的整数' });
|
||||
}
|
||||
|
||||
// 允许留空(表示不启用),但填写时必须合法
|
||||
const hostValue = typeof host === 'string' ? host.trim() : '';
|
||||
if (hostValue.length > 255) {
|
||||
return res.status(400).json({ error: 'SMTP 主机地址过长' });
|
||||
}
|
||||
const userValue = typeof user === 'string' ? user.trim() : '';
|
||||
if (userValue.length > 255) {
|
||||
return res.status(400).json({ error: 'SMTP 用户名过长' });
|
||||
}
|
||||
if (typeof from_name === 'string' && from_name.length > 100) {
|
||||
return res.status(400).json({ error: '发件人名称过长' });
|
||||
}
|
||||
|
||||
const fromEmailValue = typeof from_email === 'string' ? from_email.trim() : '';
|
||||
if (fromEmailValue && !normalizeEmail(fromEmailValue)) {
|
||||
return res.status(400).json({ error: '发件人邮箱格式无效' });
|
||||
}
|
||||
|
||||
// 启用时必须把关键字段填全,否则直接存进去会让发信静默失败
|
||||
if (enabled) {
|
||||
if (!hostValue) return res.status(400).json({ error: '启用 SMTP 时需填写服务器地址' });
|
||||
if (!fromEmailValue) return res.status(400).json({ error: '启用 SMTP 时需填写发件人邮箱' });
|
||||
}
|
||||
|
||||
try {
|
||||
const entries = [
|
||||
['smtp_enabled', String(enabled)],
|
||||
['smtp_host', hostValue],
|
||||
['smtp_port', String(portNumber)],
|
||||
['smtp_secure', String(secure)],
|
||||
['smtp_user', userValue],
|
||||
['smtp_from_name', typeof from_name === 'string' ? from_name.trim() : ''],
|
||||
['smtp_from_email', fromEmailValue],
|
||||
];
|
||||
|
||||
// 密码留空表示「保持原值」,避免管理员只改端口却把密码清掉。
|
||||
// 传空字符串则显式清除。
|
||||
if (typeof password === 'string' && password.length > 0) {
|
||||
if (password.length > 255) {
|
||||
return res.status(400).json({ error: 'SMTP 密码过长' });
|
||||
}
|
||||
entries.push(['smtp_password', password]);
|
||||
}
|
||||
|
||||
for (const [key, value] of entries) {
|
||||
await pool.query(
|
||||
`INSERT INTO settings (key, value) VALUES ($1, $2)
|
||||
ON CONFLICT (key) DO UPDATE SET value = $2, updated_at = NOW()`,
|
||||
[key, value]
|
||||
);
|
||||
}
|
||||
|
||||
// 配置变了,让缓存的连接失效
|
||||
mailer.invalidateTransport();
|
||||
res.json({ success: true });
|
||||
} catch (err) {
|
||||
res.status(500).json({ error: '保存失败,请稍后重试' });
|
||||
}
|
||||
});
|
||||
|
||||
// 发送测试邮件,验证配置是否可用。可指定收件人,默认发给当前管理员。
|
||||
app.post('/api/admin/smtp/test', auth, admin, async (req, res) => {
|
||||
try {
|
||||
const config = await mailer.loadSmtpConfig(pool);
|
||||
if (!mailer.isConfigComplete(config)) {
|
||||
return res.status(400).json({ error: 'SMTP 尚未配置完成,请先填写并启用' });
|
||||
}
|
||||
|
||||
const requested = req.body && req.body.to;
|
||||
const to = requested ? normalizeEmail(requested) : null;
|
||||
if (requested && !to) {
|
||||
return res.status(400).json({ error: '收件人邮箱格式无效' });
|
||||
}
|
||||
|
||||
// 未指定则发给自己,省去管理员手填
|
||||
let target = to;
|
||||
if (!target) {
|
||||
const me = await pool.query('SELECT email FROM users WHERE id = $1', [req.user.id]);
|
||||
target = me.rows[0] && me.rows[0].email;
|
||||
if (!target) return res.status(400).json({ error: '请指定收件人邮箱' });
|
||||
}
|
||||
|
||||
await mailer.sendMail(config, {
|
||||
to: target,
|
||||
subject: 'Forumlify SMTP 测试邮件',
|
||||
text: `这是一封来自 Forumlify 的测试邮件。\n\n如果你收到它,说明 SMTP 配置正确。\n\n发信时间:${new Date().toISOString()}`,
|
||||
html: `<p>这是一封来自 <strong>Forumlify</strong> 的测试邮件。</p>
|
||||
<p>如果你收到它,说明 SMTP 配置正确。</p>
|
||||
<p style="color:#888;font-size:13px;">发信时间:${new Date().toISOString()}</p>`,
|
||||
});
|
||||
|
||||
res.json({ success: true, to: target });
|
||||
} catch (err) {
|
||||
// 把底层 SMTP 异常转成可读提示,便于管理员自行排查
|
||||
res.status(400).json({ error: mailer.describeSmtpError(err) });
|
||||
}
|
||||
});
|
||||
|
||||
// 清除已保存的 SMTP 密码
|
||||
app.delete('/api/admin/smtp/password', auth, admin, async (req, res) => {
|
||||
try {
|
||||
await pool.query(
|
||||
`INSERT INTO settings (key, value) VALUES ('smtp_password', '')
|
||||
ON CONFLICT (key) DO UPDATE SET value = '', updated_at = NOW()`
|
||||
);
|
||||
mailer.invalidateTransport();
|
||||
res.json({ success: true });
|
||||
} catch (err) {
|
||||
res.status(500).json({ error: '清除失败,请稍后重试' });
|
||||
}
|
||||
});
|
||||
|
||||
// 开关注册邮箱验证。仅在 SMTP 可用时才允许开启,避免开启后
|
||||
// 谁都注册不了。
|
||||
app.put('/api/admin/email-verify', auth, admin, async (req, res) => {
|
||||
const { required } = req.body;
|
||||
if (typeof required !== 'boolean') {
|
||||
return res.status(400).json({ error: '参数无效' });
|
||||
}
|
||||
|
||||
try {
|
||||
if (required) {
|
||||
const config = await mailer.loadSmtpConfig(pool);
|
||||
if (!mailer.isConfigComplete(config)) {
|
||||
return res.status(400).json({ error: '请先完成 SMTP 配置并发送测试邮件确认可用' });
|
||||
}
|
||||
}
|
||||
|
||||
await pool.query(
|
||||
`INSERT INTO settings (key, value) VALUES ('email_verify_required', $1)
|
||||
ON CONFLICT (key) DO UPDATE SET value = $1, updated_at = NOW()`,
|
||||
[String(required)]
|
||||
);
|
||||
res.json({ success: true, email_verify_required: required });
|
||||
} catch (err) {
|
||||
res.status(500).json({ error: '保存失败,请稍后重试' });
|
||||
}
|
||||
});
|
||||
|
||||
// ============================================================
|
||||
// 认证接口
|
||||
// ============================================================
|
||||
@@ -369,9 +565,171 @@ function issueToken(user) {
|
||||
);
|
||||
}
|
||||
|
||||
// ============================================================
|
||||
// 邮箱验证码
|
||||
// ============================================================
|
||||
// 注册需要邮箱验证时,先发一个 6 位数字码;校验通过后才允许建号。
|
||||
// 验证码只存 sha256 摘要,并限制尝试次数与有效期。
|
||||
|
||||
const EMAIL_CODE_TTL_MS = 10 * 60 * 1000; // 10 分钟有效
|
||||
const EMAIL_CODE_MAX_ATTEMPTS = 5; // 超过即作废
|
||||
|
||||
// 生成 6 位数字验证码,使用 crypto 随机源
|
||||
function generateEmailCode() {
|
||||
// randomInt 上界不含,故取 1000000 得到 000000-999999
|
||||
return String(crypto.randomInt(0, 1000000)).padStart(6, '0');
|
||||
}
|
||||
|
||||
function hashEmailCode(code) {
|
||||
return crypto.createHash('sha256').update(String(code)).digest('hex');
|
||||
}
|
||||
|
||||
// 论坛设置里是否需要邮箱验证。默认关闭,升级后行为不变。
|
||||
async function isEmailVerifyRequired() {
|
||||
const r = await pool.query("SELECT value FROM settings WHERE key = 'email_verify_required'");
|
||||
return r.rows[0]?.value === 'true';
|
||||
}
|
||||
|
||||
// 写入一条验证码记录(同邮箱同用途只保留一条有效记录)
|
||||
async function createEmailVerification(email, purpose) {
|
||||
const code = generateEmailCode();
|
||||
await pool.query(
|
||||
`INSERT INTO email_verifications (email, code_hash, purpose, expires_at, attempts, consumed_at)
|
||||
VALUES ($1, $2, $3, $4, 0, NULL)
|
||||
ON CONFLICT (LOWER(email), purpose) WHERE consumed_at IS NULL
|
||||
DO UPDATE SET code_hash = EXCLUDED.code_hash,
|
||||
expires_at = EXCLUDED.expires_at,
|
||||
attempts = 0,
|
||||
created_at = now()`,
|
||||
[email, hashEmailCode(code), purpose, new Date(Date.now() + EMAIL_CODE_TTL_MS)]
|
||||
);
|
||||
return code;
|
||||
}
|
||||
|
||||
// 校验验证码。成功时消费掉该记录并返回 true。
|
||||
// 失败返回原因字符串,便于接口给出更具体的提示。
|
||||
async function consumeEmailVerification(email, purpose, code) {
|
||||
const client = await pool.connect();
|
||||
try {
|
||||
await client.query('BEGIN');
|
||||
const r = await client.query(
|
||||
`SELECT id, code_hash, attempts, expires_at
|
||||
FROM email_verifications
|
||||
WHERE LOWER(email) = LOWER($1) AND purpose = $2 AND consumed_at IS NULL
|
||||
ORDER BY created_at DESC
|
||||
LIMIT 1
|
||||
FOR UPDATE`,
|
||||
[email, purpose]
|
||||
);
|
||||
|
||||
if (r.rows.length === 0) {
|
||||
await client.query('ROLLBACK');
|
||||
return 'missing';
|
||||
}
|
||||
|
||||
const row = r.rows[0];
|
||||
|
||||
if (new Date(row.expires_at).getTime() < Date.now()) {
|
||||
await client.query('ROLLBACK');
|
||||
return 'expired';
|
||||
}
|
||||
if (row.attempts >= EMAIL_CODE_MAX_ATTEMPTS) {
|
||||
await client.query('ROLLBACK');
|
||||
return 'too_many';
|
||||
}
|
||||
|
||||
// 定时安全比较,避免通过响应时间推断验证码
|
||||
const provided = Buffer.from(hashEmailCode(code));
|
||||
const expected = Buffer.from(row.code_hash);
|
||||
const matched = provided.length === expected.length &&
|
||||
crypto.timingSafeEqual(provided, expected);
|
||||
|
||||
if (!matched) {
|
||||
await client.query(
|
||||
'UPDATE email_verifications SET attempts = attempts + 1 WHERE id = $1',
|
||||
[row.id]
|
||||
);
|
||||
await client.query('COMMIT');
|
||||
return 'mismatch';
|
||||
}
|
||||
|
||||
await client.query(
|
||||
'UPDATE email_verifications SET consumed_at = now() WHERE id = $1',
|
||||
[row.id]
|
||||
);
|
||||
await client.query('COMMIT');
|
||||
return null; // null 表示通过
|
||||
} catch (err) {
|
||||
await client.query('ROLLBACK').catch(() => {});
|
||||
throw err;
|
||||
} finally {
|
||||
client.release();
|
||||
}
|
||||
}
|
||||
|
||||
// 把 consumeEmailVerification 的失败原因转成用户可读文案
|
||||
const EMAIL_CODE_ERRORS = {
|
||||
missing: '请先获取验证码',
|
||||
expired: '验证码已过期,请重新获取',
|
||||
too_many: '尝试次数过多,请重新获取验证码',
|
||||
mismatch: '验证码错误',
|
||||
};
|
||||
|
||||
// 校验邮件配置是否可用于发信,返回配置对象或抛出带 code 的错误
|
||||
async function requireMailConfig() {
|
||||
const config = await mailer.loadSmtpConfig(pool);
|
||||
if (!mailer.isConfigComplete(config)) {
|
||||
const error = new Error('站点尚未配置邮件服务,请联系管理员');
|
||||
error.code = 'SMTP_NOT_CONFIGURED';
|
||||
throw error;
|
||||
}
|
||||
return config;
|
||||
}
|
||||
|
||||
// 发送邮箱验证码(注册用)。独立的限流在注册路由处配置。
|
||||
app.post('/api/auth/send-code', async (req, res) => {
|
||||
const { email } = req.body;
|
||||
const normalized = normalizeEmail(email);
|
||||
if (!normalized) {
|
||||
return res.status(400).json({ error: '请输入有效邮箱' });
|
||||
}
|
||||
|
||||
try {
|
||||
if (!(await isEmailVerifyRequired())) {
|
||||
return res.status(400).json({ error: '本站未开启邮箱验证' });
|
||||
}
|
||||
|
||||
// 已注册过的邮箱直接拦下,避免泄露之外还白发一封
|
||||
const existing = await pool.query('SELECT id FROM users WHERE LOWER(email) = LOWER($1)', [normalized]);
|
||||
if (existing.rows.length > 0) {
|
||||
return res.status(409).json({ error: '该邮箱已被注册' });
|
||||
}
|
||||
|
||||
const config = await requireMailConfig();
|
||||
const code = await createEmailVerification(normalized, 'register');
|
||||
|
||||
await mailer.sendMail(config, {
|
||||
to: normalized,
|
||||
subject: '注册验证码',
|
||||
text: `你的注册验证码是:${code}\n\n有效期 10 分钟,请勿转发给他人。\n如果这不是你本人的操作,请忽略本邮件。`,
|
||||
html: `<p>你的注册验证码是:</p>
|
||||
<p style="font-size:26px;font-weight:700;letter-spacing:4px;margin:12px 0;">${code}</p>
|
||||
<p style="color:#888;font-size:13px;">有效期 10 分钟,请勿转发给他人。<br>如果这不是你本人的操作,请忽略本邮件。</p>`,
|
||||
});
|
||||
|
||||
res.json({ success: true, message: '验证码已发送,请查收邮件' });
|
||||
} catch (err) {
|
||||
if (err.code === 'SMTP_NOT_CONFIGURED') {
|
||||
return res.status(503).json({ error: err.message });
|
||||
}
|
||||
console.error('发送注册验证码失败:', err);
|
||||
res.status(400).json({ error: mailer.describeSmtpError(err) });
|
||||
}
|
||||
});
|
||||
|
||||
// 注册;管理员只能使用部署时配置的一次性引导令牌创建
|
||||
app.post('/api/auth/register', async (req, res) => {
|
||||
const { email, password, username, bootstrap_token } = req.body;
|
||||
const { email, password, username, bootstrap_token, email_code } = req.body;
|
||||
|
||||
if (!email || !password || !username) {
|
||||
return res.status(400).json({ error: '请填写完整信息' });
|
||||
@@ -386,6 +744,25 @@ app.post('/api/auth/register', async (req, res) => {
|
||||
return res.status(400).json({ error: '密码长度应为6到128个字符' });
|
||||
}
|
||||
|
||||
// 邮箱验证码校验放在所有格式校验之后,避免用户因格式错误白白消耗
|
||||
// 一次验证码(校验失败会计入尝试次数)。
|
||||
let emailVerified = false;
|
||||
try {
|
||||
if (await isEmailVerifyRequired()) {
|
||||
if (!isText(email_code, { min: 4, max: 10 })) {
|
||||
return res.status(400).json({ error: '请输入邮箱验证码' });
|
||||
}
|
||||
const failure = await consumeEmailVerification(normalizedEmail, 'register', email_code.trim());
|
||||
if (failure) {
|
||||
return res.status(400).json({ error: EMAIL_CODE_ERRORS[failure] || '验证码校验失败' });
|
||||
}
|
||||
emailVerified = true;
|
||||
}
|
||||
} catch (err) {
|
||||
console.error('校验邮箱验证码失败:', err);
|
||||
return res.status(500).json({ error: '服务器错误' });
|
||||
}
|
||||
|
||||
const hash = await bcrypt.hash(password, 10);
|
||||
const avatar = 'https://ui-avatars.com/api/?name=' + encodeURIComponent(username) + '&background=6366f1&color=fff&size=64';
|
||||
let client;
|
||||
@@ -409,10 +786,10 @@ app.post('/api/auth/register', async (req, res) => {
|
||||
|
||||
const role = validBootstrap && !hasAdmin ? 'admin' : 'user';
|
||||
const r = await client.query(
|
||||
`INSERT INTO users (email, password_hash, username, avatar_url, role, signature)
|
||||
VALUES ($1, $2, $3, $4, $5, $6)
|
||||
`INSERT INTO users (email, password_hash, username, avatar_url, role, signature, email_verified)
|
||||
VALUES ($1, $2, $3, $4, $5, $6, $7)
|
||||
RETURNING id, username, avatar_url, role, signature, created_at`,
|
||||
[normalizedEmail, hash, username.trim(), avatar, role, '']
|
||||
[normalizedEmail, hash, username.trim(), avatar, role, '', emailVerified]
|
||||
);
|
||||
await client.query('COMMIT');
|
||||
|
||||
@@ -1704,6 +2081,79 @@ app.get('/api/auth/recovery-codes/count', auth, async (req, res) => {
|
||||
});
|
||||
|
||||
// 重置密码(使用恢复码)
|
||||
// 通过邮箱发送密码重置码。与恢复码机制并行,管理员可按需启用。
|
||||
app.post('/api/auth/forgot-password', async (req, res) => {
|
||||
const { email } = req.body;
|
||||
const normalized = normalizeEmail(email);
|
||||
if (!normalized) {
|
||||
return res.status(400).json({ error: '请输入有效邮箱' });
|
||||
}
|
||||
|
||||
try {
|
||||
const user = await pool.query('SELECT id FROM users WHERE LOWER(email) = LOWER($1)', [normalized]);
|
||||
|
||||
// 无论邮箱是否存在都返回同样的成功响应,避免被用来枚举注册用户。
|
||||
if (user.rows.length === 0) {
|
||||
return res.json({ success: true, message: '如果该邮箱已注册,重置码已发送' });
|
||||
}
|
||||
|
||||
const config = await requireMailConfig();
|
||||
const code = await createEmailVerification(normalized, 'reset');
|
||||
|
||||
await mailer.sendMail(config, {
|
||||
to: normalized,
|
||||
subject: '密码重置验证码',
|
||||
text: `你的密码重置验证码是:${code}\n\n有效期 10 分钟。如果这不是你本人的操作,请忽略本邮件,你的密码不会发生变化。`,
|
||||
html: `<p>你的密码重置验证码是:</p>
|
||||
<p style="font-size:26px;font-weight:700;letter-spacing:4px;margin:12px 0;">${code}</p>
|
||||
<p style="color:#888;font-size:13px;">有效期 10 分钟。如果这不是你本人的操作,请忽略本邮件,你的密码不会发生变化。</p>`,
|
||||
});
|
||||
|
||||
res.json({ success: true, message: '如果该邮箱已注册,重置码已发送' });
|
||||
} catch (err) {
|
||||
if (err.code === 'SMTP_NOT_CONFIGURED') {
|
||||
return res.status(503).json({ error: err.message });
|
||||
}
|
||||
console.error('发送密码重置码失败:', err);
|
||||
res.status(400).json({ error: mailer.describeSmtpError(err) });
|
||||
}
|
||||
});
|
||||
|
||||
// 使用邮箱验证码重置密码
|
||||
app.post('/api/auth/reset-password-by-email', async (req, res) => {
|
||||
const { email, code, newPassword } = req.body;
|
||||
const normalized = normalizeEmail(email);
|
||||
|
||||
if (!normalized || !isText(code, { min: 4, max: 10 }) || !isText(newPassword, { min: 6, max: 128 })) {
|
||||
return res.status(400).json({ error: '请填写完整信息' });
|
||||
}
|
||||
|
||||
try {
|
||||
const failure = await consumeEmailVerification(normalized, 'reset', code.trim());
|
||||
if (failure) {
|
||||
return res.status(400).json({ error: EMAIL_CODE_ERRORS[failure] || '验证码校验失败' });
|
||||
}
|
||||
|
||||
const hash = await bcrypt.hash(newPassword, 10);
|
||||
// 递增 token_version 让所有已签发的登录令牌立即失效
|
||||
const updated = await pool.query(
|
||||
`UPDATE users SET password_hash = $1, token_version = token_version + 1
|
||||
WHERE LOWER(email) = LOWER($2)
|
||||
RETURNING id`,
|
||||
[hash, normalized]
|
||||
);
|
||||
|
||||
if (updated.rows.length === 0) {
|
||||
return res.status(400).json({ error: '账号不存在' });
|
||||
}
|
||||
|
||||
res.json({ success: true });
|
||||
} catch (err) {
|
||||
console.error('通过邮箱重置密码失败:', err);
|
||||
res.status(500).json({ error: '重置失败,请稍后重试' });
|
||||
}
|
||||
});
|
||||
|
||||
app.post('/api/auth/reset-password', async (req, res) => {
|
||||
const { email, recoveryCode, newPassword } = req.body;
|
||||
|
||||
|
||||
@@ -2181,29 +2181,32 @@ a.btn-secondary {
|
||||
论坛设置 —— 名称输入框 + 保存按钮同行
|
||||
============================================================ */
|
||||
|
||||
/* 论坛名称区域的容器(假设是 div 包着 input + button) */
|
||||
#adminContent > div:first-of-type {
|
||||
display: flex !important;
|
||||
align-items: center !important;
|
||||
justify-content: center !important;
|
||||
gap: 8px !important;
|
||||
max-width: 500px !important;
|
||||
margin: 0 auto !important;
|
||||
flex-wrap: wrap !important;
|
||||
/* 原先这里用 `#adminContent > div:first-of-type` 定位本面板,
|
||||
依赖「第一个 div 就是论坛名称区域」这一脆弱假设。任何新增的
|
||||
后台面板只要把 div 放在最前就会被打成 flex 行布局(邮件设置面板
|
||||
就踩到了这个坑)。改为显式的类名,语义明确且互不干扰。 */
|
||||
.forum-name-form {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
gap: 8px;
|
||||
max-width: 500px;
|
||||
margin: 0 auto;
|
||||
flex-wrap: wrap;
|
||||
}
|
||||
|
||||
/* 输入框 flex: 1 占满剩余空间 */
|
||||
#settingsForumName {
|
||||
flex: 1 !important;
|
||||
min-width: 200px !important;
|
||||
margin: 0 !important;
|
||||
flex: 1;
|
||||
min-width: 200px;
|
||||
margin: 0;
|
||||
}
|
||||
|
||||
/* 保存按钮不需要全宽 */
|
||||
#settingsForumSave {
|
||||
width: auto !important;
|
||||
flex-shrink: 0 !important;
|
||||
margin: 0 !important;
|
||||
width: auto;
|
||||
flex-shrink: 0;
|
||||
margin: 0;
|
||||
}
|
||||
|
||||
/* 状态提示文字紧跟按钮 */
|
||||
@@ -2877,6 +2880,90 @@ a.btn-secondary {
|
||||
}
|
||||
}
|
||||
|
||||
/* ============================================================
|
||||
📧 邮件设置面板
|
||||
------------------------------------------------------------
|
||||
管理后台的输入框原本没有统一的宽度与间距规则,靠行内样式零散
|
||||
指定。这里用一个专用容器类统一约束,避免与 label 挤在同一行。
|
||||
============================================================ */
|
||||
|
||||
.smtp-form {
|
||||
max-width: 520px;
|
||||
margin: 0 auto;
|
||||
width: 100%;
|
||||
/* 管理后台的容器默认是 flex 行布局,会把 label 与 input 横向排开。
|
||||
这里显式改回纵向块级流,让每个控件独占一行。 */
|
||||
display: block;
|
||||
}
|
||||
|
||||
/* 表单内的文本控件独占一行 */
|
||||
.smtp-form input:not([type="checkbox"]),
|
||||
.smtp-form select {
|
||||
display: block;
|
||||
width: 100%;
|
||||
box-sizing: border-box;
|
||||
margin-bottom: 14px;
|
||||
}
|
||||
|
||||
/* 复选框保持自然尺寸,与文字同一行 */
|
||||
.smtp-form input[type="checkbox"] {
|
||||
width: auto;
|
||||
margin: 0;
|
||||
flex: none;
|
||||
}
|
||||
|
||||
.smtp-form label {
|
||||
display: block;
|
||||
font-weight: 600;
|
||||
font-size: 14px;
|
||||
margin-bottom: 6px;
|
||||
}
|
||||
|
||||
/* 包裹复选框的 label 用 flex,使方框与文字对齐 */
|
||||
.smtp-form label.smtp-check {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 8px;
|
||||
margin-bottom: 14px;
|
||||
cursor: pointer;
|
||||
}
|
||||
|
||||
.smtp-form .smtp-row {
|
||||
display: flex;
|
||||
gap: 12px;
|
||||
}
|
||||
|
||||
.smtp-form .smtp-row > div {
|
||||
flex: 1;
|
||||
}
|
||||
|
||||
.smtp-form .smtp-hint {
|
||||
font-size: 12px;
|
||||
color: var(--glass-text-light);
|
||||
margin: -8px 0 14px;
|
||||
}
|
||||
|
||||
.smtp-form .smtp-actions {
|
||||
display: flex;
|
||||
gap: 10px;
|
||||
flex-wrap: wrap;
|
||||
margin: 6px 0 24px;
|
||||
}
|
||||
|
||||
.smtp-form hr {
|
||||
border: none;
|
||||
border-top: 1px solid var(--glass-border);
|
||||
margin: 0 0 20px;
|
||||
}
|
||||
|
||||
/* 窄屏时端口与加密方式改为纵向排列 */
|
||||
@media (max-width: 480px) {
|
||||
.smtp-form .smtp-row {
|
||||
flex-direction: column;
|
||||
gap: 0;
|
||||
}
|
||||
}
|
||||
|
||||
/* ============================================================
|
||||
❓ 确认对话框
|
||||
------------------------------------------------------------
|
||||
@@ -2998,10 +3085,18 @@ a.btn-secondary {
|
||||
}
|
||||
|
||||
/* 覆盖所有文本输入控件。排除 checkbox/radio/file/range/color 等
|
||||
非文本控件,它们用凹陷阴影会显得突兀。 */
|
||||
非文本控件,它们用凹陷阴影会显得突兀。
|
||||
|
||||
注意:只加视觉相关的 !important,不要给 padding / width 加,
|
||||
否则会压过各页面(如管理后台)已有的尺寸定制,导致输入框塌陷。
|
||||
这里给出兜底的 padding,让没有单独定义内边距的输入框也有正常高度。 */
|
||||
input:not([type="checkbox"]):not([type="radio"]):not([type="file"]):not([type="range"]):not([type="color"]):not([type="submit"]):not([type="button"]),
|
||||
textarea,
|
||||
select {
|
||||
padding: 10px 14px;
|
||||
font-size: 14px;
|
||||
font-family: inherit;
|
||||
color: var(--glass-text);
|
||||
background: var(--inset-bg) !important;
|
||||
border: 1px solid var(--inset-border) !important;
|
||||
box-shadow: var(--inset-shadow) !important;
|
||||
|
||||
+15
-1
@@ -70,6 +70,20 @@ test('bcryptjs hashes passwords without native install scripts', async () => {
|
||||
});
|
||||
|
||||
test('security-sensitive dependencies are on patched release lines', () => {
|
||||
assert.match(multerPackage.version, /^2\.2\./);
|
||||
// multer 2.2.0 及更早版本存在多个 DoS 与上传限制绕过漏洞
|
||||
// (GHSA-wc9g-mqfw-jrwm 等),2.3.0 起修复。
|
||||
// 这里断言「不低于已修复的版本」,而不是锁死某个小版本,
|
||||
// 否则后续的安全升级反而会让测试失败。
|
||||
const [major, minor] = multerPackage.version.split('.').map(Number);
|
||||
const multerPatched = major > 2 || (major === 2 && minor >= 3);
|
||||
assert.ok(
|
||||
multerPatched,
|
||||
`multer ${multerPackage.version} 低于已修复漏洞的 2.3.0`
|
||||
);
|
||||
|
||||
assert.equal(projectPackage.dependencies['express-rate-limit'], '8.6.2');
|
||||
assert.ok(
|
||||
projectPackage.dependencies.nodemailer,
|
||||
'nodemailer 是邮件功能的必需依赖'
|
||||
);
|
||||
});
|
||||
Reference in new issue
Block a user