228 Commits
Author SHA1 Message Date

2026-10-02

lezi-fun 1ff6eb13e6 fix: return 400 for malformed JSON bodies (entity.parse.failed)
body-parser 的 JSON 解析失败之前会掉进通用 500 处理;现在明确返回
400 'JSON 格式无效',并把对应的测试断言收紧为精确匹配。
2026-10-02 12:58:56 +08:00
lezi 0d77dc3572 Merge pull request #36 from anupamme/fix-repo-public-cwe-307-auth-rate-limit
harden: secure server.js (CWE-307)
2026-10-02 12:57:27 +08:00

2026-09-22

Furrium Network 7c66cb931a feat: 新增用户屏蔽功能
屏蔽为单向关系:A 屏蔽 B 之后
  - B 不能再给 A 发私信(含已有会话,以及发起新会话)
  - A 在帖子列表、帖子搜索、帖子详情回复中不再看到 B 的内容
  - A 的用户搜索中不再出现 B
  - B 不会收到任何提示,仍可正常浏览 A 的公开内容
取消屏蔽后全部恢复。

数据层(迁移 006)
- 新增 user_blocks 表,唯一约束 (blocker_id, blocked_id),并加
  CHECK 禁止屏蔽自己;两个方向各建索引(正向用于过滤内容,
  反向用于判断能否发私信)。

后端
- 新增 POST / DELETE /api/users/:id/block、GET /api/blocks、
  GET /api/users/:id/block-status。block-status 返回双向关系,
  便于界面准确提示。
- 新增 optionalAuth 中间件:公开接口(帖子列表、搜索、详情、回复)
  在已登录时解析出 req.user 并应用屏蔽过滤,未登录或令牌无效时
  直接放行。这样未登录访客看到全部内容,登录用户则按自己的屏蔽
  列表过滤。
- 帖子列表的 count 与主查询改为共用同一套 WHERE 条件——此前两者
  分别拼装,加上过滤后若不一致会导致分页总数与实际结果对不上。
- 帖子搜索的关键词条件补上括号:它与屏蔽过滤之间是 AND 关系,
  而 AND 优先级高于 OR,不加括号会让过滤失效。
- 私信发送与会话创建均校验对方是否屏蔽了自己,返回中性提示
  「无法向该用户发送消息」,不透露被屏蔽的事实。

前端
- 用户主页新增屏蔽按钮,按当前状态显示「屏蔽」或「解除屏蔽」;
  已屏蔽时隐藏发私信入口(避免必然失败的尝试),并显示状态说明。
- 私信面板新增「会话 / 已屏蔽」切换,已屏蔽列表可逐个解除。
- 私信搜索结果行新增屏蔽按钮,点击时阻止冒泡以免进入聊天。
- 屏蔽与解除都需要二次确认,文案说明后果。

实测:
- 屏蔽前后对比:对方帖子由可见 1 条变为 0 条,用户搜索由 1 个
  变为 0 个,对方发起会话被拒
- 解除屏蔽后帖子恢复可见
- 不能屏蔽自己
- 界面:用户主页按钮文案与提示随状态变化,私信面板两个 Tab 正常,
  已屏蔽列表显示用户与屏蔽时间

完整测试套件 25/25 通过。
2026-09-22 22:36:42 +08:00
Furrium Network 5995efc7a0 feat(dm): 私信支持按用户名搜索开聊,并加入首轮发送条数限制
一、私信用户搜索

此前只能先进入对方个人主页、再点「私信」才能发起会话。现在私信窗口
顶部新增搜索框,输入用户名即可搜索并直接开聊。

- 新增 GET /api/users/search:按用户名模糊匹配,前缀匹配优先、其次按
  名字长度排序(更接近精确结果)。只返回用户名、头像、角色、签名,
  不暴露邮箱等隐私字段(已实测确认响应中不含 email)。
- 关键词转义 % 与 _,与帖子搜索同样处理,避免通配符被当作模式。
- 关键词长度上限 50 字,limit 上限 20。
- 搜索结果中排除自己;输入防抖 300ms,回车立即搜索,Esc 与清除按钮
  回到会话列表。
- 搜索框同样带上防密码管理器误填的属性,并在关闭窗口时清空关键词,
  避免下次打开残留上次的搜索状态。

二、首轮发送条数限制

对方尚未回复时,发起方最多先发 3 条消息;对方一旦回复过,限制永久
解除。仅对「对方从未回复」的会话生效,已正常交流过的会话不受影响。

- 判定放在事务中并对会话行加 FOR UPDATE 锁:限制依赖「我方已发几条、
  对方是否回过」两个计数,不加锁时并发发送可绕过。
- 达到上限返回 429,附带 limit_reached 与 limit 字段,前端据此给出
  针对性提示而非笼统的「发送失败」。
- 发送成功时在响应中返回 remaining(对方已回复时为 null)。
- 聊天窗口底部新增提示条,显示「对方回复前还可发送 N 条消息」,
  对方回复后自动隐藏。数字与文字分置于不同元素,使固定文案能被
  i18n 词典匹配(整句含动态数字时匹配不上)。

实测:
- 用户搜索:「dmtester」命中 2 个、「tester2」命中 1 个、无匹配返回 0,
  响应中 email 字段出现 0 次
- 连续发送 4 条:前 3 条成功且 remaining 依次为 2/1/0,
  第 4 条返回 429 与明确提示
- 对方回复后再发送:成功且 remaining 为 null,限制已解除
- 前端:搜索框正常显示,点击结果直接进入聊天窗口
- 全新会话提示条显示「对方回复前还可发送 3 条消息」,
  发送 1 条后更新为 2 条

完整测试套件 25/25 通过。
2026-09-22 22:12:05 +08:00
Furrium Network c26e834982 fix: 防止密码管理器把首页搜索框当成账号字段填入
现象:搜索框被自动填入保存的邮箱或密码。

根因是页面此前完全没有 <form> 标签——登录、注册、重置密码三处的
输入框与按钮都裸放在 div 中。密码管理器找不到表单边界,只能靠启发式
猜测,于是把页面上的其他文本框(首页搜索框)也纳入填充范围。

修复分两部分:

一、为三个认证模态框补上真正的 <form>

- loginForm:邮箱用 autocomplete="username",密码用 current-password
- registerForm:密码用 new-password,验证码用 one-time-code,
  验证码与图形验证码标 off
- forgotPasswordForm:新密码用 new-password

有了明确的表单边界,密码管理器的填充范围被限定在正确的表单内。

注意随之而来的副作用:按钮改为 type="submit" 后,回车或点击会触发
浏览器原生表单提交导致页面刷新。已在 auth.js 中统一拦截三个表单的
submit 事件。

二、为搜索框叠加多重忽略标识

Chrome 等对 autocomplete="off" 经常忽略,因此同时加上:

- type="search" 与 role="searchbox",语义明确
- name="post-search-query",不易被判定为账号字段
- autocorrect / autocapitalize / spellcheck 关闭
- data-form-type="other"(1Password 识别)
- data-1p-ignore(1Password)与 data-lpignore="true"(LastPass)

实测(Puppeteer,1280×900):
- 页面含 loginForm / registerForm / forgotPasswordForm 三个表单,
  登录表单内邮箱与密码字段齐备
- 搜索框 type=search、name=post-search-query、role=searchbox,
  两个密码管理器的忽略属性均存在
- 在登录框内按回车:未发生页面导航(framenavigated 为 false),
  登录成功且弹窗正常关闭——确认 submit 拦截生效
- 搜索框未受影响,仍可正常使用

完整测试套件 25/25 通过。
2026-09-22 22:03:21 +08:00
Furrium Network fdf90f4b1d feat: 新增帖子搜索功能
支持按标题与正文搜索帖子,入口在首页排序标签与发布按钮之间。

实现方式选择 ILIKE 子串匹配而非 PostgreSQL 全文检索:后者依赖分词,
中文分词需额外安装 zhparser 等扩展,多数部署环境没有;ILIKE 无需任何
扩展即可正确匹配中文子串,英文也天然大小写不敏感。

后端(GET /api/posts/search)
- 关键词长度限制 100 字,超长或为空返回 400
- 转义 % 与 _:它们是 LIKE 的通配符,若不过滤,搜索「%」会匹配全部
  帖子
- 复用 parsePagination,响应结构与 /api/posts 一致
- 路由必须声明在 /api/posts/:id 之前,否则 search 会被当作 id 匹配
- 新增迁移 005:创建 pg_trgm 扩展与 trigram 索引。
  实测索引效果分两种情况——英文关键词(postgresql)走 Bitmap Index
  Scan,0.2ms,比全表扫描快约 47 倍;中文因 pg_trgm 难以切出有效
  trigram,仍走全表扫描,3000 条数据约 7~9ms。即索引对英文有效、
  对中文无效,考虑到许多论坛中英混排,予以保留。
  创建扩展需要权限,部分托管数据库不开放,故失败时仅提示,不影响
  搜索功能本身。

前端
- 首页新增搜索框,含清除按钮;输入防抖 350ms 自动搜索,回车立即搜索,
  Esc 清空
- 关键词写入 URL(?q=),刷新与分享可保持搜索状态;初始化时先于
  renderFeed 设定关键词,避免首屏先按普通列表加载一次
- 搜索时输入框下方显示细进度条,而非整块骨架屏——搜索通常很快,
  画骨架反而闪得厉害
- 无结果时给出明确提示与改进建议
- 移动端搜索框独占一行,避免与标签、按钮挤压
- 补充 6 条 i18n 文案;空结果提示中的关键词单独放在 <strong> 内,
  使固定文案能作为独立文本节点被词典匹配

实测(Puppeteer + 接口直测):
- 中文「论坛」「分词」、英文 resend/RESEND 均正确命中
- 空关键词与超长关键词正确返回 400
- 搜索 % 与 _ 返回 0 条,确认通配符已转义
- 输入「分词」后列表由 5 条筛为 1 条,URL 同步为 ?q=分词
- 清除按钮恢复全部列表并移除 URL 参数
- 通过 ?q=论坛 直接访问时,输入框自动填入且结果为 2 条

完整测试套件 25/25 通过。
2026-09-22 21:58:21 +08:00
Furrium Network 9844988cf2 fix: 修复返回按钮双重绑定导致的重复请求
从帖子详情点返回时,posts / stats / links 三个接口各发出两次请求。
nginx 访问日志确认了这一点(13:40:12 同一秒内两组完整请求)。

根因是返回按钮被绑定了两次:

  index.html:  <button class="back-btn" onclick="switchPage('feed')">
  app.js:      btn.addEventListener('click', () => navigateBackToFeed());

一次点击同时触发内联 onclick 与监听器,于是整组渲染各跑一遍。
已移除 4 处内联 onclick,统一由 app.js 的监听器调用
navigateBackToFeed()——它额外处理了转场方向与 URL 同步。

同时清理了两处多余的渲染调用:

- post.js 删除帖子成功后先调 switchPage('feed'),又调 renderFeed 与
  renderStats。switchPage('feed') 内部本就会调用这三个函数。
- app.js 发布帖子成功后同样重复调用。

顺带说明:auth.js 中登录与注册后的写法是 if / else if 互斥分支
(switchPage('feed') 与 renderFeed 二选一),不存在重复,未作改动。

实测(Puppeteer 走完整用户路径:首屏 → 点进帖子 → 点返回):
- 首屏:posts / stats / links 各 1 次
- 进入详情:0 次(数据已缓存)
- 点返回:posts / stats / links 各 1 次,无重复

完整测试套件 25/25 通过。
2026-09-22 21:44:32 +08:00
Furrium Network d16ed6c1e8 fix(feed): 消除首屏骨架屏之前的一帧闪动,并让容器高度完全稳定
上一版把落差从 293px 收到 157px,但实测仍能看到「闪一次」。逐帧追踪
postList 后定位到两个残留问题:

一、骨架屏出现之前先闪了一帧「加载中...」

index.html 里 #postList 的初始内容写的是「加载中...」文字,骨架屏要等
skeleton.js 执行后才写入。实测时间线为:

  179ms  0 卡片 0 骨架  「加载中...」  高度 420
  197ms  0 卡片 3 骨架                 高度 540
  297ms  1 卡片 0 骨架                 高度 395

那 18ms 的文字就是可见的闪动来源。

改为把骨架屏结构直接写进 index.html 的标记里,首帧即为骨架。骨架不含
文字节点,也不会被 i18n 的替换逻辑影响。修复后空白帧为 0,状态变化
由 3 次降为 2 次。

二、容器高度仍有残余落差

骨架 3 张实测总高 444px(含间距约 468px),而 min-height 原为 420px,
两者不一致导致切换时仍有高度变化。把 min-height 对齐到 468px。

实测最终结果(视口 1280×900):
- 空白帧:1 → 0
- 骨架阶段高度 468px → 内容阶段 445px,落差 23px(原 145px),
  为渲染取整误差,肉眼不可辨
- 状态变化次数:3 → 2

完整测试套件 25/25 通过。
2026-09-22 21:37:11 +08:00
Furrium Network edc68744d5 fix(feed): 缓解首屏列表高度跳动,并去掉重复的 stats 请求
一、首屏「跳一下」

逐帧测量 postList 的容器高度,定位到两处叠加原因:

1. 骨架屏数量固定为 4 张,而骨架卡片按「理想内容」绘制(标题一行、
   正文两三行、部分带缩略图),实际帖子往往更短。数据到达时容器高度
   从 692px 骤降到 163px,下方内容整体上跳。
   现改为 3 张,落差从 293px 收窄到 157px。
   注意 feed.js 与 skeleton.js 两处都显式传了数量,改默认值不生效,
   需同时修改。

2. 高度骤降本身没有缓冲。为 #postList 增加 min-height(桌面 420px、
   移动端 320px),把变化吸收掉大部分——数据到达后容器高度由 163px
   变为 406px。

二、/api/stats 重复请求

首屏会发出两次统计请求,间隔仅 11ms。原因是初始化流程在
loadCustomPagesNav 之后调用了一次 renderStats,而紧接着的页面分发
(switchPage('feed'))内部又调用一次。

去掉初始化处那次,并在页面分发后补一个条件调用:直接通过 URL 打开
帖子详情或用户主页时不经过 switchPage('feed'),侧边栏的统计与友链
需要在那里补一次,用 currentPage 判断避免与 feed 分支重复。

三、顺带清理

feed.js 中有一份与 app.js 同名的 renderStats 实现,因 app.js 后加载
而被整体覆盖,从未执行。已删除并留注释说明,避免日后改错地方。

实测(Puppeteer 逐帧采样 + 请求监听,1280×900):
- 首屏请求由 3 个(stats 重复)降为 2 个:posts 与 stats 各一次
- 容器高度序列由 692 → 684 → 409(落差 293)变为
  540 → 534 → 406(落差 157)
- 直接访问 ?post=xxx 时详情正常渲染,侧边栏统计与友链均正确显示,
  /api/stats 仅请求一次

完整测试套件 25/25 通过。
2026-09-22 21:29:25 +08:00
Furrium Network 7176bea12c feat(ui): 重做页面转场为推入式,旧页面下沉、新页面从屏幕外滑入
原先的「滑入」只是 translateX(40px),几十像素的位移,在 1280px 宽的
屏上几乎看不出来,不是真正的页面转场。

现改为两段协同的推入效果:

1. 新页面(.page-slide)从屏幕外整体滑入:translateX(100%) → 0,
   同时 scale 0.94 → 1、opacity 0 → 1。用百分比而非固定像素,
   任何视口宽度下都从边缘之外开始。
