Merge remote-tracking branch 'upstream/Lite' into fix-repo-public-cwe-307-auth-rate-limit
# Conflicts: # server.js
This commit is contained in:
commit
3558247aac
17 files changed
+1807
-148
No files matched your search
@@ -10,10 +10,11 @@
|
||||
|
||||
- 🎨 精致简约的界面设计,支持亮色/暗色模式
|
||||
- ⚡️ 轻量快速,无需复杂配置
|
||||
- 🔐 自带用户认证(JWT)
|
||||
- 📝 发帖、回复、举报、管理后台
|
||||
- 🔐 自带用户认证(JWT),改密码后旧令牌立即失效
|
||||
- 📝 发帖、回复、举报、私信、管理后台
|
||||
- 📧 邮件支持:后台配置 SMTP,可用于注册邮箱验证与密码找回
|
||||
- 🌍 界面中英文双语,管理后台可配置自定义页面与样式
|
||||
- 🐳 Docker 一键部署
|
||||
- 🌓 暗色/亮色模式切换
|
||||
|
||||
## 🤔 如何选择版本
|
||||
|
||||
@@ -223,6 +224,131 @@ server {
|
||||
必须为本域名单独写一个 `server_name` 的 80 端口块。
|
||||
- **ACME 挑战路径要放在 `return 301` 之前**,否则同样会被重定向。
|
||||
|
||||
### 邮件(SMTP)
|
||||
|
||||
邮件功能**默认关闭**,全部在管理后台配置,无需改环境变量或重启服务。
|
||||
入口:登录管理员账号 → 右上角头像 → **管理后台** → **邮件设置**。
|
||||
|
||||
> 配置保存在数据库的 `settings` 表中,因此在 Docker 部署下也会随
|
||||
> `db_data` 卷一起持久化,容器重建不会丢失,也不需要给 Compose 增加
|
||||
> 任何环境变量。
|
||||
|
||||
配置项:
|
||||
|
||||
| 字段 | 说明 |
|
||||
|------|------|
|
||||
| 启用邮件发送 | 总开关,关闭时所有邮件功能不可用 |
|
||||
| SMTP 服务器 | 如 `smtp.qq.com`、`smtp.gmail.com` |
|
||||
| 端口 | 587(STARTTLS)或 465(SSL/TLS) |
|
||||
| 加密方式 | 需与端口匹配:**587 选 STARTTLS,465 选 SSL/TLS** |
|
||||
| 用户名 | 通常为完整邮箱地址 |
|
||||
| 密码 / 授权码 | 见下方说明 |
|
||||
| 发件人名称 | 显示在收件人邮箱里的发件人名字 |
|
||||
| 发件人邮箱 | 必填,建议与用户名一致,否则易被判定为伪造发件人 |
|
||||
|
||||
填写后点击**发送测试邮件**验证连通性,默认发到当前管理员的邮箱。
|
||||
测试通过即表示配置可用。
|
||||
|
||||
#### 关于「授权码」
|
||||
|
||||
**QQ 邮箱、163、Gmail 等服务商不能用登录密码发信**,必须先生成专用
|
||||
授权码:
|
||||
|
||||
- **QQ 邮箱**:设置 → 账户 → 开启 SMTP 服务 → 生成授权码
|
||||
- **163 邮箱**:设置 → POP3/SMTP/IMAP → 开启服务 → 获取授权码
|
||||
- **Gmail**:需开启两步验证后创建「应用专用密码」
|
||||
|
||||
把授权码填进「密码 / 授权码」一栏即可。
|
||||
|
||||
#### 使用 Resend
|
||||
|
||||
[Resend](https://resend.com) 提供 SMTP 接口,按其官方参数填写即可:
|
||||
|
||||
| 字段 | 值 |
|
||||
|------|-----|
|
||||
| SMTP 服务器 | `smtp.resend.com` |
|
||||
| 端口 | `465`(推荐)或 `587` |
|
||||
| 加密方式 | 465 选 **SSL/TLS**;587 选 STARTTLS |
|
||||
| 用户名 | `resend` ← **固定值,不是邮箱地址** |
|
||||
| 密码 / 授权码 | 你的 **API Key**(`re_` 开头) |
|
||||
| 发件人邮箱 | 已验证域名下的地址,如 `noreply@你的域名` |
|
||||
|
||||
使用前需在 Resend 控制台完成两件事:**创建 API Key**,以及
|
||||
**添加并验证发信域名**(配置 SPF / DKIM 记录)。未验证域名时
|
||||
只能发往自己的注册邮箱,无法发给其他收件人。
|
||||
|
||||
> 用户名填成自己的邮箱地址是常见错误——Resend 要求固定填 `resend`。
|
||||
|
||||
##### Resend 的收件人限制
|
||||
|
||||
Resend **禁止向 `example.com`、`test.com` 等保留/测试域名发信**,
|
||||
会直接返回 `550 Invalid to field`。这是服务商的反滥用策略,不是本站
|
||||
的限制。
|
||||
|
||||
因此**不要用测试域名验证邮件功能**——测试时请使用真实可收信的邮箱。
|
||||
本站会把该错误翻译成中文提示。
|
||||
|
||||
若已启用注册邮箱验证,而用户恰好使用了这类邮箱注册,会看到
|
||||
「收件人邮箱被邮件服务商拒绝」的提示,属预期行为。
|
||||
|
||||
#### 使用其他服务商
|
||||
|
||||
常见服务商的 SMTP 参数:
|
||||
|
||||
| 服务商 | 服务器 | 端口 | 用户名 | 密码 |
|
||||
|--------|--------|------|--------|------|
|
||||
| QQ 邮箱 | `smtp.qq.com` | 465 / 587 | 完整邮箱 | 授权码 |
|
||||
| 163 邮箱 | `smtp.163.com` | 465 / 587 | 完整邮箱 | 授权码 |
|
||||
| Gmail | `smtp.gmail.com` | 465 / 587 | 完整邮箱 | 应用专用密码 |
|
||||
| Resend | `smtp.resend.com` | 465 / 587 | `resend` | API Key |
|
||||
| 阿里云邮件推送 | `smtpdm.aliyun.com` | 465 / 80 | 发信地址 | 设置的密码 |
|
||||
|
||||
#### 关于「允许自签证书」
|
||||
|
||||
默认开启证书校验。如果你使用的是**自建邮件服务器且用自签证书**,
|
||||
连接会因证书不受信任而失败,此时才需要打开这个开关。
|
||||
|
||||
对 Resend、QQ、Gmail 等使用可信证书的服务商,**保持关闭**。关闭校验
|
||||
会让连接暴露在中间人攻击下。
|
||||
|
||||
#### 密码的存储与显示
|
||||
|
||||
SMTP 密码**只写不读**:保存后任何接口都不会返回明文,界面只显示
|
||||
「已保存密码,留空则不修改」。因此:
|
||||
|
||||
- 想改其他字段时,**密码栏留空即可**,原密码保持不变
|
||||
- 需要更换密码时才填写新值
|
||||
- 「清除密码」按钮用于彻底移除已保存的密码
|
||||
|
||||
#### 邮件用在哪里
|
||||
|
||||
配置完成并发送测试邮件成功后,可以开启 **要求注册时验证邮箱**:
|
||||
|
||||
- **注册邮箱验证**:新用户注册时必须填写邮箱收到的 6 位验证码。
|
||||
验证码 10 分钟有效,连续输错 5 次即作废,且只能使用一次。
|
||||
该字段仅在开启此选项时才出现在注册框里。
|
||||
- **密码找回**:登录页的「忘记密码」支持通过邮箱验证码重置密码,
|
||||
与原有的恢复码机制并行,两种方式都可用。
|
||||
|
||||
> 未完成 SMTP 配置时**无法开启**注册邮箱验证——这是有意为之,
|
||||
> 避免开启后所有人都注册不了。
|
||||
|
||||
#### 常见配置问题
|
||||
|
||||
| 现象 | 原因 |
|
||||
|------|------|
|
||||
| 认证失败 | 用了登录密码而非授权码;或用 Resend 时用户名没填 `resend` |
|
||||
| 连接超时 | 端口被防火墙拦截,**或加密方式与端口不匹配**(465 必须配 SSL/TLS) |
|
||||
| 套接字错误 | 同上,端口与加密方式不匹配;也可能是证书校验未通过 |
|
||||
| 发件人被拒 | 发件人邮箱不属于已验证的域名,或与服务商要求不符 |
|
||||
| 域名解析失败 | SMTP 服务器地址拼写错误 |
|
||||
| 证书校验失败 | 自建服务器用了自签证书,需打开「允许自签证书」 |
|
||||
|
||||
多数云服务商默认封禁 25 端口,建议使用 465 或 587。
|
||||
|
||||
> 排错时最有效的两步:先在后台点**发送测试邮件**看具体报错,
|
||||
> 再对照上表定位。中间的错误提示会直接给出去改哪个字段。
|
||||
|
||||
## 📁 项目结构
|
||||
|
||||
```
|
||||
@@ -231,26 +357,39 @@ public/
|
||||
├── style.css # 全局样式
|
||||
├── config.js # 前端配置(同时也是服务端配置入口)
|
||||
├── server.js # 后端服务(Express)
|
||||
├── lib/
|
||||
│ └── mailer.js # SMTP 发信封装(配置读取、发送、错误翻译)
|
||||
├── Dockerfile # Docker 镜像构建文件
|
||||
├── docker-compose.yml # Docker 编排
|
||||
├── package-lock.json # 依赖锁定文件
|
||||
├── migrations/ # 数据库迁移(按文件名顺序执行,请勿手工修改已应用的版本)
|
||||
│ ├── 001_initial.sql
|
||||
│ └── 002_restore_auth_and_audit_columns.sql
|
||||
│ ├── 002_restore_auth_and_audit_columns.sql
|
||||
│ └── 003_email_verification.sql
|
||||
├── schema.sql # 表结构参考快照(仅供阅读,请勿用于建表)
|
||||
├── scripts/
|
||||
│ ├── migrate.js # 迁移执行器
|
||||
│ ├── docker-entrypoint.sh
|
||||
│ └── healthcheck.js
|
||||
├── test/ # 测试(node --test)
|
||||
│ ├── app.test.js # 接口与安全头
|
||||
│ ├── bootstrap-ui.test.js # 管理员引导令牌的显示条件
|
||||
│ ├── i18n-coverage.test.js # 界面文案翻译覆盖率
|
||||
│ ├── migration-schema.test.js # 迁移必须覆盖服务端依赖的列
|
||||
│ └── schema-parity.test.js # schema.sql 与 migrations 的结构一致性
|
||||
└── js/ # 前端 JS 模块
|
||||
├── app.js
|
||||
├── admin.js
|
||||
├── api.js
|
||||
├── auth.js
|
||||
├── feed.js
|
||||
├── post.js
|
||||
└── user.js
|
||||
├── app.js # 主入口、路由、Toast、确认框
|
||||
├── admin.js # 管理后台各标签页
|
||||
├── api.js # 接口封装
|
||||
├── auth.js # 登录、注册、退出
|
||||
├── captcha.js # 人机验证
|
||||
├── feed.js # 帖子列表
|
||||
├── i18n.js # 中英文词典与外挂翻译
|
||||
├── icons.js # SVG 图标
|
||||
├── post.js # 帖子详情与回复
|
||||
├── security.js # 转义与安全渲染
|
||||
├── theme.js # 亮色/暗色切换
|
||||
└── user.js # 用户主页
|
||||
```
|
||||
|
||||
## ❓ 常见问题
|
||||
@@ -264,8 +403,8 @@ public/
|
||||
|
||||
**忘记了管理员密码?**
|
||||
|
||||
使用注册后在设置页生成的恢复码,在登录页的找回密码入口重置。恢复码
|
||||
建议在生成后立即离线保存。
|
||||
两种方式:若已配置邮件,在登录页的「忘记密码」用邮箱验证码重置;
|
||||
否则使用注册后在设置页生成的恢复码重置。恢复码建议生成后立即离线保存。
|
||||
|
||||
**修改密码或邮箱后被登出?**
|
||||
|
||||
@@ -273,6 +412,38 @@ public/
|
||||
行为;服务端会随响应补发一个新令牌,前端会自动保存并保持在登录状态。
|
||||
若仍被登出,请强制刷新页面(Ctrl+F5)以载入最新的前端脚本。
|
||||
|
||||
**注册框里看不到邮箱验证码输入框?**
|
||||
|
||||
这是正常的。该字段仅在管理后台开启了「要求注册时验证邮箱」、
|
||||
且 SMTP 配置完整时才显示。未配置邮件时注册流程与以往一致。
|
||||
|
||||
**开启了邮箱验证,但收不到验证码?**
|
||||
|
||||
先在后台点「发送测试邮件」确认 SMTP 可用。若测试邮件能收到而验证码
|
||||
收不到,检查是否被投进了垃圾箱;若用的是自建发信域名,还需配置 SPF
|
||||
与 DKIM 记录,否则容易进垃圾箱或被直接拒收。
|
||||
|
||||
**用 Resend 发送失败?**
|
||||
|
||||
按顺序检查三项:用户名必须是 `resend`(不是你的邮箱)、密码必须是
|
||||
`re_` 开头的 API Key、发件人邮箱必须属于已在 Resend 验证过的域名。
|
||||
若尚未验证域名,Resend 只允许发往账号注册邮箱,发给其他地址会被拒。
|
||||
|
||||
**怎么确认 SMTP 是通的?**
|
||||
|
||||
后台「发送测试邮件」默认发到当前管理员的邮箱。收到即表示配置可用,
|
||||
不必开启注册验证去试探。
|
||||
|
||||
**邮件相关接口返回 429?**
|
||||
|
||||
发送验证码与找回密码的接口有独立限流(15 分钟 5 次),用于防止被当作
|
||||
垃圾邮件发射器。稍后再试即可。
|
||||
|
||||
**改动 SMTP 配置后没有生效?**
|
||||
|
||||
配置保存在数据库中,保存即时生效,无需重启。若填了新的密码但仍是旧
|
||||
行为,确认密码栏确实填入了新值——留空表示保持原密码不变。
|
||||
|
||||
## 📝 License
|
||||
|
||||
MIT
|
||||
|
||||
+10
@@ -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,10 @@
|
||||
<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" class="email-code-row">
|
||||
<input type="text" id="regEmailCode" placeholder="邮箱验证码" autocomplete="off" />
|
||||
<button type="button" id="regSendCodeBtn" class="btn-secondary">获取验证码</button>
|
||||
</div>
|
||||
<div class="captcha-row">
|
||||
<span id="regCaptchaQuestion">3 + 5 = ?</span>
|
||||
<input type="text" id="regCaptchaInput" placeholder="答案" style="width:80px;" />
|
||||
|
||||
+191
-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,192 @@ 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-hint">
|
||||
Resend 填 <code>smtp.resend.com</code>,端口 465、加密选 SSL/TLS、用户名填 <code>resend</code>。
|
||||
其他服务商请填写其官方 SMTP 地址。
|
||||
</div>
|
||||
|
||||
<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 等邮箱填「授权码」;<strong>Resend 填 API Key</strong>(re_ 开头)。
|
||||
</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-hint">
|
||||
必须是你已在邮件服务商处验证过的域名下的地址,否则会被拒收。
|
||||
</div>
|
||||
|
||||
<label class="smtp-check" style="margin-bottom:20px;">
|
||||
<input type="checkbox" id="smtpAllowSelfSigned" />
|
||||
允许自签证书(仅自建邮件服务器需要)
|
||||
</label>
|
||||
|
||||
<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 || '';
|
||||
$('smtpAllowSelfSigned').checked = cfg.allow_self_signed === true;
|
||||
// 密码永不回显,只用占位文字提示是否已设置
|
||||
$('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(),
|
||||
allow_self_signed: $('smtpAllowSelfSigned').checked,
|
||||
};
|
||||
// 只有填了才提交,避免把已保存的密码覆盖成空
|
||||
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 +1020,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;
|
||||
}
|
||||
};
|
||||
+63
-1
@@ -35,9 +35,62 @@ document.getElementById('loginSubmit').addEventListener('click', async () => {
|
||||
document.getElementById('registerBtn').addEventListener('click', () => {
|
||||
refreshCaptcha('reg');
|
||||
syncBootstrapTokenField();
|
||||
syncEmailCodeField();
|
||||
document.getElementById('registerModal').classList.add('active');
|
||||
});
|
||||
|
||||
// 邮箱验证码字段:仅在站点开启邮箱验证且 SMTP 可用时显示。
|
||||
// 显隐通过切换类名完成,布局交给 CSS——直接改 style.display 会覆盖
|
||||
// 掉保证输入框与按钮并排的 flex 布局。
|
||||
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.classList.toggle('is-visible', required);
|
||||
if (!required) field.value = '';
|
||||
} catch (err) {
|
||||
// 取不到设置时按「不需要」处理,避免用户卡在无法完成的注册流程上
|
||||
row.classList.remove('is-visible');
|
||||
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 +117,21 @@ document.getElementById('registerSubmit').addEventListener('click', async () =>
|
||||
const bootstrapToken = bootstrapField && bootstrapField.style.display !== 'none'
|
||||
? bootstrapField.value.trim()
|
||||
: '';
|
||||
const codeField = document.getElementById('regEmailCode');
|
||||
const codeRow = document.getElementById('regEmailCodeRow');
|
||||
// 以容器的 is-visible 类判断该字段是否启用,而不是读 style.display
|
||||
const codeEnabled = Boolean(codeRow && codeRow.classList.contains('is-visible'));
|
||||
const emailCode = codeEnabled && codeField ? 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 (codeEnabled && !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 +142,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 {
|
||||
|
||||
+34
-33
@@ -6,6 +6,18 @@ let currentSort = 'latest';
|
||||
let totalPages = 1;
|
||||
const PAGE_SIZE = 20;
|
||||
|
||||
// 翻页后滚回列表顶部。分页控件在列表末尾,不回到顶部的话用户看到的
|
||||
// 仍是新一页的底部。
|
||||
// 尊重系统的「减少动画」设置:开启时直接跳转,不做平滑滚动。
|
||||
function scrollFeedToTop() {
|
||||
const reduceMotion = window.matchMedia &&
|
||||
window.matchMedia('(prefers-reduced-motion: reduce)').matches;
|
||||
window.scrollTo({
|
||||
top: 0,
|
||||
behavior: reduceMotion ? 'auto' : 'smooth',
|
||||
});
|
||||
}
|
||||
|
||||
function renderFeed() {
|
||||
const container = document.getElementById('postList');
|
||||
container.innerHTML = '<div style="text-align:center;color:#94a3b8;padding:40px 0;">加载中...</div>';
|
||||
@@ -34,12 +46,23 @@ function renderFeed() {
|
||||
'https://ui-avatars.com/api/?name=' + encodeURIComponent(username) +
|
||||
'&background=6366f1&color=fff&size=64';
|
||||
const time = p.created_at ? new Date(p.created_at).toLocaleString('zh-CN') : '';
|
||||
// 列表里最多展示 3 张图,其余折叠为「+N」。
|
||||
// 附件上限是 6 张,若全部铺开会把卡片撑得很高,且与相邻卡片不齐。
|
||||
let imagesHtml = '';
|
||||
if (p.images && p.images.length > 0) {
|
||||
const MAX_THUMBS = 3;
|
||||
const shown = p.images.slice(0, MAX_THUMBS);
|
||||
const rest = p.images.length - shown.length;
|
||||
|
||||
imagesHtml = '<div class="post-images">';
|
||||
p.images.forEach(img => {
|
||||
imagesHtml += '<img src="' + escapeHTML(safeURL(img, { image: true })) + '" class="post-image" style="cursor:pointer;" />';
|
||||
shown.forEach(img => {
|
||||
imagesHtml += '<img src="' + escapeHTML(safeURL(img, { image: true })) +
|
||||
'" class="post-image" style="cursor:pointer;" />';
|
||||
});
|
||||
// 多于 3 张时,在末张右下角叠加剩余数量
|
||||
if (rest > 0) {
|
||||
imagesHtml += '<span class="post-image-more">+' + rest + '</span>';
|
||||
}
|
||||
imagesHtml += '</div>';
|
||||
}
|
||||
const replyCount = p.reply_count || 0;
|
||||
@@ -51,7 +74,7 @@ function renderFeed() {
|
||||
if (p.signature) {
|
||||
const sigContent = renderMarkdown(p.signature);
|
||||
signatureHtml = `
|
||||
<div style="margin-top:10px;padding-top:8px;border-top:1px solid var(--border-light);font-size:12px;color:var(--text-secondary);">
|
||||
<div class="post-signature" style="margin-top:10px;padding-top:8px;border-top:1px solid var(--border-light);font-size:12px;color:var(--text-secondary);">
|
||||
${sigContent}
|
||||
</div>
|
||||
`;
|
||||
@@ -72,16 +95,8 @@ function renderFeed() {
|
||||
<div class="post-actions">
|
||||
<span>
|
||||
<svg xmlns="http://www.w3.org/2000/svg" width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" style="display:inline;vertical-align:middle;"><path d="M21 15a2 2 0 0 1-2 2H7l-4 4V5a2 2 0 0 1 2-2h14a2 2 0 0 1 2 2z"/></svg>
|
||||
${replyCount}
|
||||
${replyCount} 条回复
|
||||
</span>
|
||||
<button class="action-report" data-postid="${p.id}">
|
||||
<svg xmlns="http://www.w3.org/2000/svg" width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" style="display:inline;vertical-align:middle;"><path d="M12 22s8-4 8-10V5l-8-3-8 3v7c0 6 8 10 8 10z"/><path d="M12 8v4"/><path d="M12 16h.01"/></svg>
|
||||
举报
|
||||
</button>
|
||||
${currentUser && currentUser.id === p.user_id ? `<button class="action-delete" data-postid="${p.id}">
|
||||
<svg xmlns="http://www.w3.org/2000/svg" width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" style="display:inline;vertical-align:middle;"><polyline points="3 6 5 6 21 6"/><path d="M19 6v14a2 2 0 0 1-2 2H7a2 2 0 0 1-2-2V6m3 0V4a2 2 0 0 1 2-2h4a2 2 0 0 1 2 2v2"/></svg>
|
||||
删除
|
||||
</button>` : ''}
|
||||
</div>
|
||||
${signatureHtml}
|
||||
</div>
|
||||
@@ -157,6 +172,9 @@ function renderFeed() {
|
||||
url.searchParams.set('postpage', page);
|
||||
window.history.pushState({}, '', url);
|
||||
renderFeed();
|
||||
// 分页控件位于列表末尾,翻页后若不回到顶部,用户看到的仍是
|
||||
// 新一页的底部,需要手动上滚才能读到第一条。这里平滑滚回顶部。
|
||||
scrollFeedToTop();
|
||||
}
|
||||
});
|
||||
});
|
||||
@@ -184,27 +202,10 @@ function renderFeed() {
|
||||
});
|
||||
});
|
||||
|
||||
container.querySelectorAll('.action-report').forEach(btn => {
|
||||
btn.addEventListener('click', function(e) {
|
||||
e.stopPropagation();
|
||||
if (!currentUser) { showToast('请先登录', 'warning'); return; }
|
||||
reportTargetPostId = this.dataset.postid;
|
||||
document.getElementById('reportModal').classList.add('active');
|
||||
});
|
||||
});
|
||||
container.querySelectorAll('.action-delete').forEach(btn => {
|
||||
btn.addEventListener('click', async function(e) {
|
||||
e.stopPropagation();
|
||||
const ok = await showConfirm('确定要删除这条帖子吗?', {
|
||||
title: '删除帖子', confirmText: '删除', danger: true,
|
||||
});
|
||||
if (!ok) return;
|
||||
API.deletePost(this.dataset.postid).then(() => {
|
||||
renderFeed();
|
||||
renderStats();
|
||||
}).catch(err => showToast('删除失败:' + err.message, 'error'));
|
||||
});
|
||||
});
|
||||
// 卡片上不再放举报与删除按钮:这两个操作针对的是帖子内容本身,
|
||||
// 放在卡片上容易被误解为对整张卡片操作,也容易误点。
|
||||
// 它们统一放在帖子详情页,用户点进帖子后操作。
|
||||
// (卡片的点击跳转绑定在上方,此处无需重复绑定。)
|
||||
}).catch(err => {
|
||||
container.innerHTML = '<div style="text-align:center;color:#ef4444;padding:40px 0;">加载失败:' + escapeHTML(err.message) +
|
||||
'</div>';
|
||||
|
||||
+86
@@ -371,6 +371,49 @@ const TRANSLATIONS = {
|
||||
'修改用户角色': '修改用户角色',
|
||||
'重新生成恢复码': '重新生成恢复码',
|
||||
'退出登录': '退出登录',
|
||||
|
||||
// ===== SMTP 与邮箱验证 =====
|
||||
'邮件设置': '邮件设置',
|
||||
'启用邮件发送': '启用邮件发送',
|
||||
'SMTP 服务器': 'SMTP 服务器',
|
||||
'端口': '端口',
|
||||
'加密方式': '加密方式',
|
||||
'密码 / 授权码': '密码 / 授权码',
|
||||
'发件人名称': '发件人名称',
|
||||
'发件人邮箱': '发件人邮箱',
|
||||
'保存配置': '保存配置',
|
||||
'发送测试邮件': '发送测试邮件',
|
||||
'清除密码': '清除密码',
|
||||
'注册邮箱验证': '注册邮箱验证',
|
||||
'要求注册时验证邮箱': '要求注册时验证邮箱',
|
||||
'获取验证码': '获取验证码',
|
||||
'邮箱验证码': '邮箱验证码',
|
||||
'配置完整,可以发信': '配置完整,可以发信',
|
||||
'尚未配置完成,邮件功能不可用': '尚未配置完成,邮件功能不可用',
|
||||
'验证码已发送,请查收邮件': '验证码已发送,请查收邮件',
|
||||
'请输入邮箱验证码': '请输入邮箱验证码',
|
||||
'请输入有效邮箱': '请输入有效邮箱',
|
||||
'该邮箱已被注册': '该邮箱已被注册',
|
||||
'本站未开启邮箱验证': '本站未开启邮箱验证',
|
||||
'请先获取验证码': '请先获取验证码',
|
||||
'验证码已过期,请重新获取': '验证码已过期,请重新获取',
|
||||
'尝试次数过多,请重新获取验证码': '尝试次数过多,请重新获取验证码',
|
||||
'验证码错误': '验证码错误',
|
||||
'配置已保存': '配置已保存',
|
||||
'密码已清除': '密码已清除',
|
||||
'已开启注册邮箱验证': '已开启注册邮箱验证',
|
||||
'已关闭注册邮箱验证': '已关闭注册邮箱验证',
|
||||
'加载配置失败:': '加载配置失败:',
|
||||
'已保存密码,留空则不修改': '已保存密码,留空则不修改',
|
||||
'尚未设置密码': '尚未设置密码',
|
||||
'留空表示不修改已保存的密码': '留空表示不修改已保存的密码',
|
||||
'通常为完整邮箱地址': '通常为完整邮箱地址',
|
||||
'例如:论坛名称': '例如:论坛名称',
|
||||
'注册验证码': '注册验证码',
|
||||
'密码重置验证码': '密码重置验证码',
|
||||
'Forumlify SMTP 测试邮件': 'Forumlify SMTP 测试邮件',
|
||||
'允许自签证书(仅自建邮件服务器需要)': '允许自签证书(仅自建邮件服务器需要)',
|
||||
'必须是你已在邮件服务商处验证过的域名下的地址,否则会被拒收。': '必须是你已在邮件服务商处验证过的域名下的地址,否则会被拒收。',
|
||||
},
|
||||
|
||||
'en': {
|
||||
@@ -740,6 +783,49 @@ 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',
|
||||
'允许自签证书(仅自建邮件服务器需要)': 'Allow self-signed certificate (self-hosted servers only)',
|
||||
'必须是你已在邮件服务商处验证过的域名下的地址,否则会被拒收。': 'Must be an address on a domain you have verified with your email provider, otherwise it will be rejected.',
|
||||
}
|
||||
};
|
||||
|
||||
|
||||
+17
-1
@@ -57,11 +57,13 @@ async function renderPostDetail(postId) {
|
||||
const renderedContent = renderMarkdown(post.content || '');
|
||||
|
||||
// 签名渲染
|
||||
// 详情页保留签名展示。补上类名以便统一样式定位——列表页的同类元素
|
||||
// 正是靠 .post-signature 隐藏的,此前详情页只有行内样式,无法选中。
|
||||
let signatureHtml = '';
|
||||
if (post.signature) {
|
||||
const sigContent = renderMarkdown(post.signature);
|
||||
signatureHtml = `
|
||||
<div style="margin-top:16px;padding-top:12px;border-top:1px solid var(--border-light);font-size:12px;color:var(--text-secondary);">
|
||||
<div class="post-signature" style="margin-top:16px;padding-top:12px;border-top:1px solid var(--border-light);font-size:12px;color:var(--text-secondary);">
|
||||
${sigContent}
|
||||
</div>
|
||||
`;
|
||||
@@ -86,6 +88,10 @@ async function renderPostDetail(postId) {
|
||||
<svg xmlns="http://www.w3.org/2000/svg" width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" style="display:inline;vertical-align:middle;"><polyline points="3 6 5 6 21 6"/><path d="M19 6v14a2 2 0 0 1-2 2H7a2 2 0 0 1-2-2V6m3 0V4a2 2 0 0 1 2-2h4a2 2 0 0 1 2 2v2"/></svg>
|
||||
删除
|
||||
</button>` : ''}
|
||||
${currentUser ? `<button class="btn-sm btn-secondary" id="detailReportBtn" data-postid="${post.id}" style="padding:4px 10px;">
|
||||
<svg xmlns="http://www.w3.org/2000/svg" width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" style="display:inline;vertical-align:middle;"><path d="M12 22s8-4 8-10V5l-8-3-8 3v7c0 6 8 10 8 10z"/><path d="M12 8v4"/><path d="M12 16h.01"/></svg>
|
||||
举报
|
||||
</button>` : ''}
|
||||
</div>
|
||||
</div>
|
||||
<div class="post-content" style="font-size:16px;line-height:1.8;">${renderedContent}</div>
|
||||
@@ -190,6 +196,16 @@ async function renderPostDetail(postId) {
|
||||
});
|
||||
}
|
||||
|
||||
// 举报按钮:原先只在列表卡片上,现移到详情页。
|
||||
// 提交逻辑在 app.js 中读取 reportTargetPostId,这里只负责记录目标并打开弹窗。
|
||||
const reportBtn = document.getElementById('detailReportBtn');
|
||||
if (reportBtn) {
|
||||
reportBtn.addEventListener('click', function() {
|
||||
reportTargetPostId = this.dataset.postid;
|
||||
document.getElementById('reportModal').classList.add('active');
|
||||
});
|
||||
}
|
||||
|
||||
document.querySelectorAll('.reply-delete-btn').forEach(btn => {
|
||||
btn.addEventListener('click', async function(e) {
|
||||
e.stopPropagation();
|
||||
|
||||
+203
@@ -0,0 +1,203 @@
|
||||
// ============================================================
|
||||
// 邮件发送
|
||||
// ------------------------------------------------------------
|
||||
// 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',
|
||||
'smtp_allow_self_signed',
|
||||
];
|
||||
|
||||
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 || '',
|
||||
allowSelfSigned: raw.smtp_allow_self_signed === 'true',
|
||||
};
|
||||
}
|
||||
|
||||
// 判断配置是否足以发信
|
||||
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,
|
||||
// 默认严格校验服务器证书。Resend、QQ、Gmail 等正规服务商都使用
|
||||
// 可信证书,关掉校验只会削弱安全性、让中间人有机可乘。
|
||||
// 自建 SMTP 若用自签证书,可在后台把「允许自签证书」打开。
|
||||
tls: { rejectUnauthorized: !config.allowSelfSigned },
|
||||
connectionTimeout: 10000,
|
||||
greetingTimeout: 10000,
|
||||
socketTimeout: 20000,
|
||||
};
|
||||
|
||||
if (config.user) {
|
||||
options.auth = {
|
||||
user: config.user,
|
||||
// 部分服务商要求使用授权码或 API Key 而非登录密码:
|
||||
// QQ/163 用授权码,Resend 用 re_ 开头的 API Key
|
||||
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 message = (error && error.message) || '';
|
||||
|
||||
// 连接超时既可能是防火墙,也可能是端口与加密方式不匹配:
|
||||
// 例如 465 只接受隐式 SSL,若按 STARTTLS 去连,服务器不会回应握手。
|
||||
// 两种原因都给出来,避免排查方向被带偏。
|
||||
if (code === 'ETIMEDOUT' || /timeout/i.test(message)) {
|
||||
return '连接超时:请检查端口是否被防火墙拦截,并确认加密方式与端口匹配(465 用 SSL/TLS,587 用 STARTTLS)';
|
||||
}
|
||||
|
||||
const map = {
|
||||
EAUTH: '认证失败:请检查用户名与密码。QQ、163 等邮箱需填写「授权码」;Resend 的用户名固定为 resend、密码填写 re_ 开头的 API Key',
|
||||
ECONNECTION: '无法连接到邮件服务器:请检查服务器地址与端口是否正确',
|
||||
ESOCKET: '套接字错误:端口与加密方式不匹配(465 需选 SSL/TLS,587 选 STARTTLS),也可能是证书校验未通过',
|
||||
EENVELOPE: '发件人或收件人地址被拒绝:请确认发件人邮箱属于已在邮件服务商处验证过的域名',
|
||||
EDNS: '域名解析失败:请检查 SMTP 服务器地址是否拼写正确',
|
||||
DEPTH_ZERO_SELF_SIGNED_CERT: '证书校验失败:服务器使用了自签证书。若这是你自己的邮件服务器,可打开「允许自签证书」',
|
||||
SELF_SIGNED_CERT_IN_CHAIN: '证书校验失败:服务器使用了自签证书。若这是你自己的邮件服务器,可打开「允许自签证书」',
|
||||
};
|
||||
if (code && map[code]) return map[code];
|
||||
|
||||
// 部分证书错误不带 code,只体现在 message 里
|
||||
if (/self.signed certificate/i.test(message)) {
|
||||
return '证书校验失败:服务器使用了自签证书。若这是你自己的邮件服务器,可打开「允许自签证书」';
|
||||
}
|
||||
|
||||
// Resend 会拒绝发往 example.com、test.com 等保留/测试域名,
|
||||
// 以及未验证域名下的地址。原始报文是英文且较长,这里转成中文。
|
||||
if (/Invalid `?to`? field/i.test(message) || /testing email address/i.test(message)) {
|
||||
return '收件人邮箱被邮件服务商拒绝:请使用真实可收信的邮箱地址。'
|
||||
+ 'Resend 不允许发送到 example.com、test.com 等测试域名,'
|
||||
+ '也不允许从尚未验证的域名发信';
|
||||
}
|
||||
if (/domain is not verified|not verified/i.test(message)) {
|
||||
return '发信域名尚未验证:请先在邮件服务商处完成发件域名的验证(配置 SPF / DKIM 记录)';
|
||||
}
|
||||
if (/API key is invalid|invalid.*api.*key/i.test(message)) {
|
||||
return 'API Key 无效:请检查后台填写的密钥是否正确、是否已被撤销';
|
||||
}
|
||||
if (/rate limit|too many requests/i.test(message)) {
|
||||
return '发送频率超出邮件服务商限制:请稍后再试,或升级服务商配额';
|
||||
}
|
||||
|
||||
return message || '发送失败';
|
||||
}
|
||||
|
||||
module.exports = {
|
||||
SMTP_KEYS,
|
||||
loadSmtpConfig,
|
||||
isConfigComplete,
|
||||
sendMail,
|
||||
verifyConnection,
|
||||
invalidateTransport,
|
||||
describeSmtpError,
|
||||
};
|
||||
@@ -0,0 +1,66 @@
|
||||
-- ============================================================
|
||||
-- 邮箱验证支持
|
||||
-- ------------------------------------------------------------
|
||||
-- 注册流程改为「先验证邮箱再建号」,因此需要一张表暂存验证码。
|
||||
-- 验证码只存哈希,不存明文,避免库被读取后可直接冒用。
|
||||
--
|
||||
-- 同时新增 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', ''),
|
||||
('smtp_allow_self_signed', 'false'),
|
||||
('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;
|
||||
@@ -0,0 +1,17 @@
|
||||
-- ============================================================
|
||||
-- SMTP 增加「允许自签证书」开关
|
||||
-- ------------------------------------------------------------
|
||||
-- 背景:邮件模块最初对所有 SMTP 服务器都关闭了 TLS 证书校验
|
||||
-- (tls.rejectUnauthorized = false),以便兼容使用自签证书的自建
|
||||
-- 邮件服务器。但这会削弱安全性——对 Resend、QQ、Gmail 等使用可信
|
||||
-- 证书的正规服务商而言,关掉校验只会给中间人留下可乘之机。
|
||||
--
|
||||
-- 现改为默认严格校验,仅在以下情况才放行自签证书:
|
||||
-- 部署者明确在后台打开该开关。
|
||||
--
|
||||
-- 003 已在部分部署中执行过,因此这里单独追加一版,
|
||||
-- 让存量库也能拿到这个配置项。
|
||||
-- ============================================================
|
||||
|
||||
INSERT INTO settings (key, value) VALUES ('smtp_allow_self_signed', 'false')
|
||||
ON CONFLICT (key) DO NOTHING;
|
||||
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": {
|
||||
|
||||
+46
@@ -287,3 +287,49 @@ 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', ''),
|
||||
('smtp_allow_self_signed', 'false'),
|
||||
('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();
|
||||
|
||||
@@ -113,10 +114,21 @@ const authAccountLimiter = 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: '请求过于频繁,请稍后再试' }),
|
||||
});
|
||||
|
||||
const AUTH_PATHS = ['/api/auth/login', '/api/auth/register', '/api/auth/reset-password'];
|
||||
|
||||
app.use('/api', apiLimiter);
|
||||
app.use(AUTH_PATHS, authIpLimiter);
|
||||
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' }));
|
||||
app.use(AUTH_PATHS, authAccountLimiter);
|
||||
@@ -347,6 +359,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: '服务器错误' });
|
||||
@@ -371,6 +390,187 @@ 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,
|
||||
allow_self_signed: config.allowSelfSigned,
|
||||
// 只告诉前端「有没有设置过」,不返回明文
|
||||
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, allow_self_signed } = req.body;
|
||||
|
||||
if (typeof enabled !== 'boolean' || typeof secure !== 'boolean') {
|
||||
return res.status(400).json({ error: '启用状态与加密方式必须为布尔值' });
|
||||
}
|
||||
// 缺省视为关闭,保持向后兼容
|
||||
const allowSelfSigned = allow_self_signed === true;
|
||||
|
||||
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],
|
||||
['smtp_allow_self_signed', String(allowSelfSigned)],
|
||||
];
|
||||
|
||||
// 密码留空表示「保持原值」,避免管理员只改端口却把密码清掉。
|
||||
// 传空字符串则显式清除。
|
||||
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: '保存失败,请稍后重试' });
|
||||
}
|
||||
});
|
||||
|
||||
// ============================================================
|
||||
// 认证接口
|
||||
// ============================================================
|
||||
@@ -394,9 +594,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: '请填写完整信息' });
|
||||
@@ -411,6 +773,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;
|
||||
@@ -434,10 +815,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');
|
||||
|
||||
@@ -1729,6 +2110,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;
|
||||
|
||||
|
||||
@@ -1938,6 +1938,16 @@ a.btn-secondary {
|
||||
|
||||
/* ============================================================
|
||||
帖子列表 —— 内容截断(纯 CSS)
|
||||
------------------------------------------------------------
|
||||
目标:无论帖子多长、标题多长、带多少张图,列表里每张卡片的高度
|
||||
都尽量接近,避免某一条把整列撑得参差不齐。
|
||||
|
||||
三处限制:
|
||||
- 标题 2 行:原先完全没有限制,长标题能占 6 行、把卡片撑高 70px
|
||||
- 正文 3 行:原有规则,保留
|
||||
- 图片最多显示 3 张:更靠后的折叠为「+N」,由 JS 负责
|
||||
|
||||
注意这些规则只作用于 #feed(列表页),帖子详情页不受影响。
|
||||
============================================================ */
|
||||
|
||||
#feed .post-content {
|
||||
@@ -1950,6 +1960,62 @@ a.btn-secondary {
|
||||
line-height: 1.7;
|
||||
}
|
||||
|
||||
/* 标题超过 2 行即截断。不加这条时,一条长标题能把卡片撑高 70px,
|
||||
与相邻卡片明显不齐。 */
|
||||
#feed .post-title {
|
||||
display: -webkit-box;
|
||||
-webkit-line-clamp: 2;
|
||||
-webkit-box-orient: vertical;
|
||||
overflow: hidden;
|
||||
text-overflow: ellipsis;
|
||||
/* 长单词或连续串也要能断行,否则会横向溢出 */
|
||||
word-break: break-word;
|
||||
overflow-wrap: anywhere;
|
||||
}
|
||||
|
||||
/* 正文里的超长链接同理 */
|
||||
#feed .post-content {
|
||||
word-break: break-word;
|
||||
overflow-wrap: anywhere;
|
||||
}
|
||||
|
||||
/* 列表页隐藏签名:签名长度不一,是卡片高度差异的主要来源之一,
|
||||
而它在列表里并不承担信息价值,放在详情页展示更合适。 */
|
||||
#feed .post-signature {
|
||||
display: none;
|
||||
}
|
||||
|
||||
/* ===== 列表页的图片折叠 ===== */
|
||||
|
||||
/* 容器需为定位上下文,好让「+N」叠在缩略图组上 */
|
||||
#feed .post-images {
|
||||
position: relative;
|
||||
}
|
||||
|
||||
/* 列表页缩略图统一尺寸。取 120×90 是为了让带图卡片的总高度
|
||||
尽量接近无图卡片,避免列表里出现忽高忽低的落差;
|
||||
单张 200px 的原限制在 3 张并排时也会把卡片撑高。 */
|
||||
#feed .post-image {
|
||||
width: 120px;
|
||||
height: 90px;
|
||||
object-fit: cover;
|
||||
}
|
||||
|
||||
/* 剩余图片计数,叠在缩略图组右侧 */
|
||||
#feed .post-image-more {
|
||||
position: absolute;
|
||||
right: 8px;
|
||||
bottom: 8px;
|
||||
padding: 3px 10px;
|
||||
border-radius: 999px;
|
||||
background: rgba(0, 0, 0, 0.62);
|
||||
color: #fff;
|
||||
font-size: 12px;
|
||||
font-weight: 600;
|
||||
line-height: 1.5;
|
||||
pointer-events: none;
|
||||
}
|
||||
|
||||
/* ============================================================
|
||||
友链输入框 + 验证码输入框 —— 玻璃风格
|
||||
============================================================ */
|
||||
@@ -2138,12 +2204,6 @@ a.btn-secondary {
|
||||
论坛设置页面 —— 对齐修复
|
||||
============================================================ */
|
||||
|
||||
/* CSS 上传区域居中 */
|
||||
#adminContent > div:last-child {
|
||||
max-width: 500px !important;
|
||||
margin: 0 auto !important;
|
||||
}
|
||||
|
||||
/* 论坛名称输入框保持居中(已经是了) */
|
||||
#settingsForumName {
|
||||
max-width: 400px !important;
|
||||
@@ -2164,11 +2224,13 @@ a.btn-secondary {
|
||||
text-align: center !important;
|
||||
}
|
||||
|
||||
/* CSS 上传区域居中(如果还没加) */
|
||||
#adminContent > div:last-child {
|
||||
max-width: 500px !important;
|
||||
margin: 0 auto !important;
|
||||
}
|
||||
/* 注:此处原有两条 `#adminContent > div:last-child { max-width:500px }`
|
||||
规则,本意是给「自定义 CSS」页面的上传区限宽居中。但 :last-child
|
||||
会命中任何以单个 div 作为最外层容器的面板——用户列表正是这种结构,
|
||||
因而被压成 500px 居中,与占满宽度的日志列表相差 426px。
|
||||
|
||||
该页面的上传区本身已带行内 `max-width:500px; margin:0 auto`,
|
||||
这两条规则纯属多余且有害,已删除。 */
|
||||
|
||||
/* 论坛名称输入框居中 */
|
||||
#settingsForumName {
|
||||
@@ -2181,29 +2243,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 +2942,221 @@ 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;
|
||||
}
|
||||
}
|
||||
|
||||
/* ============================================================
|
||||
📧 注册邮箱验证码
|
||||
------------------------------------------------------------
|
||||
验证码输入框与「获取验证码」按钮并排,输入框占据剩余宽度。
|
||||
此前这两个元素靠行内样式排列,但容器漏了 display:flex,导致
|
||||
gap / align-items / flex:1 全部失效,实际渲染成上下两行。
|
||||
现在布局由类名控制,显隐只切 .is-visible,避免相互干扰。
|
||||
============================================================ */
|
||||
|
||||
.email-code-row {
|
||||
display: none;
|
||||
gap: 8px;
|
||||
align-items: center;
|
||||
margin-bottom: 12px;
|
||||
}
|
||||
|
||||
.email-code-row.is-visible {
|
||||
display: flex;
|
||||
}
|
||||
|
||||
/* 输入框占满按钮之外的剩余空间 */
|
||||
.email-code-row #regEmailCode {
|
||||
flex: 1;
|
||||
min-width: 0;
|
||||
margin-bottom: 0;
|
||||
font-family: monospace;
|
||||
letter-spacing: 2px;
|
||||
}
|
||||
|
||||
/* 按钮保持自然宽度,倒计时数字变化时不被压缩 */
|
||||
.email-code-row #regSendCodeBtn {
|
||||
flex: none;
|
||||
padding: 10px 14px;
|
||||
font-size: 13px;
|
||||
white-space: nowrap;
|
||||
min-width: 96px;
|
||||
/* 与输入框严格等高:按钮的行高受继承影响会比输入框高几像素,
|
||||
在 align-items:center 下会出现轻微错位,这里显式对齐。 */
|
||||
line-height: 18px;
|
||||
height: 38px;
|
||||
box-sizing: border-box;
|
||||
/* 用品牌色实心按钮,与旁边的输入框明确区分——
|
||||
若沿用模态框内按钮的浅灰底,会和输入框几乎同色,
|
||||
看起来像第二个输入框而非可点击的控件。 */
|
||||
background: var(--primary);
|
||||
border: 1px solid var(--primary);
|
||||
color: #fff;
|
||||
font-weight: 600;
|
||||
}
|
||||
|
||||
.email-code-row #regSendCodeBtn:hover:not(:disabled) {
|
||||
background: var(--primary-hover);
|
||||
border-color: var(--primary-hover);
|
||||
}
|
||||
|
||||
.email-code-row #regSendCodeBtn:disabled {
|
||||
/* 倒计时期间保持可见但明显不可点 */
|
||||
background: var(--primary);
|
||||
border-color: var(--primary);
|
||||
color: #fff;
|
||||
opacity: 0.45;
|
||||
cursor: not-allowed;
|
||||
}
|
||||
|
||||
/* ============================================================
|
||||
🔘 模态框内的按钮
|
||||
------------------------------------------------------------
|
||||
.btn-primary / .btn-secondary 的背景取自 --glass-bg,亮色下为
|
||||
18% 的不透明白。这种取值原本是叠在模糊背景上用的,但模态框现在
|
||||
已是纯白底(见 .modal-content 的说明),半透明白叠在白底上完全
|
||||
看不出按钮轮廓,只剩文字浮在那里。
|
||||
|
||||
这里为模态框内的按钮给出明确的底色与描边,并按主题分别处理。
|
||||
仅作用于 .modal-content 内部,不影响页面其他位置的按钮。
|
||||
============================================================ */
|
||||
|
||||
.modal-content .btn-primary,
|
||||
.modal-content .btn-secondary {
|
||||
border-radius: var(--radius-sm);
|
||||
font-weight: 600;
|
||||
transition: background var(--dur-base, 0.26s) ease,
|
||||
border-color var(--dur-base, 0.26s) ease,
|
||||
box-shadow var(--dur-base, 0.26s) ease;
|
||||
}
|
||||
|
||||
/* 亮色:浅灰底 + 清晰描边,主按钮略深以示强调 */
|
||||
.modal-content .btn-primary {
|
||||
background: #eef1f6;
|
||||
border: 1px solid rgba(0, 0, 0, 0.16);
|
||||
color: var(--glass-text);
|
||||
box-shadow: 0 1px 2px rgba(0, 0, 0, 0.05);
|
||||
}
|
||||
|
||||
.modal-content .btn-primary:hover {
|
||||
background: #e4e9f1;
|
||||
border-color: rgba(0, 0, 0, 0.24);
|
||||
}
|
||||
|
||||
.modal-content .btn-secondary {
|
||||
background: #f7f9fc;
|
||||
border: 1px solid rgba(0, 0, 0, 0.14);
|
||||
color: var(--glass-text);
|
||||
box-shadow: none;
|
||||
}
|
||||
|
||||
.modal-content .btn-secondary:hover {
|
||||
background: #eef1f6;
|
||||
border-color: rgba(0, 0, 0, 0.22);
|
||||
}
|
||||
|
||||
/* 暗色:沿用半透明质感,但提高对比度以保证按钮边界可见 */
|
||||
[data-theme="dark"] .modal-content .btn-primary,
|
||||
[data-theme="dark"] .modal-content .btn-secondary {
|
||||
background: rgba(255, 255, 255, 0.1);
|
||||
border: 1px solid rgba(255, 255, 255, 0.18);
|
||||
color: var(--glass-text);
|
||||
box-shadow: none;
|
||||
}
|
||||
|
||||
[data-theme="dark"] .modal-content .btn-primary:hover,
|
||||
[data-theme="dark"] .modal-content .btn-secondary:hover {
|
||||
background: rgba(255, 255, 255, 0.16);
|
||||
border-color: rgba(255, 255, 255, 0.28);
|
||||
}
|
||||
|
||||
/* 禁用态(如验证码倒计时中) */
|
||||
.modal-content .btn-secondary:disabled {
|
||||
opacity: 0.55;
|
||||
cursor: not-allowed;
|
||||
}
|
||||
|
||||
/* ============================================================
|
||||
❓ 确认对话框
|
||||
------------------------------------------------------------
|
||||
@@ -2998,10 +3278,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