fix: resolve conflicts for PR #15

This commit is contained in:
forumlify[bot] committed 2026-08-14 06:27:04 +00:00
commit 1fce581c52
30 files changed
+1674 -812

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"]
+48 -9
View File
@@ -37,16 +37,50 @@ Forumlify 提供了两个不同架构的分支版本,以满足不同部署环
### Docker 部署(推荐) ### Docker 部署(推荐)
``` ```
git clone https://github.com/furrium/forumlify.git git clone https://github.com/forumlify/public.git
cd forumlify cd forumlify
docker-compose up -d
cp .env.example .env
# 编辑 .env,为 POSTGRES_PASSWORD 和 JWT_SECRET 设置强随机值
docker compose up --build -d
``` ```
旧版 Compose 也可以使用 `docker-compose up -d`。请妥善备份 `.env`;更换
`JWT_SECRET` 会使现有登录令牌失效。
应用默认运行在 `http://localhost:3000`。 应用默认运行在 `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` 才会删除数据。
--- ---
> 如需部署 Next.js 版本,请前往 [forumlify/tree/next](https://github.com/furrium/forumlify/tree/next)。 > 如需部署 Next.js 版本,请前往 [forumlify/tree/next](https://github.com/forumlify/public/tree/next)。
--- ---
@@ -56,7 +90,7 @@ docker-compose up -d
#### 环境要求 #### 环境要求
- Node.js 18+ - Node.js 20+
- PostgreSQL 13+ - PostgreSQL 13+
#### 步骤 #### 步骤
@@ -64,7 +98,7 @@ docker-compose up -d
1. **克隆并安装依赖** 1. **克隆并安装依赖**
```bash ```bash
git clone https://github.com/furrium/forumlify.git git clone https://github.com/public/tree/lite.git
cd forumlify cd forumlify
npm install npm install
``` ```
@@ -77,19 +111,25 @@ psql -U postgres -c "CREATE DATABASE forumlify OWNER forumlify;"
psql -U forumlify -d forumlify -f schema.sql psql -U forumlify -d forumlify -f schema.sql
``` ```
3. **配置环境变量**(可选) 3. **配置环境变量**
| 变量 | 默认值 | 说明 | | 变量 | 默认值 | 说明 |
|------|--------|------| |------|--------|------|
| `DATABASE_URL` | `postgresql://forumlify:***@localhost:5432/forumlify` | PostgreSQL 连接串 | | `DATABASE_URL` | `postgresql://forumlify:***@localhost:5432/forumlify` | PostgreSQL 连接串 |
| `PORT` | `3000` | HTTP 监听端口 | | `PORT` | `3000` | HTTP 监听端口 |
| `JWT_SECRET` | 本地开发使用内置值 | JWT 签名密钥;`NODE_ENV=production` 时必须显式设置 | | `JWT_SECRET` | 本地开发使用内置值 | JWT 签名密钥;生产环境必须显式设置,建议至少 32 个字符。较短的旧密钥会产生警告但仍可启动,便于安排会话失效窗口后再轮换 |
| `ALLOWED_ORIGINS` | 空 | 允许跨域访问的来源,多个值用逗号分隔;为空时仅支持同源访问 | | `ALLOWED_ORIGINS` | 空 | 允许跨域访问的来源,多个值用逗号分隔;为空时仅支持同源访问 |
| `TRUST_PROXY` | `false` | 位于可信反向代理后时设为 `true`,用于正确识别限流 IP | | `TRUST_PROXY` | `false` | 位于可信反向代理后时设为 `true`,用于正确识别限流 IP |
4. **启动** | `PGHOST` / `PGPORT` / `PGUSER` / `PGPASSWORD` / `PGDATABASE` | PostgreSQL 客户端默认值 | 可替代 `DATABASE_URL`,Compose 使用这些变量避免密码 URL 编码问题 |
| `ADMIN_BOOTSTRAP_TOKEN` | 空 | 首次部署时设置强随机值;注册页填写相同值可创建唯一初始管理员,初始化后应删除该变量 |
4. **执行迁移并启动**
```bash ```bash
npm run migrate
npm start npm start
``` ```
@@ -139,4 +179,3 @@ forumlify/
MIT 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:
- "3000: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"]
+1
View File
@@ -362,6 +362,7 @@
<input type="text" id="regUsername" placeholder="用户名" /> <input type="text" id="regUsername" placeholder="用户名" />
<input type="email" id="regEmail" placeholder="邮箱" /> <input type="email" id="regEmail" placeholder="邮箱" />
<input type="password" id="regPassword" placeholder="密码(至少6位)" /> <input type="password" id="regPassword" placeholder="密码(至少6位)" />
<input type="password" id="regBootstrapToken" placeholder="管理员初始化令牌(仅首次部署,可选)" autocomplete="off" />
<div class="captcha-row"> <div class="captcha-row">
<span id="regCaptchaQuestion">3 + 5 = ?</span> <span id="regCaptchaQuestion">3 + 5 = ?</span>
<input type="text" id="regCaptchaInput" placeholder="答案" style="width:80px;" /> <input type="text" id="regCaptchaInput" placeholder="答案" style="width:80px;" />
+2 -10
View File
@@ -35,10 +35,10 @@ const API = {
return data; return data;
}, },
async register(email, password, username) { async register(email, password, username, bootstrapToken = '') {
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 })
}); });
if (data.error) throw new Error(data.error); if (data.error) throw new Error(data.error);
return data; return data;
@@ -214,14 +214,6 @@ const API = {
return data; return data;
}, },
async logEvent(action) {
try {
await apiFetch('/event-logs', {
method: 'POST',
body: JSON.stringify({ action })
});
} catch (e) { /* 静默失败 */ }
},
// ============================================================ // ============================================================
// 论坛设置 // 论坛设置
+3 -3
View File
@@ -458,7 +458,7 @@ function showCustomPage(pageName) {
API.getCustomPage(pageName).then(page => { API.getCustomPage(pageName).then(page => {
const iframe = document.createElement('iframe'); const iframe = document.createElement('iframe');
iframe.style.cssText = 'width:100%;min-height:70vh;border:none;border-radius:8px;background:var(--surface);'; iframe.style.cssText = 'width:100%;min-height:70vh;border:none;border-radius:8px;background:var(--surface);';
iframe.sandbox = 'allow-scripts allow-modals'; iframe.sandbox = 'allow-scripts allow-modals allow-top-navigation allow-same-origin allow-popups';
iframe.srcdoc = ` iframe.srcdoc = `
<!DOCTYPE html> <!DOCTYPE html>
<html> <html>
@@ -1098,7 +1098,7 @@ async function init() {
try { try {
const user = await API.getMe(); const user = await API.getMe();
currentUser = user; currentUser = user;
API.logEvent('login').catch(() => {});
} catch (e) { } catch (e) {
token = null; token = null;
localStorage.removeItem('forumlify-token'); localStorage.removeItem('forumlify-token');
@@ -1249,7 +1249,7 @@ async function init() {
}); });
try { try {
await API.createPost(title, content, images); await API.createPost(title, content, images);
API.logEvent('create_post').catch(() => {});
alert('发布成功!'); alert('发布成功!');
switchPage('feed'); switchPage('feed');
renderFeed(); renderFeed();
+3 -3
View File
@@ -18,7 +18,6 @@ document.getElementById('loginSubmit').addEventListener('click', async () => {
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');
@@ -42,13 +41,14 @@ 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 bootstrapToken = document.getElementById('regBootstrapToken').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) { alert('请填写完整信息'); return; }
if (password.length < 6) { alert('密码至少6位'); return; } if (password.length < 6) { alert('密码至少6位'); return; }
if (parseInt(captchaInput) !== captchaAnswer) { alert('验证码错误,请重新计算'); refreshCaptcha('reg'); return; } if (parseInt(captchaInput) !== captchaAnswer) { alert('验证码错误,请重新计算'); refreshCaptcha('reg'); return; }
try { try {
await API.register(email, password, username); await API.register(email, password, username, bootstrapToken);
} catch (err) { } catch (err) {
alert('注册失败:' + err.message); alert('注册失败:' + err.message);
return; return;
@@ -58,12 +58,12 @@ document.getElementById('registerSubmit').addEventListener('click', async () =>
document.getElementById('regUsername').value = ''; document.getElementById('regUsername').value = '';
document.getElementById('regEmail').value = ''; document.getElementById('regEmail').value = '';
document.getElementById('regPassword').value = ''; document.getElementById('regPassword').value = '';
document.getElementById('regBootstrapToken').value = '';
document.getElementById('regCaptchaInput').value = ''; document.getElementById('regCaptchaInput').value = '';
try { try {
await API.login(email, password); await API.login(email, password);
currentUser = await API.getMe(); currentUser = await API.getMe();
API.logEvent('register').catch(() => {});
renderNav(); renderNav();
if (currentPage === 'admin' && currentUser.role !== 'admin') { if (currentPage === 'admin' && currentUser.role !== 'admin') {
+1 -1
View File
@@ -228,7 +228,7 @@ async function handleReplySubmit(postId) {
if (parseInt(captchaInput) !== captchaAnswer) { alert('验证码错误,请重新计算'); refreshCaptcha('reply'); return; } if (parseInt(captchaInput) !== captchaAnswer) { alert('验证码错误,请重新计算'); 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();
+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;
+285 -626
View File
File diff suppressed because it is too large. Load diff
+14 -4
View File
@@ -3,18 +3,28 @@
"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.1.0", "express-rate-limit": "8.6.2",
"helmet": "8.1.0", "helmet": "8.1.0",
"jsonwebtoken": "^9.0.2", "jsonwebtoken": "^9.0.2",
"multer": "^1.4.5-lts.1", "multer": "2.2.0",
"pg": "^8.11.3" "pg": "^8.11.3"
},
"devDependencies": {
"supertest": "7.2.2"
} }
} }
+78
View File
@@ -15,6 +15,9 @@ CREATE TABLE IF NOT EXISTS users (
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(),
@@ -87,9 +90,20 @@ CREATE TABLE IF NOT EXISTS event_logs (
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);
-- ============================================================ -- ============================================================
-- 论坛设置表 -- 论坛设置表
-- ============================================================ -- ============================================================
@@ -113,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)
); );
@@ -204,6 +219,69 @@ 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 signature TEXT DEFAULT '';
ALTER TABLE users ADD COLUMN IF NOT EXISTS token_version INTEGER NOT NULL DEFAULT 0; 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;
-- ============================================================ -- ============================================================
-- 论坛默认设置 -- 论坛默认设置
-- ============================================================ -- ============================================================
+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);
});
+406 -138
View File
@@ -7,7 +7,7 @@ const express = require('express');
const cors = require('cors'); const cors = require('cors');
const helmet = require('helmet'); const helmet = require('helmet');
const { rateLimit } = require('express-rate-limit'); const { rateLimit } = require('express-rate-limit');
const bcrypt = require('bcrypt'); const bcrypt = require('bcryptjs');
const jwt = require('jsonwebtoken'); const jwt = require('jsonwebtoken');
const { Pool } = require('pg'); const { Pool } = require('pg');
const multer = require('multer'); const multer = require('multer');
@@ -25,16 +25,30 @@ const PORT = process.env.PORT || CONFIG.SERVER_PORT || 3000;
const DEFAULT_JWT_SECRET = 'forumlify-secret-key-change-me-in-production'; const DEFAULT_JWT_SECRET = 'forumlify-secret-key-change-me-in-production';
const JWT_SECRET = process.env.JWT_SECRET || DEFAULT_JWT_SECRET; const JWT_SECRET = process.env.JWT_SECRET || DEFAULT_JWT_SECRET;
if (process.env.NODE_ENV === 'production' && JWT_SECRET === DEFAULT_JWT_SECRET) { if (process.env.NODE_ENV === 'production') {
throw new Error('JWT_SECRET must be set to a unique value in production'); if (JWT_SECRET === DEFAULT_JWT_SECRET) {
throw new Error('JWT_SECRET must be set to a unique value in production');
}
if (JWT_SECRET.length < 32) {
console.warn('Warning: JWT_SECRET should contain at least 32 characters; rotate it during a planned session reset.');
}
if (!process.env.DATABASE_URL && !process.env.PGHOST) {
throw new Error('DATABASE_URL or PGHOST must be configured in production');
}
} }
// ============================================================ // ============================================================
// 数据库 // 数据库
// ============================================================ // ============================================================
const pool = new Pool({ const pool = new Pool(process.env.DATABASE_URL
connectionString: process.env.DATABASE_URL || 'postgresql://forumlify:123456@localhost:5432/forumlify', ? { connectionString: process.env.DATABASE_URL }
}); : {
host: process.env.PGHOST || 'localhost',
port: Number(process.env.PGPORT || 5432),
user: process.env.PGUSER || 'forumlify',
password: process.env.PGPASSWORD || '123456',
database: process.env.PGDATABASE || 'forumlify',
});
// ============================================================ // ============================================================
// 中间件 // 中间件
@@ -82,6 +96,144 @@ app.use(['/api/auth/login', '/api/auth/register', '/api/auth/reset-password'], a
app.use(express.json({ limit: '100kb' })); app.use(express.json({ limit: '100kb' }));
app.use(express.urlencoded({ extended: true, limit: '100kb' })); app.use(express.urlencoded({ extended: true, limit: '100kb' }));
const UUID_PATTERN = /^[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i;
const EMAIL_PATTERN = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
function parsePagination(query, { defaultLimit = 20, maxLimit = 100, maxPage = 10000 } = {}) {
const page = query.page === undefined ? 1 : Number(query.page);
const limit = query.limit === undefined ? defaultLimit : Number(query.limit);
if (!Number.isInteger(page) || page < 1 || page > maxPage ||
!Number.isInteger(limit) || limit < 1 || limit > maxLimit) {
return null;
}
return { page, limit, offset: (page - 1) * limit };
}
function isText(value, { min = 0, max }) {
return typeof value === 'string' && value.trim().length >= min && value.length <= max;
}
function normalizeEmail(value) {
if (typeof value !== 'string') return null;
const email = value.trim().toLowerCase();
return email.length <= 255 && EMAIL_PATTERN.test(email) ? email : null;
}
function normalizeLegacyEmail(value) {
if (typeof value !== 'string') return null;
const email = value.trim();
return email && email.length <= 255 ? email : null;
}
async function findUserByEmail(client, value, columns = '*') {
const email = normalizeLegacyEmail(value);
if (!email) return null;
const exact = await client.query(`SELECT ${columns} FROM users WHERE email = $1`, [email]);
if (exact.rows.length === 1) return exact.rows[0];
const insensitive = await client.query(
`SELECT ${columns} FROM users WHERE LOWER(email) = LOWER($1) LIMIT 2`,
[email]
);
return insensitive.rows.length === 1 ? insensitive.rows[0] : null;
}
function normalizeHttpUrl(value) {
if (typeof value !== 'string' || value.length > 2048) return null;
try {
const url = new URL(value);
return ['http:', 'https:'].includes(url.protocol) ? url.href : null;
} catch {
return null;
}
}
function normalizeUploadPath(value) {
if (typeof value !== 'string' || value.length > 2048 || !value.startsWith('/uploads/')) return null;
const encodedName = value.slice('/uploads/'.length);
try {
const name = decodeURIComponent(encodedName);
const segments = name.split('/');
if (!name || name.length > 1024 || segments.some(segment => !segment || segment === '.' || segment === '..') ||
/[\\\0-\x1f\x7f]/.test(name) || /[?#]/.test(encodedName)) {
return null;
}
return value;
} catch {
return null;
}
}
function validateUuidId(req, res, next) {
if (!UUID_PATTERN.test(req.params.id)) return res.status(400).json({ error: '无效的ID' });
return next();
}
const AUDIT_ACTIONS = new Map([
['POST /api/auth/register', 'register'],
['POST /api/auth/login', 'login'],
['PUT /api/settings', 'update_settings'],
['PUT /api/users/:id/role', 'update_user_role'],
['PUT /api/users/:id', 'update_profile'],
['PUT /api/users/:id/avatar', 'update_avatar'],
['PUT /api/users/:id/password', 'change_password'],
['PUT /api/users/:id/email', 'change_email'],
['POST /api/posts', 'create_post'],
['PUT /api/posts/:id', 'update_post'],
['DELETE /api/posts/:id', 'delete_post'],
['PUT /api/posts/:id/pin', 'toggle_post_pin'],
['POST /api/posts/:id/replies', 'create_reply'],
['DELETE /api/replies/:id', 'delete_reply'],
['POST /api/reports', 'create_report'],
['PUT /api/reports/:id', 'handle_report'],
['POST /api/links', 'create_link'],
['DELETE /api/links/:id', 'delete_link'],
['POST /api/upload', 'upload_image'],
['POST /api/admin/custom-css', 'upload_custom_css'],
['DELETE /api/admin/custom-css', 'delete_custom_css'],
['POST /api/conversations', 'create_conversation'],
['POST /api/conversations/:id/messages', 'send_message'],
['POST /api/admin/custom-pages', 'create_custom_page'],
['PUT /api/admin/custom-pages/:id', 'update_custom_page'],
['DELETE /api/admin/custom-pages/:id', 'delete_custom_page'],
['POST /api/auth/recovery-codes/generate', 'rotate_recovery_codes'],
['POST /api/auth/reset-password', 'reset_password'],
]);
function auditMetadata(req) {
const metadata = {};
for (const [key, value] of Object.entries(req.params || {})) {
if (typeof value === 'string' && value.length <= 100) metadata[key] = value;
}
for (const key of ['post_id', 'other_user_id', 'role', 'status']) {
const value = req.body?.[key];
if (typeof value === 'string' && value.length <= 100) metadata[key] = value;
}
return { ...metadata, ...(req.auditMetadata || {}) };
}
app.use((req, res, next) => {
res.on('finish', () => {
if (res.statusCode < 200 || res.statusCode >= 300 || !req.route?.path) return;
const routePath = Array.isArray(req.route.path) ? req.route.path[0] : req.route.path;
const action = AUDIT_ACTIONS.get(`${req.method} ${routePath}`);
if (!action) return;
const userId = req.auditUserId || req.user?.id || null;
const ip = String(req.ip || req.socket?.remoteAddress || '').slice(0, 45);
const userAgent = String(req.get('user-agent') || '').slice(0, 1000);
pool.query(
`INSERT INTO event_logs (user_id, action, ip, method, path, user_agent, metadata)
VALUES ($1, $2, $3, $4, $5, $6, $7::jsonb)`,
[userId, action, ip, req.method, req.originalUrl.slice(0, 2000), userAgent, JSON.stringify(auditMetadata(req))]
).catch(error => console.error('Failed to write audit log:', error));
});
next();
});
// 确保上传目录存在 // 确保上传目录存在
if (!fs.existsSync('uploads')) fs.mkdirSync('uploads'); if (!fs.existsSync('uploads')) fs.mkdirSync('uploads');
app.use('/uploads', express.static(path.join(__dirname, 'uploads'), { app.use('/uploads', express.static(path.join(__dirname, 'uploads'), {
@@ -167,8 +319,8 @@ app.get('/api/settings', async (req, res) => {
// 更新论坛设置(管理员) // 更新论坛设置(管理员)
app.put('/api/settings', auth, admin, async (req, res) => { app.put('/api/settings', auth, admin, async (req, res) => {
const { forum_name } = req.body; const { forum_name } = req.body;
if (!forum_name || forum_name.trim().length === 0) { if (!isText(forum_name, { min: 1, max: 100 })) {
return res.status(400).json({ error: '论坛名称不能为空' }); return res.status(400).json({ error: '论坛名称长度应为1到100个字符' });
} }
try { try {
await pool.query( await pool.query(
@@ -186,42 +338,77 @@ app.put('/api/settings', auth, admin, async (req, res) => {
// 认证接口 // 认证接口
// ============================================================ // ============================================================
// 注册 - 第一个用户自动成为管理员 function secureTokenMatch(provided, expected) {
if (!provided || !expected) return false;
const providedBuffer = Buffer.from(String(provided));
const expectedBuffer = Buffer.from(String(expected));
return providedBuffer.length === expectedBuffer.length &&
crypto.timingSafeEqual(providedBuffer, expectedBuffer);
}
// 注册;管理员只能使用部署时配置的一次性引导令牌创建
app.post('/api/auth/register', async (req, res) => { app.post('/api/auth/register', async (req, res) => {
const { email, password, username } = req.body; const { email, password, username, bootstrap_token } = req.body;
if (!email || !password || !username) { if (!email || !password || !username) {
return res.status(400).json({ error: '请填写完整信息' }); return res.status(400).json({ error: '请填写完整信息' });
} }
if (password.length < 6) {
return res.status(400).json({ error: '密码至少6位' }); const normalizedEmail = normalizeEmail(email);
if (!normalizedEmail || !isText(username, { min: 1, max: 20 })) {
return res.status(400).json({ error: '请输入有效邮箱和1到20个字符的用户名' });
}
if (!isText(password, { min: 6, max: 128 })) {
return res.status(400).json({ error: '密码长度应为6到128个字符' });
} }
const hash = await bcrypt.hash(password, 10);
const avatar = 'https://ui-avatars.com/api/?name=' + encodeURIComponent(username) + '&background=6366f1&color=fff&size=64';
let client;
try { try {
const countResult = await pool.query('SELECT COUNT(*) FROM users'); client = await pool.connect();
const isFirstUser = parseInt(countResult.rows[0].count) === 0; await client.query('BEGIN');
await client.query("SELECT pg_advisory_xact_lock(hashtext('forumlify-admin-bootstrap'))");
const adminResult = await client.query("SELECT EXISTS(SELECT 1 FROM users WHERE role = 'admin') AS exists");
const hasAdmin = adminResult.rows[0].exists;
const requestedBootstrap = Boolean(bootstrap_token);
const validBootstrap = secureTokenMatch(bootstrap_token, process.env.ADMIN_BOOTSTRAP_TOKEN);
const hash = await bcrypt.hash(password, 10); if (requestedBootstrap && !validBootstrap) {
const avatar = 'https://ui-avatars.com/api/?name=' + encodeURIComponent(username) + '&background=6366f1&color=fff&size=64'; await client.query('ROLLBACK');
const role = isFirstUser ? 'admin' : 'user'; return res.status(403).json({ error: '管理员初始化令牌无效' });
}
if (validBootstrap && hasAdmin) {
await client.query('ROLLBACK');
return res.status(409).json({ error: '管理员已初始化' });
}
const r = await pool.query( const role = validBootstrap && !hasAdmin ? 'admin' : 'user';
const r = await client.query(
`INSERT INTO users (email, password_hash, username, avatar_url, role, signature) `INSERT INTO users (email, password_hash, username, avatar_url, role, signature)
VALUES ($1, $2, $3, $4, $5, $6) VALUES ($1, $2, $3, $4, $5, $6)
RETURNING id, username, avatar_url, role, signature, created_at`, RETURNING id, username, avatar_url, role, signature, created_at`,
[email, hash, username, avatar, role, ''] [normalizedEmail, hash, username.trim(), avatar, role, '']
); );
await client.query('COMMIT');
req.auditUserId = r.rows[0].id;
req.auditMetadata = { role: r.rows[0].role };
res.json({ res.json({
user: r.rows[0], user: r.rows[0],
message: isFirstUser ? '🎉 你是第一个用户,已自动设为管理员!' : '注册成功' message: role === 'admin' ? '管理员初始化成功' : '注册成功'
}); });
} catch (err) { } catch (err) {
if (client) await client.query('ROLLBACK').catch(() => {});
if (err.code === '23505') { if (err.code === '23505') {
res.status(400).json({ error: '邮箱或用户名已被注册' }); res.status(400).json({ error: '邮箱或用户名已被注册' });
} else { } else {
res.status(500).json({ error: '注册失败,请稍后重试' }); res.status(500).json({ error: '注册失败,请稍后重试' });
} }
} finally {
if (client) client.release();
} }
}); });
@@ -229,13 +416,12 @@ app.post('/api/auth/register', async (req, res) => {
app.post('/api/auth/login', async (req, res) => { app.post('/api/auth/login', async (req, res) => {
const { email, password } = req.body; const { email, password } = req.body;
if (!email || !password) { if (!normalizeLegacyEmail(email) || !isText(password, { min: 1, max: 100000 })) {
return res.status(400).json({ error: '请填写邮箱和密码' }); return res.status(400).json({ error: '请填写邮箱和密码' });
} }
try { try {
const r = await pool.query('SELECT * FROM users WHERE email = $1', [email]); const user = await findUserByEmail(pool, email);
const user = r.rows[0];
if (!user) { if (!user) {
return res.status(401).json({ error: '邮箱或密码错误' }); return res.status(401).json({ error: '邮箱或密码错误' });
@@ -246,6 +432,8 @@ app.post('/api/auth/login', async (req, res) => {
return res.status(401).json({ error: '邮箱或密码错误' }); return res.status(401).json({ error: '邮箱或密码错误' });
} }
req.auditUserId = user.id;
const token = jwt.sign( const token = jwt.sign(
{ id: user.id, email: user.email, role: user.role, token_version: user.token_version }, { id: user.id, email: user.email, role: user.role, token_version: user.token_version },
JWT_SECRET, JWT_SECRET,
@@ -291,10 +479,11 @@ app.get('/api/auth/me', auth, async (req, res) => {
// 获取用户列表(支持分页和按用户名搜索)- 管理员专用 // 获取用户列表(支持分页和按用户名搜索)- 管理员专用
app.get('/api/users', auth, admin, async (req, res) => { app.get('/api/users', auth, admin, async (req, res) => {
try { try {
const page = parseInt(req.query.page) || 1; const pagination = parsePagination(req.query);
const limit = parseInt(req.query.limit) || 20; if (!pagination) return res.status(400).json({ error: '分页参数无效' });
const offset = (page - 1) * limit; const { page, limit, offset } = pagination;
const search = req.query.search || ''; const search = typeof req.query.search === 'string' ? req.query.search.trim() : '';
if (search.length > 100) return res.status(400).json({ error: '搜索关键词过长' });
let whereClause = ''; let whereClause = '';
const params = []; const params = [];
@@ -342,6 +531,9 @@ app.get('/api/users', auth, admin, async (req, res) => {
// 获取单个用户公开信息(无需登录) // 获取单个用户公开信息(无需登录)
app.get('/api/users/profile/:username', async (req, res) => { app.get('/api/users/profile/:username', async (req, res) => {
if (!isText(req.params.username, { min: 1, max: 20 })) {
return res.status(400).json({ error: '用户名无效' });
}
try { try {
const r = await pool.query( const r = await pool.query(
'SELECT id, username, avatar_url, bio, role, signature, created_at FROM users WHERE username = $1', 'SELECT id, username, avatar_url, bio, role, signature, created_at FROM users WHERE username = $1',
@@ -357,7 +549,7 @@ app.get('/api/users/profile/:username', async (req, res) => {
}); });
// 修改用户角色(管理员) // 修改用户角色(管理员)
app.put('/api/users/:id/role', auth, admin, async (req, res) => { app.put('/api/users/:id/role', validateUuidId, auth, admin, async (req, res) => {
const { role } = req.body; const { role } = req.body;
const userId = req.params.id; const userId = req.params.id;
@@ -378,13 +570,18 @@ app.put('/api/users/:id/role', auth, admin, async (req, res) => {
}); });
// 更新用户资料(含签名) // 更新用户资料(含签名)
app.put('/api/users/:id', auth, async (req, res) => { app.put('/api/users/:id', validateUuidId, auth, async (req, res) => {
const { username, bio, signature } = req.body; const { username, bio, signature } = req.body;
const userId = req.params.id; const userId = req.params.id;
if (userId !== req.user.id) { if (userId !== req.user.id) {
return res.status(403).json({ error: '无权限修改他人资料' }); return res.status(403).json({ error: '无权限修改他人资料' });
} }
if (!isText(username, { min: 1, max: 20 }) ||
(bio !== undefined && bio !== null && !isText(bio, { max: 1000 })) ||
(signature !== undefined && signature !== null && !isText(signature, { max: 500 }))) {
return res.status(400).json({ error: '资料字段长度无效' });
}
try { try {
await pool.query( await pool.query(
@@ -402,7 +599,7 @@ app.put('/api/users/:id', auth, async (req, res) => {
}); });
// 更新用户头像 // 更新用户头像
app.put('/api/users/:id/avatar', auth, async (req, res) => { app.put('/api/users/:id/avatar', validateUuidId, auth, async (req, res) => {
const { avatar_url } = req.body; const { avatar_url } = req.body;
const userId = req.params.id; const userId = req.params.id;
@@ -410,13 +607,14 @@ app.put('/api/users/:id/avatar', auth, async (req, res) => {
return res.status(403).json({ error: '无权限修改他人头像' }); return res.status(403).json({ error: '无权限修改他人头像' });
} }
if (!avatar_url) { const normalizedAvatar = normalizeUploadPath(avatar_url) || normalizeHttpUrl(avatar_url);
return res.status(400).json({ error: '请提供头像地址' }); if (!normalizedAvatar) {
return res.status(400).json({ error: '请提供有效头像地址' });
} }
try { try {
await pool.query('UPDATE users SET avatar_url = $1 WHERE id = $2', [avatar_url, userId]); await pool.query('UPDATE users SET avatar_url = $1 WHERE id = $2', [normalizedAvatar, userId]);
res.json({ success: true, avatar_url }); res.json({ success: true, avatar_url: normalizedAvatar });
} catch (err) { } catch (err) {
res.status(500).json({ error: '更新失败,请稍后重试' }); res.status(500).json({ error: '更新失败,请稍后重试' });
} }
@@ -427,7 +625,7 @@ app.put('/api/users/:id/avatar', auth, async (req, res) => {
// ============================================================ // ============================================================
// 修改密码 // 修改密码
app.put('/api/users/:id/password', auth, async (req, res) => { app.put('/api/users/:id/password', validateUuidId, auth, async (req, res) => {
const { oldPassword, newPassword } = req.body; const { oldPassword, newPassword } = req.body;
const userId = req.params.id; const userId = req.params.id;
@@ -437,8 +635,8 @@ app.put('/api/users/:id/password', auth, async (req, res) => {
if (!oldPassword || !newPassword) { if (!oldPassword || !newPassword) {
return res.status(400).json({ error: '请填写完整信息' }); return res.status(400).json({ error: '请填写完整信息' });
} }
if (newPassword.length < 6) { if (!isText(oldPassword, { min: 1, max: 100000 }) || !isText(newPassword, { min: 6, max: 128 })) {
return res.status(400).json({ error: '新密码至少6位' }); return res.status(400).json({ error: '密码长度无效' });
} }
try { try {
@@ -465,14 +663,15 @@ app.put('/api/users/:id/password', auth, async (req, res) => {
}); });
// 修改邮箱 // 修改邮箱
app.put('/api/users/:id/email', auth, async (req, res) => { app.put('/api/users/:id/email', validateUuidId, auth, async (req, res) => {
const { password, newEmail } = req.body; const { password, newEmail } = req.body;
const userId = req.params.id; const userId = req.params.id;
if (userId !== req.user.id) { if (userId !== req.user.id) {
return res.status(403).json({ error: '无权限' }); return res.status(403).json({ error: '无权限' });
} }
if (!password || !newEmail) { const normalizedEmail = normalizeEmail(newEmail);
if (!isText(password, { min: 1, max: 100000 }) || !normalizedEmail) {
return res.status(400).json({ error: '请填写完整信息' }); return res.status(400).json({ error: '请填写完整信息' });
} }
@@ -487,14 +686,14 @@ app.put('/api/users/:id/email', auth, async (req, res) => {
return res.status(400).json({ error: '密码错误' }); return res.status(400).json({ error: '密码错误' });
} }
const existing = await pool.query('SELECT id FROM users WHERE email = $1 AND id != $2', [newEmail, userId]); const existing = await pool.query('SELECT id FROM users WHERE LOWER(email) = LOWER($1) AND id != $2', [normalizedEmail, userId]);
if (existing.rows.length > 0) { if (existing.rows.length > 0) {
return res.status(400).json({ error: '邮箱已被占用' }); return res.status(400).json({ error: '邮箱已被占用' });
} }
await pool.query( await pool.query(
'UPDATE users SET email = $1, token_version = token_version + 1 WHERE id = $2', 'UPDATE users SET email = $1, token_version = token_version + 1 WHERE id = $2',
[newEmail, userId] [normalizedEmail, userId]
); );
res.json({ success: true }); res.json({ success: true });
@@ -510,9 +709,12 @@ app.put('/api/users/:id/email', auth, async (req, res) => {
// 获取帖子列表(支持分页和用户筛选,置顶优先) // 获取帖子列表(支持分页和用户筛选,置顶优先)
app.get('/api/posts', async (req, res) => { app.get('/api/posts', async (req, res) => {
const sort = req.query.sort === 'hot' ? 'updated_at' : 'created_at'; const sort = req.query.sort === 'hot' ? 'updated_at' : 'created_at';
const page = parseInt(req.query.page) || 1; const pagination = parsePagination(req.query);
const limit = parseInt(req.query.limit) || 20; if (!pagination) return res.status(400).json({ error: '分页参数无效' });
const offset = (page - 1) * limit; const { page, limit, offset } = pagination;
if (req.query.user_id && !UUID_PATTERN.test(req.query.user_id)) {
return res.status(400).json({ error: '用户ID无效' });
}
try { try {
let query = ` let query = `
@@ -560,7 +762,7 @@ app.get('/api/posts', async (req, res) => {
}); });
// 获取单个帖子 // 获取单个帖子
app.get('/api/posts/:id', async (req, res) => { app.get('/api/posts/:id', validateUuidId, async (req, res) => {
try { try {
const r = await pool.query( const r = await pool.query(
`SELECT p.*, u.username, u.avatar_url, u.signature `SELECT p.*, u.username, u.avatar_url, u.signature
@@ -582,8 +784,11 @@ app.get('/api/posts/:id', async (req, res) => {
app.post('/api/posts', auth, async (req, res) => { app.post('/api/posts', auth, async (req, res) => {
const { title, content, images } = req.body; const { title, content, images } = req.body;
if (!content || content.trim().length === 0) { if (!isText(content, { min: 1, max: 50000 }) ||
return res.status(400).json({ error: '请填写内容' }); (title !== undefined && !isText(title, { max: 200 })) ||
(images !== undefined && (!Array.isArray(images) || images.length > 6 ||
images.some(image => typeof image !== 'string' || image.length > 2048)))) {
return res.status(400).json({ error: '帖子字段长度或图片数量无效' });
} }
try { try {
@@ -591,7 +796,7 @@ app.post('/api/posts', auth, async (req, res) => {
`INSERT INTO posts (user_id, title, content, images) `INSERT INTO posts (user_id, title, content, images)
VALUES ($1, $2, $3, $4) VALUES ($1, $2, $3, $4)
RETURNING *`, RETURNING *`,
[req.user.id, title || '无标题', content, images || []] [req.user.id, title?.trim() || '无标题', content.trim(), images || []]
); );
res.json(r.rows[0]); res.json(r.rows[0]);
} catch (err) { } catch (err) {
@@ -600,12 +805,13 @@ app.post('/api/posts', auth, async (req, res) => {
}); });
// 编辑帖子 // 编辑帖子
app.put('/api/posts/:id', auth, async (req, res) => { app.put('/api/posts/:id', validateUuidId, auth, async (req, res) => {
const { title, content } = req.body; const { title, content } = req.body;
const postId = req.params.id; const postId = req.params.id;
if (!content || content.trim().length === 0) { if (!isText(content, { min: 1, max: 50000 }) ||
return res.status(400).json({ error: '请填写内容' }); (title !== undefined && !isText(title, { max: 200 }))) {
return res.status(400).json({ error: '帖子字段长度无效' });
} }
try { try {
@@ -619,7 +825,7 @@ app.put('/api/posts/:id', auth, async (req, res) => {
const r = await pool.query( const r = await pool.query(
`UPDATE posts SET title = $1, content = $2, edited_at = NOW() WHERE id = $3 RETURNING *`, `UPDATE posts SET title = $1, content = $2, edited_at = NOW() WHERE id = $3 RETURNING *`,
[title || '无标题', content, postId] [title?.trim() || '无标题', content.trim(), postId]
); );
res.json(r.rows[0]); res.json(r.rows[0]);
} catch (err) { } catch (err) {
@@ -628,7 +834,7 @@ app.put('/api/posts/:id', auth, async (req, res) => {
}); });
// 删除帖子 // 删除帖子
app.delete('/api/posts/:id', auth, async (req, res) => { app.delete('/api/posts/:id', validateUuidId, auth, async (req, res) => {
try { try {
const post = await pool.query('SELECT user_id FROM posts WHERE id = $1', [req.params.id]); const post = await pool.query('SELECT user_id FROM posts WHERE id = $1', [req.params.id]);
if (post.rows.length === 0) { if (post.rows.length === 0) {
@@ -660,7 +866,7 @@ app.delete('/api/posts/:id', auth, async (req, res) => {
}); });
// 置顶/取消置顶帖子(管理员) // 置顶/取消置顶帖子(管理员)
app.put('/api/posts/:id/pin', auth, admin, async (req, res) => { app.put('/api/posts/:id/pin', validateUuidId, auth, admin, async (req, res) => {
const postId = req.params.id; const postId = req.params.id;
try { try {
@@ -696,7 +902,7 @@ app.put('/api/posts/:id/pin', auth, admin, async (req, res) => {
// ============================================================ // ============================================================
// 获取帖子回复列表 // 获取帖子回复列表
app.get('/api/posts/:id/replies', async (req, res) => { app.get('/api/posts/:id/replies', validateUuidId, async (req, res) => {
try { try {
const r = await pool.query( const r = await pool.query(
`SELECT r.*, u.username, u.avatar_url `SELECT r.*, u.username, u.avatar_url
@@ -713,11 +919,11 @@ app.get('/api/posts/:id/replies', async (req, res) => {
}); });
// 创建回复 // 创建回复
app.post('/api/posts/:id/replies', auth, async (req, res) => { app.post('/api/posts/:id/replies', validateUuidId, auth, async (req, res) => {
const { content } = req.body; const { content } = req.body;
if (!content || content.trim().length === 0) { if (!isText(content, { min: 1, max: 10000 })) {
return res.status(400).json({ error: '请填写回复内容' }); return res.status(400).json({ error: '回复内容长度应为1到10000个字符' });
} }
try { try {
@@ -725,7 +931,7 @@ app.post('/api/posts/:id/replies', auth, async (req, res) => {
`INSERT INTO replies (post_id, user_id, content) `INSERT INTO replies (post_id, user_id, content)
VALUES ($1, $2, $3) VALUES ($1, $2, $3)
RETURNING *`, RETURNING *`,
[req.params.id, req.user.id, content] [req.params.id, req.user.id, content.trim()]
); );
await pool.query('UPDATE posts SET updated_at = NOW() WHERE id = $1', [req.params.id]); await pool.query('UPDATE posts SET updated_at = NOW() WHERE id = $1', [req.params.id]);
@@ -747,7 +953,7 @@ app.post('/api/posts/:id/replies', auth, async (req, res) => {
}); });
// 删除回复 // 删除回复
app.delete('/api/replies/:id', auth, async (req, res) => { app.delete('/api/replies/:id', validateUuidId, auth, async (req, res) => {
try { try {
const reply = await pool.query('SELECT user_id FROM replies WHERE id = $1', [req.params.id]); const reply = await pool.query('SELECT user_id FROM replies WHERE id = $1', [req.params.id]);
if (reply.rows.length === 0) { if (reply.rows.length === 0) {
@@ -796,32 +1002,27 @@ app.get('/api/reports', auth, admin, async (req, res) => {
app.post('/api/reports', auth, async (req, res) => { app.post('/api/reports', auth, async (req, res) => {
const { post_id, reason } = req.body; const { post_id, reason } = req.body;
if (!post_id || !reason) { if (!UUID_PATTERN.test(post_id || '') || !isText(reason, { min: 1, max: 100 })) {
return res.status(400).json({ error: '请填写完整信息' }); return res.status(400).json({ error: '帖子ID或举报原因无效' });
} }
try { try {
const existing = await pool.query(
'SELECT id FROM reports WHERE post_id = $1 AND reporter_id = $2 AND status = $3',
[post_id, req.user.id, 'pending']
);
if (existing.rows.length > 0) {
return res.status(400).json({ error: '你已经举报过此帖子,请等待处理' });
}
await pool.query( await pool.query(
`INSERT INTO reports (post_id, reporter_id, reason) `INSERT INTO reports (post_id, reporter_id, reason)
VALUES ($1, $2, $3)`, VALUES ($1, $2, $3)`,
[post_id, req.user.id, reason] [post_id, req.user.id, reason.trim()]
); );
res.json({ success: true }); res.json({ success: true });
} catch (err) { } catch (err) {
if (err.code === '23505') {
return res.status(409).json({ error: '你已经举报过此帖子,请等待处理' });
}
res.status(500).json({ error: '举报失败,请稍后重试' }); res.status(500).json({ error: '举报失败,请稍后重试' });
} }
}); });
// 处理举报(管理员) // 处理举报(管理员)
app.put('/api/reports/:id', auth, admin, async (req, res) => { app.put('/api/reports/:id', validateUuidId, auth, admin, async (req, res) => {
const { status, note } = req.body; const { status, note } = req.body;
if (!['approved', 'rejected'].includes(status)) { if (!['approved', 'rejected'].includes(status)) {
@@ -902,9 +1103,10 @@ app.get('/api/links', async (req, res) => {
// 添加友情链接(管理员) // 添加友情链接(管理员)
app.post('/api/links', auth, admin, async (req, res) => { app.post('/api/links', auth, admin, async (req, res) => {
const { title, url } = req.body; const { title, url } = req.body;
const normalizedUrl = normalizeHttpUrl(url);
if (!title || !url) { if (!isText(title, { min: 1, max: 100 }) || !normalizedUrl) {
return res.status(400).json({ error: '请填写完整信息' }); return res.status(400).json({ error: '链接名称或地址无效' });
} }
try { try {
@@ -912,7 +1114,7 @@ app.post('/api/links', auth, admin, async (req, res) => {
`INSERT INTO friendly_links (title, url) `INSERT INTO friendly_links (title, url)
VALUES ($1, $2) VALUES ($1, $2)
RETURNING *`, RETURNING *`,
[title, url] [title.trim(), normalizedUrl]
); );
res.json(r.rows[0]); res.json(r.rows[0]);
} catch (err) { } catch (err) {
@@ -921,7 +1123,7 @@ app.post('/api/links', auth, admin, async (req, res) => {
}); });
// 删除友情链接(管理员) // 删除友情链接(管理员)
app.delete('/api/links/:id', auth, admin, async (req, res) => { app.delete('/api/links/:id', validateUuidId, auth, admin, async (req, res) => {
try { try {
await pool.query('DELETE FROM friendly_links WHERE id = $1', [req.params.id]); await pool.query('DELETE FROM friendly_links WHERE id = $1', [req.params.id]);
res.json({ success: true }); res.json({ success: true });
@@ -957,9 +1159,9 @@ app.get('/api/stats', async (req, res) => {
// 获取事件日志(管理员)—— 支持分页 // 获取事件日志(管理员)—— 支持分页
app.get('/api/event-logs', auth, admin, async (req, res) => { app.get('/api/event-logs', auth, admin, async (req, res) => {
try { try {
const page = parseInt(req.query.page) || 1; const pagination = parsePagination(req.query);
const limit = parseInt(req.query.limit) || 20; if (!pagination) return res.status(400).json({ error: '分页参数无效' });
const offset = (page - 1) * limit; const { page, limit, offset } = pagination;
// 查询总数 // 查询总数
const countResult = await pool.query('SELECT COUNT(*) FROM event_logs'); const countResult = await pool.query('SELECT COUNT(*) FROM event_logs');
@@ -988,20 +1190,7 @@ app.get('/api/event-logs', auth, admin, async (req, res) => {
} }
}); });
// 记录事件
app.post('/api/event-logs', auth, async (req, res) => {
const { action } = req.body;
try {
await pool.query(
`INSERT INTO event_logs (user_id, action, ip)
VALUES ($1, $2, $3)`,
[req.user.id, action, req.ip || '0.0.0.0']
);
res.json({ success: true });
} catch (err) {
res.json({ success: true });
}
});
// ============================================================ // ============================================================
// 图片上传 // 图片上传
@@ -1042,7 +1231,10 @@ const CUSTOM_CSS_DIR = path.join(__dirname, 'uploads/custom');
if (!fs.existsSync(CUSTOM_CSS_DIR)) fs.mkdirSync(CUSTOM_CSS_DIR, { recursive: true }); if (!fs.existsSync(CUSTOM_CSS_DIR)) fs.mkdirSync(CUSTOM_CSS_DIR, { recursive: true });
// 保存自定义 CSS(管理员) // 保存自定义 CSS(管理员)
const cssUpload = multer({ dest: 'uploads/temp/' }); const cssUpload = multer({
dest: 'uploads/temp/',
limits: { fileSize: 256 * 1024, files: 1 },
});
app.post('/api/admin/custom-css', auth, admin, cssUpload.single('file'), async (req, res) => { app.post('/api/admin/custom-css', auth, admin, cssUpload.single('file'), async (req, res) => {
if (!req.file) { if (!req.file) {
return res.status(400).json({ error: '请选择文件' }); return res.status(400).json({ error: '请选择文件' });
@@ -1127,10 +1319,10 @@ app.get('/api/conversations', auth, async (req, res) => {
// 获取或创建会话 // 获取或创建会话
app.post('/api/conversations', auth, async (req, res) => { app.post('/api/conversations', auth, async (req, res) => {
const { other_user_id } = req.body; const { other_user_id } = req.body;
if (!other_user_id) { if (!UUID_PATTERN.test(other_user_id || '')) {
return res.status(400).json({ error: '缺少对方用户ID' }); return res.status(400).json({ error: '对方用户ID无效' });
} }
if (other_user_id === req.user.id) { if (String(other_user_id).toLowerCase() === String(req.user.id).toLowerCase()) {
return res.status(400).json({ error: '不能与自己私信' }); return res.status(400).json({ error: '不能与自己私信' });
} }
@@ -1140,18 +1332,11 @@ app.post('/api/conversations', auth, async (req, res) => {
return res.status(404).json({ error: '用户不存在' }); return res.status(404).json({ error: '用户不存在' });
} }
const existing = await pool.query(`
SELECT id FROM conversations
WHERE (user1_id = $1 AND user2_id = $2) OR (user1_id = $2 AND user2_id = $1)
`, [req.user.id, other_user_id]);
if (existing.rows.length > 0) {
return res.json({ id: existing.rows[0].id });
}
const r = await pool.query(` const r = await pool.query(`
INSERT INTO conversations (user1_id, user2_id) INSERT INTO conversations (user1_id, user2_id)
VALUES ($1, $2) SELECT LEAST($1::uuid, $2::uuid), GREATEST($1::uuid, $2::uuid)
ON CONFLICT (user1_id, user2_id)
DO UPDATE SET user1_id = EXCLUDED.user1_id
RETURNING id RETURNING id
`, [req.user.id, other_user_id]); `, [req.user.id, other_user_id]);
@@ -1162,7 +1347,7 @@ app.post('/api/conversations', auth, async (req, res) => {
}); });
// 获取会话消息 // 获取会话消息
app.get('/api/conversations/:id/messages', auth, async (req, res) => { app.get('/api/conversations/:id/messages', validateUuidId, auth, async (req, res) => {
const conversationId = req.params.id; const conversationId = req.params.id;
try { try {
@@ -1198,12 +1383,12 @@ app.get('/api/conversations/:id/messages', auth, async (req, res) => {
}); });
// 发送消息 // 发送消息
app.post('/api/conversations/:id/messages', auth, async (req, res) => { app.post('/api/conversations/:id/messages', validateUuidId, auth, async (req, res) => {
const conversationId = req.params.id; const conversationId = req.params.id;
const { content } = req.body; const { content } = req.body;
if (!content || content.trim().length === 0) { if (!isText(content, { min: 1, max: 10000 })) {
return res.status(400).json({ error: '请填写消息内容' }); return res.status(400).json({ error: '消息长度应为1到10000个字符' });
} }
try { try {
@@ -1220,7 +1405,7 @@ app.post('/api/conversations/:id/messages', auth, async (req, res) => {
INSERT INTO messages (conversation_id, sender_id, content) INSERT INTO messages (conversation_id, sender_id, content)
VALUES ($1, $2, $3) VALUES ($1, $2, $3)
RETURNING * RETURNING *
`, [conversationId, req.user.id, content]); `, [conversationId, req.user.id, content.trim()]);
await pool.query(` await pool.query(`
UPDATE conversations SET last_message_at = NOW() UPDATE conversations SET last_message_at = NOW()
@@ -1242,7 +1427,7 @@ app.post('/api/conversations/:id/messages', auth, async (req, res) => {
}); });
// 标记消息已读 // 标记消息已读
app.put('/api/messages/:id/read', auth, async (req, res) => { app.put('/api/messages/:id/read', validateUuidId, auth, async (req, res) => {
try { try {
const result = await pool.query(` const result = await pool.query(`
UPDATE messages AS m SET is_read = true UPDATE messages AS m SET is_read = true
@@ -1280,6 +1465,9 @@ app.get('/api/custom-pages', async (req, res) => {
// 获取单个自定义页面(公开) // 获取单个自定义页面(公开)
app.get('/api/custom-pages/:name', async (req, res) => { app.get('/api/custom-pages/:name', async (req, res) => {
if (!/^[a-zA-Z0-9\-_]{1,50}$/.test(req.params.name)) {
return res.status(400).json({ error: '页面名称无效' });
}
try { try {
const r = await pool.query( const r = await pool.query(
'SELECT id, name, title, content FROM custom_pages WHERE name = $1 AND enabled = true', 'SELECT id, name, title, content FROM custom_pages WHERE name = $1 AND enabled = true',
@@ -1309,18 +1497,17 @@ app.get('/api/admin/custom-pages', auth, admin, async (req, res) => {
// 创建自定义页面(管理员) // 创建自定义页面(管理员)
app.post('/api/admin/custom-pages', auth, admin, async (req, res) => { app.post('/api/admin/custom-pages', auth, admin, async (req, res) => {
const { name, title, content } = req.body; const { name, title, content } = req.body;
if (!name || !title || !content) { if (!/^[a-zA-Z0-9\-_]{1,50}$/.test(name || '') ||
return res.status(400).json({ error: '请填写完整信息' }); !isText(title, { min: 1, max: 100 }) ||
} !isText(content, { min: 1, max: 100000 })) {
if (!/^[a-zA-Z0-9\-_]+$/.test(name)) { return res.status(400).json({ error: '页面名称、标题或内容长度无效' });
return res.status(400).json({ error: '页面名称只允许字母、数字、短横线和下划线' });
} }
try { try {
const r = await pool.query( const r = await pool.query(
`INSERT INTO custom_pages (name, title, content) `INSERT INTO custom_pages (name, title, content)
VALUES ($1, $2, $3) VALUES ($1, $2, $3)
RETURNING *`, RETURNING *`,
[name, title, content] [name, title.trim(), content]
); );
res.json(r.rows[0]); res.json(r.rows[0]);
} catch (err) { } catch (err) {
@@ -1333,16 +1520,21 @@ app.post('/api/admin/custom-pages', auth, admin, async (req, res) => {
}); });
// 更新自定义页面(管理员) // 更新自定义页面(管理员)
app.put('/api/admin/custom-pages/:id', auth, admin, async (req, res) => { app.put('/api/admin/custom-pages/:id', validateUuidId, auth, admin, async (req, res) => {
const { title, content, enabled } = req.body; const { title, content, enabled } = req.body;
const id = req.params.id; const id = req.params.id;
if (!isText(title, { min: 1, max: 100 }) ||
!isText(content, { min: 1, max: 100000 }) ||
typeof enabled !== 'boolean') {
return res.status(400).json({ error: '页面标题、内容或状态无效' });
}
try { try {
const r = await pool.query( const r = await pool.query(
`UPDATE custom_pages `UPDATE custom_pages
SET title = $1, content = $2, enabled = $3, updated_at = NOW() SET title = $1, content = $2, enabled = $3, updated_at = NOW()
WHERE id = $4 WHERE id = $4
RETURNING *`, RETURNING *`,
[title, content, enabled, id] [title.trim(), content, enabled, id]
); );
if (r.rows.length === 0) { if (r.rows.length === 0) {
return res.status(404).json({ error: '页面不存在' }); return res.status(404).json({ error: '页面不存在' });
@@ -1354,7 +1546,7 @@ app.put('/api/admin/custom-pages/:id', auth, admin, async (req, res) => {
}); });
// 删除自定义页面(管理员) // 删除自定义页面(管理员)
app.delete('/api/admin/custom-pages/:id', auth, admin, async (req, res) => { app.delete('/api/admin/custom-pages/:id', validateUuidId, auth, admin, async (req, res) => {
try { try {
await pool.query('DELETE FROM custom_pages WHERE id = $1', [req.params.id]); await pool.query('DELETE FROM custom_pages WHERE id = $1', [req.params.id]);
res.json({ success: true }); res.json({ success: true });
@@ -1381,7 +1573,7 @@ app.get('/api/notifications', auth, async (req, res) => {
}); });
// 标记通知已读 // 标记通知已读
app.put('/api/notifications/:id/read', auth, async (req, res) => { app.put('/api/notifications/:id/read', validateUuidId, auth, async (req, res) => {
try { try {
await pool.query( await pool.query(
'UPDATE notifications SET is_read = true WHERE id = $1 AND user_id = $2', 'UPDATE notifications SET is_read = true WHERE id = $1 AND user_id = $2',
@@ -1462,26 +1654,24 @@ app.get('/api/auth/recovery-codes/count', auth, async (req, res) => {
app.post('/api/auth/reset-password', async (req, res) => { app.post('/api/auth/reset-password', async (req, res) => {
const { email, recoveryCode, newPassword } = req.body; const { email, recoveryCode, newPassword } = req.body;
if (!email || !recoveryCode || !newPassword) { if (!normalizeLegacyEmail(email) || !isText(recoveryCode, { min: 1, max: 64 }) ||
!isText(newPassword, { min: 6, max: 128 })) {
return res.status(400).json({ error: '请填写完整信息' }); return res.status(400).json({ error: '请填写完整信息' });
} }
if (newPassword.length < 6) {
return res.status(400).json({ error: '密码至少6位' });
}
let client; let client;
try { try {
client = await pool.connect(); client = await pool.connect();
await client.query('BEGIN'); await client.query('BEGIN');
const user = await client.query('SELECT id FROM users WHERE LOWER(email) = LOWER($1)', [email]); const user = await findUserByEmail(client, email, 'id');
if (user.rows.length === 0) { if (!user) {
await client.query('ROLLBACK'); await client.query('ROLLBACK');
return res.status(400).json({ error: '恢复码无效或已使用' }); return res.status(400).json({ error: '恢复码无效或已使用' });
} }
const codes = await client.query( const codes = await client.query(
'SELECT id, code_hash FROM recovery_codes WHERE user_id = $1 AND is_used = false FOR UPDATE', 'SELECT id, code_hash FROM recovery_codes WHERE user_id = $1 AND is_used = false FOR UPDATE',
[user.rows[0].id] [user.id]
); );
if (codes.rows.length === 0) { if (codes.rows.length === 0) {
await client.query('ROLLBACK'); await client.query('ROLLBACK');
@@ -1512,7 +1702,7 @@ app.post('/api/auth/reset-password', async (req, res) => {
); );
await client.query( await client.query(
'UPDATE users SET password_hash = $1, token_version = token_version + 1 WHERE id = $2', 'UPDATE users SET password_hash = $1, token_version = token_version + 1 WHERE id = $2',
[hash, user.rows[0].id] [hash, user.id]
); );
await client.query('COMMIT'); await client.query('COMMIT');
@@ -1529,6 +1719,19 @@ app.post('/api/auth/reset-password', async (req, res) => {
// 托管公开前端文件 // 托管公开前端文件
// ============================================================ // ============================================================
app.get('/health/live', (req, res) => {
res.json({ status: 'ok' });
});
app.get('/health/ready', async (req, res) => {
try {
await pool.query('SELECT 1');
res.json({ status: 'ready' });
} catch (error) {
res.status(503).json({ status: 'not_ready' });
}
});
app.use('/js', express.static(path.join(__dirname, 'js'), { app.use('/js', express.static(path.join(__dirname, 'js'), {
dotfiles: 'deny', dotfiles: 'deny',
fallthrough: false, fallthrough: false,
@@ -1549,6 +1752,10 @@ app.get('*', (req, res) => {
app.use((err, req, res, next) => { app.use((err, req, res, next) => {
if (res.headersSent) return next(err); if (res.headersSent) return next(err);
if (err instanceof multer.MulterError) {
const status = err.code === 'LIMIT_FILE_SIZE' ? 413 : 400;
return res.status(status).json({ error: '上传文件超过限制或格式无效' });
}
if (err.type === 'entity.too.large') { if (err.type === 'entity.too.large') {
return res.status(413).json({ error: '请求内容过大' }); return res.status(413).json({ error: '请求内容过大' });
} }
@@ -1563,10 +1770,71 @@ app.use((err, req, res, next) => {
// 启动服务器 // 启动服务器
// ============================================================ // ============================================================
app.listen(PORT, '0.0.0.0', () => {
console.log('========================================'); let server = null;
console.log(' 🌊 Forumlify 已启动'); let shuttingDown = false;
console.log(' 📡 http://localhost:' + PORT);
console.log(' 📡 API: http://localhost:' + PORT + '/api'); function startServer() {
console.log('========================================'); if (server) return server;
});
server = app.listen(PORT, '0.0.0.0', () => {
console.log('========================================');
console.log(' 🌊 Forumlify 已启动');
console.log(' 📡 http://localhost:' + PORT);
console.log(' 📡 API: http://localhost:' + PORT + '/api');
console.log('========================================');
});
return server;
}
function shutdown(signal, { exitProcess = true } = {}) {
if (shuttingDown) return Promise.resolve();
shuttingDown = true;
console.log(`${signal} received, shutting down gracefully`);
return new Promise((resolve, reject) => {
const forceExit = exitProcess
? setTimeout(() => process.exit(1), 10000)
: null;
if (forceExit) forceExit.unref();
const finish = async error => {
try {
await pool.end();
if (error) throw error;
resolve();
} catch (shutdownError) {
reject(shutdownError);
} finally {
if (forceExit) clearTimeout(forceExit);
server = null;
shuttingDown = false;
}
};
if (server) server.close(finish);
else finish();
}).finally(() => {
if (exitProcess) process.exitCode = 0;
});
}
if (require.main === module) {
startServer();
process.on('SIGTERM', () => {
shutdown('SIGTERM').catch(error => {
console.error('Graceful shutdown failed:', error);
process.exitCode = 1;
});
});
process.on('SIGINT', () => {
shutdown('SIGINT').catch(error => {
console.error('Graceful shutdown failed:', error);
process.exitCode = 1;
});
});
}
module.exports = { app, pool, startServer, shutdown };
+35 -1
View File
@@ -2522,8 +2522,42 @@ a.btn-secondary {
-webkit-backdrop-filter: blur(32px) !important; -webkit-backdrop-filter: blur(32px) !important;
border: 1px solid var(--glass-border) !important; border: 1px solid var(--glass-border) !important;
} }
/* ============================================================ /* ============================================================
🌍 国际化加载前隐藏 📄 自定义页面 —— 全屏沉浸式
============================================================ */ ============================================================ */
/* ============================================================
📄 自定义页面 —— 全屏沉浸式(位置修正版)
============================================================ */
#customPageContainer {
position: fixed !important;
top: 64px !important;
left: 0 !important;
width: 100vw !important;
height: calc(100vh - 64px) !important;
padding: 0 !important;
margin: 0 !important;
background: transparent !important;
z-index: 40 !important;
overflow: hidden !important;
}
#customPageContainer iframe {
display: block !important;
width: 100% !important;
height: 100% !important;
border: none !important;
border-radius: 0 !important;
background: transparent !important;
}
/* 移动端适配 */
@media (max-width: 768px) {
#customPageContainer {
top: 56px !important;
height: calc(100vh - 56px) !important;
}
}
+75
View File
@@ -0,0 +1,75 @@
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', () => {
assert.match(multerPackage.version, /^2\.2\./);
assert.equal(projectPackage.dependencies['express-rate-limit'], '8.6.2');
});