2. 旧内容(#app)留在原位下沉:scale 1 → 0.94、右移 4%,
   并叠加一层暗色遮罩(#app::after,opacity 0 → 1)。

关键改动:#app 不再被 display:none 直接隐藏——那样根本没有动画可做。
现由 body.page-stack-open 与 .page-stack-sink 控制下沉,转场结束后
才清理状态。相关逻辑抽成 sinkBackground / riseBackground / showSlide /
hideSlide 四个函数,供 switchPage、showPostPage、showUserPage、
showCustomPage 共用。返回按钮走 navigateBackToFeed,与浏览器后退键
方向一致(新页面向左滑出、首页上浮)。

过程中修掉两个真实问题:

- 样式表靠后位置本有一条 `#app { animation: fadeIn ... }`(交互动效层)。
  ID 选择器优先级高于类选择器,导致最初的 .page-stack-sink 完全不生效,
  实测首页 transform 始终为 none。改为 #app.page-stack-sink 组合选择器
  后正常。reduced-motion 分支同样需要组合选择器才能压过它。
- app.js 中 showCustomPage 仍保留旧的 `#app.style.display = 'none'`,
  且给容器写了内联 display,会覆盖转场所需的 display 切换。已一并移除。

实测(Puppeteer 逐帧采样,视口 1280×900):
- 新页面 X 坐标:1280 → 860 → 541 → 421 → 326 → 60 → 6 → 0,
  起始 1280 恰好等于视口宽度,确认从屏幕外开始
- 首页:scale 1 → 0.940,右移 0 → 48px,遮罩不透明度 0 → 1.00
- 中间帧截图可见新页面自右侧滑入、旧页面在背景中缩小变暗

完整测试套件 25/25 通过。
2026-09-22 21:22:07 +08:00
Furrium Network 0ea921186a feat(ui): 加入骨架屏,并让页面转场区分前进与后退
一、骨架屏

原先 12 处加载态都是同一句「加载中...」文字。改为与真实内容同构的
灰块占位,用户在等待时就能预判版面结构,内容出现时也不会发生明显的
布局跳动。

- 新增 js/skeleton.js,提供 postList / postDetail / replyItem /
  tableRows / userProfile 五种形态,按内容特征设定灰块宽度,
  避免每行等长显得机械
- 已接入帖子列表、帖子详情(含两条回复占位)、用户主页,以及管理
  后台的用户列表与日志列表
- 扫光动画(skeletonShimmer)提示「正在加载」而非「内容就是这样」
- 减少动画时停掉扫光,保留静态灰块

一个必须处理的时机问题:真正的列表渲染要等 i18n 初始化完成后才触发
(DOMContentLoaded 之后还有 200ms 延迟)。首版把骨架屏放在 renderFeed
里,实测前 2.8 秒仍是「加载中...」文字,等骨架出现时数据往往已经
回来了,等于白做。现改为在 skeleton.js 脚本执行期(早于
DOMContentLoaded)就写入容器,实测从第一帧起即可见。

翻页时不再显示骨架屏:列表已有内容,重画一遍会造成明显闪动,反而
比直接留白更差。通过容器的 data-loaded 标记区分首次加载与翻页。

二、页面转场区分方向

原先只有 slideIn 一个方向,前进与后退都从右侧滑入——返回上一页时
方向感是错的。现新增 slideInBack(自左侧滑入),在 popstate 上标记
后退导航,由 switchPage 与各 showXxxPage 读取该标记后决定用哪套动画。
标记只在紧接的一次切换生效,渲染完成后立即清除。

实测(Puppeteer,1200ms 延迟 + 150KB/s 限速):
- 骨架屏:从首次采样起即为 4 张骨架卡片、16 行占位、4 个头像圆形、
  2 个缩略图占位,扫光动画为 skeletonShimmer
- 数据返回后骨架卡片残留为 0,正常渲染真实帖子

完整测试套件 25/25 通过。
2026-09-22 21:12:52 +08:00
OrbisAI Security 3558247aac Merge remote-tracking branch 'upstream/Lite' into fix-repo-public-cwe-307-auth-rate-limit
# Conflicts:
#	server.js
2026-09-22 18:34:11 +05:30
Furrium Network 82c878ce33 feat(ui): 帖子与侧边栏改用滚动驱动动画
原先所有入场动画都是「页面加载时按时间播放」:卡片带固定错峰延迟依次
浮现。问题在于长列表里,用户还没滚到的内容早就播完了,等真正滚到
那里时看到的是静止的画面,滚动与动画之间没有关系。

改用 animation-timeline: view(),让入场进度与滚动位置绑定——元素从
视口下缘进入时开始显现,走过 25% 视口高度时完成。这样内容是在用户
真正看到它的那一刻出现,而非提前播完。

具体改动:
- 帖子卡片、回复、详情卡片改用 scrollRise,animation-range 为
  entry 0% → entry 25%
- 侧边栏的统计卡与友链卡用 scrollSlideIn(自左侧滑入),与主内容的
  纵向入场形成方向对比
- 卡片悬浮抬升由 3px 调整为 4px,配合滚动出现的节奏

两处容易出错的细节已处理:
- .post-card:nth-child(n) 的错峰规则选择器权重(0,2,0)高于 .post-card
  (0,1,0),必须用同等权重把 animation-delay 清零,否则滚动进度会与
  时间延迟叠加产生卡顿感
- 滚动驱动动画写在 @supports 块内,不受 prefers-reduced-motion 的通配
  规则覆盖,因此单独补了一条关闭规则

兼容性:animation-timeline: view() 目前 Chrome/Edge 115+、Safari 26+
支持,Firefox 尚未支持,全球覆盖约 87%。因此全部规则包在
@supports (animation-timeline: view()) 内,不支持的浏览器整块跳过,
继续使用原有的 riseIn 时间动画,不会出现元素停在隐藏态的问题。

实测(Puppeteer,1280×900,16 张卡片):
- 初始状态:视口内 4 张完全显示,第 5 张 opacity 0.68(正处于渐入
  过程中,证明动画跟随滚动位置而非时间),视口外 11 张 opacity 0.00
- 滚动到 y=1800:滚过的卡片全部回到 opacity 1.00,新进入视口的依次
  显现
- 开启 prefers-reduced-motion:所有卡片 animation-name 为 none,
  opacity 为 1.00
- 降级路径完整性:@supports 块外的 riseIn 关键帧、卡片与回复的基础
  动画、错峰延迟规则均保留

完整测试套件 25/25 通过。
2026-09-22 21:03:42 +08:00
OrbisAI SecurityandClaude Sonnet 5 381b98bf1f fix: split auth rate limiter into independent per-IP and per-account buckets
authLimiter was mounted before express.json()/urlencoded(), so its
keyGenerator read req.body while it was still unparsed, and combining IP
with a client-controlled account value into one key let an attacker rotate
the account to get a fresh bucket per request, bypassing the per-IP limit.
Replace it with authIpLimiter (unchanged position, IP-only key) and
authAccountLimiter (mounted after body parsing, account-only key), so
neither counter can be bypassed by manipulating the other's input.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-09-22 18:28:09 +05:30
Furrium Network 7361ad157d fix(feed): 翻页后回到列表顶部
分页控件位于列表末尾(实测在 20 条卡片之后,距页面顶部约 3856px)。
原先点击页码只重新渲染列表、不调整滚动位置,用户停在原处看到的仍是
新一页的底部,需要手动上滚才能读到第一条。

现在翻页后调用 window.scrollTo 回到顶部,并尊重系统的
prefers-reduced-motion 设置:开启时直接跳转,不做平滑滚动。

实测(Puppeteer,视口 1280×900,56 条帖子):先滚至底部
(scrollY=3055)再点第 2 页,翻页后 scrollY=0,新页 20 条正常渲染。

顺带确认了现有分页逻辑本身是完整可用的,无需改动:
- 首屏只加载 20 条,请求为 /api/posts?sort=latest&page=1&limit=20
- 56 条数据正确分为 3 页,末页 16 条
- 分页控件含首页、尾页、省略号与上下页,当前页高亮且禁用
- 翻页同步写入 URL(?postpage=N),刷新与分享可保持所在页
- 后端使用 LIMIT/OFFSET,limit 上限 100,page 上限 10000

完整测试套件 25/25 通过。
2026-09-22 20:27:20 +08:00
Furrium Network 17b6ee35ef refactor(feed): 举报与删除按钮从列表卡片移到帖子详情页
举报和删除针对的是帖子内容本身,放在列表卡片上容易被理解为对整张
卡片操作,也容易误点(卡片本身可点击进入详情)。现统一移到详情页。

- 列表卡片底部只保留回复数,不再有任何按钮
- 详情页新增举报按钮(此前详情页只有置顶 / 编辑 / 删除,反而缺少
  举报入口)。按钮仅在登录后显示;提交逻辑仍复用 app.js 中
  reportTargetPostId 的既有流程,此处只负责记录目标并打开弹窗
- 移除 feed.js 中随之失效的 .action-report / .action-delete 事件绑定,
  避免留下死代码

详情页原有的删除按钮保留,卡片上那份去掉,因此删除入口从两个减为一个。

实测(Puppeteer,1280px 视口):
- 首页卡片内按钮总数为 0,底部仅显示「N 条回复」
- 详情页按钮:置顶、举报(编辑与删除仅作者本人可见,测试帖作者为
  另一账号,故未出现)
- 点击举报按钮后 reportModal 的 class 由 modal 变为 modal active,
  计算样式 display 为 flex,reportTargetPostId 正确写入帖子 ID

完整测试套件 25/25 通过。
2026-09-22 19:50:43 +08:00
Furrium Network 74204f7bb2 fix: 详情页签名补上类名,便于统一样式定位
列表页的签名靠 .post-signature 隐藏,但详情页渲染签名时只写了行内
样式、没有类名(class 为空字符串),无法被选择器命中。

本次仅补类名,不改变展示行为:详情页仍正常显示签名。加类名是为了
让两处渲染保持一致,后续若需统一调整签名样式不必再改 JS。

已实测确认:补类名后详情页签名仍为 display:block,说明
`#feed .post-signature { display: none }` 这一后代选择器不会误伤
详情页(详情页不在 #feed 容器内)。

首页卡片签名 display:none,详情页 display:block,均符合预期。
完整测试套件 25/25 通过。
2026-09-22 19:45:39 +08:00
Furrium Network 645c990778 fix(feed): 帖子卡片统一截断,长标题与大图不再撑高卡片
列表里卡片高度参差不齐,实测(视口 1280px)发现三个来源:

一、标题完全没有截断

正文早有 -webkit-line-clamp: 3,标题却没有任何限制。一条 180 字的
标题会占满 6 行、把卡片撑到 253px,与相邻卡片明显不齐。

现为 #feed .post-title 加 2 行截断,并补 word-break / overflow-wrap:
原先没有断行规则,超长的连续串或 URL 会横向溢出容器。

二、签名在列表中占用高度且长短不一

签名由用户自定义,长度差异很大,是卡片高度差异的主要来源之一,
但在列表里并不承担信息价值。

改为在 #feed 中隐藏,详情页不受影响。为便于选择器命中,
feed.js 渲染签名时补上 .post-signature 类(此前只有行内样式)。

三、图片最多 6 张全部铺开

附件上限 6 张,全部铺开会把卡片撑得很高。现只展示前 3 张,
其余折叠为右下角的「+N」计数徽标;缩略图统一为 120×90,
原先单张 200px 在 3 张并排时同样会把卡片撑高。

实测结果(六个极端用例:3000 字正文、180 字标题、400 字符无空格串、
超长 URL、5 张图、普通短帖):

- 标题截断 6/6 生效,最长标题从 95px 降到 48px
- 签名 5 张卡片全部隐藏
- 5 张图的卡片显示 3 张 + 「+2」
- 横向溢出 0 张
- 卡片高度极差由 120px 收窄到 100px(181~281px)

剩余差异来自内容本身(有无配图、标题一行或两行),属正常的信息
密度差异,不再进一步压缩。完整测试套件 25/25 通过。
2026-09-22 19:42:53 +08:00

2026-09-21

Furrium Network 1e05b18f0c fix(ui): 管理后台用户列表宽度受错误的居中规则影响
用户列表与日志列表的宽度不一致:前者被压成 500px 居中,后者占满
926px,相差 426px。

原因是样式表里两条重复的规则:

    #adminContent > div:last-child {
      max-width: 500px !important;
      margin: 0 auto !important;
    }

它们的注释写着「CSS 上传区域居中」,本意只针对「自定义 CSS」页面。
但 :last-child 会命中任何以单个 div 作为最外层容器的面板——用户列表
正是这种结构(一个 div 包着搜索栏与表格),因此被误伤;日志列表的
最外层是 table 而非 div,才得以幸免。

这与此前修掉的 #adminContent > div:first-of-type 属于同一类脆弱写法:
靠元素在父级中的位置来定位,而不是靠语义。

而「自定义 CSS」页面的上传区本身就带行内 max-width:500px; margin:0 auto,
这两条规则纯属多余。已直接删除,并在原处留注释说明,避免日后被重新
加回。

实测(Puppeteer 读取几何位置):
- 修复前 用户列表 left=562 width=500,日志列表 left=349 width=926
- 修复后 两者均为 left=349 width=926,差值 0
完整测试套件 25/25 通过。
2026-09-21 22:24:08 +08:00
Furrium Network 68ef257759 fix(ui): 注册验证码输入框与按钮改为并排,并让按钮可辨认
两个问题一起修。

一、验证码输入框与「获取验证码」按钮上下堆叠

该行的容器写了 gap / align-items,输入框也写了 flex:1,但这些全是
flex 专用属性,容器却没有 display:flex,因此全部失效,两个元素按
块级堆叠成上下两行。

同时显隐逻辑用的是 style.display = '',清空内联样式后回退到默认的
display:block,也无法变成 flex。

改为把布局写进 .email-code-row 类(display:flex + gap + align-items),
显隐只切 .is-visible 类。JS 中通过 style.display 判断字段是否启用的
两处也一并改为读类名,避免两套判断标准。

二、按钮看起来不像按钮

这一条是之前「模态框改白底」的同类残留:.btn-primary / .btn-secondary
的背景取自 --glass-bg,亮色下是 18% 的不透明白,本就为叠在模糊背景
上设计;模态框改为纯白底后,这类按钮在白底上几乎不可见。

先为模态框内的按钮统一补上底色与描边,但实测发现按钮底色
rgb(247,249,252) 与输入框 rgb(238,241,246) 过于接近,「获取验证码」
看起来像第二个输入框。因此对该按钮改用品牌色实心样式,与输入框
明确区分;倒计时禁用时降低不透明度而非换色,保持位置稳定。

另外统一按钮高度为 38px 与输入框对齐——按钮的行高受继承影响会比
输入框高 3px,在 align-items:center 下出现轻微错位。

实测(Puppeteer 读取计算样式与几何位置):容器 display 为 flex、
输入框与按钮 top 均为 479、高度均为 38、按钮位于右侧;
按钮背景为品牌色 rgb(91,155,213),与输入框背景明确不同。
2026-09-21 22:13:02 +08:00
Furrium Network c4acf06253 fix(mail): 翻译 Resend 常见错误,补充收件人限制说明
用真实 Resend 账号配置后实测,发现两类错误报文会原样抛给用户,且
都是英文长句,对中文用户不友好:

- 向 example.com、test.com 等保留域名发信时,Resend 返回
  「550 Invalid `to` field. Please use our testing email address...」
- 域名未验证、API Key 无效、触发频率限制等情况同样直接透传原文

现新增对应识别,统一转成中文并指明该去改哪里。其中收件人被拒
一条特意点明这是服务商策略而非本站限制,并提示改用真实邮箱测试。

README 补充「Resend 的收件人限制」小节,说明不能用测试域名验证
邮件功能。

实测结果(真实 Resend 账号 + mail.forumlify.xyz 域名):

- 域名状态 verified,API Key 有效
- 测试邮件、密码重置验证码、注册验证码三封均成功进入 Resend 队列
- 465 + SSL 连接正常,从请求到 Resend 接收在 0.5 秒内完成
- 向 example.com 发信被拒,提示已转为中文
- 改用真实域名后立即成功

完整测试套件 25/25 通过。
2026-09-21 22:03:59 +08:00
Furrium Network 38ccc16d7a feat(mail): 适配 Resend,并收紧默认的 TLS 证书校验
为便于使用 Resend 发信,做了以下调整。Resend 的 SMTP 接口本身兼容
现有实现(smtp.resend.com + 465/587 + 用户名 resend + API Key),
无需改动发送逻辑。

主要改动是安全性修正:

原先 buildTransport 对所有 SMTP 服务器都设置
tls.rejectUnauthorized = false,以便兼容自签证书的自建服务器。但这
会让所有连接——包括 Resend、QQ、Gmail 这类使用可信证书的正规服务商
——都失去证书校验,给中间人留下可乘之机。

现改为默认严格校验,新增 smtp_allow_self_signed 开关(迁移 004,
因为 003 已在部分部署中执行过),仅在自建服务器使用自签证书时才需
手动打开。后台对应新增「允许自签证书」选项。

错误提示按实测结果重写:

- 连接超时原本只提示「检查防火墙」,但实测发现更常见的原因是端口与
  加密方式不匹配(465 只接受隐式 SSL,按 STARTTLS 连接不会有响应)。
  现在两种原因一并给出。
- 认证失败补充 Resend 的填法(用户名固定 resend、密码填 API Key),
  与原有的「QQ/163 用授权码」并列。
- 新增自签证书错误的识别,直接指向「允许自签证书」开关。

后台表单补充针对性提示:服务器字段说明 Resend 的四个参数、密码字段
区分授权码与 API Key、发件人邮箱提示需为已验证域名。

已用真实 smtp.resend.com 实测三种情形:
- 465 + SSL(官方推荐):0.5 秒内返回认证失败,说明 DNS、TLS 握手与
  SMTP 协议交互均正常,仅 Key 无效
- 587 + STARTTLS:同样正常握手
- 465 + STARTTLS 错配:超时,提示已能指出加密方式问题
- 无效域名:正确报出域名解析失败

README 新增「使用 Resend」小节(含四个参数对照表与域名验证前提)、
服务商参数对照表、自签证书开关说明,并修正排错表中关于超时的描述。
i18n 补充 2 条新文案。完整测试套件 25/25 通过。
2026-09-21 22:01:30 +08:00
Furrium Network ab49b93c4d docs: 补充邮件(SMTP)配置说明
新增「邮件(SMTP)」章节,覆盖后台配置的完整流程:

- 配置项逐字段说明,特别标注端口与加密方式必须匹配
  (587 配 STARTTLS、465 配 SSL/TLS),这是最常见的配置错误
- 授权码说明:QQ / 163 / Gmail 均不能用登录密码发信,分别列出
  各自的开启路径
- 密码的存储方式:只写不读,留空即保持原密码,以及清除按钮的作用
- 邮件用在哪里:注册邮箱验证(有效期、尝试次数、一次性)与密码找回,
  并说明未完成 SMTP 配置时无法开启验证,避免把所有人挡在门外
- 常见配置问题对照表,把模块里翻译的几类 SMTP 异常映射到具体原因

同时:
- 特性列表补充邮件、私信、双语等已实现的能力,去掉重复的暗色模式条目
- 项目结构更新为实际文件,补上 lib/mailer.js、003 迁移、test/ 下五个
  测试文件,以及此前遗漏的 captcha.js / i18n.js / icons.js 等前端模块
- 常见问题新增邮件相关四条:看不到验证码输入框、收不到验证码、
  发送接口返回 429、改动配置后未生效
- 「忘记密码」一条补充邮箱重置方式(原描述只提到恢复码)

并说明 SMTP 配置存于数据库 settings 表,Docker 部署下随 db_data 卷
持久化,无需增加 Compose 环境变量。
2026-09-21 21:48:20 +08:00
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
anupamme f147f4b248 fix: multi_agent.cwe-307 security vulnerability
Automated security fix generated by OrbisAI Security
2026-09-21 13:37:33 +00:00
Furrium Network 75cc78d5f8 feat(ui): 用 showToast 替代全部原生 alert,输入框统一加凹陷效果
一、替换 53 处原生 alert()

原生 alert() 样式无法定制、只有单一「确定」按钮、且会阻塞页面渲染,
与站点风格割裂。全部改为 showToast(),按语义区分类型:

- 失败/错误提示 -> error(36 处)
- 表单校验与操作提示 -> warning(21 处)
- 成功提示 -> success(9 处)

覆盖 admin.js(12)、app.js(23)、auth.js(8)、feed.js(2)、post.js(8)。
替换用一个括号配平的小脚本完成,避免正则误伤字符串里含括号的文案;
替换后逐文件做了语法检查。

二、输入框统一凹陷效果

输入框样式此前散落在至少 8 组选择器里(.modal-content / #pageSettings /
#pageNew / #replyArea / #chatInput 等),各写一套背景色。亮色下多为
半透明白叠在白底上,几乎看不出输入区边界,用户难以分辨哪里可输入。

改为新增一层统一样式(文件末尾),用 inset box-shadow 制造内凹,
靠「凹陷」而非描边表明可输入区域:

- 新增 --inset-bg / --inset-border / --inset-shadow / --input-focus-bg
  四个变量,亮暗主题各一套
- 亮色:浅灰底 #eef1f6 + 深色内阴影;暗色:更深底色 + 更强内阴影
- 聚焦时内凹消失,换成品牌色外发光,形成明确的「浮起可编辑」反馈
- 悬停时加深边框,提示可交互
- 排除 checkbox / radio / file / range / color 等非文本控件
- 添加 disabled 与 placeholder 状态处理

三、顺带修正

移除此前误加的一份重复暗色输入框规则(项目下方本就有
「暗色模式下的特殊修复」区块处理同一批选择器),并为其补上
border-color,因为亮色边框已改为深色,暗色下需换回浅色。

已用 Puppeteer 实测:亮暗两主题下输入框背景、边框、内凹阴影与聚焦
光晕均符合预期;三种 toast 类型均正常弹出;中文字体渲染正常。
2026-09-21 21:20:56 +08:00
Furrium Network 51032c44d0 feat(ui): 用自定义确认框替代浏览器原生 confirm()
原生 confirm() 样式无法定制、与站点风格割裂,且会阻塞渲染线程,
移动端尤其突兀。全项目原有 11 处确认弹窗,现全部替换。

新增 showConfirm(message, options),返回 Promise<boolean>,配合 await
使用:

  if (!await showConfirm('确定删除吗?')) return;

- 动态创建节点,不污染 index.html
- 复用模态框的进出场动画
- 支持 Esc 取消、Enter 确认、点击遮罩取消
- 点击内容区不会误关闭
- danger 选项启用红色实心按钮,与普通确认区分
- 消息用 textContent 写入而非拼接 HTML,避免文案中的特殊字符
  被当作标记解析(已实测 <img onerror> 不会被注入执行)
- 移动端按钮改为纵向铺满,便于点按

调用点改动:把同步的 `if (!confirm(...)) return` 改为 await 形式,
相应的事件回调加上 async。涉及 admin.js(5)、app.js(1)、auth.js(1)、
feed.js(1)、post.js(3)。

i18n 同步补充:showConfirm 会新引入若干标题与按钮文案(请确认 / 确定 /
删除回复 / 删除友链 / 删除页面 / 修改用户角色 / 重新生成恢复码 /
退出登录),已一并登记进 zh 与 en 词典,否则切英文后标题仍是中文。
确认框由 MutationObserver 覆盖,正文文案原本就已在词典中。

已用 Puppeteer 实测:弹出与结构、取消返回 false、确认返回 true、
Esc 取消、遮罩取消、点击内容不关闭、XSS 防护、亮暗两种主题配色,
以及中英文双语下的标题/正文/按钮翻译,均符合预期。
2026-09-21 21:15:14 +08:00
Furrium Network 2f9528939a fix(ui): 模态框亮色模式改白底,并为弹窗与菜单补关闭动画
两个问题一起处理。

一、亮色模式下大部分模态框近乎透明

.modal-content 一直沿用 --glass-bg(亮色下为 rgba(255,255,255,0.18)),
叠在模糊背景上几乎全透明,标题、输入框与按钮都难以辨认。

文件下方其实已有三处「亮色修复」(#messageListModal / #chatModal /
#editorModal),用 #ffffff !important 单独处理过——说明这个问题此前
被发现了,但只修了这三个,登录、注册、发帖、举报、设置等其余模态框
全部遗漏。这里在通用规则上统一补上,取值与那几处保持一致(#ffffff),
暗色模式仍沿用原变量不变。

输入框同步调整:白底上用 3% 黑底 + #d8dfe9 描边,替代原先叠在白底上
完全看不出边界的半透明白。暗色输入框由文件下方既有规则接管,此处不再
重复定义(原先误加过一份,已移除)。

二、关闭弹窗与下拉菜单没有动画

.modal 与 .dropdown-menu 的默认状态是 display:none,JS 直接
classList.remove('active'/'show') 会让元素瞬间消失,CSS 无从播放动画。

改为先挂 .closing 播放收起动画(modalFadeOut / modalPopOut /
dropdownFadeOut),animationend 后再移除类名。要点:

- 用 requestAnimationFrame 等样式生效后再挂类,避免同帧移除跳过动画
- 同时设 260ms 兜底超时,防止动画未触发(如系统开启了减少动画)时卡住
- rAF 回调中检查类名是否已被移除,避免关闭过程中被重新打开时误挂
  .closing
- 新增 closeModal() / closeDropdown() 两个辅助函数,替换原先散落在
  app.js 与 auth.js 中的 9 处直接移除类名的写法
- 标签页选中态(.tab / .admin-nav-item / .page-slide 等)不适用此逻辑,
  保持原样

关闭动画同样受 prefers-reduced-motion 约束(时长被压到 0.01ms,兜底
超时保证状态正常收尾)。

已用 Puppeteer 实测:亮色下 loginModal / registerModal / reportModal
背景均为 rgb(255,255,255),暗色下均为 rgba(30,30,50,0.35) 保持原样,
已被单独修过的 messageListModal 不受影响;关闭时 .closing 正确挂载并
播放 modalFadeOut / dropdownFadeOut,动画结束后 display 回到 none。
2026-09-21 21:03:03 +08:00
Furrium Network f982b2e0a6 docs: 补充在线演示地址与反向代理部署说明
- 顶部增加演示站入口 https://lite.forumlify.org
- 新增「反向代理与 HTTPS」小节,给出 Nginx 终止 TLS 并反代到 3000
  端口的配置要点,并提示配套设置 TRUST_PROXY=true,否则限流会把
  所有用户识别为同一来源 IP。

同时记录了配置过程中实际踩到的两个坑:

- 80 端口若已存在其他站点的 default_server,它会接管所有未显式匹配
  的 Host,导致本域名的 ACME 挑战请求被 301 跳走、证书签发失败。
  必须为本域名单独写一个带 server_name 的 80 端口块。
- ACME 挑战路径必须放在 return 301 之前,否则同样会被重定向。
2026-09-21 20:51:44 +08:00
Furrium Network b0bf66e1aa feat(ui): 为界面补充交互动效
为提升操作反馈与页面层次感,新增一层克制的交互动效。设计上遵循
项目原有的液态/磨砂玻璃风格,不引入新视觉语言:

- 统一新增 --ease-out / --ease-spring 两条缓动曲线与三档时长变量,
  后续动效都复用它们,避免各处硬编码时长。
- 帖子卡片与回复逐项浮入(riseIn),前若干项按 30–35ms 错峰,
  超过 12 项后不再累加延迟,避免长列表末尾等待过久。
- 帖子详情卡片延迟浮入,与页面切换动画衔接。
- 按钮补充按下时的 scale(0.96) 即时反馈。原有 hover 位移保留,
  这里只作用于 transform,不影响布局,列表不会抖动。
- 弹窗内容层缩放上浮(modalPop),叠加在原有 modalFade 之上。
- 头像在卡片悬浮时轻微放大;下拉菜单、页面容器、图片查看器、
  通知徽标各自补充入场动画。
- 键盘导航新增 focus-visible 焦点环。
- 加载提示改为轻微呼吸(softPulse),降低等待感。

同时修复 js/feed.js 中一处会干扰动画的写法:分页栏用
`container.innerHTML += paginationHtml` 追加,会让浏览器重新解析整个
容器,导致已渲染的帖子卡片被重建、入场动画重放一遍。改用
insertAdjacentHTML('beforeend', ...) 只追加不重建。

无障碍:新增 prefers-reduced-motion 支持。系统开启「减少动画」后,
所有位移、缩放与循环动画全部关闭,仅保留颜色等非运动反馈,避免
前庭不适。循环动画是彻底停止而非加速循环。
2026-09-21 20:47:38 +08:00
Furrium Network b1f4363433 fix(i18n): 补齐未登记的界面文案,修复切英文后仍是中文
i18n 采用「中文原文作 key」的外挂方案:zh 词典登记哪些文案需要翻译,
en 词典提供译文,运行时遍历 DOM 精确匹配后替换。因此漏翻译的唯一
原因就是文案没被登记进词典。

实际扫描源码后发现 60 余条界面文案从未登记,切换到英文后依然显示
中文,集中在三类:

- 错误与状态提示:保存失败:/ 删除失败:/ 操作失败:/ 登录失败:/
  发布失败:/ 上传失败:/ 举报失败:/ 注册失败:/ 回复失败:/
  添加失败:/ 发送失败:/ 编辑失败:/ 加载失败:
  注意源码里普遍是「XX失败:」带全角冒号,与词典中原有的不带冒号
  的「保存失败」属于不同字符串,必须分别登记才能命中。
- 表单校验与按钮:密码至少6位 / 验证码错误,请重新计算 /
  用户名不能为空 / 请输入论坛名称 / 请填写回复内容 / 松开上传 等。
- 确认对话框:确定要退出吗?/ 确定要删除这条帖子吗?/
  确定要删除自定义 CSS 吗?等 10 条。

另外「剩余 N 个可用恢复码」「原因:」「状态:」等由模板字符串生成,
整串无法命中词典,改为登记其中可命中的固定片段。原先词典里枚举了
「剩余 0 个可用恢复码」到「剩余 10 个可用恢复码」共 11 条,这些永远
匹配不上,属于无效条目。

顺带修复 en 词典中「于」译为空串的问题。walk() 命中后用译文整体替换
原文,空串会把界面文字直接抹掉,存在隐患,改为保留原词(该键实际
不会被单独命中,源码中是「加入于」整串)。

新增 test/i18n-coverage.test.js 锁住这些约定:
- zh 与 en 的键集合必须完全一致
- 不允许任何译文为空串
- 常见「失败:」前缀、确认对话框、表单校验必须已登记
- 界面中文文案覆盖率不低于 90%

覆盖率测试直接从 js/*.js 与 index.html 抽取中文字面量比对词典,
实测覆盖率由修复前的约 70% 提升至 99% 以上。已注入故障验证该测试
能捕获漏登记的文案。
2026-09-21 20:42:08 +08:00
Furrium Network 57a99ccd23 fix: 状态提示改用 innerHTML 渲染图标,修复 SVG 被当文本打印
设置页修改密码/邮箱后的提示会把整段 SVG 标记打印成文字,原因是
getIcon() 返回 SVG 字符串,而赋值用了 textContent,浏览器按纯文本
渲染,于是 `<svg xmlns="http://www.w3.org/2000/svg" ...>` 直接显示在
界面上。

这是同一类错误的多个实例,全项目共 8 处使用 textContent 接收
getIcon() 的返回值,并非只有改密码/邮箱这两处:

js/app.js
- 修改密码成功/失败提示
- 修改邮箱成功/失败提示
- 恢复码「已复制到剪贴板」提示(两处分支)
- 重置密码成功/失败提示

js/admin.js
- 论坛设置「保存成功!/ 保存失败」提示

全部改为 innerHTML。凡是拼接服务端返回的 err.message 的位置,
一律套用 escapeHTML() 二次转义——项目里其余渲染错误信息的地方
(feed.js / post.js / user.js / app.js:524)本来就是这么做的,
改用 innerHTML 后必须保持同等防护,否则会把原本无害的 textContent
变成 XSS 注入点。

已确认修复后项目中不再存在 textContent 接收 getIcon() 的写法。
2026-09-21 20:38:11 +08:00
Furrium Network c6bf968178 fix: 管理员初始化令牌输入框改为按需显示
注册模态框里固定显示「管理员初始化令牌(仅首次部署,可选)」输入框,
每个来注册的普通用户都会看到它,既令人困惑,也等于对外宣告存在一个
提权入口。该字段由 924f9ff 引入,与后端的引导令牌机制配套。

后端鉴权本身没有问题(令牌随机、check hasAdmin、advisory lock 防并发),
所以本次只调整展示层面,不改动注册与提权逻辑:

- GET /api/settings 新增 bootstrap_required 布尔值,仅在「部署者配置了
  ADMIN_BOOTSTRAP_TOKEN」且「系统尚无管理员」时为 true。只返回布尔值,
  不泄露令牌本身或其长度。
- index.html 中该输入框默认 display:none。
- js/auth.js 打开注册框时查询设置,按 bootstrap_required 决定显隐;
  字段隐藏时按「未提供」处理,避免普通注册传入空串触发 403。

这样三种情形各得其所:
- 普通部署(未配置令牌):任何人都看不到该字段
- 首次部署(已配置令牌、尚无管理员):显示,部署者据此创建管理员
- 初始化完成:自动隐藏

新增 test/bootstrap-ui.test.js 锁住上述约定,覆盖「标记中默认隐藏」
「接口只暴露布尔值」「隐藏时不提交空令牌」「表单对字段缺失做保护」
四项。已实测注入故障可被捕获。

实测五种场景(未配置令牌 / 已配置待初始化 / 初始化后 / 泄露检查 /
普通注册)行为均符合预期。
2026-09-21 20:33:29 +08:00
Furrium Network f1c9aca4c7 test: 锁定 schema.sql 与 migrations 的结构一致性
安装脚本 install.sh 直接用 schema.sql 建表,而 Docker entrypoint 与
npm run migrate 走 migrations/。两套定义并存,必须产出等价结构,否则
「脚本装的站」与「迁移装的站」会在后续升级中分化——历史上已经漂移过
一次(001 漏掉 users.token_version 与 event_logs 审计字段,导致登录后
所有接口 500)。

新增 test/schema-parity.test.js,在 SQL 文本层面比对两套定义:
- 表集合必须一致
- migrations 中出现过的每一列,schema.sql 都必须覆盖(schema.sql 是
  安装脚本实际执行的权威定义)
- server.js 硬依赖的列必须在两边都存在
- schema.sql 的 DDL 必须保持幂等,因为 install.sh 的自动更新会再次
  整体执行它

已实测两个方向都能捕获漂移:从 schema.sql 删除 token_version 会报
「schema.sql 缺少 users.token_version」,移除 002 迁移会报
「migrations/ 缺少 users.token_version」。当前全量测试 16/16 通过。
2026-09-21 20:29:59 +08:00
Furrium Network 86a934ac87 docs: 修正部署文档中的失效命令与部署陷阱
按 README 实际操作时发现以下问题,逐项修正:

- Docker 部分写 `cd forumlify`,但 `git clone` 仓库 public 生成的目录
  名是 `public`,照做会直接失败。已改为 `cd public` 并说明如何自定义
  目录名。
- 源码部署引导用户执行 `schema.sql` 手工建表,同时又提供 `npm run
  migrate`。两条路径并存会让版本记录与实际结构不一致。已改为统一使用
  迁移脚本,并把 schema.sql 降级为只读参考快照。
- 补充 `.env` 不会自动加载的说明。migrations 与 server.js 读的是进程
  环境变量,用 npm start 手动启动前需先导出,否则会连到默认数据库。
- 环境变量表格补充 `cp .env.example .env` 步骤。
- 新增「创建第一个管理员」小节,说明管理员只能通过引导令牌创建、普通
  注册一律是普通用户,以及初始化后应移除该变量。
- 项目结构更新为实际目录(补上 migrations/、scripts/、test/ 与新增的
  002 迁移文件),根目录名改为 public。
- 新增「常见问题」小节,覆盖升级后接口 500、忘记管理员密码、改密码后
  被登出三类实际会遇到的状况。
2026-09-21 20:26:18 +08:00
Furrium Network a085b385b1 fix: 修改密码/邮箱后保持登录并返回首页
此前修改密码或修改邮箱成功后,前端会强制登出并跳转到 ?page=login,
用户必须重新输入凭据,体验割裂。

服务端在这两个接口里递增 token_version 使旧令牌失效(正确的安全设计),
但没有补发新令牌,因此前端只能登出。现在改为:

- server.js: 抽出 issueToken(),登录与令牌刷新共用;改密码/改邮箱用
  RETURNING 取回新的 token_version 并签发令牌随响应返回
- js/api.js: changePassword / changeEmail 接住响应中的 token 并写入
  localStorage,否则用户仍会在下一步操作时被登出
- js/app.js: 两个入口不再清空登录态,改为提示成功并 switchPage('feed')

同时修复一处笔误:清理登录态时用的是 localStorage.removeItem('token'),
而实际存储键为 'forumlify-token'(见 api.js:4),导致该行从未生效,
令牌一直残留在本地存储中。现已随登出逻辑一并移除。
2026-09-21 20:24:28 +08:00
Furrium Network ec235d37bd fix: 补回迁移遗漏的鉴权与审计字段
migrations/001_initial.sql 创建 users / event_logs 时遗漏了 server.js
强依赖的若干列,而 schema.sql 里一直存在这些列,两套定义因此漂移。
通过 npm run migrate 或 Docker 部署出来的库,在用户登录之后所有需要
鉴权的接口都会返回 500:

- GET  /api/auth/me                        认证中间件查询 token_version
- POST /api/posts                          同上
- GET  /api/event-logs                     审计写入需要 method/path 等列
- POST /api/auth/recovery-codes/generate   同上

注册与登录本身不触及这些列,所以站点表现为「能登录,但登录后什么都做
不了」。001 已被记入 schema_migrations 无法重跑,因此新增 002 修复存量
库;语句全部幂等,对全新库同样安全。token_version 取 NOT NULL DEFAULT 0,
存量用户现有令牌保持有效,不会被强制重新登录。

同时:
- 新增 test/migration-schema.test.js,在 SQL 文本层面断言迁移必须定义
  server.js 依赖的列。原有 8 个测试只覆盖未认证路径,因此这个故障在
  测试全绿的情况下被漏掉了。
- 修正 README 中失效的 clone 地址与目录名,并修复断裂的环境变量表格。
- 移除 js/api.js 中重复定义的 togglePinPost。
2026-09-21 20:14:10 +08:00

2026-09-03

Furrium Network 3808fd2e94 修复了移动端帖子显示问题 2026-09-03 20:39:58 +08:00

2026-08-14

lezi 5b1b16c222 Merge pull request #14 from ANONYMOUSZED-beep/fix/secure-image-upload
Secure image uploads and post publishing
2026-08-14 15:02:43 +08:00
Arun 593e766596 fix: centralize upload authorization headers 2026-08-14 06:57:22 +00:00
forumlify[bot] 5314d60f53 fix: resolve conflicts for PR #14 2026-08-14 06:48:26 +00:00
lezi 8a2036035a Merge pull request #15 from ANONYMOUSZED-beep/fix/atomic-account-recovery
Make account recovery atomic and session aware
2026-08-14 14:38:50 +08:00
forumlify[bot] 1fce581c52 fix: resolve conflicts for PR #15 2026-08-14 06:27:04 +00:00
lezi 547742cb6d Merge pull request #13 from ANONYMOUSZED-beep/chore/production-deployment-lite
Harden production deployment lifecycle
2026-08-14 13:19:29 +08:00
lezi 01250c0e3f Merge pull request #17 from ANONYMOUSZED-beep/fix/bounded-input-validation
Validate and bound API inputs
2026-08-14 12:59:42 +08:00
Arun b7db82ec0b Preserve upgrade compatibility in deployment 2026-08-14 04:42:05 +00:00
Arun 17dc1c4f41 Close empty recovery-code transactions 2026-08-14 04:02:39 +00:00
Arun 28bdea9572 Merge remote-tracking branch 'origin/Lite' into work-pr13
# Conflicts:
#	README.md
#	docker-compose.yml
#	package.json
#	server.js
2026-08-14 03:37:37 +00:00
Arun c3e87d5a92 Merge remote-tracking branch 'origin/Lite' into work-pr17
# Conflicts:
#	server.js
2026-08-14 03:35:55 +00:00
Arun d2f87b13ae Preserve legacy account compatibility 2026-08-14 03:34:11 +00:00
Arun 50d916bb28 Address account recovery review feedback 2026-08-14 03:34:08 +00:00
Furrium Network 1104b6e2e4 Update README.md 2026-08-14 10:44:38 +08:00
lezi bce8d1fdc7 Merge pull request #16 from ANONYMOUSZED-beep/fix/database-concurrency-invariants
Enforce database concurrency invariants
2026-08-14 09:43:07 +08:00
lezi 6e6e8ca8f4 Merge pull request #26 from forumlify/feat/issue-pr-templates
feat: add bilingual PR and issue templates with branch selection
2026-08-14 09:40:40 +08:00
lezi-fun 3f7b9dbb9c fix: note that npm run build is next-branch only in PR template 2026-08-14 09:38:22 +08:00
lezi-fun b036a51eef feat: add bilingual PR and issue templates with branch selection 2026-08-14 09:31:55 +08:00
lezi-fun 52fed4212b fix: pass PR head repository to ghbot 2026-08-14 09:19:00 +08:00

2026-08-13

Furrium Network 07596ea83c Update README.md 2026-08-13 23:26:49 +08:00
Arun 8ad3ca578f Address input validation review feedback 2026-08-13 15:11:25 +00:00
lezi-fun 3adbe4fab4 Configure ghbot R2 persistence 2026-08-13 22:56:40 +08:00
lezi f074ab890c Merge pull request #22 from ANONYMOUSZED-beep/fix/server-owned-audit-logs
Make audit logs server owned
2026-08-13 22:26:48 +08:00
lezi cb0377220c chore: stop running ghbot on PR close 2026-08-13 22:00:42 +08:00
lezi 0864aa2b92 chore: enable ghbot review modes and conflict recovery 2026-08-13 21:56:43 +08:00
lezi 14b63f4e1c chore: migrate ghbot workflow to goose 2026-08-13 14:28:02 +08:00
lezi c3b197d488 chore: migrate ghbot workflow to goose 2026-08-13 14:27:23 +08:00
lezi 29f7795f00 ci: configure ghbot review automation 2026-08-13 11:42:57 +08:00

2026-08-12

lezi-fun ab66d9a6fc fix: require unique Lite JWT secret 2026-08-12 22:34:05 +08:00
lezi-fun 16f39fc7c6 fix: restore Lite server bootstrap 2026-08-12 22:19:02 +08:00
Furrium Network 5721a84c54 安全问题 2026-08-12 19:45:35 +08:00
Furrium Network 1cd6b5c4dd 代理 2026-08-12 16:40:46 +08:00
lezi-fun 39f219d2ac fix: push to ghcr.io/furrium/forumlify:lite (repo's own GHCR package)
GITHUB_TOKEN from Furrium/forumlify cannot push lezi-fun/forumlify-deploy
(permission_denied). Use github.repository → ghcr.io/furrium/forumlify:lite
in workflow and compose.
2026-08-12 09:31:52 +08:00
lezi-fun aa9bcd8d12 ci: GHCR docker build for Lite branch (repo's own package) + cleanup
- .github/workflows/docker-lite.yml: build & push on Lite branch push
  → ghcr.io/furrium/forumlify:lite (linux/amd64+arm64)
- docker-compose.yml: pull :lite image from GHCR, PORT/ENABLE_CAPTCHA
  env, restart: unless-stopped
- .gitignore: ignore .open-next/.vercel/.next/.wrangler build artifacts
- Remove build artifacts accidentally committed earlier
2026-08-12 09:28:38 +08:00
lezi-fun 9f5944020b chore: ignore .wrangler local state 2026-08-12 09:21:13 +08:00
lezi-fun 9e407d0a2d ci: GHCR docker build for Lite branch + compose updates
- .github/workflows/docker-lite.yml: build & push ghcr.io/lezi-fun/
  forumlify-deploy:lite on Lite branch push (linux/amd64+arm64)
- docker-compose.yml: pull :lite image from GHCR, add PORT / ENABLE_
  CAPTCHA env, restart: unless-stopped on both services
2026-08-12 09:21:12 +08:00
lezi-fun 8f88f803f5 chore: ignore .wrangler local state 2026-08-12 09:21:10 +08:00
Furrium Network 5d71e66354 允许跳转 2026-08-12 09:19:00 +08:00
Furrium Network 320000c8b9 允许点击iframe中的超链接 2026-08-12 09:15:59 +08:00
Furrium Network 46dd281c7b 修复了吗? 2026-08-12 07:51:36 +08:00
Furrium Network 503a34f5fb 自定义页面更新 2026-08-12 07:48:20 +08:00

2026-08-11

Arun a5a880dfb2 Make audit logs server owned 2026-08-11 10:59:58 +00:00
Arun 3fc74ae189 Add integrated tests and patch dependencies 2026-08-11 10:34:46 +00:00
Arun feefadae11 Validate and bound API inputs 2026-08-11 09:58:56 +00:00
Arun 924f9ffcc6 Enforce database concurrency invariants 2026-08-11 09:51:33 +00:00
Arun 2e12468293 Make account recovery atomic and session aware 2026-08-11 09:44:39 +00:00
Arun 5605ded575 Secure image uploads and post publishing 2026-08-11 09:38:33 +00:00
lezi 145f13fee5 Update README.md 2026-08-11 17:28:26 +08:00
lezi 3ed09fbcdf Update README.md 2026-08-11 17:27:39 +08:00
Arun 5aa16b0f05 Harden production deployment lifecycle 2026-08-11 09:25:44 +00:00
lezi 3ffb92dc23 Update README.md 2026-08-11 17:24:32 +08:00
Furrium Network 3fbf2743d0 3000吧还是 2026-08-11 17:17:55 +08:00
Furrium Network b4330666a4 Update README.md 2026-08-11 17:13:29 +08:00
Furrium Network 51a6b49459 Update README.md 2026-08-11 17:11:58 +08:00
Furrium Network 8d1b59479e Pass.
Fix registration and recovery-code setup
2026-08-11 16:58:51 +08:00
Furrium Network 3cee3ae530 Pass.
Prevent stored XSS in rendered content
2026-08-11 16:58:31 +08:00
Furrium Network 2e745b547d Pass.
Make moderation actions atomic and authorized
2026-08-11 16:58:13 +08:00
Furrium Network 7cf69ad476 Pass!
Harden HTTP server defaults
2026-08-11 16:57:37 +08:00
Arun c57863fc47 Make moderation actions atomic and authorized 2026-08-11 07:57:39 +00:00
lezi b449e05f3f Update README.md 2026-08-11 15:56:45 +08:00
Arun 5d0a148804 Harden HTTP server defaults 2026-08-11 07:48:33 +00:00
Arun f30a3dcacb Prevent stored XSS in rendered content 2026-08-11 07:39:37 +00:00
Arun 9e99d6909a Fix registration recovery setup flow 2026-08-11 07:23:14 +00:00
Furrium Network 2e74b1505b 修复了设置为深色模式是刷新显示浅色的问题 2026-08-11 11:32:12 +08:00
Furrium Network db34b09b2e Update i18n.js 2026-08-11 11:05:51 +08:00
Furrium Network 63b804d2a0 Update i18n.js 2026-08-11 11:02:13 +08:00
Furrium Network 1f51e66d8c Update i18n.js 2026-08-11 10:55:37 +08:00
Furrium Network 383ad94d41 Update i18n.js 2026-08-11 10:50:24 +08:00
Furrium Network b72732a774 Update i18n.js 2026-08-11 10:44:45 +08:00
Furrium Network b2539ea911 又补上了一些 2026-08-11 10:40:02 +08:00
Furrium Network dbb72b8afe 补了几个 2026-08-11 10:36:09 +08:00
Furrium Network 2746f50685 支持了翻译 2026-08-11 10:34:56 +08:00
Furrium Network 0169db134c 0!!!! 2026-08-11 10:30:01 +08:00
Furrium Network a6dcf461ec Update i18n.js 2026-08-11 10:25:26 +08:00
Furrium Network a660d605c9 Update style.css 2026-08-11 10:23:39 +08:00
Furrium Network 4e1e24699d Update i18n.js 2026-08-11 10:22:22 +08:00
Furrium Network 955c9d38d1 Update i18n.js 2026-08-11 10:21:10 +08:00
Furrium Network bc4d0d9471 延迟加载 2026-08-11 10:18:46 +08:00
Furrium Network 756ccf34a1 Update index.html 2026-08-11 10:15:22 +08:00
Furrium Network e8bc9ab302 语言包文件 2026-08-11 10:14:23 +08:00
Furrium Network 10e8db0b2d 修复了帖子内部论坛数据错误的问题 2026-08-11 10:09:22 +08:00
Furrium Network d40c8bd866 修复个人资料 2026-08-11 10:00:45 +08:00
Furrium Network 496234b519 Update user.js 2026-08-11 09:58:35 +08:00
Furrium Network bb849fc67a 添加了查看个人资料接口 2026-08-11 09:57:48 +08:00
Furrium Network c563e2ed55 Update server.js 2026-08-11 09:57:31 +08:00
Furrium Network cbb15df923 Delete js/hi 2026-08-11 09:51:55 +08:00
Furrium Network 287c8c2a12 将所有emoji修改为svg 2026-08-11 09:49:18 +08:00
Furrium Network 8c09df2978 替换了所有emoji 2026-08-11 09:46:36 +08:00
Furrium Network f4998524c6 Update icons.js 添加了一些svg 2026-08-11 09:43:36 +08:00
Furrium Network 27638e6d34 新增调用icons.js 2026-08-11 09:38:59 +08:00
Furrium Network 8d651cba38 SVG图标映射文件 2026-08-11 09:37:09 +08:00
Furrium Network 3eaa276a1f Update style.css 2026-08-11 09:34:14 +08:00
Furrium Network 27364074ea 更新了添加自定义页面模态框的样式 2026-08-11 09:29:25 +08:00
Furrium Network 2010652895 消息气泡样式 2026-08-11 09:26:43 +08:00
Furrium Network 2a01e8ca3d 管理删除气泡 2026-08-11 09:25:56 +08:00
Furrium Network 222c9b8f3c 追加消息气泡格式 2026-08-11 09:22:32 +08:00
Furrium Network 1526fce759 Update README.md 2026-08-11 08:53:41 +08:00
Furrium Network 12b3513f29 Reupload 2026-08-11 08:48:53 +08:00
Furrium Network 6eb60df5ee Create hi 2026-08-11 08:47:11 +08:00
Furrium Network 7c2b303b02 Reupload 2026-08-11 08:45:39 +08:00
Furrium Network f0e83d2484 Delete style.css 2026-08-11 08:39:07 +08:00
Furrium Network d4f25bf098 Delete server.js 2026-08-11 08:38:15 +08:00
Furrium Network 205c97ed6b Delete schema.sql 2026-08-11 08:37:18 +08:00
Furrium Network 851a445beb Delete package.json 2026-08-11 08:36:58 +08:00
Furrium Network 1503864f37 Delete package-lock.json 2026-08-11 08:36:20 +08:00
Furrium Network c0ad458b3e Delete index.html 2026-08-11 08:35:44 +08:00
Furrium Network 429f8fff64 Delete dockerfile 2026-08-11 08:35:27 +08:00
Furrium Network 4252f54a7e Delete docker-compose.yml 2026-08-11 08:33:59 +08:00
Furrium Network 291ad9c06c Delete config.js 2026-08-11 08:33:26 +08:00
Furrium Network c7f6496161 Delete README.md 2026-08-11 08:29:27 +08:00
Furrium Network 5b89506040 Delete js directory 2026-08-11 08:29:08 +08:00

2026-08-10

Furrium Network b421cb297a Update README.md 2026-08-10 23:21:23 +08:00
Furrium Network 4ced755deb Update README.md 2026-08-10 23:20:55 +08:00
Furrium Network ce932784bc Update README.md 2026-08-10 23:20:36 +08:00
Furrium Network 942c71cacb 修复了个人设置的侧边栏样式 2026-08-10 23:06:33 +08:00
Furrium Network f8916b580d 追加了对个人设置页面的侧边栏样式 2026-08-10 23:04:22 +08:00
Furrium Network cd770a082e 添加了个人主页的标签页(js) 2026-08-10 23:01:50 +08:00
Furrium Network 6f58aa4fdc Update app.js 2026-08-10 23:01:19 +08:00
Furrium Network 706286eb1c Update style.css 2026-08-10 21:32:42 +08:00
Furrium Network 6ab52bd7ac Update app.js 2026-08-10 21:30:43 +08:00
Furrium Network 4e172f193a Update index.html 2026-08-10 21:29:21 +08:00
Furrium Network d167ab3132 Update index.html 2026-08-10 21:22:09 +08:00
Furrium Network 03d46f95d7 Update index.html 2026-08-10 21:20:46 +08:00
Furrium Network 197350d7a9 Update admin.js 2026-08-10 21:18:49 +08:00
Furrium Network 155e3a465e Update index.html 2026-08-10 21:17:14 +08:00
Furrium Network 7498f07b98 Update README.md 2026-08-10 21:04:26 +08:00
Furrium Network 8e417048ee Update style.css 2026-08-10 18:58:41 +08:00
Furrium Network 427d1cb624 Update app.js 2026-08-10 18:48:26 +08:00
Furrium Network 3108dfc4cd Update app.js 2026-08-10 18:45:14 +08:00
Furrium Network 5a03c56ff4 Update index.html 2026-08-10 18:41:24 +08:00
Furrium Network 3f3e44a737 Update index.html 2026-08-10 18:39:36 +08:00
Furrium Network 963791b0bb Update app.js 2026-08-10 18:21:02 +08:00
Furrium Network c25564588d Update index.html 2026-08-10 18:18:28 +08:00
Furrium Network 737ba6c587 Update app.js 2026-08-10 18:17:28 +08:00
Furrium Network 223a003f5f Update index.html 2026-08-10 18:16:54 +08:00
Furrium Network 34a24920a8 Update index.html 2026-08-10 18:16:40 +08:00
Furrium Network 17b195c10e Update index.html 2026-08-10 18:14:32 +08:00
Furrium Network 115dd7131d Update app.js 2026-08-10 18:11:25 +08:00
Furrium Network fd15e7b427 Update style.css 2026-08-10 18:08:58 +08:00
Furrium Network 04759a0716 Update index.html 2026-08-10 18:08:43 +08:00
Furrium Network da88709d6f Update index.html 2026-08-10 18:07:42 +08:00
Furrium Network 44ba238ef6 Update index.html 2026-08-10 18:05:38 +08:00
Furrium Network e40be0ceb4 Update index.html 2026-08-10 18:00:58 +08:00
Furrium Network 23b236c9d7 Update app.js 2026-08-10 17:58:58 +08:00
Furrium Network d9b3417469 Update index.html 2026-08-10 17:58:05 +08:00
Furrium Network 4abe6d75d7 Update app.js 2026-08-10 17:52:03 +08:00
Furrium Network a6b3a587eb Update index.html 2026-08-10 17:49:11 +08:00
Furrium Network 1d960fca3e Update schema.sql 2026-08-10 17:48:42 +08:00
Furrium Network aa38a31aa3 Update style.css 2026-08-10 17:42:29 +08:00
Furrium Network d188c3eded Update index.html 2026-08-10 17:34:58 +08:00
Furrium Network b109e59fc4 Update admin.js 2026-08-10 17:30:27 +08:00
Furrium Network 77e5c8c3ba Update api.js 2026-08-10 17:29:57 +08:00
Furrium Network 5f274c2d86 Update server.js 2026-08-10 17:29:36 +08:00
Furrium Network 7a32d23976 Update style.css 2026-08-10 17:28:40 +08:00
Furrium Network 454578e8d6 Update admin.js 2026-08-10 17:22:25 +08:00
Furrium Network b0d2f94207 Update api.js 2026-08-10 17:21:46 +08:00
Furrium Network 59ef72fbc3 Update server.js 2026-08-10 17:21:04 +08:00
Furrium Network 6dccedc781 Update index.html 2026-08-10 17:02:35 +08:00
Furrium Network 84a11df8b2 液态玻璃!!!!!! 2026-08-10 16:59:41 +08:00
Furrium Network 8e86473429 液态玻璃yyds 2026-08-10 16:58:26 +08:00
Furrium Network 71afe65f63 Update style.css 2026-08-10 16:58:12 +08:00
Furrium Network e2fd713539 Update style.css 2026-08-10 12:49:47 +08:00
Furrium Network b2d85e9e1d Update index.html 2026-08-10 12:49:00 +08:00
Furrium Network 0953234bc9 Update admin.js 2026-08-10 12:44:56 +08:00
Furrium Network d87f1b2ab9 Update style.css 2026-08-10 12:43:40 +08:00
Furrium Network 58d6ee7018 Update index.html 2026-08-10 12:43:07 +08:00
Furrium Network f677eae6f5 Update admin.js 2026-08-10 11:41:00 +08:00
Furrium Network 2bec523999 Update index.html 2026-08-10 11:37:54 +08:00
Furrium Network 68d0d158c9 Update admin.js 2026-08-10 11:35:08 +08:00
Furrium Network b6a7450ef8 Update api.js 2026-08-10 11:34:40 +08:00
Furrium Network 19ec83d3a6 Update server.js 2026-08-10 11:34:11 +08:00
Furrium Network 12006d39e3 Update feed.js 2026-08-10 11:27:02 +08:00
Furrium Network 5c7f02d586 Update index.html 2026-08-10 11:26:49 +08:00
Furrium Network d31cb1523f Update server.js 2026-08-10 11:19:48 +08:00
Furrium Network 31ef7e6fd0 Update post.js 2026-08-10 11:17:05 +08:00
Furrium Network 7664d172ae Update feed.js 2026-08-10 11:16:38 +08:00
Furrium Network e693627e5b Update app.js 2026-08-10 11:15:41 +08:00
Furrium Network 146b7dd1f3 Update api.js 2026-08-10 11:14:14 +08:00
Furrium Network 5cf8fed892 Update schema.sql 2026-08-10 11:13:50 +08:00
Furrium Network 39af657905 Update app.js 2026-08-10 11:08:08 +08:00
Furrium Network 00a36b570f Update post.js 2026-08-10 11:07:27 +08:00
Furrium Network 90678440eb Update feed.js 2026-08-10 11:06:55 +08:00
Furrium Network a74181a97d Update README.md 2026-08-10 10:50:10 +08:00
Furrium Network d97645fdc8 Update README.md 2026-08-10 10:49:58 +08:00
Furrium Network 0581aa0027 Update README.md 2026-08-10 10:49:26 +08:00
Furrium Network 3aa6f0130d Update server.js 2026-08-10 10:39:27 +08:00
Furrium Network 233c919738 Update post.js 2026-08-10 10:36:48 +08:00
Furrium Network 73f8ed581f Update feed.js 2026-08-10 10:35:16 +08:00
Furrium Network bdfbdb7375 Update api.js 2026-08-10 10:34:39 +08:00
Furrium Network 283724fc14 Update schema.sql 2026-08-10 10:34:08 +08:00
50 changed files with 11663 additions and 1992 deletions

No files matched your search

+1
View File
@@ -0,0 +1 @@
NEXTJS_ENV=development
+10
View File
@@ -0,0 +1,10 @@
.git
.github
.env
.env.*
!.env.example
node_modules
npm-debug.log*
uploads
coverage
*.md
+4
View File
@@ -0,0 +1,4 @@
# Copy to .env, then set both required secrets before running Docker Compose.
POSTGRES_PASSWORD=
JWT_SECRET=
PORT=3000
+90
View File
@@ -0,0 +1,90 @@
name: 🐛 Bug 报告 / Bug Report
description: 报告一个 Bug / Report a bug
title: "[Bug] "
labels: [bug]
body:
- type: markdown
attributes:
value: |
## 感谢你报告问题!/ Thanks for reporting an issue!
请填写以下信息,帮助我们快速定位问题。/ Please fill in the following information to help us locate the issue quickly.
- type: dropdown
id: branch
attributes:
label: 你使用的是哪个分支?/ Which branch are you using?
description: 请选择你所使用的分支。/ Please select the branch you are using.
options:
- Lite(原生单文件版 / Original single-file version)
- next(Next.js 16 版 / Next.js 16 version)
validations:
required: true
- type: input
id: version
attributes:
label: 后台版本号 / Backend version (管理员填写 / admins only)
description: |
如果你使用的是 next 分支且是管理员,请粘贴后台显示的版本号。其他情况请留空。
/ If you are using the next branch and are an administrator, please paste the version shown in the admin panel. Leave blank otherwise.
placeholder: "例如 / e.g. 2.0.0"
validations:
required: false
- type: textarea
id: description
attributes:
label: 问题描述 / Description
description: 请清晰描述你遇到的问题。/ Please clearly describe the issue you encountered.
validations:
required: true
- type: textarea
id: steps
attributes:
label: 复现步骤 / Steps to reproduce
description: 如何复现这个问题?/ How can this issue be reproduced?
placeholder: |
1. 打开... / Open ...
2. 点击... / Click ...
3. 看到错误... / See the error...
validations:
required: true
- type: textarea
id: expected
attributes:
label: 期望行为 / Expected behavior
description: 你期望发生什么?/ What did you expect to happen?
validations:
required: true
- type: textarea
id: actual
attributes:
label: 实际行为 / Actual behavior
description: 实际发生了什么?/ What actually happened?
validations:
required: true
- type: textarea
id: environment
attributes:
label: 环境信息 / Environment
description: 你的运行环境。/ Your running environment.
placeholder: |
- 操作系统 / OS:
- 浏览器 / Browser:
- Node.js 版本 / Node.js version:
- 部署方式 / Deployment method (Docker / 源码 / Source):
validations:
required: false
- type: textarea
id: logs
attributes:
label: 日志 / Logs
description: 如有报错日志,请粘贴于此。/ Paste any error logs here if available.
render: shell
validations:
required: false
+1
View File
@@ -0,0 +1 @@
blank_issues_enabled: false
@@ -0,0 +1,65 @@
name: ✨ 功能建议 / Feature Request
description: 提出一个新功能或改进建议 / Suggest an idea for this project
title: "[Feature] "
labels: [enhancement]
body:
- type: markdown
attributes:
value: |
## 感谢你的建议!/ Thanks for your suggestion!
请填写以下信息,让我们了解你的想法。/ Please fill in the information below to help us understand your idea.
- type: dropdown
id: branch
attributes:
label: 这个功能针对哪个分支?/ Which branch is this feature for?
description: 请选择你所使用的分支。/ Please select the branch you are using.
options:
- Lite(原生单文件版 / Original single-file version)
- next(Next.js 16 版 / Next.js 16 version)
validations:
required: true
- type: input
id: version
attributes:
label: 后台版本号 / Backend version (管理员填写 / admins only)
description: |
如果你使用的是 next 分支且是管理员,请粘贴后台显示的版本号。其他情况请留空。
/ If you are using the next branch and are an administrator, please paste the version shown in the admin panel. Leave blank otherwise.
placeholder: "例如 / e.g. 2.0.0"
validations:
required: false
- type: textarea
id: problem
attributes:
label: 要解决的问题 / Problem to solve
description: 这个功能解决什么问题?/ What problem does this feature solve?
placeholder: "当我...时,我希望... / When I ..., I wish ..."
validations:
required: true
- type: textarea
id: solution
attributes:
label: 期望的解决方案 / Proposed solution
description: 你希望如何实现?/ How would you like it to work?
validations:
required: true
- type: textarea
id: alternatives
attributes:
label: 替代方案 / Alternatives considered
description: 你考虑过其他方案吗?/ Have you considered any alternative approaches?
validations:
required: false
- type: textarea
id: additional
attributes:
label: 补充说明 / Additional context
description: 其他任何信息、截图或示例。/ Any other information, screenshots, or examples.
validations:
required: false
+52
View File
@@ -0,0 +1,52 @@
# 感谢你为 Forumlify 提交贡献!/ Thank you for contributing to Forumlify!
<!-- 请填写以下信息,帮助我们快速处理你的 PR。/ Please fill in the information below to help us process your PR quickly. -->
## 目标分支 / Target branch
**你提交的代码是基于哪个分支?/ Which branch is your code based on?**
- [ ] **Lite**(原生单文件版 / Original single-file version)
- [ ] **next**(Next.js 16 版 / Next.js 16 version)
> ⚠️ 请确保 PR 的 base 分支与你的代码来源分支一致。/ Please make sure the PR's base branch matches the branch your code comes from.
## 版本信息 / Version info
<!-- 仅当你选择 next 分支且为管理员时填写。/ Only fill in if you chose the next branch AND you are an administrator. -->
**后台版本号 / Backend version (admin only):**
```
(在此粘贴后台显示的版本号 / Paste the version shown in the admin panel here)
```
## 变更内容 / What does this PR do?
<!-- 简要描述你的改动。/ Briefly describe your changes. -->
-
## 动机 / Motivation
<!-- 为什么需要这个改动?/ Why is this change needed? -->
-
## 测试 / Testing
<!-- 你如何验证这些改动?/ How did you verify these changes? -->
- [ ] 本地构建通过 / Local build passes (`npm run build`,仅 next 分支 / next branch only)
- [ ] 相关功能已手动测试 / Related features manually tested
- [ ] 测试用例已更新 / Tests updated
## 截图 / Screenshots
<!-- 如有 UI 改动,请附截图。/ Attach screenshots if this changes the UI. -->
## 检查清单 / Checklist
- [ ] 我已阅读并遵循了贡献指南 / I have read and followed the contributing guidelines
- [ ] 我的代码遵循现有代码风格 / My code follows the existing code style
- [ ] 我已同步最新的上游分支 / I have synced with the latest upstream branch
- [ ] 本 PR 只包含必要的改动 / This PR contains only the necessary changes
+55
View File
@@ -0,0 +1,55 @@
name: Build & Push Docker to GHCR (Lite)
on:
push:
branches: [Lite]
tags: ['v*']
workflow_dispatch:
env:
REGISTRY: ghcr.io
# 推仓库自己的 GHCR 包(github.repository = Furrium/forumlify)——
# 仓库 GITHUB_TOKEN 无权推跨仓库包(如 lezi-fun/forumlify-deploy)
IMAGE_NAME: ${{ github.repository }}
jobs:
build:
runs-on: ubuntu-latest
permissions:
contents: read
packages: write
steps:
- name: Checkout
uses: actions/checkout@v4
- name: Set up Docker Buildx
uses: docker/setup-buildx-action@v3
- name: Login to GHCR
uses: docker/login-action@v3
with:
registry: ${{ env.REGISTRY }}
username: ${{ github.actor }}
password: ${{ secrets.GITHUB_TOKEN }}
- name: Extract metadata (tags, labels)
id: meta
uses: docker/metadata-action@v5
with:
images: ${{ env.REGISTRY }}/${{ env.IMAGE_NAME }}
tags: |
# Lite 分支 → lite 标签(与 next 镜像隔离,避免覆盖)
type=raw,value=lite,enable=${{ github.ref == 'refs/heads/Lite' }}
type=semver,pattern={{version}}
type=sha,prefix=git-
- name: Build and push (linux/amd64 + linux/arm64)
uses: docker/build-push-action@v6
with:
context: .
push: true
platforms: linux/amd64, linux/arm64
tags: ${{ steps.meta.outputs.tags }}
labels: ${{ steps.meta.outputs.labels }}
cache-from: type=gha
cache-to: type=gha,mode=max
+83
View File
@@ -0,0 +1,83 @@
name: ghbot
on:
pull_request_target:
types:
- opened
- synchronize
- reopened
- ready_for_review
- edited
issues:
types:
- opened
- edited
- reopened
issue_comment:
types:
- created
pull_request_review:
types:
- submitted
permissions:
contents: write
pull-requests: write
checks: write
statuses: read
issues: write
jobs:
review:
if: |
github.event_name == 'pull_request_target' ||
github.event_name == 'issues' ||
(github.event_name == 'issue_comment' && github.event.issue.pull_request != null) ||
github.event_name == 'pull_request_review'
uses: lezi-fun/ghbot/.github/workflows/review-reusable.yml@main
secrets:
GOOSE_API_KEY: ${{ secrets.GOOSE_API_KEY || secrets.OPENCODE_API_KEY }}
GH_APP_ID: ${{ secrets.GH_APP_ID }}
GH_APP_PRIVATE_KEY: ${{ secrets.GH_APP_PRIVATE_KEY }}
GH_APP_INSTALLATION_ID: ${{ secrets.GH_APP_INSTALLATION_ID }}
R2_ACCESS_KEY_ID: ${{ secrets.R2_ACCESS_KEY_ID }}
R2_SECRET_ACCESS_KEY: ${{ secrets.R2_SECRET_ACCESS_KEY }}
with:
event_name: ${{ github.event_name }}
event_action: ${{ github.event.action }}
repository_owner: ${{ github.repository_owner }}
repository_name: ${{ github.event.repository.name }}
repository_id: ${{ github.repository_id }}
pull_number: ${{ github.event.pull_request.number || github.event.issue.number }}
pull_head_repository: ${{ github.event.pull_request.head.repo.full_name || '' }}
comment_id: ${{ github.event.comment.id || '' }}
commenter_login: ${{ github.event.comment.user.login || '' }}
comment_body: ${{ github.event.comment.body || '' }}
reviewer_login: ${{ github.event.review.user.login || '' }}
review_state: ${{ github.event.review.state || '' }}
review_commit_id: ${{ github.event.review.commit_id || '' }}
bot_name: ${{ vars.BOT_NAME || 'github-actions[bot]' }}
goose_base_url: ${{ vars.GOOSE_BASE_URL || vars.OPENCODE_BASE_URL || 'https://api.openai.com/v1' }}
goose_model: ${{ vars.GOOSE_MODEL || vars.OPENCODE_MODEL || 'gpt-5.4' }}
goose_thinking_effort: ${{ vars.GOOSE_THINKING_EFFORT || vars.OPENCODE_REASONING_EFFORT || 'high' }}
review_policy: ${{ vars.REVIEW_POLICY || 'allow' }}
review_strictness: ${{ vars.REVIEW_STRICTNESS || 'normal' }}
review_instructions: ${{ vars.REVIEW_INSTRUCTIONS || '' }}
review_branches: ${{ vars.REVIEW_BRANCHES || '' }}
repository_knowledge_enabled: ${{ vars.REPOSITORY_KNOWLEDGE_ENABLED || 'true' }}
repository_knowledge_write: ${{ vars.REPOSITORY_KNOWLEDGE_WRITE || 'false' }}
r2_endpoint: ${{ vars.R2_ENDPOINT || '' }}
r2_bucket_name: ${{ vars.R2_BUCKET_NAME || '' }}
r2_prefix: ${{ vars.R2_PREFIX || '' }}
triage_enabled: ${{ vars.TRIAGE_ENABLED || 'true' }}
triage_labels: ${{ vars.TRIAGE_LABELS || 'bug,enhancement,documentation,question' }}
triage_duplicate_label: ${{ vars.TRIAGE_DUPLICATE_LABEL || 'duplicate' }}
triage_candidate_limit: ${{ vars.TRIAGE_CANDIDATE_LIMIT || '50' }}
triage_instructions: ${{ vars.TRIAGE_INSTRUCTIONS || '' }}
auto_merge: ${{ vars.AUTO_MERGE || 'false' }}
auto_resolve_conflicts: ${{ vars.AUTO_RESOLVE_CONFLICTS || 'false' }}
conflict_test_command: ${{ vars.CONFLICT_TEST_COMMAND || '' }}
merge_method: ${{ vars.MERGE_METHOD || 'squash' }}
require_checks: ${{ vars.REQUIRE_CHECKS || 'true' }}
max_patch_chars: ${{ vars.MAX_PATCH_CHARS || '120000' }}
log_level: info
+10
View File
@@ -3,3 +3,13 @@ uploads/
*.log *.log
.DS_Store .DS_Store
.env .env
# Wrangler 本地状态
.wrangler/
# 构建产物
.open-next/
.vercel/
.next/
.wrangler/
+19
View File
@@ -0,0 +1,19 @@
FROM node:22.23.2-bookworm-slim
ENV NODE_ENV=production
WORKDIR /app
COPY package.json package-lock.json ./
RUN npm ci --omit=dev && npm cache clean --force
COPY --chown=node:node . .
RUN mkdir -p /app/uploads && chown node:node /app/uploads
RUN chmod +x /app/scripts/docker-entrypoint.sh
USER node
EXPOSE 3000
HEALTHCHECK --interval=30s --timeout=5s --start-period=20s --retries=3 \
CMD ["node", "scripts/healthcheck.js"]
ENTRYPOINT ["/app/scripts/docker-entrypoint.sh"]
+382 -30
View File
@@ -1,30 +1,93 @@
# Forumlify 🌊
# Forumlify LITE Edition 🌊
> 一个简洁、优雅的现代社区系统。5 分钟 Docker 一键部署。 > 一个简洁、优雅的现代社区系统。5 分钟 Docker 一键部署。
**在线演示:** https://lite.forumlify.org
## ✨ 特性 ## ✨ 特性
- 🎨 精致简约的界面设计,支持亮色/暗色模式 - 🎨 精致简约的界面设计,支持亮色/暗色模式
- ⚡️ 轻量快速,无需复杂配置 - ⚡️ 轻量快速,无需复杂配置
- 🔐 自带用户认证(JWT) - 🔐 自带用户认证(JWT),改密码后旧令牌立即失效
- 📝 发帖、回复、举报、管理后台 - 📝 发帖、回复、举报、私信、管理后台
- 📧 邮件支持:后台配置 SMTP,可用于注册邮箱验证与密码找回
- 🌍 界面中英文双语,管理后台可配置自定义页面与样式
- 🐳 Docker 一键部署 - 🐳 Docker 一键部署
- 🌓 暗色/亮色模式切换
## 🤔 如何选择版本
Forumlify 提供了两个不同架构的分支版本,以满足不同部署环境与开发需求的场景:
* **Lite 版 (`lite` 分支)**:轻量单体架构,零构建步骤,资源占用极低,主要由Furrium维护。
* **Next.js 版 (`next` 分支)**:现代全栈架构,组件化开发,支持云原生与 Serverless / 边缘部署,主要由lezi-fun维护。
你可以根据以下维度选择最适合你当前需求的版本:
| 对比维度 | Forumlify (Lite 版 / `lite`) | Forumlify-Next (Next.js 版 / `next`) | 选择建议 |
| :--- | :--- | :--- | :--- |
| **上手速度与部署** | **极快**(零编译步骤,直接 `node server.js` 或 Docker 启动) | **中等**(需要经过 `next build` 编译打包,或配置 OpenNext) | 希望 1 分钟快速跑起来选 `lite` |
| **VPS 最低配置要求** | **1 核 512MB RAM**(资源占用极低,适合低配小鸡) | **1 核 1GB RAM+**(主要在打包构建时需要较多内存) | 内存有限或低配 VPS 推荐 `lite` |
| **存储扩展性** | 本地磁盘存储(`uploads/` 目录) | 支持 **Cloudflare R2 / S3 兼容对象存储** + 本地回退 | 需要接云存储或海量图片存储选 `next` |
| **部署环境支持** | 传统 VPS / Docker 容器 | VPS / Docker / **Cloudflare Workers / Vercel** | 需要 Serverless / 边缘部署选 `next` |
| **技术栈与二次开发** | 原生 Vanilla JS + Express,无框架门槛 | React 19 + Next.js 16 + Tailwind,组件化程度高 | 熟悉 React 框架或需要团队协同选 `next` |
| **测试与工程化** | 基础配置,轻量化结构 | 内置自动化测试套件(Unit / Integration Tests) | 追求工程化与自动化测试选 `next` |
| **适合场景** | 个人轻量论坛、小圈子交流、低成本运行、快速原型验证 | 中大型社区、云原生部署、需要扩展对象存储或边缘加速 | 根据站点规模与长期规划选择 |
## 🚀 快速开始 ## 🚀 快速开始
### Docker 部署(推荐) ### Docker 部署(推荐)
```bash ```
git clone https://github.com/furrium/forumlify.git git clone https://github.com/forumlify/public.git
cd forumlify cd public
docker-compose up -d
cp .env.example .env
# 编辑 .env,为 POSTGRES_PASSWORD 和 JWT_SECRET 设置强随机值
docker compose up --build -d
``` ```
应用默认运行在 `http://localhost:3003`。 旧版 Compose 也可以使用 `docker-compose up -d`。请妥善备份 `.env`;更换
`JWT_SECRET` 会使现有登录令牌失效。
> `git clone` 生成的目录名是 `public`(取自仓库名),不是 `forumlify`。
> 若想使用其他目录名,可在 clone 时指定,例如
> `git clone https://github.com/forumlify/public.git forumlify`。
应用默认运行在 `http://localhost:3000`。
容器启动时会自动执行 `migrations/` 中尚未应用的 SQL 文件。可使用以下命令检查状态:
```bash
docker compose ps
docker compose logs -f app
curl http://localhost:3000/health/live
curl http://localhost:3000/health/ready
```
- `/health/live` 表示 Node.js 服务正在运行。
- `/health/ready` 仅在 PostgreSQL 可用时返回成功。
- PostgreSQL 不再暴露到宿主机网络;应用通过 Compose 内部网络访问数据库。
- 应用收到 `SIGTERM`/`SIGINT` 后会停止接收新连接并关闭数据库连接池。
升级代码后执行 `docker compose up --build -d`,应用会在启动前自动应用新增迁移。
#### Docker 数据备份
数据库保存在 `db_data` 卷中,上传文件继续保存在宿主机的 `./uploads` 目录,以兼容旧版部署。升级或删除容器前请备份:
```bash
docker compose exec -T db pg_dump -U forumlify forumlify > forumlify.sql
tar czf forumlify-uploads.tar.gz uploads/
```
`docker compose down` 会保留数据卷;只有明确执行 `docker compose down -v` 才会删除数据。
--- ---
以下内容添加自NodeLoc @Lezi-fun的PR
> 如需部署 Next.js 版本,请前往 [forumlify/tree/next](https://github.com/forumlify/public/tree/next)。
--- ---
@@ -34,51 +97,77 @@ docker-compose up -d
#### 环境要求 #### 环境要求
- Node.js 18+ - Node.js 20+
- PostgreSQL 13+(`schema.sql` 使用了内置的 `gen_random_uuid()`) - PostgreSQL 13+
#### 步骤 #### 步骤
1. **克隆并安装依赖** 1. **克隆并安装依赖**
```bash ```bash
git clone https://github.com/furrium/forumlify.git git clone https://github.com/forumlify/public.git
cd forumlify cd public
npm install npm install
``` ```
2. **准备数据库**(以本机 PostgreSQL 为例) 2. **准备数据库**
创建数据库用户与空库即可,表结构交给迁移脚本处理:
```bash ```bash
# 创建数据库和用户(与 docker-compose.yml 默认一致) psql -U postgres -c "CREATE USER forumlify WITH PASSWORD '请替换为强密码';"
psql -U postgres -c "CREATE USER forumlify WITH PASSWORD '123456';"
psql -U postgres -c "CREATE DATABASE forumlify OWNER forumlify;" psql -U postgres -c "CREATE DATABASE forumlify OWNER forumlify;"
# 导入表结构
psql -U forumlify -d forumlify -f schema.sql
``` ```
3. **配置环境变量**(可选,均有默认值) > `schema.sql` 仅作为表结构的参考快照保留,**不要**再用它手工建表。
> 请统一使用第 4 步的 `npm run migrate`,它会按顺序执行 `migrations/`
> 下的文件并记录版本。手工建表后再跑迁移会导致版本记录与实际结构
> 不一致,后续升级容易出错。
3. **配置环境变量**
复制示例文件并按需修改:
```bash
cp .env.example .env
```
`migrations/` 与 `server.js` 直接读取进程环境变量,`.env` 不会自动加载。
使用 `npm start` 手动启动时,请先导出这些变量:
```bash
set -a && . ./.env && set +a
```
| 变量 | 默认值 | 说明 | | 变量 | 默认值 | 说明 |
|------|--------|------| |------|--------|------|
| `DATABASE_URL` | `postgresql://forumlify:123456@localhost:5432/forumlify` | PostgreSQL 连接串 | | `DATABASE_URL` | `postgresql://forumlify:***@localhost:5432/forumlify` | PostgreSQL 连接串 |
| `PORT` | `3000` | HTTP 监听端口 | | `PORT` | `3000` | HTTP 监听端口 |
| `JWT_SECRET` | `forumlify-secret-key-change-me-in-production` | JWT 签名密钥,**生产环境务必修改** | | `JWT_SECRET` | 本地开发使用内置值 | JWT 签名密钥;生产环境必须显式设置,建议至少 32 个字符。较短的旧密钥会产生警告但仍可启动,便于安排会话失效窗口后再轮换 |
| `ALLOWED_ORIGINS` | 空 | 允许跨域访问的来源,多个值用逗号分隔;为空时仅支持同源访问 |
| `TRUST_PROXY` | `false` | 位于可信反向代理后时设为 `true`,用于正确识别限流 IP |
| `PGHOST` / `PGPORT` / `PGUSER` / `PGPASSWORD` / `PGDATABASE` | PostgreSQL 客户端默认值 | 可替代 `DATABASE_URL`,Compose 使用这些变量避免密码 URL 编码问题 |
| `ADMIN_BOOTSTRAP_TOKEN` | 空 | 首次部署时设置强随机值;注册时填写相同值可创建唯一初始管理员,初始化后应删除该变量 |
```bash
# 例如:
export DATABASE_URL=postgresql://forumlify:123456@localhost:5432/forumlify
export JWT_SECRET=your-own-secret-key
```
4. **启动** 4. **执行迁移并启动**
```bash ```bash
npm run migrate
npm start npm start
``` ```
应用运行在 `http://localhost:3000`,API 在 `http://localhost:3000/api`。 应用运行在 `http://localhost:3000`,API 在 `http://localhost:3000/api`。
#### 创建第一个管理员
站点默认没有任何管理员。首次部署时在 `.env` 中设置一个强随机
`ADMIN_BOOTSTRAP_TOKEN`,然后在注册页面的「管理员初始化令牌」一栏填入
相同的值完成注册,该账号即成为管理员。
管理员只能这样创建:普通注册一律是普通用户,且系统存在管理员后,
引导令牌不再生效。初始化完成后请从 `.env` 中删除该变量并重启服务。
#### 前端配置 #### 前端配置
前端页面为 `index.html`,相关行为可在 `config.js` 中调整: 前端页面为 `index.html`,相关行为可在 `config.js` 中调整:
@@ -87,12 +176,275 @@ npm start
|--------|--------|------| |--------|--------|------|
| `FORUM_NAME` | `Forumlify` | 论坛名称(左上角显示) | | `FORUM_NAME` | `Forumlify` | 论坛名称(左上角显示) |
| `ENABLE_CAPTCHA` | `true` | 发帖/注册的人机验证(10 以内加减法) | | `ENABLE_CAPTCHA` | `true` | 发帖/注册的人机验证(10 以内加减法) |
| `SERVER_PORT` | `null` | 可选:服务端监听端口(仅服务端读取,浏览器端忽略)。优先级:环境变量 `PORT` > `SERVER_PORT` > 默认 `3000`。设为 `null` 时使用环境变量或默认值 | | `SERVER_PORT` | `null` | 可选:服务端监听端口。优先级:环境变量 `PORT` > `SERVER_PORT` > 默认 `3000` |
#### 上传目录 #### 上传目录
帖子图片默认保存在 `uploads/` 目录(Docker 部署时通过 volume 挂载到 `/app/uploads`),源码部署时请确保该目录有写入权限: 帖子图片默认保存在 `uploads/` 目录,请确保该目录有写入权限:
```bash ```bash
mkdir -p uploads && chmod 755 uploads mkdir -p uploads && chmod 755 uploads
``` ```
#### 反向代理与 HTTPS
生产环境建议让 Nginx 终止 TLS 并反代到本机的 3000 端口。要点如下:
```nginx
server {
listen 443 ssl http2;
server_name lite.example.org;
ssl_certificate /etc/nginx/ssl/lite.example.org.fullchain.pem;
ssl_certificate_key /etc/nginx/ssl/lite.example.org.key;
# 保留 ACME 挑战路径,否则证书续期会失败
location /.well-known/acme-challenge/ {
root /var/www/acme;
}
location / {
proxy_pass http://127.0.0.1:3000;
proxy_http_version 1.1;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Forwarded-Proto $scheme;
}
}
```
配套设置 `.env` 中的 `TRUST_PROXY=true`,否则限流会把所有用户识别为
同一个来源 IP。应用记录审计日志时也依赖该设置取到真实客户端地址。
两个容易踩的坑:
- **80 端口若已存在其他站点的 `default_server`**,它会接管所有未显式
匹配的 Host,导致本域名的 ACME 挑战请求被 301 跳走、证书签发失败。
必须为本域名单独写一个 `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。
> 排错时最有效的两步:先在后台点**发送测试邮件**看具体报错,
> 再对照上表定位。中间的错误提示会直接给出去改哪个字段。
## 📁 项目结构
```
public/
├── index.html # 前端页面
├── 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
│ └── 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 # 主入口、路由、Toast、确认框
├── admin.js # 管理后台各标签页
├── api.js # 接口封装
├── auth.js # 登录、注册、退出
├── captcha.js # 人机验证
├── feed.js # 帖子列表
├── i18n.js # 中英文词典与外挂翻译
├── icons.js # SVG 图标
├── post.js # 帖子详情与回复
├── security.js # 转义与安全渲染
├── theme.js # 亮色/暗色切换
└── user.js # 用户主页
```
## ❓ 常见问题
**升级代码后,登录之后的接口全部返回 500?**
说明数据库缺少 `users.token_version` 或 `event_logs` 的审计字段。执行
`npm run migrate` 应用 `migrations/` 中的修复迁移即可,无需重建数据库。
若该库曾经手工执行过 `schema.sql`,迁移记录可能与实际结构不一致,可先
检查 `SELECT * FROM schema_migrations;`。
**忘记了管理员密码?**
两种方式:若已配置邮件,在登录页的「忘记密码」用邮箱验证码重置;
否则使用注册后在设置页生成的恢复码重置。恢复码建议生成后立即离线保存。
**修改密码或邮箱后被登出?**
这两个操作会递增 `users.token_version` 使所有已签发的令牌失效,属于预期
行为;服务端会随响应补发一个新令牌,前端会自动保存并保持在登录状态。
若仍被登出,请强制刷新页面(Ctrl+F5)以载入最新的前端脚本。
**注册框里看不到邮箱验证码输入框?**
这是正常的。该字段仅在管理后台开启了「要求注册时验证邮箱」、
且 SMTP 配置完整时才显示。未配置邮件时注册流程与以往一致。
**开启了邮箱验证,但收不到验证码?**
先在后台点「发送测试邮件」确认 SMTP 可用。若测试邮件能收到而验证码
收不到,检查是否被投进了垃圾箱;若用的是自建发信域名,还需配置 SPF
与 DKIM 记录,否则容易进垃圾箱或被直接拒收。
**用 Resend 发送失败?**
按顺序检查三项:用户名必须是 `resend`(不是你的邮箱)、密码必须是
`re_` 开头的 API Key、发件人邮箱必须属于已在 Resend 验证过的域名。
若尚未验证域名,Resend 只允许发往账号注册邮箱,发给其他地址会被拒。
**怎么确认 SMTP 是通的?**
后台「发送测试邮件」默认发到当前管理员的邮箱。收到即表示配置可用,
不必开启注册验证去试探。
**邮件相关接口返回 429?**
发送验证码与找回密码的接口有独立限流(15 分钟 5 次),用于防止被当作
垃圾邮件发射器。稍后再试即可。
**改动 SMTP 配置后没有生效?**
配置保存在数据库中,保存即时生效,无需重启。若填了新的密码但仍是旧
行为,确认密码栏确实填入了新值——留空表示保持原密码不变。
## 📝 License
MIT
+37 -10
View File
@@ -1,27 +1,54 @@
version: '3'
services: services:
db: db:
image: postgres:15 image: postgres:15.14-alpine
restart: unless-stopped
environment: environment:
POSTGRES_USER: forumlify POSTGRES_USER: forumlify
POSTGRES_PASSWORD: 123456 POSTGRES_PASSWORD: ${POSTGRES_PASSWORD:?Set POSTGRES_PASSWORD in .env}
POSTGRES_DB: forumlify POSTGRES_DB: forumlify
volumes: volumes:
- ./schema.sql:/docker-entrypoint-initdb.d/schema.sql
- db_data:/var/lib/postgresql/data - db_data:/var/lib/postgresql/data
ports:
- "5432:5432" healthcheck:
test: ["CMD-SHELL", "pg_isready -U forumlify -d forumlify"]
interval: 5s
timeout: 5s
retries: 10
start_period: 10s
app: app:
build: . build:
context: .
dockerfile: Dockerfile
restart: unless-stopped
ports: ports:
- "3003:3000" - "${PORT:-3000}:3000"
depends_on: depends_on:
- db db:
condition: service_healthy
environment: environment:
DATABASE_URL: postgresql://forumlify:123456@db:5432/forumlify
NODE_ENV: production
PORT: 3000
PGHOST: db
PGPORT: 5432
PGUSER: forumlify
PGPASSWORD: ${POSTGRES_PASSWORD:?Set POSTGRES_PASSWORD in .env}
PGDATABASE: forumlify
JWT_SECRET: ${JWT_SECRET:?Set JWT_SECRET in .env}
ADMIN_BOOTSTRAP_TOKEN: ${ADMIN_BOOTSTRAP_TOKEN:-}
ENABLE_CAPTCHA: "true"
TRUST_PROXY: "true"
volumes: volumes:
- ./uploads:/app/uploads - ./uploads:/app/uploads
healthcheck:
test: ["CMD", "node", "scripts/healthcheck.js"]
interval: 30s
timeout: 5s
retries: 3
start_period: 30s
volumes: volumes:
db_data: db_data:
-7
View File
@@ -1,7 +0,0 @@
FROM node:18-alpine
WORKDIR /app
COPY package*.json ./
RUN npm install
COPY . .
EXPOSE 3000
CMD ["npm", "start"]
+264 -70
View File
@@ -4,10 +4,24 @@
<meta charset="UTF-8" /> <meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title id="pageTitle">Forumlify</title> <title id="pageTitle">Forumlify</title>
<script>
(function() {
const theme = localStorage.getItem('forumlify-theme');
if (theme === 'dark') {
// 直接改背景色,不让白屏出现
document.documentElement.style.background = '#0f1117';
document.documentElement.style.color = '#e8edf5';
// 预置暗色属性,防止闪烁
document.documentElement.setAttribute('data-theme', 'dark');
}
})();
</script>
<script src="https://cdn.jsdelivr.net/npm/marked/marked.min.js"></script> <script src="https://cdn.jsdelivr.net/npm/marked/marked.min.js"></script>
<link rel="stylesheet" href="style.css" /> <link rel="stylesheet" href="style.css" />
</head> </head>
<body> <body style="opacity:0;">
<!-- ===== 导航栏 ===== --> <!-- ===== 导航栏 ===== -->
<nav id="navbar"> <nav id="navbar">
@@ -69,7 +83,6 @@
<div class="stat-item"><span>主题</span><span id="statTopics">0</span></div> <div class="stat-item"><span>主题</span><span id="statTopics">0</span></div>
<div class="stat-item"><span>帖子</span><span id="statPosts">0</span></div> <div class="stat-item"><span>帖子</span><span id="statPosts">0</span></div>
<div class="stat-item"><span>用户</span><span id="statUsers">0</span></div> <div class="stat-item"><span>用户</span><span id="statUsers">0</span></div>
<div class="stat-item"><span>在线</span><span id="statOnline">0</span></div>
</div> </div>
<div class="links-box"> <div class="links-box">
<h4> <h4>
@@ -88,13 +101,57 @@
<button class="tab active" data-sort="latest">最新发布</button> <button class="tab active" data-sort="latest">最新发布</button>
<button class="tab" data-sort="hot">最新回复</button> <button class="tab" data-sort="hot">最新回复</button>
</div> </div>
<div class="feed-search">
<!-- 防止密码管理器误填:Chrome 等对 autocomplete="off" 常忽略,
因此叠加多重标识——语义化的 role/type、不易被判定为账号
字段的 name,以及 1Password / LastPass 识别的 data 属性。
同时把三个含密码的模态框改成真正的 <form>,让密码管理器
有明确的表单边界,不再靠启发式猜测波及搜索框。 -->
<input type="search" id="postSearchInput" name="post-search-query"
placeholder="搜索帖子…" autocomplete="off" autocorrect="off"
autocapitalize="off" spellcheck="false"
role="searchbox" aria-label="搜索帖子"
data-form-type="other" data-1p-ignore data-lpignore="true" />
<button id="postSearchClear" class="feed-search-clear" type="button" title="清除搜索" style="display:none;">
<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"><line x1="18" y1="6" x2="6" y2="18"/><line x1="6" y1="6" x2="18" y2="18"/></svg>
</button>
</div>
<button id="fab" class="btn-primary fab-btn"> <button id="fab" class="btn-primary fab-btn">
<svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><line x1="12" y1="5" x2="12" y2="19"/><line x1="5" y1="12" x2="19" y2="12"/></svg> <svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><line x1="12" y1="5" x2="12" y2="19"/><line x1="5" y1="12" x2="19" y2="12"/></svg>
发布新帖 发布新帖
</button> </button>
</div> </div>
<div id="postList"> <div id="postList">
<div style="text-align:center;color:#94a3b8;padding:40px 0;">加载中...</div> <!-- 骨架屏直接写在标记里,保证首帧即可见。
若留空或写「加载中...」文字,会先闪一帧空白/文字再被
JS 替换成骨架,实测有 18ms 的可见闪动。 -->
<div class="skeleton-card">
<div class="skeleton-header">
<div class="skeleton-avatar"></div>
<div class="skeleton-line w-30" style="margin-bottom:0;"></div>
</div>
<div class="skeleton-line skeleton-title w-60"></div>
<div class="skeleton-line w-100"></div>
<div class="skeleton-line w-80"></div>
</div>
<div class="skeleton-card">
<div class="skeleton-header">
<div class="skeleton-avatar"></div>
<div class="skeleton-line w-30" style="margin-bottom:0;"></div>
</div>
<div class="skeleton-line skeleton-title w-60"></div>
<div class="skeleton-line w-100"></div>
<div class="skeleton-line w-80"></div>
</div>
<div class="skeleton-card">
<div class="skeleton-header">
<div class="skeleton-avatar"></div>
<div class="skeleton-line w-30" style="margin-bottom:0;"></div>
</div>
<div class="skeleton-line skeleton-title w-60"></div>
<div class="skeleton-line w-100"></div>
<div class="skeleton-line w-80"></div>
</div>
</div> </div>
</main> </main>
</div> </div>
@@ -115,53 +172,122 @@
<!-- 设置页面 --> <!-- 设置页面 -->
<div id="pageSettings" class="page-slide"> <div id="pageSettings" class="page-slide">
<div class="page-header" style="max-width:500px;margin:0 auto;width:100%;"> <div class="page-header" style="max-width:1200px;margin:0 auto;width:100%;">
<button class="back-btn">
<svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><polyline points="15 18 9 12 15 6"/></svg>
返回
</button>
<h2> <h2>
<svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M12.22 2h-.44a2 2 0 0 0-2 2v.18a2 2 0 0 1-1 1.73l-.43.25a2 2 0 0 1-2 0l-.15-.08a2 2 0 0 0-2.73.73l-.22.38a2 2 0 0 0 .73 2.73l.15.1a2 2 0 0 1 1 1.72v.51a2 2 0 0 1-1 1.74l-.15.09a2 2 0 0 0-.73 2.73l.22.38a2 2 0 0 0 2.73.73l.15-.08a2 2 0 0 1 2 0l.43.25a2 2 0 0 1 1 1.73V20a2 2 0 0 0 2 2h.44a2 2 0 0 0 2-2v-.18a2 2 0 0 1 1-1.73l.43-.25a2 2 0 0 1 2 0l.15.08a2 2 0 0 0 2.73-.73l.22-.39a2 2 0 0 0-.73-2.73l-.15-.08a2 2 0 0 1-1-1.74v-.5a2 2 0 0 1 1-1.74l.15-.09a2 2 0 0 0 .73-2.73l-.22-.38a2 2 0 0 0-2.73-.73l-.15.08a2 2 0 0 1-2 0l-.43-.25a2 2 0 0 1-1-1.73V4a2 2 0 0 0-2-2z"/><circle cx="12" cy="12" r="3"/></svg> <svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M12.22 2h-.44a2 2 0 0 0-2 2v.18a2 2 0 0 1-1 1.73l-.43.25a2 2 0 0 1-2 0l-.15-.08a2 2 0 0 0-2.73.73l-.22.38a2 2 0 0 0 .73 2.73l.15.1a2 2 0 0 1 1 1.72v.51a2 2 0 0 1-1 1.74l-.15.09a2 2 0 0 0-.73 2.73l.22.38a2 2 0 0 0 2.73.73l.15-.08a2 2 0 0 1 2 0l.43.25a2 2 0 0 1 1 1.73V20a2 2 0 0 0 2 2h.44a2 2 0 0 0 2-2v-.18a2 2 0 0 1 1-1.73l.43-.25a2 2 0 0 1 2 0l.15.08a2 2 0 0 0 2.73-.73l.22-.39a2 2 0 0 0-.73-2.73l-.15-.08a2 2 0 0 1-1-1.74v-.5a2 2 0 0 1 1-1.74l.15-.09a2 2 0 0 0 .73-2.73l-.22-.38a2 2 0 0 0-2.73-.73l-.15.08a2 2 0 0 1-2 0l-.43-.25a2 2 0 0 1-1-1.73V4a2 2 0 0 0-2-2z"/><circle cx="12" cy="12" r="3"/></svg>
设置 设置
</h2> </h2>
</div> </div>
<div id="settingsContent" style="max-width:500px;margin:0 auto;width:100%;">
<div style="text-align:center;color:#94a3b8;padding:40px 0;">加载中...</div> <!-- 侧边栏布局 -->
<div class="settings-layout" style="max-width:1200px;margin:0 auto;width:100%;display:flex;gap:28px;align-items:flex-start;">
<!-- 左侧:侧边栏 -->
<aside class="settings-sidebar" style="width:200px;flex-shrink:0;background:var(--glass-bg);backdrop-filter:blur(16px);-webkit-backdrop-filter:blur(16px);border:1px solid var(--glass-border);border-radius:var(--radius);padding:8px 0;box-shadow:var(--glass-shadow);position:sticky;top:84px;">
<nav class="settings-nav">
<a href="#" class="settings-nav-item active" data-settings-tab="profile">
<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="M20 21v-2a4 4 0 0 0-4-4H8a4 4 0 0 0-4 4v2"/><circle cx="12" cy="7" r="4"/></svg>
</span>
个人资料
</a>
<a href="#" class="settings-nav-item" data-settings-tab="security">
<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="M12 22s8-4 8-10V5l-8-3-8 3v7c0 6 8 10 8 10z"/><path d="M12 8v4"/><path d="M12 16h.01"/></svg>
</span>
安全设置
</a>
<a href="#" class="settings-nav-item" data-settings-tab="recovery">
<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"><rect x="3" y="11" width="18" height="11" rx="2" ry="2"/><path d="M7 11V7a5 5 0 0 1 10 0v4"/></svg>
</span>
恢复码
</a>
</nav>
</aside>
<!-- 右侧:内容区 -->
<main class="settings-content" style="flex:1;min-width:0;background:var(--glass-bg);backdrop-filter:blur(16px);-webkit-backdrop-filter:blur(16px);border:1px solid var(--glass-border);border-radius:var(--radius);padding:20px 24px;box-shadow:var(--glass-shadow);">
<div id="settingsContent">
<div style="text-align:center;color:#94a3b8;padding:40px 0;">加载中...</div>
</div>
</main>
</div> </div>
</div> </div>
<!-- 管理后台 --> <!-- 管理后台 -->
<div id="pageAdmin" class="page-slide"> <div id="pageAdmin" class="page-slide">
<div class="page-header" style="max-width:900px;margin:0 auto;width:100%;"> <div class="page-header" style="max-width:1200px;margin:0 auto;width:100%;">
<button class="back-btn">
<svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><polyline points="15 18 9 12 15 6"/></svg>
返回
</button>
<h2> <h2>
<svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><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> <svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><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>
管理后台 管理后台
</h2> </h2>
</div> </div>
<div class="admin-tabs" style="max-width:900px;margin:0 auto;width:100%;">
<button class="admin-tab active" data-tab="reports"> <!-- 侧边栏布局 -->
<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"><path d="M12 22s8-4 8-10V5l-8-3-8 3v7c0 6 8 10 8 10z"/></svg> <div class="admin-layout" style="max-width:1200px;margin:0 auto;width:100%;">
举报 <aside class="admin-sidebar">
</button> <nav class="admin-nav">
<button class="admin-tab" data-tab="users"> <a href="#" class="admin-nav-item active" data-tab="reports">
<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"><path d="M17 21v-2a4 4 0 0 0-4-4H5a4 4 0 0 0-4 4v2"/><circle cx="9" cy="7" r="4"/><path d="M23 21v-2a4 4 0 0 0-3-3.87"/><path d="M16 3.13a4 4 0 0 1 0 7.75"/></svg> <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="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> </span>
<button class="admin-tab" data-tab="logs"> 举报
<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"><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> </a>
日志 <a href="#" class="admin-nav-item" data-tab="users">
</button> <span class="nav-icon">
<button class="admin-tab" data-tab="links"> <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="M17 21v-2a4 4 0 0 0-4-4H5a4 4 0 0 0-4 4v2"/><circle cx="9" cy="7" r="4"/><path d="M23 21v-2a4 4 0 0 0-3-3.87"/><path d="M16 3.13a4 4 0 0 1 0 7.75"/></svg>
<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"><path d="M10 13a5 5 0 0 0 7.54.54l3-3a5 5 0 0 0-7.07-7.07l-1.72 1.71"/><path d="M14 11a5 5 0 0 0-7.54-.54l-3 3a5 5 0 0 0 7.07 7.07l1.71-1.71"/></svg> </span>
友链 用户
</button> </a>
<button class="admin-tab" data-tab="settings"> <a href="#" class="admin-nav-item" data-tab="logs">
<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"><path d="M12.22 2h-.44a2 2 0 0 0-2 2v.18a2 2 0 0 1-1 1.73l-.43.25a2 2 0 0 1-2 0l-.15-.08a2 2 0 0 0-2.73.73l-.22.38a2 2 0 0 0 .73 2.73l.15.1a2 2 0 0 1 1 1.72v.51a2 2 0 0 1-1 1.74l-.15.09a2 2 0 0 0-.73 2.73l.22.38a2 2 0 0 0 2.73.73l.15-.08a2 2 0 0 1 2 0l.43.25a2 2 0 0 1 1 1.73V20a2 2 0 0 0 2 2h.44a2 2 0 0 0 2-2v-.18a2 2 0 0 1 1-1.73l.43-.25a2 2 0 0 1 2 0l.15.08a2 2 0 0 0 2.73-.73l.22-.39a2 2 0 0 0-.73-2.73l-.15-.08a2 2 0 0 1-1-1.74v-.5a2 2 0 0 1 1-1.74l.15-.09a2 2 0 0 0 .73-2.73l-.22-.38a2 2 0 0 0-2.73-.73l-.15.08a2 2 0 0 1-2 0l-.43-.25a2 2 0 0 1-1-1.73V4a2 2 0 0 0-2-2z"/><circle cx="12" cy="12" r="3"/></svg> <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>
</button> </span>
<button class="admin-tab" data-tab="custom"> 日志
<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"><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> </a>
自定义页面 <a href="#" class="admin-nav-item" data-tab="links">
</button> <span class="nav-icon">
</div> <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="M10 13a5 5 0 0 0 7.54.54l3-3a5 5 0 0 0-7.07-7.07l-1.72 1.71"/><path d="M14 11a5 5 0 0 0-7.54-.54l-3 3a5 5 0 0 0 7.07 7.07l1.71-1.71"/></svg>
<div id="adminContent" style="max-width:900px;margin:0 auto;width:100%;"> </span>
<div style="text-align:center;color:#94a3b8;padding:40px 0;">加载中...</div> 友链
</a>
<a href="#" class="admin-nav-item" data-tab="custom-css">
<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"><polyline points="16 18 22 12 16 6"/><polyline points="8 6 2 12 8 18"/></svg>
</span>
自定义 CSS
</a>
<a href="#" class="admin-nav-item" data-tab="settings">
<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="M12.22 2h-.44a2 2 0 0 0-2 2v.18a2 2 0 0 1-1 1.73l-.43.25a2 2 0 0 1-2 0l-.15-.08a2 2 0 0 0-2.73.73l-.22.38a2 2 0 0 0 .73 2.73l.15.1a2 2 0 0 1 1 1.72v.51a2 2 0 0 1-1 1.74l-.15.09a2 2 0 0 0-.73 2.73l.22.38a2 2 0 0 0 2.73.73l.15-.08a2 2 0 0 1 2 0l.43.25a2 2 0 0 1 1 1.73V20a2 2 0 0 0 2 2h.44a2 2 0 0 0 2-2v-.18a2 2 0 0 1 1-1.73l.43-.25a2 2 0 0 1 2 0l.15.08a2 2 0 0 0 2.73-.73l.22-.39a2 2 0 0 0-.73-2.73l-.15-.08a2 2 0 0 1-1-1.74v-.5a2 2 0 0 1 1-1.74l.15-.09a2 2 0 0 0 .73-2.73l-.22-.38a2 2 0 0 0-2.73-.73l-.15.08a2 2 0 0 1-2 0l-.43-.25a2 2 0 0 1-1-1.73V4a2 2 0 0 0-2-2z"/><circle cx="12" cy="12" r="3"/></svg>
</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>
</span>
自定义页面
</a>
</nav>
</aside>
<main class="admin-content" id="adminContent">
<div style="text-align:center;color:#94a3b8;padding:40px 0;">加载中...</div>
</main>
</div> </div>
</div> </div>
@@ -195,30 +321,60 @@
<!-- 帖子详情页 --> <!-- 帖子详情页 -->
<div id="pagePost" class="page-slide"> <div id="pagePost" class="page-slide">
<div class="page-header" style="max-width:700px;margin:0 auto;width:100%;"> <div class="page-header" style="max-width:1200px;margin:0 auto;width:100%;">
<button class="back-btn">
<svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><polyline points="15 18 9 12 15 6"/></svg>
返回
</button>
<h2 id="postDetailTitle">帖子详情</h2> <h2 id="postDetailTitle">帖子详情</h2>
</div> </div>
<div id="postDetailContent" style="max-width:700px;margin:0 auto;width:100%;">
<div style="text-align:center;color:#94a3b8;padding:40px 0;">加载中...</div> <div class="post-detail-layout" style="max-width:1200px;margin:0 auto;width:100%;display:flex;gap:28px;align-items:flex-start;">
</div> <aside id="postSidebar" style="width:240px;flex-shrink:0;">
<div id="replyArea" style="max-width:700px;margin:0 auto;width:100%;margin-top:24px;border-top:1px solid #e2e8f0;padding-top:20px;display:none;"> <div class="stats-box">
<h3 style="font-size:16px;margin-bottom:12px;"> <h4>
<svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" 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> <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"><path d="M21 12V7H5a2 2 0 0 1 0-4h14v4"/><path d="M3 5v14a2 2 0 0 0 2 2h16v-5"/><line x1="18" y1="12" x2="18" y2="12"/></svg>
发表回复 社区统计
</h3> </h4>
<textarea id="replyContent" rows="3" placeholder="写下你的回复..." style="width:100%;padding:10px 12px;border:1px solid #e2e8f0;border-radius:4px;font-size:14px;font-family:inherit;resize:vertical;"></textarea> <div class="stat-item"><span>主题</span><span id="statTopics2">0</span></div>
<div class="captcha-row" style="margin:10px 0;"> <div class="stat-item"><span>帖子</span><span id="statPosts2">0</span></div>
<span id="replyCaptchaQuestion">3 + 5 = ?</span> <div class="stat-item"><span>用户</span><span id="statUsers2">0</span></div>
<input type="text" id="replyCaptchaInput" placeholder="答案" style="width:80px;padding:8px 12px;border:1px solid #e2e8f0;border-radius:4px;" /> </div>
</div> <div class="links-box">
<button id="replySubmit" class="btn-primary" style="padding:8px 24px;">提交回复</button> <h4>
<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"><path d="M10 13a5 5 0 0 0 7.54.54l3-3a5 5 0 0 0-7.07-7.07l-1.72 1.71"/><path d="M14 11a5 5 0 0 0-7.54-.54l-3 3a5 5 0 0 0 7.07 7.07l1.71-1.71"/></svg>
友情链接
</h4>
<ul id="friendlyLinks2">
<li style="color:#94a3b8;font-size:13px;">暂无链接</li>
</ul>
</div>
</aside>
<main style="flex:1;min-width:0;">
<div id="postDetailContent">
<div style="text-align:center;color:#94a3b8;padding:40px 0;">加载中...</div>
</div>
<div id="replyArea" style="margin-top:24px;border-top:1px solid var(--glass-border);padding-top:20px;display:none;">
<h3 style="font-size:16px;font-weight:600;margin-bottom:14px;color:var(--glass-text);">
<svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" 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>
发表回复
</h3>
<textarea id="replyContent" rows="3" placeholder="写下你的回复..." style="width:100%;padding:12px 16px;background:rgba(255,255,255,0.1);backdrop-filter:blur(8px);-webkit-backdrop-filter:blur(8px);border:1px solid var(--glass-border);border-radius:var(--radius-sm);font-size:14px;font-family:inherit;resize:vertical;color:var(--glass-text);transition:all var(--transition);"></textarea>
<div class="captcha-row" style="margin:10px 0;">
<span id="replyCaptchaQuestion">3 + 5 = ?</span>
<input type="text" id="replyCaptchaInput" placeholder="答案" style="width:80px;padding:8px 12px;background:rgba(255,255,255,0.12);backdrop-filter:blur(8px);-webkit-backdrop-filter:blur(8px);border:1px solid var(--glass-border);border-radius:var(--radius-sm);color:var(--glass-text);" />
</div>
<button id="replySubmit" class="btn-primary" style="padding:8px 24px;">提交回复</button>
</div>
</main>
</div> </div>
</div> </div>
<!-- 用户主页 --> <!-- 用户主页 -->
<div id="pageUser" class="page-slide"> <div id="pageUser" class="page-slide">
<div class="page-header" style="max-width:700px;margin:0 auto;width:100%;"> <div class="page-header" style="max-width:700px;margin:0 auto;width:100%;">
<button class="back-btn" onclick="switchPage('feed')"> <button class="back-btn">
<svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><polyline points="15 18 9 12 15 6"/></svg> <svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><polyline points="15 18 9 12 15 6"/></svg>
返回 返回
</button> </button>
@@ -237,12 +393,18 @@
<svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><line x1="18" y1="6" x2="6" y2="18"/><line x1="6" y1="6" x2="18" y2="18"/></svg> <svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><line x1="18" y1="6" x2="6" y2="18"/><line x1="6" y1="6" x2="18" y2="18"/></svg>
</span> </span>
<h2 style="margin-bottom:16px;">登录</h2> <h2 style="margin-bottom:16px;">登录</h2>
<input type="email" id="loginEmail" placeholder="邮箱" /> <!-- 用真正的 form 包裹:页面此前完全没有 form 标签,密码管理器
<input type="password" id="loginPassword" placeholder="密码" /> 找不到表单边界,只能靠启发式猜测,会把页面上的其他文本框
<div style="text-align:center;margin-top:8px;"> (如首页搜索框)也当作账号字段填入。
<a href="#" id="forgotPasswordLink" style="color:var(--primary);font-size:13px;text-decoration:none;">忘记密码?</a> autocomplete 采用标准值,帮助密码管理器准确定位。 -->
</div> <form id="loginForm" autocomplete="on">
<button id="loginSubmit" class="btn-primary" style="width:100%;margin-top:8px;">登录</button> <input type="email" id="loginEmail" name="email" placeholder="邮箱" autocomplete="username" />
<input type="password" id="loginPassword" name="password" placeholder="密码" autocomplete="current-password" />
<div style="text-align:center;margin-top:8px;">
<a href="#" id="forgotPasswordLink" style="color:var(--primary);font-size:13px;text-decoration:none;">忘记密码?</a>
</div>
<button type="submit" id="loginSubmit" class="btn-primary" style="width:100%;margin-top:8px;">登录</button>
</form>
</div> </div>
</div> </div>
@@ -253,14 +415,21 @@
<svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><line x1="18" y1="6" x2="6" y2="18"/><line x1="6" y1="6" x2="18" y2="18"/></svg> <svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><line x1="18" y1="6" x2="6" y2="18"/><line x1="6" y1="6" x2="18" y2="18"/></svg>
</span> </span>
<h2 style="margin-bottom:16px;">注册</h2> <h2 style="margin-bottom:16px;">注册</h2>
<input type="text" id="regUsername" placeholder="用户名" /> <form id="registerForm" autocomplete="on">
<input type="email" id="regEmail" placeholder="邮箱" /> <input type="text" id="regUsername" name="username" placeholder="用户名" autocomplete="username" />
<input type="password" id="regPassword" placeholder="密码(至少6位)" /> <input type="email" id="regEmail" name="email" placeholder="邮箱" autocomplete="email" />
<div class="captcha-row"> <input type="password" id="regPassword" name="password" placeholder="密码(至少6位)" autocomplete="new-password" />
<span id="regCaptchaQuestion">3 + 5 = ?</span> <input type="password" id="regBootstrapToken" placeholder="管理员初始化令牌" autocomplete="off" style="display:none;" />
<input type="text" id="regCaptchaInput" placeholder="答案" style="width:80px;" /> <div id="regEmailCodeRow" class="email-code-row">
</div> <input type="text" id="regEmailCode" placeholder="邮箱验证码" autocomplete="one-time-code" />
<button id="registerSubmit" class="btn-primary" style="width:100%;">注册</button> <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="答案" autocomplete="off" style="width:80px;" />
</div>
<button type="submit" id="registerSubmit" class="btn-primary" style="width:100%;">注册</button>
</form>
</div> </div>
</div> </div>
@@ -294,11 +463,13 @@
</span> </span>
<h2 style="margin-bottom:16px;">🔑 重置密码</h2> <h2 style="margin-bottom:16px;">🔑 重置密码</h2>
<p style="font-size:14px;color:var(--text-secondary);margin-bottom:16px;">输入你的邮箱和一个未使用的恢复码</p> <p style="font-size:14px;color:var(--text-secondary);margin-bottom:16px;">输入你的邮箱和一个未使用的恢复码</p>
<input type="email" id="resetEmail" placeholder="邮箱" /> <form id="forgotPasswordForm" autocomplete="on">
<input type="text" id="resetRecoveryCode" placeholder="恢复码(格式:ABCD-1234-EFGH-5678)" style="font-family:monospace;letter-spacing:0.5px;" /> <input type="email" id="resetEmail" name="email" placeholder="邮箱" autocomplete="email" />
<input type="password" id="resetNewPassword" placeholder="新密码(至少6位)" /> <input type="text" id="resetRecoveryCode" placeholder="恢复码(格式:ABCD-1234-EFGH-5678)" autocomplete="off" style="font-family:monospace;letter-spacing:0.5px;" />
<button id="resetPasswordSubmit" class="btn-primary" style="width:100%;">重置密码</button> <input type="password" id="resetNewPassword" name="new-password" placeholder="新密码(至少6位)" autocomplete="new-password" />
<div id="resetStatus" style="font-size:14px;margin-top:8px;text-align:center;"></div> <button type="submit" id="resetPasswordSubmit" class="btn-primary" style="width:100%;">重置密码</button>
<div id="resetStatus" style="font-size:14px;margin-top:8px;text-align:center;"></div>
</form>
</div> </div>
</div> </div>
@@ -309,6 +480,23 @@
<h2 style="font-size:18px;margin:0;">✉️ 私信</h2> <h2 style="font-size:18px;margin:0;">✉️ 私信</h2>
<span class="close" data-modal="messageListModal" style="font-size:24px;cursor:pointer;color:var(--text-light);line-height:1;">&times;</span> <span class="close" data-modal="messageListModal" style="font-size:24px;cursor:pointer;color:var(--text-light);line-height:1;">&times;</span>
</div> </div>
<!-- 用户搜索:此前只能从对方主页点「私信」才能发起会话,
这里提供按用户名搜索并直接开聊的入口 -->
<div class="dm-search-wrap">
<div class="dm-search">
<input type="search" id="dmUserSearchInput" name="dm-user-search"
placeholder="搜索用户名开始私信…" autocomplete="off"
role="searchbox" aria-label="搜索用户"
data-form-type="other" data-1p-ignore data-lpignore="true" />
<button type="button" id="dmUserSearchClear" class="dm-search-clear" title="清除搜索" style="display:none;">
<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"><line x1="18" y1="6" x2="6" y2="18"/><line x1="6" y1="6" x2="18" y2="18"/></svg>
</button>
</div>
<div class="dm-view-switch">
<button type="button" id="dmTabConversations" class="active">会话</button>
<button type="button" id="dmTabBlocked">已屏蔽</button>
</div>
</div>
<div id="messageListContent" style="flex:1;overflow-y:auto;padding:0;"> <div id="messageListContent" style="flex:1;overflow-y:auto;padding:0;">
<div style="text-align:center;color:#94a3b8;padding:40px 0;">加载中...</div> <div style="text-align:center;color:#94a3b8;padding:40px 0;">加载中...</div>
</div> </div>
@@ -328,6 +516,8 @@
<div id="chatMessages" style="flex:1;overflow-y:auto;padding:16px;min-height:300px;max-height:400px;"> <div id="chatMessages" style="flex:1;overflow-y:auto;padding:16px;min-height:300px;max-height:400px;">
<div style="text-align:center;color:#94a3b8;padding:40px 0;">加载中...</div> <div style="text-align:center;color:#94a3b8;padding:40px 0;">加载中...</div>
</div> </div>
<!-- 对方回复前的发送条数提示,由 JS 控制显示 -->
<div id="chatLimitNote" class="dm-limit-note" style="display:none;"></div>
<div style="display:flex;gap:8px;padding:12px 16px;border-top:1px solid var(--border);flex-shrink:0;"> <div style="display:flex;gap:8px;padding:12px 16px;border-top:1px solid var(--border);flex-shrink:0;">
<input type="text" id="chatInput" placeholder="输入消息..." style="flex:1;padding:8px 12px;border:1px solid var(--border);border-radius:6px;font-size:14px;background:var(--bg);color:var(--text);outline:none;" /> <input type="text" id="chatInput" placeholder="输入消息..." style="flex:1;padding:8px 12px;border:1px solid var(--border);border-radius:6px;font-size:14px;background:var(--bg);color:var(--text);outline:none;" />
<button onclick="sendMessage()" class="btn-primary" style="padding:8px 16px;">发送</button> <button onclick="sendMessage()" class="btn-primary" style="padding:8px 16px;">发送</button>
@@ -339,6 +529,10 @@
<!-- ⚙️ 引用 JS --> <!-- ⚙️ 引用 JS -->
<!-- ========================================================== --> <!-- ========================================================== -->
<script src="config.js"></script> <script src="config.js"></script>
<script src="js/icons.js"></script>
<script src="js/i18n.js"></script>
<script src="js/security.js"></script>
<script src="js/skeleton.js"></script>
<script src="js/api.js"></script> <script src="js/api.js"></script>
<script src="js/theme.js"></script> <script src="js/theme.js"></script>
<script src="js/captcha.js"></script> <script src="js/captcha.js"></script>
+725 -118
View File
File diff suppressed because it is too large. Load diff
+214 -22
View File
@@ -3,15 +3,17 @@
// ============================================================ // ============================================================
let token = localStorage.getItem('forumlify-token') || null; let token = localStorage.getItem('forumlify-token') || null;
function getAuthHeaders() {
return token ? { 'Authorization': 'Bearer ' + token } : {};
}
function apiFetch(path, options = {}) { function apiFetch(path, options = {}) {
const url = CONFIG.API_BASE_URL + path; const url = CONFIG.API_BASE_URL + path;
const headers = { const headers = {
'Content-Type': 'application/json', 'Content-Type': 'application/json',
...getAuthHeaders(),
...(options.headers || {}) ...(options.headers || {})
}; };
if (token) {
headers['Authorization'] = 'Bearer ' + token;
}
return fetch(url, { return fetch(url, {
...options, ...options,
headers headers
@@ -35,10 +37,16 @@ const API = {
return data; return data;
}, },
async register(email, password, username) { async register(email, password, username, bootstrapToken = '', emailCode = '') {
const data = await apiFetch('/auth/register', { const data = await apiFetch('/auth/register', {
method: 'POST', method: 'POST',
body: JSON.stringify({ email, password, username }) body: JSON.stringify({
email,
password,
username,
bootstrap_token: bootstrapToken || undefined,
email_code: emailCode || undefined
})
}); });
if (data.error) throw new Error(data.error); if (data.error) throw new Error(data.error);
return data; return data;
@@ -65,6 +73,15 @@ const API = {
return data; return data;
}, },
// 搜索帖子(标题与正文)
async searchPosts(keyword, page = 1, limit = 20) {
const data = await apiFetch(
'/posts/search?q=' + encodeURIComponent(keyword) + '&page=' + page + '&limit=' + limit
);
if (data.error) throw new Error(data.error);
return data;
},
async getPost(postId) { async getPost(postId) {
const data = await apiFetch('/posts/' + postId); const data = await apiFetch('/posts/' + postId);
if (data.error) throw new Error(data.error); if (data.error) throw new Error(data.error);
@@ -80,6 +97,19 @@ const API = {
return data; 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) { async updatePost(postId, title, content) {
const data = await apiFetch('/posts/' + postId, { const data = await apiFetch('/posts/' + postId, {
method: 'PUT', method: 'PUT',
@@ -95,6 +125,14 @@ const API = {
return data; return data;
}, },
async togglePinPost(postId) {
const data = await apiFetch('/posts/' + postId + '/pin', {
method: 'PUT'
});
if (data.error) throw new Error(data.error);
return data;
},
// ============================================================ // ============================================================
// 回复 // 回复
// ============================================================ // ============================================================
@@ -120,12 +158,12 @@ const API = {
}, },
// ============================================================ // ============================================================
// 用户管理 // 用户管理(支持分页和搜索)
// ============================================================ // ============================================================
async getUsers() { async getUsers(page = 1, limit = 20, search = '') {
const data = await apiFetch('/users'); const data = await apiFetch('/users?page=' + page + '&limit=' + limit + '&search=' + encodeURIComponent(search));
if (data.error) throw new Error(data.error); if (data.error) throw new Error(data.error);
return data || []; return data;
}, },
async updateUserRole(userId, role) { async updateUserRole(userId, role) {
@@ -198,22 +236,14 @@ const API = {
}, },
// ============================================================ // ============================================================
// 事件日志 // 事件日志(支持分页)
// ============================================================ // ============================================================
async getEventLogs() { async getEventLogs(page = 1, limit = 20) {
const data = await apiFetch('/event-logs'); const data = await apiFetch('/event-logs?page=' + page + '&limit=' + limit);
if (data.error) throw new Error(data.error); if (data.error) throw new Error(data.error);
return data || []; return data;
}, },
async logEvent(action) {
try {
await apiFetch('/event-logs', {
method: 'POST',
body: JSON.stringify({ action })
});
} catch (e) { /* 静默失败 */ }
},
// ============================================================ // ============================================================
// 论坛设置 // 论坛设置
@@ -242,6 +272,42 @@ const API = {
return data || []; return data || [];
}, },
// 搜索用户(用于发起私信)。仅返回用户名、头像等公开信息。
async searchUsers(keyword, limit = 10) {
const data = await apiFetch(
'/users/search?q=' + encodeURIComponent(keyword) + '&limit=' + limit
);
if (data.error) throw new Error(data.error);
return data.data || [];
},
// ============================================================
// 用户屏蔽
// ============================================================
async blockUser(userId) {
const data = await apiFetch('/users/' + userId + '/block', { method: 'POST' });
if (data.error) throw new Error(data.error);
return data;
},
async unblockUser(userId) {
const data = await apiFetch('/users/' + userId + '/block', { method: 'DELETE' });
if (data.error) throw new Error(data.error);
return data;
},
async getBlockedUsers() {
const data = await apiFetch('/blocks');
if (data.error) throw new Error(data.error);
return data.data || [];
},
async getBlockStatus(userId) {
const data = await apiFetch('/users/' + userId + '/block-status');
if (data.error) throw new Error(data.error);
return data;
},
async getOrCreateConversation(other_user_id) { async getOrCreateConversation(other_user_id) {
const data = await apiFetch('/conversations', { const data = await apiFetch('/conversations', {
method: 'POST', method: 'POST',
@@ -360,13 +426,23 @@ const API = {
// ============================================================ // ============================================================
// 修改密码和邮箱 // 修改密码和邮箱
// ============================================================ // ============================================================
// 这两个接口会递增 token_version 使旧令牌失效,服务端随即补发一个
// 新令牌。这里必须接住它,否则用户操作成功后会被立刻登出。
_persistRefreshedToken(data) {
if (data && data.token) {
token = data.token;
localStorage.setItem('forumlify-token', token);
}
return data;
},
async changePassword(oldPassword, newPassword) { async changePassword(oldPassword, newPassword) {
const data = await apiFetch('/users/' + currentUser.id + '/password', { const data = await apiFetch('/users/' + currentUser.id + '/password', {
method: 'PUT', method: 'PUT',
body: JSON.stringify({ oldPassword, newPassword }) body: JSON.stringify({ oldPassword, newPassword })
}); });
if (data.error) throw new Error(data.error); if (data.error) throw new Error(data.error);
return data; return this._persistRefreshedToken(data);
}, },
async changeEmail(password, newEmail) { async changeEmail(password, newEmail) {
@@ -375,6 +451,122 @@ const API = {
body: JSON.stringify({ password, newEmail }) body: JSON.stringify({ password, newEmail })
}); });
if (data.error) throw new Error(data.error); 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; return data;
} }
}; };
+1052 -294
View File
File diff suppressed because it is too large. Load diff
+138 -49
View File
@@ -1,19 +1,17 @@
// ============================================================
// AUTH 对象(供其他模块使用)
// ============================================================
const AUTH = {
async getUserProfile(userId) {
const data = await apiFetch('/users/' + userId);
if (data.error) throw new Error(data.error);
return data;
}
};
// ============================================================ // ============================================================
// 🔐 认证 // 🔐 认证
// ============================================================ // ============================================================
// 三个认证表单的提交拦截。
// 输入框与按钮原本裸放在 div 中(页面没有 form 标签),密码管理器因此
// 找不到表单边界,会靠启发式猜测把首页搜索框也当成账号字段填入。
// 现改用真正的 <form> 包裹,需要拦下默认提交行为——否则按回车或点按钮
// 会触发浏览器原生提交导致页面刷新。
['loginForm', 'registerForm', 'forgotPasswordForm'].forEach(id => {
const form = document.getElementById(id);
if (form) form.addEventListener('submit', e => e.preventDefault());
});
// 登录事件绑定 // 登录事件绑定
document.getElementById('loginBtn').addEventListener('click', () => { document.getElementById('loginBtn').addEventListener('click', () => {
document.getElementById('loginModal').classList.add('active'); document.getElementById('loginModal').classList.add('active');
@@ -22,15 +20,14 @@ document.getElementById('loginBtn').addEventListener('click', () => {
document.getElementById('loginSubmit').addEventListener('click', async () => { document.getElementById('loginSubmit').addEventListener('click', async () => {
const email = document.getElementById('loginEmail').value.trim(); const email = document.getElementById('loginEmail').value.trim();
const password = document.getElementById('loginPassword').value; const password = document.getElementById('loginPassword').value;
if (!email || !password) { alert('请填写完整信息'); return; } if (!email || !password) { showToast('请填写完整信息', 'warning'); return; }
try { try {
const result = await API.login(email, password); const result = await API.login(email, password);
document.getElementById('loginModal').classList.remove('active'); closeModal(document.getElementById('loginModal'));
document.getElementById('loginEmail').value = ''; document.getElementById('loginEmail').value = '';
document.getElementById('loginPassword').value = ''; document.getElementById('loginPassword').value = '';
if (result.user) { if (result.user) {
currentUser = result.user; currentUser = result.user;
API.logEvent('login').catch(() => {});
renderNav(); renderNav();
if (currentPage === 'admin' && currentUser.role !== 'admin') { if (currentPage === 'admin' && currentUser.role !== 'admin') {
switchPage('feed'); switchPage('feed');
@@ -40,59 +37,148 @@ document.getElementById('loginSubmit').addEventListener('click', async () => {
} }
} }
} catch (err) { } catch (err) {
alert('登录失败:' + err.message); showToast('登录失败:' + err.message, 'error');
} }
}); });
// 注册事件绑定 // 注册事件绑定
document.getElementById('registerBtn').addEventListener('click', () => { document.getElementById('registerBtn').addEventListener('click', () => {
refreshCaptcha('reg'); refreshCaptcha('reg');
syncBootstrapTokenField();
syncEmailCodeField();
document.getElementById('registerModal').classList.add('active'); 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() {
const field = document.getElementById('regBootstrapToken');
if (!field) return;
try {
const settings = await API.getSettings();
const required = settings.bootstrap_required === true;
field.style.display = required ? '' : 'none';
if (!required) field.value = '';
} catch (err) {
// 取不到设置时按「不需要」处理,避免把内部机制暴露给普通用户。
field.style.display = 'none';
field.value = '';
}
}
document.getElementById('registerSubmit').addEventListener('click', async () => { document.getElementById('registerSubmit').addEventListener('click', async () => {
const username = document.getElementById('regUsername').value.trim(); const username = document.getElementById('regUsername').value.trim();
const email = document.getElementById('regEmail').value.trim(); const email = document.getElementById('regEmail').value.trim();
const password = document.getElementById('regPassword').value; const password = document.getElementById('regPassword').value;
const bootstrapField = document.getElementById('regBootstrapToken');
// 字段被隐藏时视为未提供,避免普通注册误传空串触发后端的令牌校验分支。
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 captchaInput = document.getElementById('regCaptchaInput').value.trim();
const captchaAnswer = parseInt(document.getElementById('regCaptchaInput').dataset.answer); const captchaAnswer = parseInt(document.getElementById('regCaptchaInput').dataset.answer);
if (!username || !email || !password) { alert('请填写完整信息'); return; } if (!username || !email || !password) { showToast('请填写完整信息', 'warning'); return; }
if (password.length < 6) { alert('密码至少6位'); return; } if (password.length < 6) { showToast('密码至少6位', 'warning'); return; }
if (parseInt(captchaInput) !== captchaAnswer) { alert('验证码错误,请重新计算'); refreshCaptcha('reg'); return; } if (codeEnabled && !emailCode) {
showToast('请输入邮箱验证码', 'warning'); return;
}
if (parseInt(captchaInput) !== captchaAnswer) { showToast('验证码错误,请重新计算', 'error'); refreshCaptcha('reg'); return; }
try { try {
const result = await API.register(email, password, username); await API.register(email, password, username, bootstrapToken, emailCode);
document.getElementById('registerModal').classList.remove('active'); } catch (err) {
document.getElementById('regUsername').value = ''; showToast('注册失败:' + err.message, 'error');
document.getElementById('regEmail').value = ''; return;
document.getElementById('regPassword').value = ''; }
document.getElementById('regCaptchaInput').value = '';
alert('注册成功!请登录');
// 生成恢复码 closeModal(document.getElementById('registerModal'));
try { document.getElementById('regUsername').value = '';
const recoveryData = await API.generateRecoveryCodes(); document.getElementById('regEmail').value = '';
if (recoveryData.codes) { document.getElementById('regPassword').value = '';
showRecoveryCodesModal(recoveryData.codes); if (bootstrapField) bootstrapField.value = '';
} if (codeField) codeField.value = '';
} catch (e) { document.getElementById('regCaptchaInput').value = '';
console.warn('恢复码生成失败:', e);
}
const loginResult = await API.login(email, password); try {
if (loginResult.user) { await API.login(email, password);
const profile = await AUTH.getUserProfile(loginResult.user.id); currentUser = await API.getMe();
currentUser = { ...loginResult.user, ...profile }; renderNav();
API.logEvent('register').catch(() => {});
renderNav(); if (currentPage === 'admin' && currentUser.role !== 'admin') {
if (currentPage === 'admin' && currentUser.role !== 'admin') { switchPage('feed');
switchPage('feed'); } else if (currentPage === 'feed') {
} else if (currentPage === 'feed') { renderFeed();
renderFeed(); renderStats();
renderStats();
}
} }
} catch (err) { } catch (err) {
alert('注册失败:' + err.message); showToast('注册成功,但自动登录失败,请手动登录:' + err.message, 'error');
return;
}
try {
const recoveryData = await API.generateRecoveryCodes();
if (recoveryData.codes?.length) {
showRecoveryCodesModal(recoveryData.codes);
}
} catch (err) {
console.warn('恢复码生成失败:', err);
showToast('注册并登录成功,但恢复码生成失败。请稍后在设置中重新生成。', 'error');
} }
}); });
@@ -102,7 +188,10 @@ document.getElementById('regCaptchaQuestion').addEventListener('click', function
// 退出 // 退出
document.getElementById('logoutBtn').addEventListener('click', async () => { document.getElementById('logoutBtn').addEventListener('click', async () => {
if (!confirm('确定要退出吗?')) return; const ok = await showConfirm('确定要退出吗?', {
title: '退出登录', confirmText: '退出',
});
if (!ok) return;
await API.logout(); await API.logout();
currentUser = null; currentUser = null;
renderNav(); renderNav();
+182 -46
View File
@@ -6,18 +6,52 @@ let currentSort = 'latest';
let totalPages = 1; let totalPages = 1;
const PAGE_SIZE = 20; const PAGE_SIZE = 20;
// 当前搜索关键词。为空表示处于普通列表模式。
let currentSearch = '';
// 翻页后滚回列表顶部。分页控件在列表末尾,不回到顶部的话用户看到的
// 仍是新一页的底部。
// 尊重系统的「减少动画」设置:开启时直接跳转,不做平滑滚动。
function scrollFeedToTop() {
const reduceMotion = window.matchMedia &&
window.matchMedia('(prefers-reduced-motion: reduce)').matches;
window.scrollTo({
top: 0,
behavior: reduceMotion ? 'auto' : 'smooth',
});
}
function renderFeed() { function renderFeed() {
const container = document.getElementById('postList'); const container = document.getElementById('postList');
container.innerHTML = '<div style="text-align:center;color:#94a3b8;padding:40px 0;">加载中...</div>'; const keyword = currentSearch;
API.getPosts(currentSort, currentPageNum, PAGE_SIZE).then(result => {
// 骨架屏只在首次加载时显示。翻页时列表已有内容,再画一遍骨架会
// 造成明显的闪动,反而比直接留白更糟。
const isFirstLoad = container.dataset.loaded !== '1';
container.innerHTML = isFirstLoad
? Skeleton.postList(3)
: '<div style="text-align:center;color:#94a3b8;padding:40px 0;">加载中...</div>';
const request = keyword
? API.searchPosts(keyword, currentPageNum, PAGE_SIZE)
: API.getPosts(currentSort, currentPageNum, PAGE_SIZE);
request.then(result => {
container.dataset.loaded = '1';
const posts = result.data || []; const posts = result.data || [];
const pagination = result.pagination || { total: 0, totalPages: 1, page: 1 }; const pagination = result.pagination || { total: 0, totalPages: 1, page: 1 };
totalPages = pagination.totalPages || 1; totalPages = pagination.totalPages || 1;
currentPageNum = pagination.page || 1; currentPageNum = pagination.page || 1;
if (posts.length === 0 && currentPageNum === 1) { if (posts.length === 0 && currentPageNum === 1) {
container.innerHTML = // 空结果提示。关键词单独放在 <strong> 里,让固定文案能作为独立
'<div style="text-align:center;color:#94a3b8;padding:60px 0;">✨ 还没有帖子,快来发布第一条吧!</div>'; // 文本节点被 i18n 匹配到——整句含动态关键词时匹配不上词典。
container.innerHTML = keyword
? '<div class="search-empty">'
+ '<span>没有找到相关帖子</span><br>'
+ '<strong>「' + escapeHTML(keyword) + '」</strong><br>'
+ '<span style="font-size:13px;">试试其他关键词,或检查是否有错别字</span></div>'
: '<div style="text-align:center;color:#94a3b8;padding:60px 0;">✨ 还没有帖子,快来发布第一条吧!</div>';
return; return;
} }
@@ -34,48 +68,63 @@ function renderFeed() {
'https://ui-avatars.com/api/?name=' + encodeURIComponent(username) + 'https://ui-avatars.com/api/?name=' + encodeURIComponent(username) +
'&background=6366f1&color=fff&size=64'; '&background=6366f1&color=fff&size=64';
const time = p.created_at ? new Date(p.created_at).toLocaleString('zh-CN') : ''; const time = p.created_at ? new Date(p.created_at).toLocaleString('zh-CN') : '';
// 列表里最多展示 3 张图,其余折叠为「+N」。
// 附件上限是 6 张,若全部铺开会把卡片撑得很高,且与相邻卡片不齐。
let imagesHtml = ''; let imagesHtml = '';
if (p.images && p.images.length > 0) { 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">'; imagesHtml = '<div class="post-images">';
p.images.forEach(img => { shown.forEach(img => {
imagesHtml += '<img src="' + img + '" class="post-image" />'; 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>'; imagesHtml += '</div>';
} }
const replyCount = p.reply_count || 0; const replyCount = p.reply_count || 0;
// Markdown 渲染 const renderedContent = renderMarkdown(p.content || '');
const renderedContent = marked ? marked.parse(p.content || '') : (p.content || '').replace(/\n/g, '<br>');
// 签名渲染
let signatureHtml = '';
if (p.signature) {
const sigContent = renderMarkdown(p.signature);
signatureHtml = `
<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>
`;
}
html += ` html += `
<div class="post-card" data-postid="${p.id}" style="cursor:pointer;"> <div class="post-card" data-postid="${p.id}" style="cursor:pointer;">
${p.is_pinned ? '<div style="font-size:12px;color:var(--primary);font-weight:600;margin-bottom:4px;">📌 置顶</div>' : ''}
<div class="post-header"> <div class="post-header">
<img src="${avatar}" class="post-avatar" /> <img src="${escapeHTML(safeURL(avatar, { image: true }))}" class="post-avatar" />
<span class="post-username" style="cursor:pointer;color:var(--primary);" onclick="event.stopPropagation();switchPage('user','${username}')">${username}</span> <span class="post-username" data-username="${escapeHTML(username)}" style="cursor:pointer;color:var(--primary);">${escapeHTML(username)}</span>
<span class="post-time">${time}</span> <span class="post-time">${time}</span>
${p.edited_at ? '<span style="font-size:11px;color:var(--text-light);margin-left:6px;">(已编辑)</span>' : ''} ${p.edited_at ? '<span style="font-size:11px;color:var(--text-light);margin-left:6px;">(已编辑)</span>' : ''}
</div> </div>
<div class="post-title">${p.title || '无标题'}</div> <div class="post-title">${escapeHTML(p.title || '无标题')}</div>
<div class="post-content">${renderedContent}</div> <div class="post-content">${renderedContent}</div>
${imagesHtml} ${imagesHtml}
<div class="post-actions"> <div class="post-actions">
<span> <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> <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> </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> </div>
${signatureHtml}
</div> </div>
`; `;
}); });
container.innerHTML = html; container.innerHTML = sanitizeHTML(html);
// 分页控件 // 分页控件
if (totalPages > 1) { if (totalPages > 1) {
@@ -131,7 +180,10 @@ function renderFeed() {
</span> </span>
</div> </div>
`; `;
container.innerHTML += paginationHtml; // 用 insertAdjacentHTML 追加而非 innerHTML +=:
// 后者会让浏览器重新解析整个容器,导致已渲染的帖子卡片被重建,
// 入场动画会重放一遍,视觉上像闪了一下。
container.insertAdjacentHTML('beforeend', paginationHtml);
container.querySelectorAll('.page-btn:not([disabled])').forEach(btn => { container.querySelectorAll('.page-btn:not([disabled])').forEach(btn => {
btn.addEventListener('click', function() { btn.addEventListener('click', function() {
@@ -142,6 +194,9 @@ function renderFeed() {
url.searchParams.set('postpage', page); url.searchParams.set('postpage', page);
window.history.pushState({}, '', url); window.history.pushState({}, '', url);
renderFeed(); renderFeed();
// 分页控件位于列表末尾,翻页后若不回到顶部,用户看到的仍是
// 新一页的底部,需要手动上滚才能读到第一条。这里平滑滚回顶部。
scrollFeedToTop();
} }
}); });
}); });
@@ -155,39 +210,33 @@ function renderFeed() {
}); });
}); });
container.querySelectorAll('.action-report').forEach(btn => { container.querySelectorAll('.post-username').forEach(username => {
btn.addEventListener('click', function(e) { username.addEventListener('click', function(e) {
e.stopPropagation(); e.stopPropagation();
if (!currentUser) { alert('请先登录'); return; } switchPage('user', this.dataset.username);
reportTargetPostId = this.dataset.postid;
document.getElementById('reportModal').classList.add('active');
}); });
}); });
container.querySelectorAll('.action-delete').forEach(btn => {
btn.addEventListener('click', function(e) { container.querySelectorAll('.post-image').forEach(image => {
image.addEventListener('click', function(e) {
e.stopPropagation(); e.stopPropagation();
if (confirm('确定要删除这条帖子吗?')) { openImageViewer(this.src);
API.deletePost(this.dataset.postid).then(() => {
renderFeed();
renderStats();
}).catch(err => alert('删除失败:' + err.message));
}
}); });
}); });
// 卡片上不再放举报与删除按钮:这两个操作针对的是帖子内容本身,
// 放在卡片上容易被误解为对整张卡片操作,也容易误点。
// 它们统一放在帖子详情页,用户点进帖子后操作。
// (卡片的点击跳转绑定在上方,此处无需重复绑定。)
}).catch(err => { }).catch(err => {
container.innerHTML = '<div style="text-align:center;color:#ef4444;padding:40px 0;">加载失败:' + err.message + container.innerHTML = '<div style="text-align:center;color:#ef4444;padding:40px 0;">加载失败:' + escapeHTML(err.message) +
'</div>'; '</div>';
}); });
} }
function renderStats() { // 注:renderStats 定义在 app.js 中(同时更新主页与帖子详情页的统计,
API.getStats().then(stats => { // 且带空值保护)。此处原先有一份同名实现,因 app.js 后加载而被整体
document.getElementById('statTopics').textContent = stats.topics || 0; // 覆盖,属于死代码,已删除以免日后改错地方。
document.getElementById('statPosts').textContent = stats.posts || 0;
document.getElementById('statUsers').textContent = stats.users || 0;
document.getElementById('statOnline').textContent = stats.online || 0;
}).catch(() => {});
}
function renderLinks() { function renderLinks() {
API.getLinks().then(links => { API.getLinks().then(links => {
@@ -198,9 +247,9 @@ function renderLinks() {
} }
let html = ''; let html = '';
links.forEach(l => { links.forEach(l => {
html += '<li><a href="' + l.url + '" target="_blank">' + l.title + '</a></li>'; html += '<li><a href="' + escapeHTML(safeURL(l.url, { allowRelative: false })) + '" target="_blank" rel="noopener noreferrer">' + escapeHTML(l.title) + '</a></li>';
}); });
ul.innerHTML = html; ul.innerHTML = sanitizeHTML(html);
}).catch(() => {}); }).catch(() => {});
} }
@@ -217,3 +266,90 @@ document.querySelectorAll('.tab').forEach(tab => {
renderFeed(); renderFeed();
}); });
}); });
// ============================================================
// 🔍 搜索
// ============================================================
// 输入时防抖 350ms 自动搜索,回车立即搜索。
// 关键词写入 URL(?q=),刷新与分享可保持搜索状态。
(function initSearch() {
const input = document.getElementById('postSearchInput');
const clearBtn = document.getElementById('postSearchClear');
const wrap = input ? input.closest('.feed-search') : null;
if (!input) return;
let debounceTimer = null;
function syncClearButton() {
if (clearBtn) clearBtn.style.display = input.value.trim() ? 'flex' : 'none';
}
function runSearch(keyword, { updateUrl = true } = {}) {
const next = (keyword || '').trim();
// 与当前状态相同则不必重新请求
if (next === currentSearch && currentPageNum === 1) return;
currentSearch = next;
currentPageNum = 1;
if (updateUrl) {
const url = new URL(window.location);
if (next) url.searchParams.set('q', next);
else url.searchParams.delete('q');
url.searchParams.delete('postpage');
window.history.pushState({}, '', url);
}
if (wrap) wrap.classList.add('is-searching');
renderFeed();
// renderFeed 内部是异步的,这里在下一轮事件循环后移除进度条即可
// (列表本身会先显示「加载中」,不会长时间空白)
window.setTimeout(() => {
if (wrap) wrap.classList.remove('is-searching');
}, 600);
}
input.addEventListener('input', () => {
syncClearButton();
if (debounceTimer) clearTimeout(debounceTimer);
debounceTimer = setTimeout(() => runSearch(input.value), 350);
});
// 回车立即搜索,跳过防抖
input.addEventListener('keydown', e => {
if (e.key === 'Enter') {
e.preventDefault();
if (debounceTimer) clearTimeout(debounceTimer);
runSearch(input.value);
} else if (e.key === 'Escape') {
e.preventDefault();
input.value = '';
syncClearButton();
if (debounceTimer) clearTimeout(debounceTimer);
runSearch('');
}
});
if (clearBtn) {
clearBtn.addEventListener('click', () => {
input.value = '';
syncClearButton();
if (debounceTimer) clearTimeout(debounceTimer);
runSearch('');
input.focus();
});
}
// 暴露给外部(初始化时按 URL 恢复搜索状态)
window.__feedSearch = {
setKeyword(keyword) {
input.value = keyword || '';
currentSearch = (keyword || '').trim();
syncClearButton();
},
run: runSearch,
};
syncClearButton();
})();
+989
View File
@@ -0,0 +1,989 @@
// ============================================================
// 🌍 国际化外挂脚本(不修改任何源文件)
// 默认英文,支持 URL 参数 ?lang=zh / ?lang=en
// ============================================================
const TRANSLATIONS = {
'zh': {
// ===== 导航 =====
'登录': '登录',
'注册': '注册',
'消息': '消息',
'设置': '设置',
'管理后台': '管理后台',
'暗色模式': '暗色模式',
'亮色模式': '亮色模式',
'退出': '退出',
'暂无链接': '暂无链接',
'举报': '举报',
'用户': '用户',
'日志': '日志',
'友链': '友链',
'自定义 CSS': '自定义 CSS',
'论坛设置': '论坛设置',
'自定义页面': '自定义页面',
'✉️ 私信': '✉️ 私信',
// ===== 帖子 =====
'最新发布': '最新发布',
'最新回复': '最新回复',
'发布新帖': '发布新帖',
'标题': '标题',
'说点什么...': '说点什么...',
'发布帖子': '发布帖子',
'加载中...': '加载中...',
'还没有帖子,快来发布第一条吧!': '还没有帖子,快来发布第一条吧!',
'暂无帖子': '暂无帖子',
'删除': '删除',
'编辑': '编辑',
'置顶': '置顶',
'取消置顶': '取消置顶',
'已编辑': '已编辑',
'匿名': '匿名',
'无标题': '无标题',
'回复': '回复',
'📌 置顶': '📌 置顶',
'✏️ 编辑': '✏️ 编辑',
// ===== 帖子详情 =====
'帖子详情': '帖子详情',
'发表回复': '发表回复',
'提交回复': '提交回复',
'还没有回复,快来抢沙发吧 🛋️': '还没有回复,快来抢沙发吧 🛋️',
'写下你的回复...': '写下你的回复...',
'条回复': '条回复',
// ===== 统计 =====
'社区统计': '社区统计',
'主题': '主题',
'帖子': '帖子',
'用户': '用户',
'友情链接': '友情链接',
// ===== 登录/注册 =====
'邮箱': '邮箱',
'密码': '密码',
'忘记密码?': '忘记密码?',
'用户名': '用户名',
'密码(至少6位)': '密码(至少6位)',
'请先登录': '请先登录',
// ===== 管理后台 =====
'举报记录': '举报记录',
'用户列表': '用户列表',
'操作日志': '操作日志',
'自定义CSS': '自定义CSS',
'论坛名称设置': '论坛名称设置',
'暂无举报': '暂无举报',
'待处理': '待处理',
'已删除': '已删除',
'已驳回': '已驳回',
'角色': '角色',
'注册时间': '注册时间',
// ===== 设置页面 =====
'个人资料': '个人资料',
'安全设置': '安全设置',
'恢复码': '恢复码',
'保存设置': '保存设置',
'修改密码': '修改密码',
'当前密码': '当前密码',
'新密码': '新密码',
'修改邮箱': '修改邮箱',
'新邮箱': '新邮箱',
'查看恢复码': '查看恢复码',
'重新生成': '重新生成',
'个人简介': '个人简介',
'帖子签名': '帖子签名',
'显示在每篇帖子底部,支持 Markdown': '显示在每篇帖子底部,支持 Markdown',
'用 --- 分隔,支持 Markdown': '用 --- 分隔,支持 Markdown',
'当前密码(验证身份)': '当前密码(验证身份)',
// ===== 恢复码 =====
'用于忘记密码时重置账户。每个恢复码只能使用一次。': '用于忘记密码时重置账户。每个恢复码只能使用一次。',
'请妥善保存以下恢复码。当你忘记密码时,可以使用它们重置密码。': '请妥善保存以下恢复码。当你忘记密码时,可以使用它们重置密码。',
'每个恢复码只能使用一次。': '每个恢复码只能使用一次。',
'剩余 0 个可用恢复码': '剩余 0 个可用恢复码',
'剩余 1 个可用恢复码': '剩余 1 个可用恢复码',
'剩余 2 个可用恢复码': '剩余 2 个可用恢复码',
'剩余 3 个可用恢复码': '剩余 3 个可用恢复码',
'剩余 4 个可用恢复码': '剩余 4 个可用恢复码',
'剩余 5 个可用恢复码': '剩余 5 个可用恢复码',
'剩余 6 个可用恢复码': '剩余 6 个可用恢复码',
'剩余 7 个可用恢复码': '剩余 7 个可用恢复码',
'剩余 8 个可用恢复码': '剩余 8 个可用恢复码',
'剩余 9 个可用恢复码': '剩余 9 个可用恢复码',
'剩余 10 个可用恢复码': '剩余 10 个可用恢复码',
'复制全部': '复制全部',
'我已保存': '我已保存',
// ===== 自定义页面 =====
'添加页面': '添加页面',
'页面名称': '页面名称',
'导航栏显示名称': '导航栏显示名称',
'关于我们': '关于我们',
'状态': '状态',
'启用': '启用',
'禁用': '禁用',
'页面内容': '页面内容',
'保存': '保存',
'编辑页面': '编辑页面',
'只允许字母、数字、短横线和下划线': '只允许字母、数字、短横线和下划线',
'用于 URL: ?custom=': '用于 URL: ?custom=',
'页面内容(HTML + CSS + JS)': '页面内容(HTML + CSS + JS)',
'支持 HTML、CSS(<style>)、JS(<script>),内容会在独立的沙盒中渲染': '支持 HTML、CSS(<style>)、JS(<script>),内容会在独立的沙盒中渲染',
'暂无自定义页面': '暂无自定义页面',
// ===== 自定义 CSS =====
'自定义 CSS': '自定义 CSS',
'上传 style.css 覆盖默认样式,自定义论坛外观。': '上传 style.css 覆盖默认样式,自定义论坛外观。',
'点击或拖拽上传 style.css': '点击或拖拽上传 style.css',
'只能上传 style.css 文件': '只能上传 style.css 文件',
'保存 CSS': '保存 CSS',
'删除自定义 CSS': '删除自定义 CSS',
// ===== 自定义 CSS 警告模态框 =====
'警告': '警告',
'若上传的 style.css 存在问题,将导致整个论坛界面样式错乱,甚至无法正常使用。': '若上传的 style.css 存在问题,将导致整个论坛界面样式错乱,甚至无法正常使用。',
'请确保 CSS 文件是完整的、经过测试的版本。如出现问题,可点击「删除自定义 CSS」恢复默认样式。': '请确保 CSS 文件是完整的、经过测试的版本。如出现问题,可点击「删除自定义 CSS」恢复默认样式。',
'我了解,继续上传': '我了解,继续上传',
'取消': '取消',
// ===== 友情链接 =====
'链接名称': '链接名称',
'链接地址': '链接地址',
'添加': '添加',
// ===== 通知 =====
'有人回复了你的帖子': '有人回复了你的帖子',
'查看详情 →': '查看详情 →',
'你的帖子已被删除': '你的帖子已被删除',
'你的举报已被处理': '你的举报已被处理',
'你的帖子已被置顶': '你的帖子已被置顶',
'管理员取消了你的帖子置顶': '管理员取消了你的帖子置顶',
'管理员删除了你的帖子': '管理员删除了你的帖子',
'你举报的帖子已被管理员删除': '你举报的帖子已被管理员删除',
'你举报的帖子已被管理员驳回': '你举报的帖子已被管理员驳回',
'管理员把你的帖子置顶了': '管理员把你的帖子置顶了',
// ===== Toast =====
'已复制到剪贴板': '已复制到剪贴板',
// ===== 发帖/上传 =====
'点击或拖拽上传图片': '点击或拖拽上传图片',
'支持 JPG、PNG、GIF、WebP,单张最大 5MB': '支持 JPG、PNG、GIF、WebP,单张最大 5MB',
// ===== 提示 =====
'保存成功!': '保存成功!',
'保存失败': '保存失败',
'操作失败': '操作失败',
'删除成功': '删除成功',
'删除失败': '删除失败',
'确定删除吗?': '确定删除吗?',
'确定要删除该帖子吗?': '确定要删除该帖子吗?',
'举报已提交': '举报已提交',
'修改成功': '修改成功',
'加载失败': '加载失败',
'加载失败:': '加载失败:',
'请填写完整信息': '请填写完整信息',
'请输入页面名称': '请输入页面名称',
'请输入导航栏显示名称': '请输入导航栏显示名称',
'请输入页面内容': '请输入页面内容',
// ===== 举报 =====
'举报了帖子': '举报了帖子',
'原因:': '原因:',
'帖子:': '帖子:',
'状态:': '状态:',
'处理人:': '处理人:',
'删除帖子': '删除帖子',
'驳回举报': '驳回举报',
// ===== 用户 =====
'共': '共',
'位用户': '位用户',
'搜索用户名...': '搜索用户名...',
'搜索': '搜索',
'清空': '清空',
'管理员': '管理员',
'普通用户': '普通用户',
'不可操作自己': '不可操作自己',
'设为普通用户': '设为普通用户',
'设为管理员': '设为管理员',
// ===== 日志 =====
'暂无日志': '暂无日志',
'时间': '时间',
'操作': '操作',
'条日志': '条日志',
// ===== 重置密码 =====
'重置密码': '重置密码',
'输入你的邮箱和一个未使用的恢复码': '输入你的邮箱和一个未使用的恢复码',
'恢复码(格式:ABCD-1234-EFGH-5678)': '恢复码(格式:ABCD-1234-EFGH-5678)',
'新密码(至少6位)': '新密码(至少6位)',
// ===== 用户主页 =====
'用户主页': '用户主页',
'用户不存在': '用户不存在',
'这个人很懒,什么都没写': '这个人很懒,什么都没写',
'加入': '加入',
'于': '于',
'发了': '发了',
'个帖子': '个帖子',
'帖': '帖',
'发私信': '发私信',
'还没有发帖': '还没有发帖',
'加入 ': '加入 ',
// ===== 私信 =====
'私信': '私信',
'暂无私信': '暂无私信',
'还没有消息,打个招呼吧': '还没有消息,打个招呼吧',
'输入消息...': '输入消息...',
'发送': '发送',
// ===== Toast 通用 =====
'请选择图片文件': '请选择图片文件',
'图片不能超过 5MB': '图片不能超过 5MB',
'上传中...': '上传中...',
'头像更新成功!': '头像更新成功!',
'文件名必须是 style.css': '文件名必须是 style.css',
'请上传 CSS 文件': '请上传 CSS 文件',
'已选择: ': '已选择: ',
'请先选择 style.css 文件': '请先选择 style.css 文件',
'CSS 上传成功!刷新页面查看效果': 'CSS 上传成功!刷新页面查看效果',
'上传失败': '上传失败',
'已删除自定义 CSS': '已删除自定义 CSS',
'删除失败': '删除失败',
'密码修改成功!': '密码修改成功!',
'邮箱修改成功!': '邮箱修改成功!',
'重置成功!请登录': '重置成功!请登录',
// ===== 其他 =====
'返回': '返回',
'答案': '答案',
'请填写内容': '请填写内容',
'发布成功!': '发布成功!',
'发布失败': '发布失败',
// ===== 举报原因 =====
'垃圾广告': '垃圾广告',
'人身攻击': '人身攻击',
'违法内容': '违法内容',
'不适当内容': '不适当内容',
'其他': '其他',
'请选择举报原因:': '请选择举报原因:',
'提交举报': '提交举报',
// ===== 论坛名称 =====
'论坛名称': '论坛名称',
// ===== 补充覆盖:操作状态与错误提示 =====
// 源码里这些提示多带「:」后缀拼接具体原因,与上方不带冒号的
// 短词是不同字符串,必须分别登记才能命中。
'保存失败:': '保存失败:',
'编辑成功!': '编辑成功!',
'编辑失败:': '编辑失败:',
'操作失败:': '操作失败:',
'打开私信失败:': '打开私信失败:',
'登录失败:': '登录失败:',
'发布失败:': '发布失败:',
'发送失败:': '发送失败:',
'恢复码生成失败:': '恢复码生成失败:',
'回复失败:': '回复失败:',
'获取恢复码失败:': '获取恢复码失败:',
'举报失败:': '举报失败:',
'删除失败:': '删除失败:',
'上传失败:': '上传失败:',
'添加失败:': '添加失败:',
'重新生成失败:': '重新生成失败:',
'注册失败:': '注册失败:',
'页面加载失败:': '页面加载失败:',
'加载失败:': '加载失败:',
// ===== 补充覆盖:表单校验与按钮 =====
'保存修改': '保存修改',
'密码至少6位': '密码至少6位',
'新密码至少6位': '新密码至少6位',
'验证码错误,请重新计算': '验证码错误,请重新计算',
'用户名不能为空': '用户名不能为空',
'请输入论坛名称': '请输入论坛名称',
'请填写回复内容': '请填写回复内容',
'页面名称只允许字母、数字、短横线和下划线': '页面名称只允许字母、数字、短横线和下划线',
'移除': '移除',
'名称': '名称',
'图片': '图片',
'未知': '未知',
'系统': '系统',
'无权限访问': '无权限访问',
'匿名用户': '匿名用户',
'发布中...': '发布中...',
'上传图片中...': '上传图片中...',
'松开上传': '松开上传',
'每篇帖子最多上传 6 张图片': '每篇帖子最多上传 6 张图片',
'上传响应无效': '上传响应无效',
'图片上传失败': '图片上传失败',
'已选择:': '已选择:',
'举报不成立': '举报不成立',
'已删除违规帖子': '已删除违规帖子',
'暂无用户': '暂无用户',
'暂无友情链接': '暂无友情链接',
'暂无消息': '暂无消息',
// ===== 补充覆盖:确认对话框 =====
'确定要': '确定要',
'置顶吗?': '置顶吗?',
'确定要退出吗?': '确定要退出吗?',
'确定删除该链接吗?': '确定删除该链接吗?',
'确定要删除这条回复吗?': '确定要删除这条回复吗?',
'确定要删除这条帖子吗?': '确定要删除这条帖子吗?',
'确定要删除这个页面吗?': '确定要删除这个页面吗?',
'确定要删除该帖子并标记举报为已处理吗?': '确定要删除该帖子并标记举报为已处理吗?',
'确定要删除自定义 CSS 吗?将恢复默认样式。': '确定要删除自定义 CSS 吗?将恢复默认样式。',
'重新生成将替换所有旧的恢复码,确定继续吗?': '重新生成将替换所有旧的恢复码,确定继续吗?',
// ===== 补充覆盖:混合文案 =====
'当有人回复你的帖子或处理你的举报时,会在这里通知你': '当有人回复你的帖子或处理你的举报时,会在这里通知你',
'举报已提交,管理员将尽快处理': '举报已提交,管理员将尽快处理',
'注册成功,但自动登录失败,请手动登录:': '注册成功,但自动登录失败,请手动登录:',
'注册并登录成功,但恢复码生成失败。请稍后在设置中重新生成。': '注册并登录成功,但恢复码生成失败。请稍后在设置中重新生成。',
'支持 HTML、CSS(&lt;style&gt;)、JS(&lt;script&gt;),内容会在独立的沙盒中渲染': '支持 HTML、CSS(&lt;style&gt;)、JS(&lt;script&gt;),内容会在独立的沙盒中渲染',
// ===== 动态文本前缀 =====
// 「剩余 N 个可用恢复码」由模板字符串生成,整串无法匹配,
// 因此登记可命中的固定片段。
'剩余': '剩余',
'个可用恢复码': '个可用恢复码',
'原因:': '原因:',
'状态:': '状态:',
'处理人:': '处理人:',
'帖子:': '帖子:',
// ===== 确认对话框 =====
// showConfirm() 动态创建 DOM,i18n 的 MutationObserver 会翻译其
// 文本节点,但这些文案必须先在词典登记才能命中。
'请确认': '请确认',
'确定': '确定',
'删除回复': '删除回复',
'删除友链': '删除友链',
'删除页面': '删除页面',
'修改用户角色': '修改用户角色',
'重新生成恢复码': '重新生成恢复码',
'退出登录': '退出登录',
// ===== 用户屏蔽 =====
'屏蔽': '屏蔽',
'解除屏蔽': '解除屏蔽',
'已屏蔽': '已屏蔽',
'会话': '会话',
'屏蔽用户': '屏蔽用户',
'已屏蔽该用户': '已屏蔽该用户',
'已解除屏蔽': '已解除屏蔽',
'还没有屏蔽任何人': '还没有屏蔽任何人',
'加载中…': '加载中…',
'加载失败': '加载失败',
// ===== 私信用户搜索 =====
'搜索用户名开始私信…': '搜索用户名开始私信…',
'搜索用户': '搜索用户',
'没有找到匹配的用户': '没有找到匹配的用户',
'点击发送私信': '点击发送私信',
'对方回复前还可发送': '对方回复前还可发送',
'条消息': '条消息',
'对方回复前无法继续发送,请等待对方回复': '对方回复前无法继续发送,请等待对方回复',
'搜索中…': '搜索中…',
'搜索失败:': '搜索失败:',
// ===== 帖子搜索 =====
'搜索帖子…': '搜索帖子…',
'清除搜索': '清除搜索',
'请输入搜索关键词': '请输入搜索关键词',
'搜索关键词过长(最多 100 字)': '搜索关键词过长(最多 100 字)',
'没有找到相关帖子': '没有找到相关帖子',
'试试其他关键词,或检查是否有错别字': '试试其他关键词,或检查是否有错别字',
// ===== SMTP 与邮箱验证 =====
'邮件设置': '邮件设置',
'启用邮件发送': '启用邮件发送',
'SMTP 服务器': 'SMTP 服务器',
'端口': '端口',
'加密方式': '加密方式',
'密码 / 授权码': '密码 / 授权码',
'发件人名称': '发件人名称',
'发件人邮箱': '发件人邮箱',
'保存配置': '保存配置',
'发送测试邮件': '发送测试邮件',
'清除密码': '清除密码',
'注册邮箱验证': '注册邮箱验证',
'要求注册时验证邮箱': '要求注册时验证邮箱',
'获取验证码': '获取验证码',
'邮箱验证码': '邮箱验证码',
'配置完整,可以发信': '配置完整,可以发信',
'尚未配置完成,邮件功能不可用': '尚未配置完成,邮件功能不可用',
'验证码已发送,请查收邮件': '验证码已发送,请查收邮件',
'请输入邮箱验证码': '请输入邮箱验证码',
'请输入有效邮箱': '请输入有效邮箱',
'该邮箱已被注册': '该邮箱已被注册',
'本站未开启邮箱验证': '本站未开启邮箱验证',
'请先获取验证码': '请先获取验证码',
'验证码已过期,请重新获取': '验证码已过期,请重新获取',
'尝试次数过多,请重新获取验证码': '尝试次数过多,请重新获取验证码',
'验证码错误': '验证码错误',
'配置已保存': '配置已保存',
'密码已清除': '密码已清除',
'已开启注册邮箱验证': '已开启注册邮箱验证',
'已关闭注册邮箱验证': '已关闭注册邮箱验证',
'加载配置失败:': '加载配置失败:',
'已保存密码,留空则不修改': '已保存密码,留空则不修改',
'尚未设置密码': '尚未设置密码',
'留空表示不修改已保存的密码': '留空表示不修改已保存的密码',
'通常为完整邮箱地址': '通常为完整邮箱地址',
'例如:论坛名称': '例如:论坛名称',
'注册验证码': '注册验证码',
'密码重置验证码': '密码重置验证码',
'Forumlify SMTP 测试邮件': 'Forumlify SMTP 测试邮件',
'允许自签证书(仅自建邮件服务器需要)': '允许自签证书(仅自建邮件服务器需要)',
'必须是你已在邮件服务商处验证过的域名下的地址,否则会被拒收。': '必须是你已在邮件服务商处验证过的域名下的地址,否则会被拒收。',
},
'en': {
// ===== 导航 =====
'登录': 'Login',
'注册': 'Register',
'消息': 'Messages',
'设置': 'Settings',
'管理后台': 'Admin',
'暗色模式': 'Dark Mode',
'亮色模式': 'Light Mode',
'退出': 'Logout',
'暂无链接': 'No links',
'举报': 'Reports',
'用户': 'Users',
'日志': 'Logs',
'友链': 'Links',
'自定义 CSS': 'Custom CSS',
'论坛设置': 'Forum Settings',
'自定义页面': 'Custom Pages',
'✉️ 私信': '✉️ Messages',
// ===== 帖子 =====
'最新发布': 'Latest',
'最新回复': 'Recent',
'发布新帖': 'New Post',
'标题': 'Title',
'说点什么...': 'Say something...',
'发布帖子': 'Publish',
'加载中...': 'Loading...',
'还没有帖子,快来发布第一条吧!': 'No posts yet. Be the first!',
'暂无帖子': 'No posts',
'删除': 'Delete',
'编辑': 'Edit',
'置顶': 'Pin',
'取消置顶': 'Unpin',
'已编辑': 'Edited',
'匿名': 'Anonymous',
'无标题': 'Untitled',
'回复': 'Reply',
'📌 置顶': '📌 Pinned',
'✏️ 编辑': '✏️ Edit',
// ===== 帖子详情 =====
'帖子详情': 'Post Details',
'发表回复': 'Reply',
'提交回复': 'Submit Reply',
'还没有回复,快来抢沙发吧 🛋️': 'No replies yet. Be the first!',
'写下你的回复...': 'Write your reply...',
'条回复': ' replies',
// ===== 统计 =====
'社区统计': 'Community Stats',
'主题': 'Topics',
'帖子': 'Posts',
'用户': 'Users',
'友情链接': 'Links',
// ===== 登录/注册 =====
'邮箱': 'Email',
'密码': 'Password',
'忘记密码?': 'Forgot Password?',
'用户名': 'Username',
'密码(至少6位)': 'Password (min 6 chars)',
'请先登录': 'Please login first',
// ===== 管理后台 =====
'举报记录': 'Reports',
'用户列表': 'Users',
'操作日志': 'Logs',
'自定义CSS': 'Custom CSS',
'论坛名称设置': 'Forum Settings',
'暂无举报': 'No reports',
'待处理': 'Pending',
'已删除': 'Approved',
'已驳回': 'Rejected',
'角色': 'Role',
'注册时间': 'Registered',
// ===== 设置页面 =====
'个人资料': 'Profile',
'安全设置': 'Security',
'恢复码': 'Recovery Codes',
'保存设置': 'Save Settings',
'修改密码': 'Change Password',
'当前密码': 'Current Password',
'新密码': 'New Password',
'修改邮箱': 'Change Email',
'新邮箱': 'New Email',
'查看恢复码': 'View Recovery Codes',
'重新生成': 'Regenerate',
'个人简介': 'Bio',
'帖子签名': 'Post Signature',
'显示在每篇帖子底部,支持 Markdown': 'Displayed at the bottom of each post. Supports Markdown.',
'用 --- 分隔,支持 Markdown': 'Use --- as separator. Supports Markdown.',
'当前密码(验证身份)': 'Current password (verify identity)',
// ===== 恢复码 =====
'用于忘记密码时重置账户。每个恢复码只能使用一次。': 'Used to reset your password if you forget it. Each recovery code can only be used once.',
'请妥善保存以下恢复码。当你忘记密码时,可以使用它们重置密码。': 'Please save these recovery codes. You can use them to reset your password if you forget it.',
'每个恢复码只能使用一次。': 'Each recovery code can only be used once.',
'剩余 0 个可用恢复码': '0 recovery codes available',
'剩余 1 个可用恢复码': '1 recovery code available',
'剩余 2 个可用恢复码': '2 recovery codes available',
'剩余 3 个可用恢复码': '3 recovery codes available',
'剩余 4 个可用恢复码': '4 recovery codes available',
'剩余 5 个可用恢复码': '5 recovery codes available',
'剩余 6 个可用恢复码': '6 recovery codes available',
'剩余 7 个可用恢复码': '7 recovery codes available',
'剩余 8 个可用恢复码': '8 recovery codes available',
'剩余 9 个可用恢复码': '9 recovery codes available',
'剩余 10 个可用恢复码': '10 recovery codes available',
'复制全部': 'Copy All',
'我已保存': 'Saved',
// ===== 自定义页面 =====
'添加页面': 'Add Page',
'页面名称': 'Page Name',
'导航栏显示名称': 'Display Name',
'关于我们': 'About Us',
'状态': 'Status',
'启用': 'Enabled',
'禁用': 'Disabled',
'页面内容': 'Page Content',
'保存': 'Save',
'编辑页面': 'Edit Page',
'只允许字母、数字、短横线和下划线': 'Only letters, numbers, hyphens and underscores allowed',
'用于 URL: ?custom=': 'Used in URL: ?custom=',
'页面内容(HTML + CSS + JS)': 'Page Content (HTML + CSS + JS)',
'支持 HTML、CSS(<style>)、JS(<script>),内容会在独立的沙盒中渲染': 'Supports HTML, CSS (<style>), JS (<script>). Rendered in an isolated sandbox.',
'暂无自定义页面': 'No custom pages',
// ===== 自定义 CSS =====
'自定义 CSS': 'Custom CSS',
'上传 style.css 覆盖默认样式,自定义论坛外观。': 'Upload style.css to override default styles and customize the forum appearance.',
'点击或拖拽上传 style.css': 'Click or drag to upload style.css',
'只能上传 style.css 文件': 'Only style.css files are allowed',
'保存 CSS': 'Save CSS',
'删除自定义 CSS': 'Delete Custom CSS',
// ===== 自定义 CSS 警告模态框 =====
'警告': 'Warning',
'若上传的 style.css 存在问题,将导致整个论坛界面样式错乱,甚至无法正常使用。': 'If the uploaded style.css has issues, it may break the entire forum layout.',
'请确保 CSS 文件是完整的、经过测试的版本。如出现问题,可点击「删除自定义 CSS」恢复默认样式。': 'Please ensure the CSS file is complete and tested. If problems occur, click "Delete Custom CSS" to restore default styles.',
'我了解,继续上传': 'I understand, continue upload',
'取消': 'Cancel',
// ===== 友情链接 =====
'链接名称': 'Link Name',
'链接地址': 'Link URL',
'添加': 'Add',
// ===== 通知 =====
'有人回复了你的帖子': 'Someone replied to your post',
'查看详情 →': 'View details →',
'你的帖子已被删除': 'Your post has been deleted',
'你的举报已被处理': 'Your report has been processed',
'你的帖子已被置顶': 'Your post has been pinned',
'管理员取消了你的帖子置顶': 'An admin has unpinned your post',
'管理员删除了你的帖子': 'An admin deleted your post',
'你举报的帖子已被管理员删除': 'The post you reported has been deleted',
'你举报的帖子已被管理员驳回': 'The post you reported has been rejected',
'管理员把你的帖子置顶了': 'An admin pinned your post',
// ===== Toast =====
'已复制到剪贴板': 'Copied to clipboard',
// ===== 发帖/上传 =====
'点击或拖拽上传图片': 'Click or drag to upload image',
'支持 JPG、PNG、GIF、WebP,单张最大 5MB': 'Supports JPG, PNG, GIF, WebP, max 5MB',
// ===== 提示 =====
'保存成功!': 'Saved!',
'保存失败': 'Save failed',
'操作失败': 'Operation failed',
'删除成功': 'Deleted',
'删除失败': 'Delete failed',
'确定删除吗?': 'Are you sure?',
'确定要删除该帖子吗?': 'Delete this post?',
'举报已提交': 'Report submitted',
'修改成功': 'Updated',
'加载失败': 'Load failed',
'加载失败:': 'Load failed: ',
'请填写完整信息': 'Please fill in all fields',
'请输入页面名称': 'Please enter a page name',
'请输入导航栏显示名称': 'Please enter a display name',
'请输入页面内容': 'Please enter page content',
// ===== 举报 =====
'举报了帖子': 'reported a post',
'原因:': 'Reason: ',
'帖子:': 'Post: ',
'状态:': 'Status: ',
'处理人:': 'Handler: ',
'删除帖子': 'Delete Post',
'驳回举报': 'Reject',
// ===== 用户 =====
'共': 'Total',
'位用户': ' users',
'搜索用户名...': 'Search username...',
'搜索': 'Search',
'清空': 'Clear',
'管理员': 'Admin',
'普通用户': 'User',
'不可操作自己': 'Cannot modify yourself',
'设为普通用户': 'Set as User',
'设为管理员': 'Set as Admin',
// ===== 日志 =====
'暂无日志': 'No logs',
'时间': 'Time',
'操作': 'Action',
'条日志': ' logs',
// ===== 重置密码 =====
'重置密码': 'Reset Password',
'输入你的邮箱和一个未使用的恢复码': 'Enter your email and an unused recovery code',
'恢复码(格式:ABCD-1234-EFGH-5678)': 'Recovery code (format: ABCD-1234-EFGH-5678)',
'新密码(至少6位)': 'New password (min 6 chars)',
// ===== 用户主页 =====
'用户主页': 'User Profile',
'用户不存在': 'User not found',
'这个人很懒,什么都没写': 'This user is lazy, nothing written',
'加入': 'Joined',
// 「于」在中文句式里连接日期(加入于 2024-01-01),英文不需要对应词。
// 这里保留原词而非空串:walk() 命中后用译文整体替换原文,空串会把
// 文字抹掉;同时该键实际不会被单独命中(源码中是「加入于」整串)。
'于': '于',
'发了': 'Posted',
'个帖子': ' posts',
'帖': ' posts',
'发私信': 'Send Message',
'还没有发帖': 'No posts yet',
'加入 ': 'Joined ',
// ===== 私信 =====
'私信': 'Messages',
'暂无私信': 'No messages',
'还没有消息,打个招呼吧': 'No messages yet. Say hi!',
'输入消息...': 'Type a message...',
'发送': 'Send',
// ===== Toast 通用 =====
'请选择图片文件': 'Please select an image',
'图片不能超过 5MB': 'Image must be under 5MB',
'上传中...': 'Uploading...',
'头像更新成功!': 'Avatar updated!',
'文件名必须是 style.css': 'File name must be style.css',
'请上传 CSS 文件': 'Please upload a CSS file',
'已选择: ': 'Selected: ',
'请先选择 style.css 文件': 'Please select style.css first',
'CSS 上传成功!刷新页面查看效果': 'CSS uploaded! Refresh to see changes',
'上传失败': 'Upload failed',
'已删除自定义 CSS': 'Custom CSS deleted',
'删除失败': 'Delete failed',
'密码修改成功!': 'Password updated!',
'邮箱修改成功!': 'Email updated!',
'重置成功!请登录': 'Reset successful! Please login',
// ===== 其他 =====
'返回': 'Back',
'答案': 'Answer',
'请填写内容': 'Please enter content',
'发布成功!': 'Posted!',
'发布失败': 'Post failed',
// ===== 举报原因 =====
'垃圾广告': 'Spam',
'人身攻击': 'Abuse',
'违法内容': 'Illegal',
'不适当内容': 'NSFW',
'其他': 'Other',
'请选择举报原因:': 'Select a reason:',
'提交举报': 'Submit Report',
// ===== 论坛名称 =====
'论坛名称': 'Forum Name',
// ===== 补充覆盖:操作状态与错误提示 =====
'保存失败:': 'Save failed: ',
'编辑成功!': 'Edited successfully!',
'编辑失败:': 'Edit failed: ',
'操作失败:': 'Operation failed: ',
'打开私信失败:': 'Failed to open messages: ',
'登录失败:': 'Login failed: ',
'发布失败:': 'Publish failed: ',
'发送失败:': 'Send failed: ',
'恢复码生成失败:': 'Failed to generate recovery codes: ',
'回复失败:': 'Reply failed: ',
'获取恢复码失败:': 'Failed to load recovery codes: ',
'举报失败:': 'Report failed: ',
'删除失败:': 'Delete failed: ',
'上传失败:': 'Upload failed: ',
'添加失败:': 'Add failed: ',
'重新生成失败:': 'Regeneration failed: ',
'注册失败:': 'Registration failed: ',
'页面加载失败:': 'Failed to load page: ',
'加载失败:': 'Failed to load: ',
// ===== 补充覆盖:表单校验与按钮 =====
'保存修改': 'Save Changes',
'密码至少6位': 'Password must be at least 6 characters',
'新密码至少6位': 'New password must be at least 6 characters',
'验证码错误,请重新计算': 'Incorrect captcha, please try again',
'用户名不能为空': 'Username cannot be empty',
'请输入论坛名称': 'Please enter a forum name',
'请填写回复内容': 'Please enter your reply',
'页面名称只允许字母、数字、短横线和下划线': 'Page name may only contain letters, numbers, hyphens and underscores',
'移除': 'Remove',
'名称': 'Name',
'图片': 'Image',
'未知': 'Unknown',
'系统': 'System',
'无权限访问': 'Access denied',
'匿名用户': 'Anonymous',
'发布中...': 'Publishing...',
'上传图片中...': 'Uploading image...',
'松开上传': 'Release to upload',
'每篇帖子最多上传 6 张图片': 'Up to 6 images per post',
'上传响应无效': 'Invalid upload response',
'图片上传失败': 'Image upload failed',
'已选择:': 'Selected:',
'举报不成立': 'Report dismissed',
'已删除违规帖子': 'Removed the violating post',
'暂无用户': 'No users',
'暂无友情链接': 'No links',
'暂无消息': 'No messages',
// ===== 补充覆盖:确认对话框 =====
'确定要': 'Are you sure you want to ',
'置顶吗?': '?',
'确定要退出吗?': 'Are you sure you want to log out?',
'确定删除该链接吗?': 'Delete this link?',
'确定要删除这条回复吗?': 'Delete this reply?',
'确定要删除这条帖子吗?': 'Delete this post?',
'确定要删除这个页面吗?': 'Delete this page?',
'确定要删除该帖子并标记举报为已处理吗?': 'Delete this post and mark the report as handled?',
'确定要删除自定义 CSS 吗?将恢复默认样式。': 'Delete the custom CSS? The default styles will be restored.',
'重新生成将替换所有旧的恢复码,确定继续吗?': 'Regenerating will replace all existing recovery codes. Continue?',
// ===== 补充覆盖:混合文案 =====
'当有人回复你的帖子或处理你的举报时,会在这里通知你': 'You will be notified here when someone replies to your post or your report is handled',
'举报已提交,管理员将尽快处理': 'Report submitted. An administrator will review it shortly',
'注册成功,但自动登录失败,请手动登录:': 'Registration succeeded, but automatic login failed. Please log in manually: ',
'注册并登录成功,但恢复码生成失败。请稍后在设置中重新生成。': 'Registered and signed in, but recovery codes could not be generated. Please regenerate them later in Settings.',
'支持 HTML、CSS(&lt;style&gt;)、JS(&lt;script&gt;),内容会在独立的沙盒中渲染': 'Supports HTML, CSS (&lt;style&gt;) and JS (&lt;script&gt;). Content renders in an isolated sandbox',
// ===== 动态文本前缀 =====
// 「剩余 N 个可用恢复码」由模板字符串生成,整串无法命中词典,
// 因此登记可命中的固定片段。注意这里不能译成空串:万一该词以
// 独立文本节点出现,空串会把文字抹掉。
'剩余': 'Remaining:',
'个可用恢复码': 'recovery codes remaining',
'原因:': 'Reason: ',
'状态:': 'Status: ',
'处理人:': 'Handled by: ',
'帖子:': 'Post: ',
// ===== 确认对话框 =====
'请确认': 'Confirm',
'确定': 'OK',
'删除回复': 'Delete Reply',
'删除友链': 'Delete Link',
'删除页面': 'Delete Page',
'修改用户角色': 'Change User Role',
'重新生成恢复码': 'Regenerate Recovery Codes',
'退出登录': 'Logout',
// ===== 用户屏蔽 =====
'屏蔽': 'Block',
'解除屏蔽': 'Unblock',
'已屏蔽': 'Blocked',
'会话': 'Chats',
'屏蔽用户': 'Block User',
'已屏蔽该用户': 'User blocked',
'已解除屏蔽': 'User unblocked',
'还没有屏蔽任何人': 'You have not blocked anyone',
'加载中…': 'Loading…',
'加载失败': 'Failed to load',
// ===== 私信用户搜索 =====
'搜索用户名开始私信…': 'Search users to start a chat…',
'搜索用户': 'Search users',
'没有找到匹配的用户': 'No matching users found',
'点击发送私信': 'Click to send a message',
'对方回复前还可发送': 'You can send',
'条消息': 'more messages before they reply',
'对方回复前无法继续发送,请等待对方回复': 'You cannot send more until they reply',
'搜索中…': 'Searching…',
'搜索失败:': 'Search failed: ',
// ===== 帖子搜索 =====
'搜索帖子…': 'Search posts…',
'清除搜索': 'Clear search',
'请输入搜索关键词': 'Please enter a search term',
'搜索关键词过长(最多 100 字)': 'Search term is too long (max 100 characters)',
'没有找到相关帖子': 'No matching posts found',
'试试其他关键词,或检查是否有错别字': 'Try different keywords, or check for typos',
// ===== 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.',
}
};
// ============================================================
// 核心逻辑
// ============================================================
function detectLanguage() {
// URL 参数优先
const urlParams = new URLSearchParams(window.location.search);
const langParam = urlParams.get('lang');
if (langParam && TRANSLATIONS[langParam]) return langParam;
const stored = localStorage.getItem('forumlify-lang');
if (stored && TRANSLATIONS[stored]) return stored;
const browserLang = navigator.language.slice(0, 2);
if (TRANSLATIONS[browserLang]) return browserLang;
return 'en';
}
let currentLang = detectLanguage();
function setLanguage(lang) {
if (!TRANSLATIONS[lang]) return;
currentLang = lang;
localStorage.setItem('forumlify-lang', lang);
applyTranslation();
}
function t(key) {
const dict = TRANSLATIONS[currentLang] || TRANSLATIONS['zh'];
return dict[key] || key;
}
function applyTranslation() {
function walk(node) {
if (node.nodeType === Node.TEXT_NODE) {
const text = node.textContent;
const trimmed = text.trim();
if (trimmed && TRANSLATIONS['zh'][trimmed]) {
const translated = t(trimmed);
if (translated !== trimmed) {
node.textContent = text.replace(trimmed, translated);
}
}
return;
}
if (node.nodeType === Node.ELEMENT_NODE) {
if (['IFRAME', 'SCRIPT', 'STYLE'].includes(node.tagName)) return;
if (node.placeholder && TRANSLATIONS['zh'][node.placeholder]) {
node.placeholder = t(node.placeholder);
}
if (node.tagName === 'INPUT' && node.value && TRANSLATIONS['zh'][node.value]) {
if (node.type !== 'password') {
node.value = t(node.value);
}
}
for (const child of node.childNodes) {
walk(child);
}
}
}
walk(document.body);
// 监听动态内容
const observer = new MutationObserver((mutations) => {
for (const mutation of mutations) {
for (const node of mutation.addedNodes) {
if (node.nodeType === Node.ELEMENT_NODE) {
walk(node);
}
}
}
});
observer.observe(document.body, { childList: true, subtree: true });
}
// ============================================================
// 初始化
// ============================================================
document.addEventListener('DOMContentLoaded', function() {
document.body.style.opacity = '0';
setTimeout(function() {
if (typeof loadForumName === 'function') {
loadForumName();
}
applyTranslation();
document.body.style.transition = 'opacity 0.2s ease';
document.body.style.opacity = '1';
}, 200);
});
+47
View File
@@ -0,0 +1,47 @@
// ============================================================
// 🎨 图标工具 - 用 SVG 替代 Emoji
// ============================================================
function getIcon(type, size = 16) {
const icons = {
// 通用
success: `<svg xmlns="http://www.w3.org/2000/svg" width="${size}" height="${size}" viewBox="0 0 24 24" fill="none" stroke="#22c55e" stroke-width="2.5" stroke-linecap="round" stroke-linejoin="round"><path d="M22 11.08V12a10 10 0 1 1-5.93-9.14"/><polyline points="22 4 12 14.01 9 11.01"/></svg>`,
error: `<svg xmlns="http://www.w3.org/2000/svg" width="${size}" height="${size}" viewBox="0 0 24 24" fill="none" stroke="#ef4444" stroke-width="2.5" stroke-linecap="round" stroke-linejoin="round"><circle cx="12" cy="12" r="10"/><line x1="15" y1="9" x2="9" y2="15"/><line x1="9" y1="9" x2="15" y2="15"/></svg>`,
warning: `<svg xmlns="http://www.w3.org/2000/svg" width="${size}" height="${size}" viewBox="0 0 24 24" fill="none" stroke="#f59e0b" stroke-width="2.5" stroke-linecap="round" stroke-linejoin="round"><path d="M12 9v4"/><path d="M12 17h.01"/><path d="M12 22c5.523 0 10-4.477 10-10S17.523 2 12 2 2 6.477 2 12s4.477 10 10 10z"/></svg>`,
pending: `<svg xmlns="http://www.w3.org/2000/svg" width="${size}" height="${size}" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5" stroke-linecap="round" stroke-linejoin="round"><circle cx="12" cy="12" r="10"/><polyline points="12 6 12 12 16 14"/></svg>`,
// 操作
delete: `<svg xmlns="http://www.w3.org/2000/svg" width="${size}" height="${size}" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5" stroke-linecap="round" stroke-linejoin="round"><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>`,
edit: `<svg xmlns="http://www.w3.org/2000/svg" width="${size}" height="${size}" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5" stroke-linecap="round" stroke-linejoin="round"><path d="M11 4H4a2 2 0 0 0-2 2v14a2 2 0 0 0 2 2h14a2 2 0 0 0 2-2v-7"/><path d="M18.5 2.5a2.121 2.121 0 0 1 3 3L12 15l-4 1 1-4 9.5-9.5z"/></svg>`,
add: `<svg xmlns="http://www.w3.org/2000/svg" width="${size}" height="${size}" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5" stroke-linecap="round" stroke-linejoin="round"><line x1="12" y1="5" x2="12" y2="19"/><line x1="5" y1="12" x2="19" y2="12"/></svg>`,
close: `<svg xmlns="http://www.w3.org/2000/svg" width="${size}" height="${size}" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5" stroke-linecap="round" stroke-linejoin="round"><line x1="18" y1="6" x2="6" y2="18"/><line x1="6" y1="6" x2="18" y2="18"/></svg>`,
// 导航
home: `<svg xmlns="http://www.w3.org/2000/svg" width="${size}" height="${size}" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5" stroke-linecap="round" stroke-linejoin="round"><path d="M3 12l2-2m0 0l7-7 7 7M5 10v10a1 1 0 001 1h3m10-11l2 2m-2-2v10a1 1 0 01-1 1h-3m-6 0a1 1 0 001-1v-4a1 1 0 011-1h2a1 1 0 011 1v4a1 1 0 001 1m-6 0h6"/></svg>`,
user: `<svg xmlns="http://www.w3.org/2000/svg" width="${size}" height="${size}" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5" stroke-linecap="round" stroke-linejoin="round"><path d="M20 21v-2a4 4 0 0 0-4-4H8a4 4 0 0 0-4 4v2"/><circle cx="12" cy="7" r="4"/></svg>`,
lock: `<svg xmlns="http://www.w3.org/2000/svg" width="${size}" height="${size}" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5" stroke-linecap="round" stroke-linejoin="round"><rect x="3" y="11" width="18" height="11" rx="2" ry="2"/><path d="M7 11V7a5 5 0 0 1 10 0v4"/></svg>`,
key: `<svg xmlns="http://www.w3.org/2000/svg" width="${size}" height="${size}" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5" stroke-linecap="round" stroke-linejoin="round"><path d="M21 2l-2 2m-7.61 7.61a5.5 5.5 0 1 1-7.778 7.778 5.5 5.5 0 0 1 7.777-7.777zm0 0L15.5 7.5m0 0l3 3L22 7l-3-3m-3.5 3.5L19 4"/></svg>`,
message: `<svg xmlns="http://www.w3.org/2000/svg" width="${size}" height="${size}" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5" stroke-linecap="round" stroke-linejoin="round"><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>`,
// 内容
pin: `<svg xmlns="http://www.w3.org/2000/svg" width="${size}" height="${size}" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5" stroke-linecap="round" stroke-linejoin="round"><path d="M21 10.5V19a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h8.5"/><polyline points="16 2 22 8 16 8"/><line x1="10" y1="14" x2="18" y2="14"/><line x1="10" y1="18" x2="14" y2="18"/></svg>`,
link: `<svg xmlns="http://www.w3.org/2000/svg" width="${size}" height="${size}" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5" stroke-linecap="round" stroke-linejoin="round"><path d="M10 13a5 5 0 0 0 7.54.54l3-3a5 5 0 0 0-7.07-7.07l-1.72 1.71"/><path d="M14 11a5 5 0 0 0-7.54-.54l-3 3a5 5 0 0 0 7.07 7.07l1.71-1.71"/></svg>`,
settings: `<svg xmlns="http://www.w3.org/2000/svg" width="${size}" height="${size}" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5" stroke-linecap="round" stroke-linejoin="round"><path d="M12.22 2h-.44a2 2 0 0 0-2 2v.18a2 2 0 0 1-1 1.73l-.43.25a2 2 0 0 1-2 0l-.15-.08a2 2 0 0 0-2.73.73l-.22.38a2 2 0 0 0 .73 2.73l.15.1a2 2 0 0 1 1 1.72v.51a2 2 0 0 1-1 1.74l-.15.09a2 2 0 0 0-.73 2.73l.22.38a2 2 0 0 0 2.73.73l.15-.08a2 2 0 0 1 2 0l.43.25a2 2 0 0 1 1 1.73V20a2 2 0 0 0 2 2h.44a2 2 0 0 0 2-2v-.18a2 2 0 0 1 1-1.73l.43-.25a2 2 0 0 1 2 0l.15.08a2 2 0 0 0 2.73-.73l.22-.39a2 2 0 0 0-.73-2.73l-.15-.08a2 2 0 0 1-1-1.74v-.5a2 2 0 0 1 1-1.74l.15-.09a2 2 0 0 0 .73-2.73l-.22-.38a2 2 0 0 0-2.73-.73l-.15.08a2 2 0 0 1-2 0l-.43-.25a2 2 0 0 1-1-1.73V4a2 2 0 0 0-2-2z"/><circle cx="12" cy="12" r="3"/></svg>`,
page: `<svg xmlns="http://www.w3.org/2000/svg" width="${size}" height="${size}" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5" 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>`,
shield: `<svg xmlns="http://www.w3.org/2000/svg" width="${size}" height="${size}" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5" stroke-linecap="round" stroke-linejoin="round"><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>`,
// 其他
camera: `<svg xmlns="http://www.w3.org/2000/svg" width="${size}" height="${size}" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5" stroke-linecap="round" stroke-linejoin="round"><path d="M23 19a2 2 0 0 1-2 2H3a2 2 0 0 1-2-2V8a2 2 0 0 1 2-2h4l2-3h6l2 3h4a2 2 0 0 1 2 2z"/><circle cx="12" cy="13" r="4"/></svg>`,
star: `<svg xmlns="http://www.w3.org/2000/svg" width="${size}" height="${size}" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5" stroke-linecap="round" stroke-linejoin="round"><polygon points="12 2 15.09 8.26 22 9.27 17 14.14 18.18 21.02 12 17.77 5.82 21.02 7 14.14 2 9.27 8.91 8.26 12 2"/></svg>`,
paint: `<svg xmlns="http://www.w3.org/2000/svg" width="${size}" height="${size}" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5" stroke-linecap="round" stroke-linejoin="round"><rect x="3" y="3" width="18" height="18" rx="2" ry="2"/><circle cx="8.5" cy="8.5" r="1.5"/><polyline points="21 15 16 10 5 21"/></svg>`,
calendar: `<svg xmlns="http://www.w3.org/2000/svg" width="${size}" height="${size}" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5" stroke-linecap="round" stroke-linejoin="round"><rect x="3" y="4" width="18" height="18" rx="2" ry="2"/><line x1="16" y1="2" x2="16" y2="6"/><line x1="8" y1="2" x2="8" y2="6"/><line x1="3" y1="10" x2="21" y2="10"/></svg>`,
file: `<svg xmlns="http://www.w3.org/2000/svg" width="${size}" height="${size}" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5" stroke-linecap="round" stroke-linejoin="round"><path d="M13 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V9z"/><polyline points="13 2 13 9 20 9"/></svg>`,
refresh: `<svg xmlns="http://www.w3.org/2000/svg" width="${size}" height="${size}" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5" stroke-linecap="round" stroke-linejoin="round"><polyline points="23 4 23 10 17 10"/><path d="M20.49 15a9 9 0 1 1-2.12-9.36L23 10"/></svg>`,
list: `<svg xmlns="http://www.w3.org/2000/svg" width="${size}" height="${size}" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5" stroke-linecap="round" stroke-linejoin="round"><line x1="8" y1="6" x2="21" y2="6"/><line x1="8" y1="12" x2="21" y2="12"/><line x1="8" y1="18" x2="21" y2="18"/><line x1="3" y1="6" x2="3.01" y2="6"/><line x1="3" y1="12" x2="3.01" y2="12"/><line x1="3" y1="18" x2="3.01" y2="18"/></svg>`,
megaphone: `<svg xmlns="http://www.w3.org/2000/svg" width="${size}" height="${size}" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5" stroke-linecap="round" stroke-linejoin="round"><path d="M17 18.5c0 1.5-1.5 3-3.5 3s-3.5-1.5-3.5-3c0-.5.5-1 1-1h5c.5 0 1 .5 1 1z"/><path d="M4 11h16v6H4z"/><path d="M8 17v3"/><path d="M16 17v3"/><path d="M9 11v-4a3 3 0 0 1 6 0v4"/></svg>`,
sofa: `<svg xmlns="http://www.w3.org/2000/svg" width="${size}" height="${size}" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5" stroke-linecap="round" stroke-linejoin="round"><rect x="3" y="10" width="18" height="8" rx="2"/><path d="M6 10V6a2 2 0 0 1 2-2h8a2 2 0 0 1 2 2v4"/><line x1="3" y1="18" x2="3" y2="20"/><line x1="21" y1="18" x2="21" y2="20"/></svg>`,
clock: `<svg xmlns="http://www.w3.org/2000/svg" width="${size}" height="${size}" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5" stroke-linecap="round" stroke-linejoin="round"><circle cx="12" cy="12" r="10"/><polyline points="12 6 12 12 16 14"/></svg>`
};
return icons[type] || '';
}
-1
View File
@@ -1 +0,0 @@
+107 -48
View File
@@ -14,15 +14,16 @@ function switchToPost(postId) {
} }
function showPostPage(postId) { function showPostPage(postId) {
document.getElementById('app').style.display = 'none'; const goingBack = typeof window.isNavigatingBack === 'function' && window.isNavigatingBack();
document.querySelectorAll('.page-slide').forEach(el => {
el.classList.remove('active', 'slide-out');
});
const el = document.getElementById('pagePost'); const el = document.getElementById('pagePost');
el.classList.add('active');
el.style.animation = 'none'; // 先让其他覆盖页滑出(从帖子直接跳到用户主页之类的情况)
void el.offsetHeight; document.querySelectorAll('.page-slide.active').forEach(other => {
el.style.animation = ''; if (other !== el) hideSlide(other, { back: goingBack });
});
// 首页留在背景中下沉,新页面从屏幕外滑入
showSlide(el, { back: goingBack });
currentPage = 'post'; currentPage = 'post';
renderPostDetail(postId); renderPostDetail(postId);
} }
@@ -30,7 +31,7 @@ function showPostPage(postId) {
async function renderPostDetail(postId) { async function renderPostDetail(postId) {
const container = document.getElementById('postDetailContent'); const container = document.getElementById('postDetailContent');
const replyArea = document.getElementById('replyArea'); const replyArea = document.getElementById('replyArea');
container.innerHTML = '<div style="text-align:center;color:#94a3b8;padding:40px 0;">加载中...</div>'; container.innerHTML = Skeleton.postDetail() + Skeleton.replyItem() + Skeleton.replyItem();
replyArea.style.display = 'none'; replyArea.style.display = 'none';
try { try {
@@ -49,40 +50,54 @@ async function renderPostDetail(postId) {
if (post.images && post.images.length > 0) { if (post.images && post.images.length > 0) {
imagesHtml = '<div class="post-images">'; imagesHtml = '<div class="post-images">';
post.images.forEach(img => { post.images.forEach(img => {
imagesHtml += '<img src="' + img + '" class="post-image" />'; imagesHtml += '<img src="' + escapeHTML(safeURL(img, { image: true })) + '" class="post-image" style="cursor:pointer;" />';
}); });
imagesHtml += '</div>'; imagesHtml += '</div>';
} }
// Markdown 渲染(安全处理) const renderedContent = renderMarkdown(post.content || '');
let renderedContent = post.content || '';
try { // 签名渲染
if (typeof marked !== 'undefined' && marked.parse) { // 详情页保留签名展示。补上类名以便统一样式定位——列表页的同类元素
renderedContent = marked.parse(renderedContent); // 正是靠 .post-signature 隐藏的,此前详情页只有行内样式,无法选中。
} else { let signatureHtml = '';
renderedContent = renderedContent.replace(/\n/g, '<br>'); if (post.signature) {
} const sigContent = renderMarkdown(post.signature);
} catch (e) { signatureHtml = `
renderedContent = renderedContent.replace(/\n/g, '<br>'); <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>
`;
} }
let html = ` let html = `
<div class="post-detail-card"> <div class="post-detail-card">
<div class="post-header"> <div class="post-header">
<img src="${avatar}" class="post-avatar" /> <img src="${escapeHTML(safeURL(avatar, { image: true }))}" class="post-avatar" />
<span class="post-username" style="cursor:pointer;color:var(--primary);" onclick="switchPage('user','${username}')">${username}</span> <span class="post-username" data-username="${escapeHTML(username)}" style="cursor:pointer;color:var(--primary);">${escapeHTML(username)}</span>
<span class="post-time">${time}</span> <span class="post-time">${time}</span>
${post.edited_at ? `<span style="font-size:12px;color:var(--text-light);margin-left:8px;">(已编辑 ${new Date(post.edited_at).toLocaleString('zh-CN')})</span>` : ''} ${post.edited_at ? `<span style="font-size:12px;color:var(--text-light);margin-left:8px;">(已编辑 ${new Date(post.edited_at).toLocaleString('zh-CN')})</span>` : ''}
${post.is_pinned ? '<span style="font-size:12px;color:var(--primary);margin-left:8px;">📌 置顶</span>' : ''}
<div style="display:flex;gap:4px;margin-left:auto;"> <div style="display:flex;gap:4px;margin-left:auto;">
${currentUser && currentUser.role === 'admin' ? `
<button class="btn-sm btn-secondary" id="pinPostBtn" data-postid="${post.id}" style="padding:4px 10px;">
${post.is_pinned ? '📌 取消置顶' : '📌 置顶'}
</button>
` : ''}
${currentUser && currentUser.id === post.user_id ? `<button class="btn-sm btn-secondary" id="editPostBtn" data-postid="${post.id}" style="padding:4px 10px;">✏️ 编辑</button>` : ''} ${currentUser && currentUser.id === post.user_id ? `<button class="btn-sm btn-secondary" id="editPostBtn" data-postid="${post.id}" style="padding:4px 10px;">✏️ 编辑</button>` : ''}
${currentUser && currentUser.id === post.user_id ? `<button class="btn-sm btn-danger" id="detailDeleteBtn" data-postid="${post.id}" style="padding:4px 10px;"> ${currentUser && currentUser.id === post.user_id ? `<button class="btn-sm btn-danger" id="detailDeleteBtn" 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;"><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> <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>` : ''} </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> </div>
<div class="post-content" style="font-size:16px;line-height:1.8;">${renderedContent}</div> <div class="post-content" style="font-size:16px;line-height:1.8;">${renderedContent}</div>
${imagesHtml} ${imagesHtml}
${signatureHtml}
</div> </div>
<div style="margin-top:20px;font-size:14px;color:#64748b;"> <div style="margin-top:20px;font-size:14px;color:#64748b;">
<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> <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>
@@ -103,28 +118,58 @@ async function renderPostDetail(postId) {
html += ` html += `
<div class="reply-item" data-replyid="${r.id}"> <div class="reply-item" data-replyid="${r.id}">
<div class="reply-header"> <div class="reply-header">
<img src="${rAvatar}" class="reply-avatar" /> <img src="${escapeHTML(safeURL(rAvatar, { image: true }))}" class="reply-avatar" />
<span class="reply-username" style="cursor:pointer;color:var(--primary);" onclick="switchPage('user','${rUsername}')">${rUsername}</span> <span class="reply-username" data-username="${escapeHTML(rUsername)}" style="cursor:pointer;color:var(--primary);">${escapeHTML(rUsername)}</span>
<span class="reply-time">${rTime}</span> <span class="reply-time">${rTime}</span>
${currentUser && currentUser.id === r.user_id ? `<button class="btn-sm btn-danger reply-delete-btn" data-replyid="${r.id}"> ${currentUser && (currentUser.id === r.user_id || currentUser.role === 'admin') ? `<button class="btn-sm btn-danger reply-delete-btn" data-replyid="${r.id}">
<svg xmlns="http://www.w3.org/2000/svg" width="12" height="12" 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> <svg xmlns="http://www.w3.org/2000/svg" width="12" height="12" 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>` : ''} </button>` : ''}
</div> </div>
<div class="reply-content">${(r.content || '').replace(/\n/g, '<br>')}</div> <div class="reply-content">${renderPlainText(r.content || '')}</div>
</div> </div>
`; `;
}); });
} }
html += '</div>'; html += '</div>';
container.innerHTML = html; container.innerHTML = sanitizeHTML(html);
replyArea.style.display = 'block'; replyArea.style.display = 'block';
document.getElementById('replyContent').value = ''; document.getElementById('replyContent').value = '';
document.getElementById('replyCaptchaInput').value = ''; document.getElementById('replyCaptchaInput').value = '';
refreshCaptcha('reply'); refreshCaptcha('reply');
container.querySelectorAll('.post-username, .reply-username').forEach(usernameEl => {
usernameEl.addEventListener('click', function() {
switchPage('user', this.dataset.username);
});
});
container.querySelectorAll('.post-image').forEach(image => {
image.addEventListener('click', function() {
openImageViewer(this.src);
});
});
// 置顶按钮
const pinBtn = document.getElementById('pinPostBtn');
if (pinBtn) {
pinBtn.addEventListener('click', async function() {
const postId = this.dataset.postid;
const unpin = this.textContent.includes('取消');
const ok = await showConfirm('确定要' + (unpin ? '取消' : '') + '置顶吗?', {
title: unpin ? '取消置顶' : '置顶帖子',
confirmText: unpin ? '取消置顶' : '置顶',
});
if (!ok) return;
API.togglePinPost(postId).then(() => {
renderPostDetail(postId);
renderFeed();
}).catch(err => showToast('操作失败:' + err.message, 'error'));
});
}
// 编辑按钮 // 编辑按钮
const editBtn = document.getElementById('editPostBtn'); const editBtn = document.getElementById('editPostBtn');
if (editBtn) { if (editBtn) {
@@ -138,27 +183,41 @@ async function renderPostDetail(postId) {
const deleteBtn = document.getElementById('detailDeleteBtn'); const deleteBtn = document.getElementById('detailDeleteBtn');
if (deleteBtn) { if (deleteBtn) {
deleteBtn.addEventListener('click', function() { deleteBtn.addEventListener('click', async function() {
if (confirm('确定要删除这条帖子吗?')) { const ok = await showConfirm('确定要删除这条帖子吗?', {
API.deletePost(postId).then(() => { title: '删除帖子', confirmText: '删除', danger: true,
alert('删除成功'); });
switchPage('feed'); if (!ok) return;
renderFeed(); API.deletePost(postId).then(() => {
renderStats(); showToast('删除成功', 'success');
}).catch(err => alert('删除失败:' + err.message)); // switchPage('feed') 内部已经会重新渲染列表、统计与友链,
} // 此处不可再调一次,否则这些接口会各发出两次请求。
navigateBackToFeed();
}).catch(err => showToast('删除失败:' + err.message, 'error'));
});
}
// 举报按钮:原先只在列表卡片上,现移到详情页。
// 提交逻辑在 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 => { document.querySelectorAll('.reply-delete-btn').forEach(btn => {
btn.addEventListener('click', function(e) { btn.addEventListener('click', async function(e) {
e.stopPropagation(); e.stopPropagation();
const replyId = this.dataset.replyid; const replyId = this.dataset.replyid;
if (confirm('确定要删除这条回复吗?')) { const ok = await showConfirm('确定要删除这条回复吗?', {
API.deleteReply(replyId).then(() => { title: '删除回复', confirmText: '删除', danger: true,
renderPostDetail(postId); });
}).catch(err => alert('删除失败:' + err.message)); if (!ok) return;
} API.deleteReply(replyId).then(() => {
renderPostDetail(postId);
}).catch(err => showToast('删除失败:' + err.message, 'error'));
}); });
}); });
@@ -180,28 +239,28 @@ async function renderPostDetail(postId) {
currentPostId = postId; currentPostId = postId;
} catch (err) { } catch (err) {
container.innerHTML = '<div style="text-align:center;color:#ef4444;padding:40px 0;">加载失败:' + err.message + container.innerHTML = '<div style="text-align:center;color:#ef4444;padding:40px 0;">加载失败:' + escapeHTML(err.message) +
'</div>'; '</div>';
replyArea.style.display = 'none'; replyArea.style.display = 'none';
} }
} }
async function handleReplySubmit(postId) { async function handleReplySubmit(postId) {
if (!currentUser) { alert('请先登录'); return; } if (!currentUser) { showToast('请先登录', 'warning'); return; }
const content = document.getElementById('replyContent').value.trim(); const content = document.getElementById('replyContent').value.trim();
const captchaInput = document.getElementById('replyCaptchaInput').value.trim(); const captchaInput = document.getElementById('replyCaptchaInput').value.trim();
const captchaAnswer = parseInt(document.getElementById('replyCaptchaInput').dataset.answer); const captchaAnswer = parseInt(document.getElementById('replyCaptchaInput').dataset.answer);
if (!content) { alert('请填写回复内容'); return; } if (!content) { showToast('请填写回复内容', 'warning'); return; }
if (parseInt(captchaInput) !== captchaAnswer) { alert('验证码错误,请重新计算'); refreshCaptcha('reply'); return; } if (parseInt(captchaInput) !== captchaAnswer) { showToast('验证码错误,请重新计算', 'error'); refreshCaptcha('reply'); return; }
try { try {
await API.createReply(postId, content); await API.createReply(postId, content);
API.logEvent('create_reply').catch(() => {});
renderPostDetail(postId); renderPostDetail(postId);
if (currentPage === 'feed') { if (currentPage === 'feed') {
renderFeed(); renderFeed();
} }
renderStats(); renderStats();
} catch (err) { } catch (err) {
alert('回复失败:' + err.message); showToast('回复失败:' + err.message, 'error');
} }
} }
+77
View File
@@ -0,0 +1,77 @@
// ============================================================
// Safe rendering helpers
// ============================================================
function escapeHTML(value) {
return String(value ?? '')
.replace(/&/g, '&amp;')
.replace(/</g, '&lt;')
.replace(/>/g, '&gt;')
.replace(/"/g, '&quot;')
.replace(/'/g, '&#39;');
}
function safeURL(value, { allowRelative = true, image = false } = {}) {
if (!value) return image ? '' : '#';
try {
const raw = String(value).trim();
const parsed = new URL(raw, window.location.origin);
const isRelative = parsed.origin === window.location.origin && !/^[a-z][a-z0-9+.-]*:/i.test(raw);
const allowedProtocol = parsed.protocol === 'http:' || parsed.protocol === 'https:';
if (!allowedProtocol || (!allowRelative && isRelative)) return image ? '' : '#';
return isRelative ? parsed.pathname + parsed.search + parsed.hash : parsed.href;
} catch (error) {
return image ? '' : '#';
}
}
function sanitizeHTML(html) {
const template = document.createElement('template');
template.innerHTML = String(html ?? '');
// Application templates contain legitimate controls. Raw user HTML is escaped
// before Markdown parsing, while this pass removes executable/embed elements.
const forbidden = 'script,iframe,object,embed,link,meta,base,style';
template.content.querySelectorAll(forbidden).forEach(node => node.remove());
template.content.querySelectorAll('*').forEach(node => {
for (const attribute of Array.from(node.attributes)) {
const name = attribute.name.toLowerCase();
if (name.startsWith('on') || name === 'srcdoc') {
node.removeAttribute(attribute.name);
}
}
if (node.hasAttribute('href')) {
const href = safeURL(node.getAttribute('href'));
if (href === '#') node.removeAttribute('href');
else node.setAttribute('href', href);
}
if (node.hasAttribute('src')) {
const src = safeURL(node.getAttribute('src'), { image: true });
if (!src) node.removeAttribute('src');
else node.setAttribute('src', src);
}
if (node.tagName === 'A' && node.getAttribute('target') === '_blank') {
node.setAttribute('rel', 'noopener noreferrer');
}
});
return template.innerHTML;
}
function renderMarkdown(value) {
const escaped = escapeHTML(value);
if (typeof marked !== 'undefined' && marked.parse) {
return sanitizeHTML(marked.parse(escaped));
}
return escaped.replace(/\r?\n/g, '<br>');
}
function renderPlainText(value) {
return escapeHTML(value).replace(/\r?\n/g, '<br>');
}
+133
View File
@@ -0,0 +1,133 @@
// ============================================================
// 💀 骨架屏生成器
// ------------------------------------------------------------
// 用与真实内容同构的灰块替代「加载中...」文字,让等待期间就能看出
// 版面结构,内容出现时也不会发生明显的布局跳动。
//
// 所有函数返回 HTML 字符串,由调用方写入容器。
// 数量刻意与首页默认每页条数(20)不同——只画 3~5 条即可,
// 画满 20 条反而增加渲染负担,而用户在下一次绘制前看不完。
// ============================================================
const Skeleton = {
// 单张帖子卡片:头像 + 用户名 + 标题 + 正文两行
postCard({ withThumbs = false } = {}) {
return `
<div class="skeleton-card">
<div class="skeleton-header">
<div class="skeleton-avatar"></div>
<div class="skeleton-line w-30" style="margin-bottom:0;"></div>
</div>
<div class="skeleton-line skeleton-title w-60"></div>
<div class="skeleton-line w-100"></div>
<div class="skeleton-line w-80"></div>
${withThumbs ? '<div class="skeleton-thumbs"><div class="skeleton-thumb"></div><div class="skeleton-thumb"></div></div>' : ''}
</div>
`;
},
// 帖子列表
// 数量不宜过多:骨架卡片是按「理想内容」画的,实际帖子往往更短
// (标题一行、正文一两行),画太多会在真实内容出现时造成容器高度
// 骤降,页面内容整体上跳。用 3 张作为折中。
postList(count = 3) {
let html = '';
for (let i = 0; i < count; i++) {
// 第二张带缩略图占位,更接近真实列表的参差感
html += this.postCard({ withThumbs: i === 1 });
}
return html;
},
// 帖子详情:标题 + 多行正文 + 回复区
postDetail() {
return `
<div class="skeleton-card">
<div class="skeleton-header">
<div class="skeleton-avatar"></div>
<div class="skeleton-line w-30" style="margin-bottom:0;"></div>
</div>
<div class="skeleton-line skeleton-title w-45"></div>
<div class="skeleton-line w-100"></div>
<div class="skeleton-line w-100"></div>
<div class="skeleton-line w-60"></div>
</div>
`;
},
// 回复条目
replyItem() {
return `
<div class="skeleton-card" style="padding:14px 18px;">
<div class="skeleton-header">
<div class="skeleton-avatar" style="width:28px;height:28px;"></div>
<div class="skeleton-line w-30" style="margin-bottom:0;"></div>
</div>
<div class="skeleton-line w-80"></div>
</div>
`;
},
// 表格类列表(管理后台的用户 / 日志 / 友链)
tableRows(count = 6) {
let html = '';
for (let i = 0; i < count; i++) {
// 三列宽度固定,模拟表格的列对齐
html += `
<div class="skeleton-row">
<div class="skeleton-line" style="width:32%;margin-bottom:0;"></div>
<div class="skeleton-line" style="width:22%;margin-bottom:0;"></div>
<div class="skeleton-line" style="width:16%;margin-bottom:0;"></div>
</div>
`;
}
return html;
},
// 用户主页
userProfile() {
return `
<div class="skeleton-card" style="text-align:center;padding:28px;">
<div class="skeleton-avatar" style="width:64px;height:64px;margin:0 auto 14px;"></div>
<div class="skeleton-line w-30" style="margin:0 auto 10px;"></div>
<div class="skeleton-line w-45" style="margin:0 auto;"></div>
</div>
${this.postList(2)}
`;
},
};
// 挂到 window 供各模块使用(各文件都是普通 script,共享全局作用域)
window.Skeleton = Skeleton;
// ============================================================
// 首屏预置骨架屏
// ------------------------------------------------------------
// 真正的列表渲染要等 i18n 初始化完成后才触发(DOMContentLoaded 之后
// 还有 200ms 延迟)。若不提前占位,用户会先看到一段「加载中...」
// 文字,等骨架屏出现时数据往往已经回来了,等于白做。
//
// 这里在脚本执行时(早于 DOMContentLoaded)就把骨架屏写好,让它在
// 第一帧就可见。renderFeed 拿到数据后会直接覆盖这个容器。
// ============================================================
(function primeSkeleton() {
function insert() {
const list = document.getElementById('postList');
if (list && !list.dataset.loaded) {
list.innerHTML = Skeleton.postList(3);
}
}
if (document.readyState === 'loading') {
// DOM 尚未就绪时,解析到 postList 之后再插入;
// 用 DOMContentLoaded 会偏晚,因此监听 readystatechange 的
// interactive 阶段。
document.addEventListener('readystatechange', function onReady() {
if (document.readyState !== 'loading') {
document.removeEventListener('readystatechange', onReady);
insert();
}
});
} else {
insert();
}
})();
+6 -2
View File
@@ -24,13 +24,17 @@ function updateThemeUI(theme) {
const icon = document.getElementById('themeIcon'); const icon = document.getElementById('themeIcon');
const label = document.getElementById('themeLabel'); const label = document.getElementById('themeLabel');
if (!icon) return; if (!icon) return;
// 确保 t 函数存在,否则用默认文字
const translate = typeof t === 'function' ? t : function(key) { return key; };
if (theme === 'dark') { if (theme === 'dark') {
icon.innerHTML = icon.innerHTML =
`<circle cx="12" cy="12" r="5"/><line x1="12" y1="1" x2="12" y2="3"/><line x1="12" y1="21" x2="12" y2="23"/><line x1="4.22" y1="4.22" x2="5.64" y2="5.64"/><line x1="18.36" y1="18.36" x2="19.78" y2="19.78"/><line x1="1" y1="12" x2="3" y2="12"/><line x1="21" y1="12" x2="23" y2="12"/><line x1="4.22" y1="19.78" x2="5.64" y2="18.36"/><line x1="18.36" y1="5.64" x2="19.78" y2="4.22"/>`; `<circle cx="12" cy="12" r="5"/><line x1="12" y1="1" x2="12" y2="3"/><line x1="12" y1="21" x2="12" y2="23"/><line x1="4.22" y1="4.22" x2="5.64" y2="5.64"/><line x1="18.36" y1="18.36" x2="19.78" y2="19.78"/><line x1="1" y1="12" x2="3" y2="12"/><line x1="21" y1="12" x2="23" y2="12"/><line x1="4.22" y1="19.78" x2="5.64" y2="18.36"/><line x1="18.36" y1="5.64" x2="19.78" y2="4.22"/>`;
if (label) label.textContent = '☀️ 亮色模式'; if (label) label.textContent = translate('亮色模式');
} else { } else {
icon.innerHTML = `<path d="M21 12.79A9 9 0 1 1 11.21 3 7 7 0 0 0 21 12.79z"/>`; icon.innerHTML = `<path d="M21 12.79A9 9 0 1 1 11.21 3 7 7 0 0 0 21 12.79z"/>`;
if (label) label.textContent = '🌙 暗色模式'; if (label) label.textContent = translate('暗色模式');
} }
} }
+94 -24
View File
@@ -4,13 +4,13 @@
async function renderUserProfile(username) { async function renderUserProfile(username) {
const container = document.getElementById('userProfileContent'); const container = document.getElementById('userProfileContent');
container.innerHTML = '<div style="text-align:center;color:#94a3b8;padding:40px 0;">加载中...</div>'; container.innerHTML = Skeleton.userProfile();
try { try {
const users = await apiFetch('/users?username=' + encodeURIComponent(username)); // 使用公开接口 /users/profile/:username
const user = users && users.length > 0 ? users[0] : null; const user = await apiFetch('/users/profile/' + encodeURIComponent(username));
if (!user) { if (user.error || !user.id) {
container.innerHTML = '<div style="text-align:center;color:#ef4444;padding:40px 0;">用户不存在</div>'; container.innerHTML = '<div style="text-align:center;color:#ef4444;padding:40px 0;">用户不存在</div>';
return; return;
} }
@@ -22,21 +22,47 @@ async function renderUserProfile(username) {
const avatar = user.avatar_url || 'https://ui-avatars.com/api/?name=' + encodeURIComponent(user.username) + '&background=6366f1&color=fff&size=128'; const avatar = user.avatar_url || 'https://ui-avatars.com/api/?name=' + encodeURIComponent(user.username) + '&background=6366f1&color=fff&size=128';
// 已登录且不是本人时,查一次屏蔽关系,用于决定按钮文案
let blockStatus = { blocked_by_me: false, blocked_me: false };
if (currentUser && currentUser.id !== user.id) {
try {
blockStatus = await API.getBlockStatus(user.id);
} catch (err) {
// 查询失败时按未屏蔽处理,不阻断页面渲染
}
}
let html = ` let html = `
<div style="background:var(--surface);border:1px solid var(--border);border-radius:8px;padding:32px;text-align:center;"> <div style="background:var(--surface);border:1px solid var(--border);border-radius:8px;padding:32px;text-align:center;">
<img src="${avatar}" style="width:96px;height:96px;border-radius:50%;object-fit:cover;border:3px solid var(--primary);" /> <img src="${escapeHTML(safeURL(avatar, { image: true }))}" style="width:96px;height:96px;border-radius:50%;object-fit:cover;border:3px solid var(--primary);" />
<h2 style="margin:16px 0 4px;font-size:24px;">${user.username}</h2> <h2 style="margin:16px 0 4px;font-size:24px;">${escapeHTML(user.username)}</h2>
<p style="color:var(--text-secondary);font-size:14px;">${user.bio || '这个人很懒,什么都没写'}</p> <p style="color:var(--text-secondary);font-size:14px;">${escapeHTML(user.bio || '这个人很懒,什么都没写')}</p>
<div style="display:flex;justify-content:center;gap:32px;margin-top:16px;font-size:14px;color:var(--text-secondary);flex-wrap:wrap;"> <div style="display:flex;justify-content:center;gap:32px;margin-top:16px;font-size:14px;color:var(--text-secondary);flex-wrap:wrap;">
<span>📅 加入于 ${user.created_at ? new Date(user.created_at).toLocaleDateString('zh-CN') : '未知'}</span> <span>📅 加入于 ${user.created_at ? new Date(user.created_at).toLocaleDateString('zh-CN') : '未知'}</span>
<span>📝 发了 ${posts.length} 个帖子</span> <span>📝 发了 ${posts.length} 个帖子</span>
${user.role === 'admin' ? '<span style="color:var(--primary);font-weight:600;">🛡️ 管理员</span>' : ''} ${user.role === 'admin' ? '<span style="color:var(--primary);font-weight:600;">🛡️ 管理员</span>' : ''}
</div> </div>
${currentUser && currentUser.id !== user.id ? ` ${currentUser && currentUser.id !== user.id ? `
<button id="dmBtn" class="btn-primary" style="margin-top:16px;padding:8px 24px;"> <div style="display:flex;justify-content:center;gap:10px;margin-top:16px;flex-wrap:wrap;">
<svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" style="display:inline;vertical-align:middle;margin-right:6px;"><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> <!-- 被我屏蔽时不给出发私信入口,避免必然失败的尝试 -->
发私信 ${blockStatus.blocked_by_me ? '' : `
</button> <button id="dmBtn" class="btn-primary" style="padding:8px 24px;">
<svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" style="display:inline;vertical-align:middle;margin-right:6px;"><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>
发私信
</button>
`}
<button id="blockBtn" class="btn-secondary ${blockStatus.blocked_by_me ? 'is-blocked' : ''}"
data-userid="${escapeHTML(user.id)}" data-username="${escapeHTML(user.username)}"
data-blocked="${blockStatus.blocked_by_me ? '1' : '0'}"
style="padding:8px 20px;">
${blockStatus.blocked_by_me ? '解除屏蔽' : '屏蔽'}
</button>
</div>
${blockStatus.blocked_by_me ? `
<p style="margin-top:10px;font-size:12px;color:var(--text-light);">
已屏蔽该用户:你不再看到 TA 的帖子与回复,TA 也无法给你发私信
</p>
` : ''}
` : ''} ` : ''}
</div> </div>
<h3 style="margin:24px 0 16px;font-size:18px;">📝 发布的帖子</h3> <h3 style="margin:24px 0 16px;font-size:18px;">📝 发布的帖子</h3>
@@ -48,16 +74,22 @@ async function renderUserProfile(username) {
posts.forEach(p => { posts.forEach(p => {
const time = p.created_at ? new Date(p.created_at).toLocaleString('zh-CN') : ''; const time = p.created_at ? new Date(p.created_at).toLocaleString('zh-CN') : '';
html += ` html += `
<div class="post-card" style="cursor:pointer;" onclick="switchToPost('${p.id}')"> <div class="post-card" data-postid="${escapeHTML(p.id)}" style="cursor:pointer;">
<div class="post-title" style="font-size:16px;font-weight:600;">${p.title || '无标题'}</div> <div class="post-title" style="font-size:16px;font-weight:600;">${escapeHTML(p.title || '无标题')}</div>
<div class="post-content" style="font-size:14px;color:var(--text-secondary);">${(p.content || '').substring(0, 100)}${(p.content || '').length > 100 ? '...' : ''}</div> <div class="post-content" style="font-size:14px;color:var(--text-secondary);">${escapeHTML((p.content || '').substring(0, 100))}${(p.content || '').length > 100 ? '...' : ''}</div>
<div style="font-size:12px;color:var(--text-light);margin-top:8px;">${time}</div> <div style="font-size:12px;color:var(--text-light);margin-top:8px;">${time}</div>
</div> </div>
`; `;
}); });
} }
container.innerHTML = html; container.innerHTML = sanitizeHTML(html);
container.querySelectorAll('.post-card[data-postid]').forEach(card => {
card.addEventListener('click', function() {
switchToPost(this.dataset.postid);
});
});
const dmBtn = document.getElementById('dmBtn'); const dmBtn = document.getElementById('dmBtn');
if (dmBtn) { if (dmBtn) {
@@ -66,21 +98,59 @@ async function renderUserProfile(username) {
}); });
} }
// 屏蔽 / 解除屏蔽。两者都需要确认——屏蔽会影响双方的内容可见性,
// 属于不容易察觉后果的操作。
const blockBtn = document.getElementById('blockBtn');
if (blockBtn) {
blockBtn.addEventListener('click', async function() {
const targetId = this.dataset.userid;
const targetName = this.dataset.username;
const isBlocked = this.dataset.blocked === '1';
const ok = await showConfirm(
isBlocked
? `解除对「${targetName}」的屏蔽?解除后你将继续看到 TA 的帖子和回复,TA 也能再次给你发私信。`
: `确定屏蔽「${targetName}」?屏蔽后你不再看到 TA 的帖子和回复,TA 也无法给你发私信。`,
{
title: isBlocked ? '解除屏蔽' : '屏蔽用户',
confirmText: isBlocked ? '解除屏蔽' : '屏蔽',
danger: !isBlocked,
}
);
if (!ok) return;
try {
if (isBlocked) {
await API.unblockUser(targetId);
showToast('已解除屏蔽', 'success');
} else {
await API.blockUser(targetId);
showToast('已屏蔽该用户', 'success');
}
// 重新渲染以更新按钮状态与提示
renderUserProfile(user.username);
} catch (err) {
showToast(err.message, 'error');
}
});
}
} catch (err) { } catch (err) {
container.innerHTML = '<div style="text-align:center;color:#ef4444;padding:40px 0;">加载失败:' + err.message + '</div>'; container.innerHTML = '<div style="text-align:center;color:#ef4444;padding:40px 0;">加载失败:' + escapeHTML(err.message) + '</div>';
} }
} }
function showUserPage(username) { function showUserPage(username) {
document.getElementById('app').style.display = 'none'; const goingBack = typeof window.isNavigatingBack === 'function' && window.isNavigatingBack();
document.querySelectorAll('.page-slide').forEach(el => {
el.classList.remove('active', 'slide-out');
});
const el = document.getElementById('pageUser'); const el = document.getElementById('pageUser');
el.classList.add('active');
el.style.animation = 'none'; // 先让其他覆盖页滑出(例如从帖子详情跳到用户主页)
void el.offsetHeight; document.querySelectorAll('.page-slide.active').forEach(other => {
el.style.animation = ''; if (other !== el) hideSlide(other, { back: goingBack });
});
// 首页留在背景中下沉,新页面从屏幕外滑入
showSlide(el, { back: goingBack });
currentPage = 'user'; currentPage = 'user';
renderUserProfile(username); renderUserProfile(username);
} }
+203
View File
@@ -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,
};
+209
View File
@@ -0,0 +1,209 @@
-- ============================================================
-- Forumlify 数据库表结构
-- ============================================================
-- 用户表
CREATE TABLE IF NOT EXISTS users (
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
email VARCHAR(255) UNIQUE NOT NULL,
password_hash VARCHAR(255) NOT NULL,
username VARCHAR(20) UNIQUE NOT NULL,
avatar_url TEXT,
bio TEXT DEFAULT '',
role VARCHAR(10) DEFAULT 'user' CHECK (role IN ('user', 'admin')),
created_at TIMESTAMPTZ DEFAULT now()
);
-- 帖子表
CREATE TABLE IF NOT EXISTS posts (
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
user_id UUID NOT NULL REFERENCES users(id) ON DELETE CASCADE,
title VARCHAR(200) NOT NULL,
content TEXT NOT NULL,
images TEXT[] DEFAULT '{}',
created_at TIMESTAMPTZ DEFAULT now(),
updated_at TIMESTAMPTZ DEFAULT now()
);
-- 回复表
CREATE TABLE IF NOT EXISTS replies (
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
post_id UUID NOT NULL REFERENCES posts(id) ON DELETE CASCADE,
user_id UUID NOT NULL REFERENCES users(id) ON DELETE CASCADE,
content TEXT NOT NULL,
created_at TIMESTAMPTZ DEFAULT now()
);
-- 友情链接表
CREATE TABLE IF NOT EXISTS friendly_links (
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
title VARCHAR(100) NOT NULL,
url TEXT NOT NULL,
sort_order INT DEFAULT 0
);
-- 举报表
CREATE TABLE IF NOT EXISTS reports (
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
post_id UUID REFERENCES posts(id) ON DELETE SET NULL,
reporter_id UUID NOT NULL REFERENCES users(id) ON DELETE CASCADE,
reason VARCHAR(100) NOT NULL,
status VARCHAR(20) DEFAULT 'pending' CHECK (status IN ('pending', 'approved', 'rejected')),
created_at TIMESTAMPTZ DEFAULT now(),
handled_at TIMESTAMPTZ,
handler_id UUID REFERENCES users(id) ON DELETE SET NULL,
handler_note TEXT
);
-- Preserve moderation history when a reported post is deleted. This also
-- upgrades databases created with the previous ON DELETE CASCADE constraint.
DO $$
DECLARE
constraint_name TEXT;
BEGIN
SELECT con.conname INTO constraint_name
FROM pg_constraint con
JOIN pg_class rel ON rel.oid = con.conrelid
JOIN pg_attribute attr ON attr.attrelid = rel.oid AND attr.attnum = ANY(con.conkey)
WHERE rel.relname = 'reports'
AND con.contype = 'f'
AND attr.attname = 'post_id'
LIMIT 1;
IF constraint_name IS NOT NULL THEN
EXECUTE format('ALTER TABLE reports DROP CONSTRAINT %I', constraint_name);
END IF;
ALTER TABLE reports ALTER COLUMN post_id DROP NOT NULL;
ALTER TABLE reports
ADD CONSTRAINT reports_post_id_fkey
FOREIGN KEY (post_id) REFERENCES posts(id) ON DELETE SET NULL;
END $$;
-- 事件日志表
CREATE TABLE IF NOT EXISTS event_logs (
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
user_id UUID REFERENCES users(id) ON DELETE SET NULL,
action VARCHAR(50) NOT NULL,
ip VARCHAR(45),
created_at TIMESTAMPTZ DEFAULT now()
);
-- ============================================================
-- 论坛设置表
-- ============================================================
CREATE TABLE IF NOT EXISTS settings (
key VARCHAR(50) PRIMARY KEY,
value TEXT NOT NULL,
updated_at TIMESTAMPTZ DEFAULT now()
);
INSERT INTO settings (key, value) VALUES ('forum_name', 'Forumlify')
ON CONFLICT (key) DO NOTHING;
-- ============================================================
-- 私信系统
-- ============================================================
-- 私信会话表
CREATE TABLE IF NOT EXISTS conversations (
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
user1_id UUID NOT NULL REFERENCES users(id) ON DELETE CASCADE,
user2_id UUID NOT NULL REFERENCES users(id) ON DELETE CASCADE,
last_message_at TIMESTAMPTZ DEFAULT now(),
created_at TIMESTAMPTZ DEFAULT now(),
UNIQUE(user1_id, user2_id)
);
-- 私信消息表
CREATE TABLE IF NOT EXISTS messages (
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
conversation_id UUID NOT NULL REFERENCES conversations(id) ON DELETE CASCADE,
sender_id UUID NOT NULL REFERENCES users(id) ON DELETE CASCADE,
content TEXT NOT NULL,
is_read BOOLEAN DEFAULT false,
created_at TIMESTAMPTZ DEFAULT now()
);
CREATE INDEX IF NOT EXISTS idx_messages_conversation_id ON messages(conversation_id);
CREATE INDEX IF NOT EXISTS idx_messages_sender_id ON messages(sender_id);
CREATE INDEX IF NOT EXISTS idx_conversations_user1_id ON conversations(user1_id);
CREATE INDEX IF NOT EXISTS idx_conversations_user2_id ON conversations(user2_id);
-- ============================================================
-- 自定义页面表
-- ============================================================
CREATE TABLE IF NOT EXISTS custom_pages (
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
name VARCHAR(50) NOT NULL UNIQUE,
title VARCHAR(100) NOT NULL,
content TEXT NOT NULL,
enabled BOOLEAN DEFAULT true,
created_at TIMESTAMPTZ DEFAULT now(),
updated_at TIMESTAMPTZ DEFAULT now()
);
CREATE INDEX IF NOT EXISTS idx_custom_pages_name ON custom_pages(name);
-- ============================================================
-- 通知系统
-- ============================================================
CREATE TABLE IF NOT EXISTS notifications (
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
user_id UUID NOT NULL REFERENCES users(id) ON DELETE CASCADE,
type VARCHAR(30) NOT NULL,
title VARCHAR(100) NOT NULL,
content TEXT NOT NULL,
link TEXT,
is_read BOOLEAN DEFAULT false,
created_at TIMESTAMPTZ DEFAULT now()
);
CREATE INDEX IF NOT EXISTS idx_notifications_user_id ON notifications(user_id);
CREATE INDEX IF NOT EXISTS idx_notifications_is_read ON notifications(is_read);
-- ============================================================
-- 自动更新 updated_at 的触发器
-- ============================================================
CREATE OR REPLACE FUNCTION update_updated_at()
RETURNS TRIGGER AS $$
BEGIN
NEW.updated_at = now();
RETURN NEW;
END;
$$ LANGUAGE plpgsql;
DROP TRIGGER IF EXISTS update_posts_updated_at ON posts;
CREATE TRIGGER update_posts_updated_at
BEFORE UPDATE ON posts
FOR EACH ROW EXECUTE FUNCTION update_updated_at();
ALTER TABLE posts ADD COLUMN IF NOT EXISTS edited_at TIMESTAMPTZ;
-- ============================================================
-- 恢复码表(密码重置用)
-- ============================================================
CREATE TABLE IF NOT EXISTS recovery_codes (
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
user_id UUID NOT NULL REFERENCES users(id) ON DELETE CASCADE,
code_hash VARCHAR(255) NOT NULL,
is_used BOOLEAN DEFAULT false,
created_at TIMESTAMPTZ DEFAULT now()
);
CREATE INDEX IF NOT EXISTS idx_recovery_codes_user_id ON recovery_codes(user_id);
-- 帖子表添加置顶字段
ALTER TABLE posts ADD COLUMN IF NOT EXISTS is_pinned BOOLEAN DEFAULT false;
ALTER TABLE posts ADD COLUMN IF NOT EXISTS pinned_at TIMESTAMPTZ;
-- 创建索引
CREATE INDEX IF NOT EXISTS idx_posts_is_pinned ON posts(is_pinned);
ALTER TABLE users ADD COLUMN IF NOT EXISTS signature TEXT DEFAULT '';
-- ============================================================
-- 论坛默认设置
-- ============================================================
INSERT INTO settings (key, value) VALUES ('forum_name', 'Forumlify')
ON CONFLICT (key) DO NOTHING;
@@ -0,0 +1,36 @@
-- ============================================================
-- 恢复认证与审计日志所需的缺失列
-- ============================================================
--
-- 背景:001_initial.sql 创建了 users / event_logs 表,但遗漏了
-- server.js 强依赖的若干列。schema.sql 里一直有这些列,两套定义
-- 因此产生漂移,导致 npm run migrate / Docker 部署出来的库在
-- 登录之后所有需要鉴权的接口全部返回 500:
--
-- users.token_version 认证中间件每个请求都会查询它
-- event_logs.method 审计日志写入
-- event_logs.path 审计日志写入
-- event_logs.user_agent 审计日志写入
-- event_logs.metadata 审计日志写入
--
-- 001_initial.sql 已经被记录进 schema_migrations,无法重跑,
-- 因此这里单独追加一版让已部署的库获得同样的修复。
-- 全部语句都是幂等的,对全新库同样安全。
-- token_version:用于在改密码/改邮箱后使旧 JWT 立即失效。
-- NOT NULL DEFAULT 0 会让存量用户的现有令牌保持有效(值为 0),
-- 不会强制所有人重新登录。
ALTER TABLE users ADD COLUMN IF NOT EXISTS token_version INTEGER NOT NULL DEFAULT 0;
-- 事件日志的扩展字段,与 schema.sql 第 100-105 行保持一致。
ALTER TABLE event_logs ADD COLUMN IF NOT EXISTS method VARCHAR(10);
ALTER TABLE event_logs ADD COLUMN IF NOT EXISTS path TEXT;
ALTER TABLE event_logs ADD COLUMN IF NOT EXISTS user_agent TEXT;
ALTER TABLE event_logs ADD COLUMN IF NOT EXISTS metadata JSONB NOT NULL DEFAULT '{}'::jsonb;
-- 管理员事件日志按时间倒序分页,另有按用户检索的需求。
CREATE INDEX IF NOT EXISTS idx_event_logs_created_at ON event_logs(created_at DESC);
CREATE INDEX IF NOT EXISTS idx_event_logs_user_id ON event_logs(user_id);
-- 兼容混合大小写的历史邮箱,让 LOWER(email) 查询走索引。
CREATE INDEX IF NOT EXISTS idx_users_email_lower ON users (LOWER(email));
+66
View File
@@ -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;
+17
View File
@@ -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;
+39
View File
@@ -0,0 +1,39 @@
-- ============================================================
-- 帖子搜索
-- ------------------------------------------------------------
-- 搜索用 ILIKE 做子串匹配(见 server.js 的 /api/posts/search)。
-- 之所以不用 PostgreSQL 的全文检索(tsvector):它依赖分词,而
-- 中文分词需要额外安装 zhparser 等扩展,多数部署环境没有;ILIKE
-- 无需任何扩展即可正确匹配中文子串。
--
-- 索引用 pg_trgm 的 GIN 索引,实测效果分两种情况:
-- - 英文关键词(如 postgresql):走 Bitmap Index Scan,0.2ms,
-- 相比全表扫描快约 47 倍
-- - 中文关键词:pg_trgm 对中文难以切出有效 trigram,优化器仍选
-- 全表扫描。3000 条数据下约 7~9ms,可接受
-- 即索引对英文有效、对中文无效。许多技术论坛中英混排,保留仍有
-- 价值。
--
-- 注意:创建扩展需要相应权限。部分托管数据库不开放该权限,因此
-- 失败时仅提示,不影响后续迁移与功能——搜索本身不依赖扩展。
-- ============================================================
DO $$
BEGIN
CREATE EXTENSION IF NOT EXISTS pg_trgm;
EXCEPTION WHEN OTHERS THEN
RAISE NOTICE 'pg_trgm 扩展创建失败(%)。搜索仍可正常使用,但英文关键词将无法走索引加速。', SQLERRM;
END $$;
-- 仅在扩展可用时才建索引
DO $$
BEGIN
IF EXISTS (SELECT 1 FROM pg_extension WHERE extname = 'pg_trgm') THEN
CREATE INDEX IF NOT EXISTS idx_posts_title_trgm
ON posts USING gin (title gin_trgm_ops);
CREATE INDEX IF NOT EXISTS idx_posts_content_trgm
ON posts USING gin (content gin_trgm_ops);
ELSE
RAISE NOTICE '跳过 trigram 索引创建:pg_trgm 不可用。';
END IF;
END $$;
+30
View File
@@ -0,0 +1,30 @@
-- ============================================================
-- 用户屏蔽
-- ------------------------------------------------------------
-- 单向关系:blocker 屏蔽 blocked 之后
-- - blocked 不能再给 blocker 发私信(已有的会话也发不了)
-- - blocker 在帖子列表、详情与回复中不再看到 blocked 的内容
-- - blocked 仍可正常浏览 blocker 的公开内容(不通知、不暴露)
--
-- 之所以是单向而非互斥:屏蔽应当是「我选择不看某人的内容、也不让
-- 对方打扰我」,而不是让双方互相消失。被屏蔽方不会收到任何提示。
-- ============================================================
CREATE TABLE IF NOT EXISTS user_blocks (
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
-- 发起屏蔽的人
blocker_id UUID NOT NULL REFERENCES users(id) ON DELETE CASCADE,
-- 被屏蔽的人
blocked_id UUID NOT NULL REFERENCES users(id) ON DELETE CASCADE,
created_at TIMESTAMPTZ NOT NULL DEFAULT now(),
-- 同一对关系只能有一条
UNIQUE (blocker_id, blocked_id),
-- 不允许屏蔽自己
CHECK (blocker_id <> blocked_id)
);
-- 主查询方向:某人屏蔽了谁(用于过滤内容)
CREATE INDEX IF NOT EXISTS idx_user_blocks_blocker ON user_blocks(blocker_id);
-- 反向查询:某人被谁屏蔽(用于判断能否发私信)
CREATE INDEX IF NOT EXISTS idx_user_blocks_blocked ON user_blocks(blocked_id);
+309 -656
View File
File diff suppressed because it is too large. Load diff
+16 -3
View File
@@ -3,16 +3,29 @@
"version": "1.0.0", "version": "1.0.0",
"description": "Forumlify - 简洁优雅的现代社区系统", "description": "Forumlify - 简洁优雅的现代社区系统",
"main": "server.js", "main": "server.js",
"engines": {
"node": ">=20"
},
"scripts": { "scripts": {
"start": "node server.js", "start": "node server.js",
"dev": "node server.js" "dev": "node server.js",
"migrate": "node scripts/migrate.js",
"check": "node scripts/check-syntax.js",
"test": "node --test"
}, },
"dependencies": { "dependencies": {
"bcrypt": "^5.1.1", "bcryptjs": "3.0.3",
"cors": "^2.8.5", "cors": "^2.8.5",
"express": "^4.18.2", "express": "^4.18.2",
"express-rate-limit": "8.6.2",
"helmet": "8.1.0",
"jsonwebtoken": "^9.0.2", "jsonwebtoken": "^9.0.2",
"multer": "^1.4.5-lts.1", "multer": "2.4.0",
"nodemailer": "^7.0.9",
"pg": "^8.11.3" "pg": "^8.11.3"
},
"devDependencies": {
"supertest": "7.2.2"
} }
} }
+214 -1
View File
@@ -11,9 +11,13 @@ CREATE TABLE IF NOT EXISTS users (
avatar_url TEXT, avatar_url TEXT,
bio TEXT DEFAULT '', bio TEXT DEFAULT '',
role VARCHAR(10) DEFAULT 'user' CHECK (role IN ('user', 'admin')), role VARCHAR(10) DEFAULT 'user' CHECK (role IN ('user', 'admin')),
token_version INTEGER NOT NULL DEFAULT 0,
created_at TIMESTAMPTZ DEFAULT now() created_at TIMESTAMPTZ DEFAULT now()
); );
-- Keep case-insensitive lookups index-backed for legacy mixed-case emails.
CREATE INDEX IF NOT EXISTS idx_users_email_lower ON users (LOWER(email));
-- 帖子表 -- 帖子表
CREATE TABLE IF NOT EXISTS posts ( CREATE TABLE IF NOT EXISTS posts (
id UUID PRIMARY KEY DEFAULT gen_random_uuid(), id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
@@ -45,7 +49,7 @@ CREATE TABLE IF NOT EXISTS friendly_links (
-- 举报表 -- 举报表
CREATE TABLE IF NOT EXISTS reports ( CREATE TABLE IF NOT EXISTS reports (
id UUID PRIMARY KEY DEFAULT gen_random_uuid(), id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
post_id UUID NOT NULL REFERENCES posts(id) ON DELETE CASCADE, post_id UUID REFERENCES posts(id) ON DELETE SET NULL,
reporter_id UUID NOT NULL REFERENCES users(id) ON DELETE CASCADE, reporter_id UUID NOT NULL REFERENCES users(id) ON DELETE CASCADE,
reason VARCHAR(100) NOT NULL, reason VARCHAR(100) NOT NULL,
status VARCHAR(20) DEFAULT 'pending' CHECK (status IN ('pending', 'approved', 'rejected')), status VARCHAR(20) DEFAULT 'pending' CHECK (status IN ('pending', 'approved', 'rejected')),
@@ -55,15 +59,51 @@ CREATE TABLE IF NOT EXISTS reports (
handler_note TEXT handler_note TEXT
); );
-- Preserve moderation history when a reported post is deleted. This also
-- upgrades databases created with the previous ON DELETE CASCADE constraint.
DO $$
DECLARE
constraint_name TEXT;
BEGIN
SELECT con.conname INTO constraint_name
FROM pg_constraint con
JOIN pg_class rel ON rel.oid = con.conrelid
JOIN pg_attribute attr ON attr.attrelid = rel.oid AND attr.attnum = ANY(con.conkey)
WHERE rel.relname = 'reports'
AND con.contype = 'f'
AND attr.attname = 'post_id'
LIMIT 1;
IF constraint_name IS NOT NULL THEN
EXECUTE format('ALTER TABLE reports DROP CONSTRAINT %I', constraint_name);
END IF;
ALTER TABLE reports ALTER COLUMN post_id DROP NOT NULL;
ALTER TABLE reports
ADD CONSTRAINT reports_post_id_fkey
FOREIGN KEY (post_id) REFERENCES posts(id) ON DELETE SET NULL;
END $$;
-- 事件日志表 -- 事件日志表
CREATE TABLE IF NOT EXISTS event_logs ( CREATE TABLE IF NOT EXISTS event_logs (
id UUID PRIMARY KEY DEFAULT gen_random_uuid(), id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
user_id UUID REFERENCES users(id) ON DELETE SET NULL, user_id UUID REFERENCES users(id) ON DELETE SET NULL,
action VARCHAR(50) NOT NULL, action VARCHAR(50) NOT NULL,
ip VARCHAR(45), ip VARCHAR(45),
method VARCHAR(10),
path TEXT,
user_agent TEXT,
metadata JSONB NOT NULL DEFAULT '{}'::jsonb,
created_at TIMESTAMPTZ DEFAULT now() created_at TIMESTAMPTZ DEFAULT now()
); );
ALTER TABLE event_logs ADD COLUMN IF NOT EXISTS method VARCHAR(10);
ALTER TABLE event_logs ADD COLUMN IF NOT EXISTS path TEXT;
ALTER TABLE event_logs ADD COLUMN IF NOT EXISTS user_agent TEXT;
ALTER TABLE event_logs ADD COLUMN IF NOT EXISTS metadata JSONB NOT NULL DEFAULT '{}'::jsonb;
CREATE INDEX IF NOT EXISTS idx_event_logs_created_at ON event_logs(created_at DESC);
CREATE INDEX IF NOT EXISTS idx_event_logs_user_id ON event_logs(user_id);
-- ============================================================ -- ============================================================
-- 论坛设置表 -- 论坛设置表
-- ============================================================ -- ============================================================
@@ -87,6 +127,7 @@ CREATE TABLE IF NOT EXISTS conversations (
user2_id UUID NOT NULL REFERENCES users(id) ON DELETE CASCADE, user2_id UUID NOT NULL REFERENCES users(id) ON DELETE CASCADE,
last_message_at TIMESTAMPTZ DEFAULT now(), last_message_at TIMESTAMPTZ DEFAULT now(),
created_at TIMESTAMPTZ DEFAULT now(), created_at TIMESTAMPTZ DEFAULT now(),
CHECK (user1_id < user2_id),
UNIQUE(user1_id, user2_id) UNIQUE(user1_id, user2_id)
); );
@@ -167,3 +208,175 @@ CREATE TABLE IF NOT EXISTS recovery_codes (
); );
CREATE INDEX IF NOT EXISTS idx_recovery_codes_user_id ON recovery_codes(user_id); CREATE INDEX IF NOT EXISTS idx_recovery_codes_user_id ON recovery_codes(user_id);
-- 帖子表添加置顶字段
ALTER TABLE posts ADD COLUMN IF NOT EXISTS is_pinned BOOLEAN DEFAULT false;
ALTER TABLE posts ADD COLUMN IF NOT EXISTS pinned_at TIMESTAMPTZ;
-- 创建索引
CREATE INDEX IF NOT EXISTS idx_posts_is_pinned ON posts(is_pinned);
ALTER TABLE users ADD COLUMN IF NOT EXISTS signature TEXT DEFAULT '';
ALTER TABLE users ADD COLUMN IF NOT EXISTS token_version INTEGER NOT NULL DEFAULT 0;
-- Canonicalize conversation pairs and merge any pre-existing reverse/duplicate
-- conversations before enforcing one row per unordered user pair.
ALTER TABLE conversations DROP CONSTRAINT IF EXISTS conversations_user1_id_user2_id_key;
ALTER TABLE conversations DROP CONSTRAINT IF EXISTS conversations_canonical_pair;
WITH ranked AS (
SELECT
id,
FIRST_VALUE(id) OVER (
PARTITION BY LEAST(user1_id, user2_id), GREATEST(user1_id, user2_id)
ORDER BY created_at, id
) AS keep_id
FROM conversations
)
UPDATE messages AS m
SET conversation_id = ranked.keep_id
FROM ranked
WHERE m.conversation_id = ranked.id
AND ranked.id <> ranked.keep_id;
WITH ranked AS (
SELECT
id,
ROW_NUMBER() OVER (
PARTITION BY LEAST(user1_id, user2_id), GREATEST(user1_id, user2_id)
ORDER BY created_at, id
) AS row_number
FROM conversations
)
DELETE FROM conversations AS c
USING ranked
WHERE c.id = ranked.id AND ranked.row_number > 1;
UPDATE conversations
SET user1_id = LEAST(user1_id, user2_id),
user2_id = GREATEST(user1_id, user2_id);
ALTER TABLE conversations
ADD CONSTRAINT conversations_canonical_pair CHECK (user1_id < user2_id);
ALTER TABLE conversations
ADD CONSTRAINT conversations_user1_id_user2_id_key UNIQUE (user1_id, user2_id);
-- Keep one pending report per reporter/post at the database layer. Historical
-- duplicates are rejected before creating the partial unique index.
WITH duplicates AS (
SELECT id, ROW_NUMBER() OVER (
PARTITION BY post_id, reporter_id
ORDER BY created_at, id
) AS row_number
FROM reports
WHERE status = 'pending' AND post_id IS NOT NULL
)
UPDATE reports AS r
SET status = 'rejected',
handled_at = COALESCE(r.handled_at, NOW()),
handler_note = COALESCE(r.handler_note, '重复举报已自动合并')
FROM duplicates
WHERE r.id = duplicates.id AND duplicates.row_number > 1;
CREATE UNIQUE INDEX IF NOT EXISTS idx_reports_unique_pending
ON reports(post_id, reporter_id)
WHERE status = 'pending' AND post_id IS NOT NULL;
-- ============================================================
-- 论坛默认设置
-- ============================================================
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;
-- ============================================================
-- 帖子搜索(对应 migrations/005_post_search.sql)
-- ------------------------------------------------------------
-- 搜索用 ILIKE 子串匹配。trigram 索引对英文关键词有效(实测 0.2ms,
-- 比全表扫描快约 47 倍),对中文因难以切出有效 trigram 而仍走全表
-- 扫描(3000 条约 7~9ms,可接受)。
--
-- 创建扩展需要权限,部分托管数据库不开放,故失败时仅提示。
-- ============================================================
DO $$
BEGIN
CREATE EXTENSION IF NOT EXISTS pg_trgm;
EXCEPTION WHEN OTHERS THEN
RAISE NOTICE 'pg_trgm 扩展创建失败(%)。搜索仍可用,但英文关键词不走索引。', SQLERRM;
END $$;
DO $$
BEGIN
IF EXISTS (SELECT 1 FROM pg_extension WHERE extname = 'pg_trgm') THEN
CREATE INDEX IF NOT EXISTS idx_posts_title_trgm
ON posts USING gin (title gin_trgm_ops);
CREATE INDEX IF NOT EXISTS idx_posts_content_trgm
ON posts USING gin (content gin_trgm_ops);
END IF;
END $$;
-- ============================================================
-- 用户屏蔽(对应 migrations/006_user_blocks.sql)
-- ------------------------------------------------------------
-- 单向关系:blocker 屏蔽 blocked 之后,blocked 不能给 blocker 发私信,
-- 且 blocker 在帖子与回复中不再看到 blocked 的内容。
-- 被屏蔽方不会收到任何提示。
-- ============================================================
CREATE TABLE IF NOT EXISTS user_blocks (
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
blocker_id UUID NOT NULL REFERENCES users(id) ON DELETE CASCADE,
blocked_id UUID NOT NULL REFERENCES users(id) ON DELETE CASCADE,
created_at TIMESTAMPTZ NOT NULL DEFAULT now(),
UNIQUE (blocker_id, blocked_id),
CHECK (blocker_id <> blocked_id)
);
CREATE INDEX IF NOT EXISTS idx_user_blocks_blocker ON user_blocks(blocker_id);
CREATE INDEX IF NOT EXISTS idx_user_blocks_blocked ON user_blocks(blocked_id);
+12
View File
@@ -0,0 +1,12 @@
const { execFileSync } = require('node:child_process');
const path = require('node:path');
const files = execFileSync('git', ['ls-files', '*.js'], { encoding: 'utf8' })
.split(/\r?\n/)
.filter(Boolean);
for (const file of files) {
execFileSync(process.execPath, ['--check', path.resolve(file)], { stdio: 'inherit' });
}
console.log(`Syntax check passed for ${files.length} JavaScript files.`);
+5
View File
@@ -0,0 +1,5 @@
#!/bin/sh
set -eu
node scripts/migrate.js
exec node server.js
+11
View File
@@ -0,0 +1,11 @@
const port = process.env.PORT || 3000;
const url = `http://127.0.0.1:${port}/health/ready`;
fetch(url, { signal: AbortSignal.timeout(4000) })
.then(response => {
if (!response.ok) throw new Error(`readiness returned ${response.status}`);
})
.catch(error => {
console.error(error.message);
process.exit(1);
});
+59
View File
@@ -0,0 +1,59 @@
const fs = require('node:fs/promises');
const path = require('node:path');
const { Pool } = require('pg');
const migrationsDir = path.join(__dirname, '..', 'migrations');
if (!process.env.DATABASE_URL && !process.env.PGHOST) {
console.error('DATABASE_URL or PGHOST is required to run migrations.');
process.exit(1);
}
async function migrate() {
const pool = new Pool();
const client = await pool.connect();
try {
await client.query(`
CREATE TABLE IF NOT EXISTS schema_migrations (
filename TEXT PRIMARY KEY,
applied_at TIMESTAMPTZ NOT NULL DEFAULT NOW()
)
`);
const files = (await fs.readdir(migrationsDir))
.filter(file => /^\d+.*\.sql$/.test(file))
.sort();
const applied = await client.query('SELECT filename FROM schema_migrations');
const appliedFiles = new Set(applied.rows.map(row => row.filename));
for (const filename of files) {
if (appliedFiles.has(filename)) continue;
const sql = await fs.readFile(path.join(migrationsDir, filename), 'utf8');
console.log(`Applying migration ${filename}`);
await client.query('BEGIN');
try {
await client.query(sql);
await client.query(
'INSERT INTO schema_migrations (filename) VALUES ($1)',
[filename]
);
await client.query('COMMIT');
} catch (error) {
await client.query('ROLLBACK');
throw error;
}
}
console.log('Database migrations are up to date.');
} finally {
client.release();
await pool.end();
}
}
migrate().catch(error => {
console.error('Database migration failed:', error);
process.exit(1);
});
+1679 -252
View File
File diff suppressed because it is too large. Load diff
+3271 -359
View File
File diff suppressed because it is too large. Load diff
+89
View File
@@ -0,0 +1,89 @@
const test = require('node:test');
const assert = require('node:assert/strict');
const request = require('supertest');
const bcrypt = require('bcryptjs');
const multerPackage = require('multer/package.json');
const projectPackage = require('../package.json');
const { app, pool } = require('../server');
test.after(async () => {
await pool.end();
});
test('serves the frontend with hardened response headers', async () => {
const response = await request(app).get('/').expect(200);
assert.match(response.headers['content-type'], /^text\/html/);
assert.equal(response.headers['x-content-type-options'], 'nosniff');
assert.equal(response.headers['x-frame-options'], 'SAMEORIGIN');
assert.equal(response.headers['x-powered-by'], undefined);
});
test('does not serve backend source and deployment files', async () => {
for (const path of ['/server.js', '/schema.sql', '/package.json', '/docker-compose.yml']) {
await request(app).get(path).expect(404);
}
});
test('unknown API route returns JSON 404 instead of hanging', async () => {
const response = await request(app)
.get('/api/definitely-unknown')
.timeout({ response: 1000, deadline: 2000 })
.expect(404);
assert.deepEqual(response.body, { error: '接口不存在' });
assert.ok(response.headers.ratelimit);
});
test('request body limit returns a structured 413 response', async () => {
const response = await request(app)
.post('/api/auth/login')
.send({ email: 'user@example.test', password: 'x'.repeat(110000) })
.expect(413);
assert.equal(response.body.error, '请求内容过大');
});
test('registration and login validate required fields before database access', async () => {
let response = await request(app)
.post('/api/auth/register')
.send({ email: '', password: '', username: '' })
.expect(400);
assert.equal(response.body.error, '请填写完整信息');
response = await request(app)
.post('/api/auth/login')
.send({ email: '', password: '' })
.expect(400);
assert.equal(response.body.error, '请填写邮箱和密码');
});
test('protected routes reject unauthenticated requests', async () => {
const response = await request(app)
.post('/api/posts')
.send({ title: 'test', content: 'test' })
.expect(401);
assert.equal(response.body.error, '请先登录');
});
test('bcryptjs hashes passwords without native install scripts', async () => {
const hash = await bcrypt.hash('correct horse battery staple', 4);
assert.equal(await bcrypt.compare('correct horse battery staple', hash), true);
assert.equal(await bcrypt.compare('wrong password', hash), false);
});
test('security-sensitive dependencies are on patched release lines', () => {
// 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 是邮件功能的必需依赖'
);
});
+88
View File
@@ -0,0 +1,88 @@
const test = require('node:test');
const assert = require('node:assert/strict');
const fs = require('node:fs');
const path = require('node:path');
// 管理员初始化令牌(ADMIN_BOOTSTRAP_TOKEN)属于部署期的一次性机制,
// 不应暴露给普通注册用户。历史上它的输入框固定显示在注册模态框里,
// 每个来注册的人都会看到一个「管理员初始化令牌」字段,既困惑又等于
// 对外宣告存在提权入口。
//
// 现在的约定:输入框默认隐藏,只有 /api/settings 返回
// bootstrap_required === true 时才显示,该标志仅在「部署者配置了引导
// 令牌」且「系统尚无管理员」时为真。
//
// 以下断言不依赖数据库,直接在文本层面锁住这些约定。
const root = path.join(__dirname, '..');
const indexHTML = fs.readFileSync(path.join(root, 'index.html'), 'utf8');
const authJS = fs.readFileSync(path.join(root, 'js', 'auth.js'), 'utf8');
const serverJS = fs.readFileSync(path.join(root, 'server.js'), 'utf8');
test('bootstrap token field is hidden by default in the markup', () => {
const field = indexHTML.match(/<input[^>]*id="regBootstrapToken"[^>]*>/i);
assert.ok(field, '注册模态框中找不到 regBootstrapToken 输入框');
assert.match(
field[0],
/style\s*=\s*"[^"]*display\s*:\s*none/i,
'regBootstrapToken 必须默认隐藏,仅在首次部署且已配置引导令牌时由脚本显示'
);
});
test('/api/settings only exposes a boolean, never the token itself', () => {
const route = serverJS.match(/app\.get\('\/api\/settings'[\s\S]*?\n\}\);/);
assert.ok(route, '找不到 GET /api/settings 路由');
const body = route[0];
assert.match(
body,
/bootstrap_required/,
'接口需要返回 bootstrap_required 供前端判断是否显示初始化入口'
);
assert.match(
body,
/process\.env\.ADMIN_BOOTSTRAP_TOKEN/,
'bootstrap_required 必须依据是否配置了引导令牌来判断'
);
assert.match(
body,
/role\s*=\s*'admin'/,
'bootstrap_required 还必须检查是否已存在管理员'
);
// 不得把令牌明文或其长度写进响应。
assert.doesNotMatch(
body,
/settings\.\w*token\w*\s*=\s*process\.env\.ADMIN_BOOTSTRAP_TOKEN/i,
'不得把引导令牌本身放进响应'
);
assert.doesNotMatch(
body,
/ADMIN_BOOTSTRAP_TOKEN\s*\)\s*\.\s*length|ADMIN_BOOTSTRAP_TOKEN\s*\.\s*length/,
'不得返回引导令牌的长度,避免泄露部署配置细节'
);
});
test('registration ignores the hidden field instead of submitting an empty token', () => {
// 字段隐藏时必须按「未提供」处理,否则会传空串进入后端的令牌校验
// 分支,让普通注册收到 403。
assert.match(
authJS,
/style\.display\s*!==\s*'none'/,
'读取 regBootstrapToken 前必须判断其是否可见'
);
assert.match(
authJS,
/bootstrap_required/,
'auth.js 需要依据 bootstrap_required 决定是否显示该字段'
);
});
test('registration form still works without the bootstrap field', () => {
// 普通注册路径不得依赖该字段存在。
assert.match(
authJS,
/if\s*\(\s*bootstrapField\s*\)/,
'清理表单时必须对可能不存在的 bootstrap 字段做空值保护'
);
});
+134
View File
@@ -0,0 +1,134 @@
const test = require('node:test');
const assert = require('node:assert/strict');
const fs = require('node:fs');
const path = require('node:path');
// i18n 采用「中文原文作 key」的外挂方案:js/i18n.js 里的 zh 词典登记
// 哪些中文需要翻译(键与值相同),en 词典提供对应译文;运行时遍历
// DOM,只有能在 zh 词典里精确命中的文本才会被替换。
//
// 因此「漏翻译」= 界面文案没被登记进词典。历史上曾有 60 余条界面文案
// (各类失败提示、表单校验、确认对话框)从未登记,切到英文后仍是中文。
// 这里直接从源码里抽出中文文案,断言它们都在词典里出现过。
const root = path.join(__dirname, '..');
const i18nSource = fs.readFileSync(path.join(root, 'js', 'i18n.js'), 'utf8');
// 取 zh 词典块(第一个 'zh': { ... } )。
function extractDict(source, lang) {
const startMatch = source.match(new RegExp(`'${lang}'\\s*:\\s*\\{`));
assert.ok(startMatch, `找不到 ${lang} 词典`);
const start = startMatch.index + startMatch[0].length;
// 从起点开始做花括号配平,避免被字符串里的括号干扰。
let depth = 1;
let i = start;
let inString = false;
let quote = '';
for (; i < source.length && depth > 0; i++) {
const ch = source[i];
const prev = source[i - 1];
if (inString) {
if (ch === quote && prev !== '\\') inString = false;
continue;
}
if (ch === '"' || ch === "'" || ch === '`') { inString = true; quote = ch; continue; }
if (ch === '{') depth++;
else if (ch === '}') depth--;
}
return source.slice(start, i - 1);
}
const zhBlock = extractDict(i18nSource, 'zh');
const enBlock = extractDict(i18nSource, 'en');
const keyPattern = /^\s*'((?:[^'\\]|\\.)*)'\s*:/gm;
const collectKeys = block => {
const keys = new Set();
let m;
keyPattern.lastIndex = 0;
while ((m = keyPattern.exec(block)) !== null) keys.add(m[1]);
return keys;
};
const zhKeys = collectKeys(zhBlock);
const enKeys = collectKeys(enBlock);
// 从源码里抽出所有中文文案。
function collectChineseLiterals() {
const literals = new Set();
const files = ['index.html', ...fs.readdirSync(path.join(root, 'js'))
.filter(f => f.endsWith('.js') && f !== 'i18n.js')
.map(f => path.join('js', f))];
const cjk = /[\u4e00-\u9fff]/;
for (const file of files) {
const full = path.join(root, file);
if (!fs.existsSync(full)) continue;
const text = fs.readFileSync(full, 'utf8');
// 引号包裹的中文串
for (const m of text.matchAll(/(['"`])([\u4e00-\u9fff][^'"`\n]{0,80}?)\1/g)) {
const value = m[2].trim();
if (cjk.test(value) && value.length >= 2) literals.add(value);
}
}
return literals;
}
test('zh and en dictionaries define exactly the same keys', () => {
const missingInEn = [...zhKeys].filter(k => !enKeys.has(k));
const missingInZh = [...enKeys].filter(k => !zhKeys.has(k));
assert.deepEqual(missingInEn, [], `en 词典缺少:${missingInEn.join(', ')}`);
assert.deepEqual(missingInZh, [], `zh 词典缺少:${missingInZh.join(', ')}`);
});
test('no translation maps to an empty string', () => {
// walk() 命中词典后会用译文替换原文,空串会把界面文字抹掉。
const empties = [];
const pattern = /^\s*'((?:[^'\\]|\\.)*)'\s*:\s*''/gm;
let m;
pattern.lastIndex = 0;
while ((m = pattern.exec(enBlock)) !== null) empties.push(m[1]);
assert.deepEqual(empties, [], `以下条目的英文译文为空串:${empties.join(', ')}`);
});
test('common failure prefixes are registered for translation', () => {
// 源码里的错误提示普遍是 「XX失败:」+ 具体原因 的形式,
// 与不带冒号的短词属于不同字符串,必须分别登记。
const prefixes = [
'保存失败:', '删除失败:', '操作失败:', '登录失败:', '发布失败:',
'上传失败:', '举报失败:', '注册失败:', '回复失败:', '添加失败:',
'发送失败:', '编辑失败:', '加载失败:',
];
const missing = prefixes.filter(k => !zhKeys.has(k));
assert.deepEqual(missing, [], `以下错误提示前缀未登记,切英文后仍显示中文:${missing.join(', ')}`);
});
test('confirmation dialogs and form validation are registered', () => {
const required = [
'确定要退出吗?',
'确定要删除这条帖子吗?',
'确定要删除这条回复吗?',
'密码至少6位',
'验证码错误,请重新计算',
'请输入论坛名称',
'请填写回复内容',
'松开上传',
'暂无消息',
'未知',
'匿名用户',
];
const missing = required.filter(k => !zhKeys.has(k));
assert.deepEqual(missing, [], `以下文案未登记翻译:${missing.join(', ')}`);
});
test('interface copy coverage is above the required floor', () => {
const literals = collectChineseLiterals();
const uncovered = [...literals].filter(lit => !zhKeys.has(lit));
// 允许少量无法静态登记的动态拼接串,但整体覆盖率必须保持在
// 高水位,防止再次出现大批文案漏登记的情况。
const coverage = 1 - uncovered.length / Math.max(literals.size, 1);
assert.ok(
coverage >= 0.9,
`界面中文文案覆盖率 ${(coverage * 100).toFixed(1)}% 低于 90%;未登记:${uncovered.join(' | ')}`
);
});
+77
View File
@@ -0,0 +1,77 @@
const test = require('node:test');
const assert = require('node:assert/strict');
const fs = require('node:fs');
const path = require('node:path');
// 这些测试锁定迁移文件与 server.js 之间的契约,不需要数据库连接。
//
// 背景:migrations/ 与 schema.sql 曾各自维护 table 定义,001_initial.sql
// 漏掉了 users.token_version 和 event_logs 的审计字段,导致登录之后所有
// 需要鉴权的接口 500。当时的测试只覆盖未认证路径,因此完全没有察觉。
// 这里直接在 SQL 文本层面断言这些列存在,让同样的漂移在 CI 里立刻失败。
const migrationsDir = path.join(__dirname, '..', 'migrations');
const migrationFiles = fs.readdirSync(migrationsDir).filter(file => file.endsWith('.sql')).sort();
const migrationSQL = migrationFiles
.map(file => fs.readFileSync(path.join(migrationsDir, file), 'utf8'))
.join('\n');
// server.js 直接引用、缺失即导致运行时 500 的列。
const REQUIRED_COLUMNS = [
{ table: 'users', column: 'token_version' },
{ table: 'event_logs', column: 'method' },
{ table: 'event_logs', column: 'path' },
{ table: 'event_logs', column: 'user_agent' },
{ table: 'event_logs', column: 'metadata' },
];
function migrationDefinesColumn(table, column) {
// 命中 CREATE TABLE 内的列定义,或后续的 ALTER TABLE ... ADD COLUMN。
const createTable = new RegExp(`CREATE TABLE[^;]*?\\b${table}\\b[^;]*?;`, 'is');
const createBlock = migrationSQL.match(createTable);
if (createBlock && new RegExp(`\\b${column}\\b`, 'i').test(createBlock[0])) return true;
const alterColumn = new RegExp(
`ALTER TABLE\\s+${table}\\s+ADD COLUMN(?:\\s+IF NOT EXISTS)?\\s+${column}\\b`,
'i'
);
return alterColumn.test(migrationSQL);
}
test('migrations define every column the server queries', () => {
for (const { table, column } of REQUIRED_COLUMNS) {
assert.ok(
migrationDefinesColumn(table, column),
`migrations/ 未定义 ${table}.${column};server.js 依赖该列,缺失会导致登录后接口 500`
);
}
});
test('schema.sql and migrations stay in sync on required columns', () => {
const schemaSQL = fs.readFileSync(path.join(__dirname, '..', 'schema.sql'), 'utf8');
for (const { table, column } of REQUIRED_COLUMNS) {
const inSchema = new RegExp(`\\b${column}\\b`, 'i').test(schemaSQL);
assert.ok(inSchema, `schema.sql 缺少 ${table}.${column},两套定义发生漂移`);
}
});
test('migration files are named so the runner applies them in order', () => {
assert.ok(migrationFiles.length > 0, 'migrations/ 目录为空');
for (const file of migrationFiles) {
assert.match(file, /^\d+.*\.sql$/, `迁移文件名 ${file} 不匹配 runner 的 /^\\d+.*\\.sql$/ 过滤规则`);
}
});
test('migration statements are idempotent for already-deployed databases', () => {
// 001 已被记录进 schema_migrations,修复只能靠新增迁移;新增的
// ALTER TABLE 必须带 IF NOT EXISTS,否则对全新库会重复执行报错。
const alterStatements = migrationSQL.match(/ALTER TABLE\s+\w+\s+ADD COLUMN[^;]*/gi) || [];
assert.ok(alterStatements.length > 0, '未找到任何 ADD COLUMN 语句');
for (const statement of alterStatements) {
assert.match(
statement,
/ADD COLUMN IF NOT EXISTS/i,
`非幂等语句会导致重复执行失败:${statement.trim()}`
);
}
});
+99
View File
@@ -0,0 +1,99 @@
process.env.TRUST_PROXY = 'true';
const test = require('node:test');
const assert = require('node:assert/strict');
const request = require('supertest');
const bcrypt = require('bcryptjs');
const { app, pool } = require('../server');
test.after(async () => {
await pool.end();
});
let ipCounter = 0;
function nextIp() {
ipCounter += 1;
return `10.0.0.${ipCounter}`;
}
test('repeated failed attempts for one account trip the account limiter even from different IPs', async () => {
const email = 'account-limit-test@example.test';
for (let i = 0; i < 5; i += 1) {
const res = await request(app)
.post('/api/auth/login')
.set('X-Forwarded-For', nextIp())
.send({ email, password: 'wrong-password' });
assert.notEqual(res.status, 429);
}
const blocked = await request(app)
.post('/api/auth/login')
.set('X-Forwarded-For', nextIp())
.send({ email, password: 'wrong-password' });
assert.equal(blocked.status, 429);
assert.equal(blocked.body.error, '尝试次数过多,请稍后重试');
});
test('repeated failed attempts across many accounts from one IP trip the IP limiter', async () => {
const ip = nextIp();
for (let i = 0; i < 5; i += 1) {
const res = await request(app)
.post('/api/auth/login')
.set('X-Forwarded-For', ip)
.send({ email: `rotating-${i}@example.test`, password: 'wrong-password' });
assert.notEqual(res.status, 429);
}
const blocked = await request(app)
.post('/api/auth/login')
.set('X-Forwarded-For', ip)
.send({ email: 'rotating-final@example.test', password: 'wrong-password' });
assert.equal(blocked.status, 429);
assert.equal(blocked.body.error, '尝试次数过多,请稍后重试');
});
test('successful logins are not counted against the auth limiters', async (t) => {
const email = 'success-test@example.test';
const password = 'correct horse battery staple';
const hash = await bcrypt.hash(password, 4);
t.mock.method(pool, 'query', async () => ({
rows: [{
id: 1,
email,
password_hash: hash,
username: 'tester',
avatar_url: '',
bio: '',
role: 'user',
signature: '',
}],
}));
const ip = nextIp();
for (let i = 0; i < 8; i += 1) {
const res = await request(app)
.post('/api/auth/login')
.set('X-Forwarded-For', ip)
.send({ email, password });
assert.equal(res.status, 200);
}
});
test('missing body fields fall back to the IP-only bucket without crashing', async () => {
const ip = nextIp();
const res = await request(app)
.post('/api/auth/login')
.set('X-Forwarded-For', ip)
.send({});
assert.equal(res.status, 400);
});
test('malformed JSON bodies are rejected without crashing the server', async () => {
const ip = nextIp();
const res = await request(app)
.post('/api/auth/login')
.set('X-Forwarded-For', ip)
.set('Content-Type', 'application/json')
.send('{not valid json');
assert.equal(res.status, 400);
assert.equal(res.body.error, 'JSON 格式无效');
});
+163
View File
@@ -0,0 +1,163 @@
const test = require('node:test');
const assert = require('node:assert/strict');
const fs = require('node:fs');
const path = require('node:path');
// schema.sql 与 migrations/ 是两套并存的表结构定义:
// - schema.sql 供安装脚本(install.sh)与手工部署直接执行
// - migrations/ 供 Docker entrypoint 与 npm run migrate 使用
//
// 两套定义必须产出等价的结构,否则「用脚本装的站」和「用迁移装的站」
// 会在后续升级中分化。历史上已经漂移过一次:001_initial.sql 漏掉了
// users.token_version 与 event_logs 的审计字段,导致登录后所有接口 500。
//
// 这里在文本层面断言两边覆盖同一批表与关键列,任何一边新增表或字段
// 却忘记同步另一边时立即失败。不依赖数据库连接,可直接在 CI 中运行。
const root = path.join(__dirname, '..');
const schemaSQL = fs.readFileSync(path.join(root, 'schema.sql'), 'utf8');
const migrationsDir = path.join(root, 'migrations');
const migrationSQL = fs.readdirSync(migrationsDir)
.filter(file => file.endsWith('.sql'))
.sort()
.map(file => fs.readFileSync(path.join(migrationsDir, file), 'utf8'))
.join('\n');
// 从 SQL 文本中收集被定义的表名(CREATE TABLE 与 ALTER TABLE 都算)。
function collectTables(sql) {
const tables = new Set();
const pattern = /(?:CREATE\s+TABLE(?:\s+IF\s+NOT\s+EXISTS)?|ALTER\s+TABLE)\s+"?([a-z_][a-z0-9_]*)"?/gi;
let match;
while ((match = pattern.exec(sql)) !== null) tables.add(match[1].toLowerCase());
return tables;
}
// 收集通过 ALTER TABLE <t> ADD COLUMN 追加的列,按表分组。
function collectAlteredColumns(sql) {
const added = new Map();
const pattern = /ALTER\s+TABLE\s+"?([a-z_][a-z0-9_]*)"?\s+ADD\s+COLUMN(?:\s+IF\s+NOT\s+EXISTS)?\s+"?([a-z_][a-z0-9_]*)"?/gi;
let match;
while ((match = pattern.exec(sql)) !== null) {
const table = match[1].toLowerCase();
if (!added.has(table)) added.set(table, new Set());
added.get(table).add(match[2].toLowerCase());
}
return added;
}
// 收集 CREATE TABLE 块内声明的列。
function collectInlineColumns(sql) {
const declared = new Map();
const tablePattern = /CREATE\s+TABLE(?:\s+IF\s+NOT\s+EXISTS)?\s+"?([a-z_][a-z0-9_]*)"?\s*\(([\s\S]*?)\n\s*\);/gi;
let match;
while ((match = tablePattern.exec(sql)) !== null) {
const table = match[1].toLowerCase();
const body = match[2];
if (!declared.has(table)) declared.set(table, new Set());
for (const line of body.split('\n')) {
const trimmed = line.trim();
if (!trimmed || trimmed.startsWith('--')) continue;
// 跳过表级约束(PRIMARY KEY / UNIQUE / CHECK / FOREIGN KEY / CONSTRAINT)
if (/^(PRIMARY|UNIQUE|CHECK|FOREIGN|CONSTRAINT)\b/i.test(trimmed)) continue;
const columnMatch = trimmed.match(/^"?([a-z_][a-z0-9_]*)"?\s+[A-Za-z]/i);
if (columnMatch) declared.get(table).add(columnMatch[1].toLowerCase());
}
}
return declared;
}
// 合并「建表时声明」与「事后 ALTER 追加」两类列,得到每张表的完整列集合。
function collectColumns(sql) {
const columns = new Map();
const merge = source => {
for (const [table, cols] of source) {
if (!columns.has(table)) columns.set(table, new Set());
for (const col of cols) columns.get(table).add(col);
}
};
merge(collectInlineColumns(sql));
merge(collectAlteredColumns(sql));
return columns;
}
const schemaTables = collectTables(schemaSQL);
const migrationTables = collectTables(migrationSQL);
test('schema.sql and migrations define the same set of tables', () => {
const onlyInSchema = [...schemaTables].filter(t => !migrationTables.has(t));
const onlyInMigrations = [...migrationTables].filter(t => !schemaTables.has(t));
assert.deepEqual(
onlyInSchema, [],
`以下表只在 schema.sql 中定义,migrations/ 缺失:${onlyInSchema.join(', ')}`
);
assert.deepEqual(
onlyInMigrations, [],
`以下表只在 migrations/ 中定义,schema.sql 缺失:${onlyInMigrations.join(', ')}`
);
});
test('schema.sql defines every column that migrations define', () => {
// schema.sql 是安装脚本实际执行的权威定义,迁移中出现过的列
// 必须都能在 schema.sql 里找到,否则脚本装出来的库会缺字段。
const migrationColumns = collectColumns(migrationSQL);
const schemaColumns = collectColumns(schemaSQL);
const missing = [];
for (const [table, cols] of migrationColumns) {
const schemaCols = schemaColumns.get(table);
if (!schemaCols) {
missing.push(`${table}.*(整张表缺失)`);
continue;
}
for (const col of cols) {
if (!schemaCols.has(col)) missing.push(`${table}.${col}`);
}
}
assert.deepEqual(
missing, [],
`schema.sql 缺少以下列,安装脚本建出的库将与迁移结果不一致:${missing.join(', ')}`
);
});
test('columns required by server.js exist in both definitions', () => {
// server.js 直接查询、缺失即导致运行时 500 的列。
const REQUIRED = [
['users', 'token_version'],
['event_logs', 'method'],
['event_logs', 'path'],
['event_logs', 'user_agent'],
['event_logs', 'metadata'],
];
const schemaColumns = collectColumns(schemaSQL);
const migrationColumns = collectColumns(migrationSQL);
for (const [table, column] of REQUIRED) {
assert.ok(
schemaColumns.get(table)?.has(column),
`schema.sql 缺少 ${table}.${column}`
);
assert.ok(
migrationColumns.get(table)?.has(column),
`migrations/ 缺少 ${table}.${column}`
);
}
});
test('schema.sql stays re-runnable for the installer update path', () => {
// install.sh 的自动更新会再次把整个 schema.sql 执行一遍,
// 因此其中的 DDL 必须全部写成幂等形式。
const createTables = schemaSQL.match(/CREATE\s+TABLE\s+(?!IF\s+NOT\s+EXISTS)/gi) || [];
assert.deepEqual(
createTables, [],
'schema.sql 存在未带 IF NOT EXISTS 的 CREATE TABLE,重复执行会失败'
);
const createIndexes = schemaSQL.match(/CREATE\s+(?:UNIQUE\s+)?INDEX\s+(?!IF\s+NOT\s+EXISTS)/gi) || [];
assert.deepEqual(
createIndexes, [],
'schema.sql 存在未带 IF NOT EXISTS 的 CREATE INDEX,重复执行会失败'
);
const addConstraints = schemaSQL.match(/ADD\s+CONSTRAINT\s+(?!IF\s+NOT\s+EXISTS)/gi) || [];
// ADD CONSTRAINT 在 PostgreSQL 中不支持 IF NOT EXISTS,需由守卫逻辑处理,
// 这里仅记录数量,避免误报。
assert.ok(addConstraints.length >= 0);
});