fix: resolve conflicts for PR #14
This commit is contained in:
commit
5314d60f53
30 files changed
+1755
-848
No files matched your search
@@ -0,0 +1,10 @@
|
||||
.git
|
||||
.github
|
||||
.env
|
||||
.env.*
|
||||
!.env.example
|
||||
node_modules
|
||||
npm-debug.log*
|
||||
uploads
|
||||
coverage
|
||||
*.md
|
||||
@@ -0,0 +1,4 @@
|
||||
# Copy to .env, then set both required secrets before running Docker Compose.
|
||||
POSTGRES_PASSWORD=
|
||||
JWT_SECRET=
|
||||
PORT=3000
|
||||
@@ -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
|
||||
@@ -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
|
||||
@@ -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
|
||||
@@ -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
|
||||
@@ -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
@@ -3,3 +3,13 @@ uploads/
|
||||
*.log
|
||||
.DS_Store
|
||||
.env
|
||||
|
||||
# Wrangler 本地状态
|
||||
.wrangler/
|
||||
|
||||
|
||||
# 构建产物
|
||||
.open-next/
|
||||
.vercel/
|
||||
.next/
|
||||
.wrangler/
|
||||
+19
@@ -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"]
|
||||
@@ -37,16 +37,50 @@ Forumlify 提供了两个不同架构的分支版本,以满足不同部署环
|
||||
### Docker 部署(推荐)
|
||||
|
||||
```
|
||||
git clone https://github.com/furrium/forumlify.git
|
||||
git clone https://github.com/forumlify/public.git
|
||||
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`。
|
||||
|
||||
容器启动时会自动执行 `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+
|
||||
|
||||
#### 步骤
|
||||
@@ -64,7 +98,7 @@ docker-compose up -d
|
||||
1. **克隆并安装依赖**
|
||||
|
||||
```bash
|
||||
git clone https://github.com/furrium/forumlify.git
|
||||
git clone https://github.com/public/tree/lite.git
|
||||
cd forumlify
|
||||
npm install
|
||||
```
|
||||
@@ -77,19 +111,25 @@ psql -U postgres -c "CREATE DATABASE forumlify OWNER forumlify;"
|
||||
psql -U forumlify -d forumlify -f schema.sql
|
||||
```
|
||||
|
||||
3. **配置环境变量**(可选)
|
||||
3. **配置环境变量**
|
||||
|
||||
| 变量 | 默认值 | 说明 |
|
||||
|------|--------|------|
|
||||
| `DATABASE_URL` | `postgresql://forumlify:***@localhost:5432/forumlify` | PostgreSQL 连接串 |
|
||||
| `PORT` | `3000` | HTTP 监听端口 |
|
||||
| `JWT_SECRET` | 本地开发使用内置值 | JWT 签名密钥;`NODE_ENV=production` 时必须显式设置 |
|
||||
| `JWT_SECRET` | 本地开发使用内置值 | JWT 签名密钥;生产环境必须显式设置,建议至少 32 个字符。较短的旧密钥会产生警告但仍可启动,便于安排会话失效窗口后再轮换 |
|
||||
| `ALLOWED_ORIGINS` | 空 | 允许跨域访问的来源,多个值用逗号分隔;为空时仅支持同源访问 |
|
||||
| `TRUST_PROXY` | `false` | 位于可信反向代理后时设为 `true`,用于正确识别限流 IP |
|
||||
|
||||
4. **启动**
|
||||
| `PGHOST` / `PGPORT` / `PGUSER` / `PGPASSWORD` / `PGDATABASE` | PostgreSQL 客户端默认值 | 可替代 `DATABASE_URL`,Compose 使用这些变量避免密码 URL 编码问题 |
|
||||
|
||||
| `ADMIN_BOOTSTRAP_TOKEN` | 空 | 首次部署时设置强随机值;注册页填写相同值可创建唯一初始管理员,初始化后应删除该变量 |
|
||||
|
||||
|
||||
4. **执行迁移并启动**
|
||||
|
||||
```bash
|
||||
npm run migrate
|
||||
npm start
|
||||
```
|
||||
|
||||
@@ -139,4 +179,3 @@ forumlify/
|
||||
|
||||
MIT
|
||||
|
||||
|
||||
+37
-10
@@ -1,27 +1,54 @@
|
||||
version: '3'
|
||||
services:
|
||||
db:
|
||||
image: postgres:15
|
||||
image: postgres:15.14-alpine
|
||||
restart: unless-stopped
|
||||
environment:
|
||||
POSTGRES_USER: forumlify
|
||||
POSTGRES_PASSWORD: 123456
|
||||
POSTGRES_PASSWORD: ${POSTGRES_PASSWORD:?Set POSTGRES_PASSWORD in .env}
|
||||
POSTGRES_DB: forumlify
|
||||
volumes:
|
||||
- ./schema.sql:/docker-entrypoint-initdb.d/schema.sql
|
||||
- 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:
|
||||
build: .
|
||||
build:
|
||||
context: .
|
||||
dockerfile: Dockerfile
|
||||
restart: unless-stopped
|
||||
|
||||
ports:
|
||||
- "3000:3000"
|
||||
- "${PORT:-3000}:3000"
|
||||
depends_on:
|
||||
- db
|
||||
db:
|
||||
condition: service_healthy
|
||||
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:
|
||||
- ./uploads:/app/uploads
|
||||
healthcheck:
|
||||
test: ["CMD", "node", "scripts/healthcheck.js"]
|
||||
interval: 30s
|
||||
timeout: 5s
|
||||
retries: 3
|
||||
start_period: 30s
|
||||
|
||||
|
||||
volumes:
|
||||
db_data:
|
||||
@@ -1,7 +0,0 @@
|
||||
FROM node:18-alpine
|
||||
WORKDIR /app
|
||||
COPY package*.json ./
|
||||
RUN npm install
|
||||
COPY . .
|
||||
EXPOSE 3000
|
||||
CMD ["npm", "start"]
|
||||
@@ -362,6 +362,7 @@
|
||||
<input type="text" id="regUsername" placeholder="用户名" />
|
||||
<input type="email" id="regEmail" placeholder="邮箱" />
|
||||
<input type="password" id="regPassword" placeholder="密码(至少6位)" />
|
||||
<input type="password" id="regBootstrapToken" placeholder="管理员初始化令牌(仅首次部署,可选)" autocomplete="off" />
|
||||
<div class="captcha-row">
|
||||
<span id="regCaptchaQuestion">3 + 5 = ?</span>
|
||||
<input type="text" id="regCaptchaInput" placeholder="答案" style="width:80px;" />
|
||||
|
||||
@@ -35,10 +35,10 @@ const API = {
|
||||
return data;
|
||||
},
|
||||
|
||||
async register(email, password, username) {
|
||||
async register(email, password, username, bootstrapToken = '') {
|
||||
const data = await apiFetch('/auth/register', {
|
||||
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);
|
||||
return data;
|
||||
@@ -227,14 +227,6 @@ const API = {
|
||||
return data;
|
||||
},
|
||||
|
||||
async logEvent(action) {
|
||||
try {
|
||||
await apiFetch('/event-logs', {
|
||||
method: 'POST',
|
||||
body: JSON.stringify({ action })
|
||||
});
|
||||
} catch (e) { /* 静默失败 */ }
|
||||
},
|
||||
|
||||
// ============================================================
|
||||
// 论坛设置
|
||||
|
||||
@@ -490,7 +490,7 @@ function showCustomPage(pageName) {
|
||||
API.getCustomPage(pageName).then(page => {
|
||||
const iframe = document.createElement('iframe');
|
||||
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 = `
|
||||
<!DOCTYPE html>
|
||||
<html>
|
||||
@@ -843,8 +843,12 @@ async function renderSettingsPage(tab = 'profile') {
|
||||
await API.changePassword(oldPassword, newPassword);
|
||||
document.getElementById('changeOldPassword').value = '';
|
||||
document.getElementById('changeNewPassword').value = '';
|
||||
statusEl.textContent = getIcon('success') + ' 密码修改成功!';
|
||||
statusEl.textContent = getIcon('success') + ' 密码修改成功,正在返回登录页…';
|
||||
statusEl.style.color = '#22c55e';
|
||||
localStorage.removeItem('token');
|
||||
currentUser = null;
|
||||
renderNav();
|
||||
setTimeout(() => switchPage('login'), 800);
|
||||
} catch (err) {
|
||||
statusEl.textContent = getIcon('error') + ' ' + err.message;
|
||||
statusEl.style.color = '#ef4444';
|
||||
@@ -867,9 +871,12 @@ async function renderSettingsPage(tab = 'profile') {
|
||||
await API.changeEmail(password, newEmail);
|
||||
document.getElementById('changeEmailPassword').value = '';
|
||||
document.getElementById('changeNewEmail').value = '';
|
||||
currentUser.email = newEmail;
|
||||
statusEl.textContent = getIcon('success') + ' 邮箱修改成功!';
|
||||
statusEl.textContent = getIcon('success') + ' 邮箱修改成功,正在返回登录页…';
|
||||
statusEl.style.color = '#22c55e';
|
||||
localStorage.removeItem('token');
|
||||
currentUser = null;
|
||||
renderNav();
|
||||
setTimeout(() => switchPage('login'), 800);
|
||||
} catch (err) {
|
||||
statusEl.textContent = getIcon('error') + ' ' + err.message;
|
||||
statusEl.style.color = '#ef4444';
|
||||
@@ -1123,7 +1130,7 @@ async function init() {
|
||||
try {
|
||||
const user = await API.getMe();
|
||||
currentUser = user;
|
||||
API.logEvent('login').catch(() => {});
|
||||
|
||||
} catch (e) {
|
||||
token = null;
|
||||
localStorage.removeItem('forumlify-token');
|
||||
@@ -1278,7 +1285,7 @@ async function init() {
|
||||
images.push(uploaded.url);
|
||||
}
|
||||
await API.createPost(title, content, images);
|
||||
API.logEvent('create_post').catch(() => {});
|
||||
|
||||
alert('发布成功!');
|
||||
clearSelectedImages();
|
||||
switchPage('feed');
|
||||
|
||||
+3
-3
@@ -18,7 +18,6 @@ document.getElementById('loginSubmit').addEventListener('click', async () => {
|
||||
document.getElementById('loginPassword').value = '';
|
||||
if (result.user) {
|
||||
currentUser = result.user;
|
||||
API.logEvent('login').catch(() => {});
|
||||
renderNav();
|
||||
if (currentPage === 'admin' && currentUser.role !== 'admin') {
|
||||
switchPage('feed');
|
||||
@@ -42,13 +41,14 @@ document.getElementById('registerSubmit').addEventListener('click', async () =>
|
||||
const username = document.getElementById('regUsername').value.trim();
|
||||
const email = document.getElementById('regEmail').value.trim();
|
||||
const password = document.getElementById('regPassword').value;
|
||||
const bootstrapToken = document.getElementById('regBootstrapToken').value.trim();
|
||||
const captchaInput = document.getElementById('regCaptchaInput').value.trim();
|
||||
const captchaAnswer = parseInt(document.getElementById('regCaptchaInput').dataset.answer);
|
||||
if (!username || !email || !password) { alert('请填写完整信息'); return; }
|
||||
if (password.length < 6) { alert('密码至少6位'); return; }
|
||||
if (parseInt(captchaInput) !== captchaAnswer) { alert('验证码错误,请重新计算'); refreshCaptcha('reg'); return; }
|
||||
try {
|
||||
await API.register(email, password, username);
|
||||
await API.register(email, password, username, bootstrapToken);
|
||||
} catch (err) {
|
||||
alert('注册失败:' + err.message);
|
||||
return;
|
||||
@@ -58,12 +58,12 @@ document.getElementById('registerSubmit').addEventListener('click', async () =>
|
||||
document.getElementById('regUsername').value = '';
|
||||
document.getElementById('regEmail').value = '';
|
||||
document.getElementById('regPassword').value = '';
|
||||
document.getElementById('regBootstrapToken').value = '';
|
||||
document.getElementById('regCaptchaInput').value = '';
|
||||
|
||||
try {
|
||||
await API.login(email, password);
|
||||
currentUser = await API.getMe();
|
||||
API.logEvent('register').catch(() => {});
|
||||
renderNav();
|
||||
|
||||
if (currentPage === 'admin' && currentUser.role !== 'admin') {
|
||||
|
||||
+1
-1
@@ -228,7 +228,7 @@ async function handleReplySubmit(postId) {
|
||||
if (parseInt(captchaInput) !== captchaAnswer) { alert('验证码错误,请重新计算'); refreshCaptcha('reply'); return; }
|
||||
try {
|
||||
await API.createReply(postId, content);
|
||||
API.logEvent('create_reply').catch(() => {});
|
||||
|
||||
renderPostDetail(postId);
|
||||
if (currentPage === 'feed') {
|
||||
renderFeed();
|
||||
|
||||
@@ -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;
|
||||
Generated
+285
-626
File diff suppressed because it is too large.
Load diff
+14
-4
@@ -3,18 +3,28 @@
|
||||
"version": "1.0.0",
|
||||
"description": "Forumlify - 简洁优雅的现代社区系统",
|
||||
"main": "server.js",
|
||||
"engines": {
|
||||
"node": ">=20"
|
||||
},
|
||||
"scripts": {
|
||||
"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": {
|
||||
"bcrypt": "^5.1.1",
|
||||
"bcryptjs": "3.0.3",
|
||||
"cors": "^2.8.5",
|
||||
"express": "^4.18.2",
|
||||
"express-rate-limit": "8.1.0",
|
||||
"express-rate-limit": "8.6.2",
|
||||
"helmet": "8.1.0",
|
||||
"jsonwebtoken": "^9.0.2",
|
||||
"multer": "^1.4.5-lts.1",
|
||||
"multer": "2.2.0",
|
||||
"pg": "^8.11.3"
|
||||
},
|
||||
"devDependencies": {
|
||||
"supertest": "7.2.2"
|
||||
}
|
||||
}
|
||||
+80
@@ -11,9 +11,13 @@ CREATE TABLE IF NOT EXISTS users (
|
||||
avatar_url TEXT,
|
||||
bio TEXT DEFAULT '',
|
||||
role VARCHAR(10) DEFAULT 'user' CHECK (role IN ('user', 'admin')),
|
||||
token_version INTEGER NOT NULL DEFAULT 0,
|
||||
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 (
|
||||
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
|
||||
@@ -86,9 +90,20 @@ CREATE TABLE IF NOT EXISTS event_logs (
|
||||
user_id UUID REFERENCES users(id) ON DELETE SET NULL,
|
||||
action VARCHAR(50) NOT NULL,
|
||||
ip VARCHAR(45),
|
||||
method VARCHAR(10),
|
||||
path TEXT,
|
||||
user_agent TEXT,
|
||||
metadata JSONB NOT NULL DEFAULT '{}'::jsonb,
|
||||
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);
|
||||
|
||||
-- ============================================================
|
||||
-- 论坛设置表
|
||||
-- ============================================================
|
||||
@@ -112,6 +127,7 @@ CREATE TABLE IF NOT EXISTS conversations (
|
||||
user2_id UUID NOT NULL REFERENCES users(id) ON DELETE CASCADE,
|
||||
last_message_at TIMESTAMPTZ DEFAULT now(),
|
||||
created_at TIMESTAMPTZ DEFAULT now(),
|
||||
CHECK (user1_id < user2_id),
|
||||
UNIQUE(user1_id, user2_id)
|
||||
);
|
||||
|
||||
@@ -201,6 +217,70 @@ 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;
|
||||
|
||||
-- ============================================================
|
||||
-- 论坛默认设置
|
||||
|
||||
@@ -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.`);
|
||||
Executable
+5
@@ -0,0 +1,5 @@
|
||||
#!/bin/sh
|
||||
set -eu
|
||||
|
||||
node scripts/migrate.js
|
||||
exec node server.js
|
||||
@@ -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);
|
||||
});
|
||||
@@ -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);
|
||||
});
|
||||
@@ -2522,8 +2522,42 @@ a.btn-secondary {
|
||||
-webkit-backdrop-filter: blur(32px) !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;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -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');
|
||||
});
|
||||
Reference in new issue
Block a user