Files
forumlify/js/api.js
T
Furrium Network 627d284b02 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 通过。
2026-09-21 21:45:41 +08:00

528 lines
16 KiB
JavaScript

// ============================================================
// API 请求封装
// ============================================================
let token = localStorage.getItem('forumlify-token') || null;
function getAuthHeaders() {
return token ? { 'Authorization': 'Bearer ' + token } : {};
}
function apiFetch(path, options = {}) {
const url = CONFIG.API_BASE_URL + path;
const headers = {
'Content-Type': 'application/json',
...getAuthHeaders(),
...(options.headers || {})
};
return fetch(url, {
...options,
headers
}).then(res => res.json());
}
const API = {
// ============================================================
// 认证
// ============================================================
async login(email, password) {
const data = await apiFetch('/auth/login', {
method: 'POST',
body: JSON.stringify({ email, password })
});
if (data.error) throw new Error(data.error);
if (data.token) {
token = data.token;
localStorage.setItem('forumlify-token', token);
}
return data;
},
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,
email_code: emailCode || undefined
})
});
if (data.error) throw new Error(data.error);
return data;
},
async logout() {
token = null;
localStorage.removeItem('forumlify-token');
currentUser = null;
},
async getMe() {
const data = await apiFetch('/auth/me');
if (data.error) throw new Error(data.error);
return data;
},
// ============================================================
// 帖子(含分页)
// ============================================================
async getPosts(sort, page = 1, limit = 20) {
const data = await apiFetch('/posts?sort=' + (sort || 'latest') + '&page=' + page + '&limit=' + limit);
if (data.error) throw new Error(data.error);
return data;
},
async getPost(postId) {
const data = await apiFetch('/posts/' + postId);
if (data.error) throw new Error(data.error);
return data;
},
async createPost(title, content, images) {
const data = await apiFetch('/posts', {
method: 'POST',
body: JSON.stringify({ title, content, images: images || [] })
});
if (data.error) throw new Error(data.error);
return data;
},
async uploadImage(file) {
const formData = new FormData();
formData.append('file', file);
const response = await fetch(CONFIG.API_BASE_URL + '/upload', {
method: 'POST',
headers: getAuthHeaders(),
body: formData
});
const data = await response.json().catch(() => ({ error: '上传响应无效' }));
if (!response.ok || data.error) throw new Error(data.error || '图片上传失败');
return data;
},
async updatePost(postId, title, content) {
const data = await apiFetch('/posts/' + postId, {
method: 'PUT',
body: JSON.stringify({ title, content })
});
if (data.error) throw new Error(data.error);
return data;
},
async deletePost(postId) {
const data = await apiFetch('/posts/' + postId, { method: 'DELETE' });
if (data.error) throw new Error(data.error);
return data;
},
async togglePinPost(postId) {
const data = await apiFetch('/posts/' + postId + '/pin', {
method: 'PUT'
});
if (data.error) throw new Error(data.error);
return data;
},
// ============================================================
// 回复
// ============================================================
async getReplies(postId) {
const data = await apiFetch('/posts/' + postId + '/replies');
if (data.error) throw new Error(data.error);
return data || [];
},
async createReply(postId, content) {
const data = await apiFetch('/posts/' + postId + '/replies', {
method: 'POST',
body: JSON.stringify({ content })
});
if (data.error) throw new Error(data.error);
return data;
},
async deleteReply(replyId) {
const data = await apiFetch('/replies/' + replyId, { method: 'DELETE' });
if (data.error) throw new Error(data.error);
return data;
},
// ============================================================
// 用户管理(支持分页和搜索)
// ============================================================
async getUsers(page = 1, limit = 20, search = '') {
const data = await apiFetch('/users?page=' + page + '&limit=' + limit + '&search=' + encodeURIComponent(search));
if (data.error) throw new Error(data.error);
return data;
},
async updateUserRole(userId, role) {
const data = await apiFetch('/users/' + userId + '/role', {
method: 'PUT',
body: JSON.stringify({ role })
});
if (data.error) throw new Error(data.error);
return data;
},
// ============================================================
// 举报
// ============================================================
async getReports() {
const data = await apiFetch('/reports');
if (data.error) throw new Error(data.error);
return data || [];
},
async createReport(postId, reason) {
const data = await apiFetch('/reports', {
method: 'POST',
body: JSON.stringify({ post_id: postId, reason })
});
if (data.error) throw new Error(data.error);
return data;
},
async updateReport(reportId, status, note) {
const data = await apiFetch('/reports/' + reportId, {
method: 'PUT',
body: JSON.stringify({ status, note })
});
if (data.error) throw new Error(data.error);
return data;
},
// ============================================================
// 统计
// ============================================================
async getStats() {
const data = await apiFetch('/stats');
if (data.error) throw new Error(data.error);
return data;
},
// ============================================================
// 友情链接
// ============================================================
async getLinks() {
const data = await apiFetch('/links');
if (data.error) throw new Error(data.error);
return data || [];
},
async addLink(title, url) {
const data = await apiFetch('/links', {
method: 'POST',
body: JSON.stringify({ title, url })
});
if (data.error) throw new Error(data.error);
return data;
},
async deleteLink(id) {
const data = await apiFetch('/links/' + id, { method: 'DELETE' });
if (data.error) throw new Error(data.error);
return data;
},
// ============================================================
// 事件日志(支持分页)
// ============================================================
async getEventLogs(page = 1, limit = 20) {
const data = await apiFetch('/event-logs?page=' + page + '&limit=' + limit);
if (data.error) throw new Error(data.error);
return data;
},
// ============================================================
// 论坛设置
// ============================================================
async getSettings() {
const data = await apiFetch('/settings');
if (data.error) throw new Error(data.error);
return data;
},
async updateSettings(forum_name) {
const data = await apiFetch('/settings', {
method: 'PUT',
body: JSON.stringify({ forum_name })
});
if (data.error) throw new Error(data.error);
return data;
},
// ============================================================
// 私信
// ============================================================
async getConversations() {
const data = await apiFetch('/conversations');
if (data.error) throw new Error(data.error);
return data || [];
},
async getOrCreateConversation(other_user_id) {
const data = await apiFetch('/conversations', {
method: 'POST',
body: JSON.stringify({ other_user_id })
});
if (data.error) throw new Error(data.error);
return data;
},
async getMessages(conversationId) {
const data = await apiFetch('/conversations/' + conversationId + '/messages');
if (data.error) throw new Error(data.error);
return data || [];
},
async sendMessage(conversationId, content) {
const data = await apiFetch('/conversations/' + conversationId + '/messages', {
method: 'POST',
body: JSON.stringify({ content })
});
if (data.error) throw new Error(data.error);
return data;
},
async markMessageRead(messageId) {
const data = await apiFetch('/messages/' + messageId + '/read', {
method: 'PUT'
});
if (data.error) throw new Error(data.error);
return data;
},
// ============================================================
// 自定义页面
// ============================================================
async getCustomPages() {
const data = await apiFetch('/custom-pages');
if (data.error) throw new Error(data.error);
return data || [];
},
async getCustomPage(name) {
const data = await apiFetch('/custom-pages/' + encodeURIComponent(name));
if (data.error) throw new Error(data.error);
return data;
},
async getAdminCustomPages() {
const data = await apiFetch('/admin/custom-pages');
if (data.error) throw new Error(data.error);
return data || [];
},
async createCustomPage(name, title, content) {
const data = await apiFetch('/admin/custom-pages', {
method: 'POST',
body: JSON.stringify({ name, title, content })
});
if (data.error) throw new Error(data.error);
return data;
},
async updateCustomPage(id, title, content, enabled) {
const data = await apiFetch('/admin/custom-pages/' + id, {
method: 'PUT',
body: JSON.stringify({ title, content, enabled })
});
if (data.error) throw new Error(data.error);
return data;
},
async deleteCustomPage(id) {
const data = await apiFetch('/admin/custom-pages/' + id, { method: 'DELETE' });
if (data.error) throw new Error(data.error);
return data;
},
// ============================================================
// 头像
// ============================================================
async updateAvatar(userId, avatar_url) {
const data = await apiFetch('/users/' + userId + '/avatar', {
method: 'PUT',
body: JSON.stringify({ avatar_url })
});
if (data.error) throw new Error(data.error);
return data;
},
// ============================================================
// 恢复码
// ============================================================
async generateRecoveryCodes() {
const data = await apiFetch('/auth/recovery-codes/generate', {
method: 'POST'
});
if (data.error) throw new Error(data.error);
return data;
},
async getRecoveryCodesCount() {
const data = await apiFetch('/auth/recovery-codes/count');
if (data.error) throw new Error(data.error);
return data;
},
async resetPassword(email, recoveryCode, newPassword) {
const data = await apiFetch('/auth/reset-password', {
method: 'POST',
body: JSON.stringify({ email, recoveryCode, newPassword })
});
if (data.error) throw new Error(data.error);
return data;
},
// ============================================================
// 修改密码和邮箱
// ============================================================
// 这两个接口会递增 token_version 使旧令牌失效,服务端随即补发一个
// 新令牌。这里必须接住它,否则用户操作成功后会被立刻登出。
_persistRefreshedToken(data) {
if (data && data.token) {
token = data.token;
localStorage.setItem('forumlify-token', token);
}
return data;
},
async changePassword(oldPassword, newPassword) {
const data = await apiFetch('/users/' + currentUser.id + '/password', {
method: 'PUT',
body: JSON.stringify({ oldPassword, newPassword })
});
if (data.error) throw new Error(data.error);
return this._persistRefreshedToken(data);
},
async changeEmail(password, newEmail) {
const data = await apiFetch('/users/' + currentUser.id + '/email', {
method: 'PUT',
body: JSON.stringify({ password, newEmail })
});
if (data.error) throw new Error(data.error);
return this._persistRefreshedToken(data);
},
// ============================================================
// 更新用户资料(含签名)
// ============================================================
async updateProfile(userId, username, bio, signature) {
const data = await apiFetch('/users/' + userId, {
method: 'PUT',
body: JSON.stringify({ username, bio, signature })
});
if (data.error) throw new Error(data.error);
return data;
},
// ============================================================
// 自定义 CSS
// ============================================================
async uploadCustomCSS(file) {
const formData = new FormData();
formData.append('file', file);
const url = CONFIG.API_BASE_URL + '/admin/custom-css';
const response = await fetch(url, {
method: 'POST',
headers: {
'Authorization': 'Bearer ' + localStorage.getItem('forumlify-token')
},
body: formData
});
const data = await response.json();
if (data.error) throw new Error(data.error);
return data;
},
async deleteCustomCSS() {
const data = await apiFetch('/admin/custom-css', {
method: 'DELETE'
});
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;
}
};