Author SHA1 Message Date

2026-08-14

lezi-fun 3f7b9dbb9c fix: note that npm run build is next-branch only in PR template 2026-08-14 09:38:22 +08:00
lezi-fun b036a51eef feat: add bilingual PR and issue templates with branch selection 2026-08-14 09:31:55 +08:00

2026-08-13

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

2026-08-12

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

2026-08-11

Arun a5a880dfb2 Make audit logs server owned 2026-08-11 10:59:58 +00:00
Arun 3fc74ae189 Add integrated tests and patch dependencies 2026-08-11 10:34:46 +00:00
lezi 145f13fee5 Update README.md 2026-08-11 17:28:26 +08:00
lezi 3ed09fbcdf Update README.md 2026-08-11 17:27:39 +08:00
lezi 3ffb92dc23 Update README.md 2026-08-11 17:24:32 +08:00
Furrium Network 3fbf2743d0 3000吧还是 2026-08-11 17:17:55 +08:00
Furrium Network b4330666a4 Update README.md 2026-08-11 17:13:29 +08:00
Furrium Network 51a6b49459 Update README.md 2026-08-11 17:11:58 +08:00
Furrium Network 8d1b59479e Pass.
Fix registration and recovery-code setup
2026-08-11 16:58:51 +08:00
Furrium Network 3cee3ae530 Pass.
Prevent stored XSS in rendered content
2026-08-11 16:58:31 +08:00
Furrium Network 2e745b547d Pass.
Make moderation actions atomic and authorized
2026-08-11 16:58:13 +08:00
Furrium Network 7cf69ad476 Pass!
Harden HTTP server defaults
2026-08-11 16:57:37 +08:00
Arun c57863fc47 Make moderation actions atomic and authorized 2026-08-11 07:57:39 +00:00
lezi b449e05f3f Update README.md 2026-08-11 15:56:45 +08:00
Arun 5d0a148804 Harden HTTP server defaults 2026-08-11 07:48:33 +00:00
Arun f30a3dcacb Prevent stored XSS in rendered content 2026-08-11 07:39:37 +00:00
Arun 9e99d6909a Fix registration recovery setup flow 2026-08-11 07:23:14 +00:00
26 changed files with 1331 additions and 830 deletions

No files matched your search

+1
View File
@@ -0,0 +1 @@
NEXTJS_ENV=development
+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
+82
View File
@@ -0,0 +1,82 @@
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 }}
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/
+33 -9
View File
@@ -1,6 +1,6 @@
# Forumlify Express Edition 🌊 # Forumlify LITE Edition 🌊
> 一个简洁、优雅的现代社区系统。5 分钟 Docker 一键部署。 > 一个简洁、优雅的现代社区系统。5 分钟 Docker 一键部署。
@@ -13,21 +13,44 @@
- 🐳 Docker 一键部署 - 🐳 Docker 一键部署
- 🌓 暗色/亮色模式切换 - 🌓 暗色/亮色模式切换
## 🤔 如何选择版本
Forumlify 提供了两个不同架构的分支版本,以满足不同部署环境与开发需求的场景:
* **Lite 版 (`lite` 分支)**:轻量单体架构,零构建步骤,资源占用极低,主要由Furrium维护。
* **Next.js 版 (`next` 分支)**:现代全栈架构,组件化开发,支持云原生与 Serverless / 边缘部署,主要由lezi-fun维护。
你可以根据以下维度选择最适合你当前需求的版本:
| 对比维度 | Forumlify (Lite 版 / `lite`) | Forumlify-Next (Next.js 版 / `next`) | 选择建议 |
| :--- | :--- | :--- | :--- |
| **上手速度与部署** | **极快**(零编译步骤,直接 `node server.js` 或 Docker 启动) | **中等**(需要经过 `next build` 编译打包,或配置 OpenNext) | 希望 1 分钟快速跑起来选 `lite` |
| **VPS 最低配置要求** | **1 核 512MB RAM**(资源占用极低,适合低配小鸡) | **1 核 1GB RAM+**(主要在打包构建时需要较多内存) | 内存有限或低配 VPS 推荐 `lite` |
| **存储扩展性** | 本地磁盘存储(`uploads/` 目录) | 支持 **Cloudflare R2 / S3 兼容对象存储** + 本地回退 | 需要接云存储或海量图片存储选 `next` |
| **部署环境支持** | 传统 VPS / Docker 容器 | VPS / Docker / **Cloudflare Workers / Vercel** | 需要 Serverless / 边缘部署选 `next` |
| **技术栈与二次开发** | 原生 Vanilla JS + Express,无框架门槛 | React 19 + Next.js 16 + Tailwind,组件化程度高 | 熟悉 React 框架或需要团队协同选 `next` |
| **测试与工程化** | 基础配置,轻量化结构 | 内置自动化测试套件(Unit / Integration Tests) | 追求工程化与自动化测试选 `next` |
| **适合场景** | 个人轻量论坛、小圈子交流、低成本运行、快速原型验证 | 中大型社区、云原生部署、需要扩展对象存储或边缘加速 | 根据站点规模与长期规划选择 |
## 🚀 快速开始 ## 🚀 快速开始
### Docker 部署(推荐) ### Docker 部署(推荐)
``` ```
git clone https://github.com/furrium/forumlify.git git clone https://github.com/forumlify/public.git
cd forumlify cd forumlify
docker-compose up -d printf 'JWT_SECRET=%s\n' "$(openssl rand -hex 32)" > .env
docker compose up -d
``` ```
旧版 Compose 也可以使用 `docker-compose up -d`。请妥善备份 `.env`;更换
`JWT_SECRET` 会使现有登录令牌失效。
应用默认运行在 `http://localhost:3000`。 应用默认运行在 `http://localhost:3000`。
--- ---
> 如需部署 Next.js 版本,请前往 [forumlify/tree/next](https://github.com/furrium/forumlify/tree/next)。 > 如需部署 Next.js 版本,请前往 [forumlify/tree/next](https://github.com/forumlify/public/tree/next)。
--- ---
@@ -37,7 +60,7 @@ docker-compose up -d
#### 环境要求 #### 环境要求
- Node.js 18+ - Node.js 20+
- PostgreSQL 13+ - PostgreSQL 13+
#### 步骤 #### 步骤
@@ -45,7 +68,7 @@ docker-compose up -d
1. **克隆并安装依赖** 1. **克隆并安装依赖**
```bash ```bash
git clone https://github.com/furrium/forumlify.git git clone https://github.com/public/tree/next.git
cd forumlify cd forumlify
npm install npm install
``` ```
@@ -62,9 +85,11 @@ psql -U forumlify -d forumlify -f schema.sql
| 变量 | 默认值 | 说明 | | 变量 | 默认值 | 说明 |
|------|--------|------| |------|--------|------|
| `DATABASE_URL` | `postgresql://forumlify:123456@localhost:5432/forumlify` | PostgreSQL 连接串 | | `DATABASE_URL` | `postgresql://forumlify:***@localhost:5432/forumlify` | PostgreSQL 连接串 |
| `PORT` | `3000` | HTTP 监听端口 | | `PORT` | `3000` | HTTP 监听端口 |
| `JWT_SECRET` | `forumlify-secret-key-change-me-in-production` | JWT 签名密钥,**生产环境务必修改** | | `JWT_SECRET` | 本地开发使用内置值 | JWT 签名密钥;`NODE_ENV=production` 时必须显式设置 |
| `ALLOWED_ORIGINS` | 空 | 允许跨域访问的来源,多个值用逗号分隔;为空时仅支持同源访问 |
| `TRUST_PROXY` | `false` | 位于可信反向代理后时设为 `true`,用于正确识别限流 IP |
4. **启动** 4. **启动**
@@ -118,4 +143,3 @@ forumlify/
MIT MIT
+10 -2
View File
@@ -11,17 +11,25 @@ services:
- db_data:/var/lib/postgresql/data - db_data:/var/lib/postgresql/data
ports: ports:
- "5432:5432" - "5432:5432"
restart: unless-stopped
app: app:
build: . # 从 GHCR 拉取镜像(每次 push Lite 自动重建),不再本地构建
image: ghcr.io/furrium/forumlify:lite
ports: ports:
- "3003:3000" - "3000:3000"
depends_on: depends_on:
- db - db
environment: environment:
DATABASE_URL: postgresql://forumlify:123456@db:5432/forumlify DATABASE_URL: postgresql://forumlify:123456@db:5432/forumlify
PORT: 3000
ENABLE_CAPTCHA: "true"
JWT_SECRET: "${JWT_SECRET:?Set JWT_SECRET in .env before starting Forumlify}"
# 信任反向代理(Nginx / Docker 端口转发),修复限流警告
TRUST_PROXY: "true"
volumes: volumes:
- ./uploads:/app/uploads - ./uploads:/app/uploads
restart: unless-stopped
volumes: volumes:
db_data: db_data:
+2 -1
View File
@@ -446,7 +446,8 @@
<!-- ========================================================== --> <!-- ========================================================== -->
<script src="config.js"></script> <script src="config.js"></script>
<script src="js/icons.js"></script> <script src="js/icons.js"></script>
<script src="js/i18n.js"></script> <script src="js/i18n.js"></script>
<script src="js/security.js"></script>
<script src="js/api.js"></script> <script src="js/api.js"></script>
<script src="js/theme.js"></script> <script src="js/theme.js"></script>
<script src="js/captcha.js"></script> <script src="js/captcha.js"></script>
+22 -28
View File
@@ -20,11 +20,11 @@ function renderAdminReports() {
const postTitle = r.post_title || '无标题'; const postTitle = r.post_title || '无标题';
html += ` html += `
<div class="report-item"> <div class="report-item">
<div><strong>${r.reporter_name || '匿名'}</strong> 举报了帖子</div> <div><strong>${escapeHTML(r.reporter_name || '匿名')}</strong> 举报了帖子</div>
<div style="font-size:13px;color:#64748b;margin:4px 0;">原因:${r.reason}</div> <div style="font-size:13px;color:#64748b;margin:4px 0;">原因:${escapeHTML(r.reason)}</div>
<div style="font-size:13px;color:#64748b;margin:4px 0;">帖子:${postTitle} — ${(r.post_content || '').substring(0, 30)}${(r.post_content || '').length > 30 ? '...' : ''}</div> <div style="font-size:13px;color:#64748b;margin:4px 0;">帖子:${escapeHTML(postTitle)} — ${escapeHTML((r.post_content || '').substring(0, 30))}${(r.post_content || '').length > 30 ? '...' : ''}</div>
<div style="font-size:13px;font-weight:600;">状态:${statusMap[r.status] || r.status}</div> <div style="font-size:13px;font-weight:600;">状态:${statusMap[r.status] || escapeHTML(r.status)}</div>
${r.handler_name ? `<div style="font-size:12px;color:#94a3b8;">处理人:${r.handler_name}${r.handler_note ? ' (' + r.handler_note + ')' : ''}</div>` : ''} ${r.handler_name ? `<div style="font-size:12px;color:#94a3b8;">处理人:${escapeHTML(r.handler_name)}${r.handler_note ? ' (' + escapeHTML(r.handler_note) + ')' : ''}</div>` : ''}
${r.status === 'pending' ? ` ${r.status === 'pending' ? `
<div class="report-actions"> <div class="report-actions">
<button class="btn-sm btn-danger" data-reportid="${r.id}" data-action="approve"> <button class="btn-sm btn-danger" data-reportid="${r.id}" data-action="approve">
@@ -40,7 +40,7 @@ function renderAdminReports() {
</div> </div>
`; `;
}); });
container.innerHTML = html; container.innerHTML = sanitizeHTML(html);
container.querySelectorAll('[data-action]').forEach(btn => { container.querySelectorAll('[data-action]').forEach(btn => {
btn.addEventListener('click', function() { btn.addEventListener('click', function() {
const id = this.dataset.reportid; const id = this.dataset.reportid;
@@ -49,12 +49,6 @@ function renderAdminReports() {
const note = action === 'approve' ? '已删除违规帖子' : '举报不成立'; const note = action === 'approve' ? '已删除违规帖子' : '举报不成立';
if (action === 'approve' && !confirm('确定要删除该帖子并标记举报为已处理吗?')) return; if (action === 'approve' && !confirm('确定要删除该帖子并标记举报为已处理吗?')) return;
API.updateReport(id, status, note).then(() => { API.updateReport(id, status, note).then(() => {
if (action === 'approve') {
const report = reports.find(r => r.id === id);
if (report && report.post_id) {
API.deletePost(report.post_id).catch(() => {});
}
}
renderAdminReports(); renderAdminReports();
}).catch(err => alert('操作失败:' + err.message)); }).catch(err => alert('操作失败:' + err.message));
}); });
@@ -88,7 +82,7 @@ function renderAdminUsers(page = 1, search = '') {
<div style="display:flex;justify-content:space-between;align-items:center;margin-bottom:12px;flex-wrap:wrap;gap:8px;"> <div style="display:flex;justify-content:space-between;align-items:center;margin-bottom:12px;flex-wrap:wrap;gap:8px;">
<span style="font-size:13px;color:#94a3b8;">共 <strong>${pagination.total}</strong> 位用户</span> <span style="font-size:13px;color:#94a3b8;">共 <strong>${pagination.total}</strong> 位用户</span>
<div style="display:flex;gap:6px;"> <div style="display:flex;gap:6px;">
<input type="text" id="userSearchInput" placeholder="搜索用户名..." value="${search}" <input type="text" id="userSearchInput" placeholder="搜索用户名..." value="${escapeHTML(search)}"
style="padding:6px 12px;border:1px solid var(--border);border-radius:4px;font-size:13px;background:var(--bg);color:var(--text);" /> style="padding:6px 12px;border:1px solid var(--border);border-radius:4px;font-size:13px;background:var(--bg);color:var(--text);" />
<button id="userSearchBtn" class="btn-sm btn-primary" style="padding:6px 14px;">搜索</button> <button id="userSearchBtn" class="btn-sm btn-primary" style="padding:6px 14px;">搜索</button>
<button id="userClearSearchBtn" class="btn-sm btn-secondary" style="padding:6px 14px;">清空</button> <button id="userClearSearchBtn" class="btn-sm btn-secondary" style="padding:6px 14px;">清空</button>
@@ -117,9 +111,9 @@ function renderAdminUsers(page = 1, search = '') {
<tr style="border-bottom:1px solid #f1f5f9;${isCurrentUser ? 'background:var(--primary-bg);' : ''}"> <tr style="border-bottom:1px solid #f1f5f9;${isCurrentUser ? 'background:var(--primary-bg);' : ''}">
<td style="padding:10px 12px;"> <td style="padding:10px 12px;">
<div style="display:flex;align-items:center;gap:8px;"> <div style="display:flex;align-items:center;gap:8px;">
<img src="${u.avatar_url || 'https://ui-avatars.com/api/?name=' + encodeURIComponent(u.username) + '&background=6366f1&color=fff&size=64'}" <img src="${escapeHTML(safeURL(u.avatar_url || 'https://ui-avatars.com/api/?name=' + encodeURIComponent(u.username) + '&background=6366f1&color=fff&size=64', { image: true }))}"
style="width:28px;height:28px;border-radius:50%;object-fit:cover;" /> style="width:28px;height:28px;border-radius:50%;object-fit:cover;" />
<span style="font-weight:500;">${u.username}</span> <span style="font-weight:500;">${escapeHTML(u.username)}</span>
${isCurrentUser ? '<span style="font-size:11px;color:#94a3b8;background:#eef2ff;padding:1px 8px;border-radius:4px;">你</span>' : ''} ${isCurrentUser ? '<span style="font-size:11px;color:#94a3b8;background:#eef2ff;padding:1px 8px;border-radius:4px;">你</span>' : ''}
</div> </div>
</td> </td>
@@ -193,7 +187,7 @@ function renderAdminUsers(page = 1, search = '') {
`; `;
} }
container.innerHTML = html; container.innerHTML = sanitizeHTML(html);
// 绑定分页按钮事件 // 绑定分页按钮事件
container.querySelectorAll('.users-page-btn:not([disabled])').forEach(btn => { container.querySelectorAll('.users-page-btn:not([disabled])').forEach(btn => {
@@ -285,8 +279,8 @@ function renderAdminLogs(page = 1) {
html += ` html += `
<tr style="border-bottom:1px solid #f1f5f9;"> <tr style="border-bottom:1px solid #f1f5f9;">
<td style="padding:6px 0;">${new Date(l.created_at).toLocaleString('zh-CN')}</td> <td style="padding:6px 0;">${new Date(l.created_at).toLocaleString('zh-CN')}</td>
<td style="padding:6px 0;">${l.username || '系统'}</td> <td style="padding:6px 0;">${escapeHTML(l.username || '系统')}</td>
<td style="padding:6px 0;">${l.action}</td> <td style="padding:6px 0;">${escapeHTML(l.action)}</td>
</tr> </tr>
`; `;
}); });
@@ -340,7 +334,7 @@ function renderAdminLogs(page = 1) {
`; `;
} }
container.innerHTML = html; container.innerHTML = sanitizeHTML(html);
// 绑定分页按钮事件 // 绑定分页按钮事件
container.querySelectorAll('.logs-page-btn:not([disabled])').forEach(btn => { container.querySelectorAll('.logs-page-btn:not([disabled])').forEach(btn => {
@@ -383,7 +377,7 @@ function renderAdminLinks() {
links.forEach(l => { links.forEach(l => {
html += ` html += `
<div style="display:flex;justify-content:space-between;align-items:center;padding:8px 0;border-bottom:1px solid #f1f5f9;"> <div style="display:flex;justify-content:space-between;align-items:center;padding:8px 0;border-bottom:1px solid #f1f5f9;">
<span><a href="${l.url}" target="_blank" style="color:#6366f1;text-decoration:none;">${l.title}</a></span> <span><a href="${escapeHTML(safeURL(l.url, { allowRelative: false }))}" target="_blank" rel="noopener noreferrer" style="color:#6366f1;text-decoration:none;">${escapeHTML(l.title)}</a></span>
<button class="btn-sm btn-danger" data-linkid="${l.id}" style="background:rgba(239,68,68,0.08);border:1.5px solid #ef4444;color:#1a1a2e;padding:2px 10px;border-radius:6px;transition:all 0.2s;cursor:pointer;font-size:12px;font-weight:500;"> <button class="btn-sm btn-danger" data-linkid="${l.id}" style="background:rgba(239,68,68,0.08);border:1.5px solid #ef4444;color:#1a1a2e;padding:2px 10px;border-radius:6px;transition:all 0.2s;cursor:pointer;font-size:12px;font-weight:500;">
<svg xmlns="http://www.w3.org/2000/svg" width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" style="display:inline;vertical-align:middle;"><polyline points="3 6 5 6 21 6"/><path d="M19 6v14a2 2 0 0 1-2 2H7a2 2 0 0 1-2-2V6m3 0V4a2 2 0 0 1 2-2h4a2 2 0 0 1 2 2v2"/></svg> <svg xmlns="http://www.w3.org/2000/svg" width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" style="display:inline;vertical-align:middle;"><polyline points="3 6 5 6 21 6"/><path d="M19 6v14a2 2 0 0 1-2 2H7a2 2 0 0 1-2-2V6m3 0V4a2 2 0 0 1 2-2h4a2 2 0 0 1 2 2v2"/></svg>
删除 删除
@@ -391,7 +385,7 @@ function renderAdminLinks() {
</div> </div>
`; `;
}); });
ul.innerHTML = html; ul.innerHTML = sanitizeHTML(html);
ul.querySelectorAll('[data-linkid]').forEach(btn => { ul.querySelectorAll('[data-linkid]').forEach(btn => {
btn.addEventListener('click', function() { btn.addEventListener('click', function() {
if (!confirm('确定删除该链接吗?')) return; if (!confirm('确定删除该链接吗?')) return;
@@ -624,9 +618,9 @@ function loadCustomPageList() {
pages.forEach(p => { pages.forEach(p => {
html += ` html += `
<tr style="border-bottom:1px solid var(--border-light);"> <tr style="border-bottom:1px solid var(--border-light);">
<td style="padding:8px 12px;"><code style="background:var(--bg);padding:2px 6px;border-radius:4px;font-size:12px;">${p.name}</code></td> <td style="padding:8px 12px;"><code style="background:var(--bg);padding:2px 6px;border-radius:4px;font-size:12px;">${escapeHTML(p.name)}</code></td>
<td style="padding:8px 12px;">${p.title}</td> <td style="padding:8px 12px;">${escapeHTML(p.title)}</td>
<td style="padding:8px 12px;"><code style="background:var(--bg);padding:2px 6px;border-radius:4px;font-size:12px;">?custom=${p.name}</code></td> <td style="padding:8px 12px;"><code style="background:var(--bg);padding:2px 6px;border-radius:4px;font-size:12px;">?custom=${escapeHTML(p.name)}</code></td>
<td style="padding:8px 12px;"><span style="color:${p.enabled ? '#22c55e' : '#ef4444'};">${p.enabled ? `${getIcon('success')} 启用` : `${getIcon('error')} 禁用`}</span></td> <td style="padding:8px 12px;"><span style="color:${p.enabled ? '#22c55e' : '#ef4444'};">${p.enabled ? `${getIcon('success')} 启用` : `${getIcon('error')} 禁用`}</span></td>
<td style="padding:8px 12px;text-align:center;display:flex;gap:6px;justify-content:center;"> <td style="padding:8px 12px;text-align:center;display:flex;gap:6px;justify-content:center;">
<button class="btn-sm btn-secondary" data-id="${p.id}" data-action="edit">${getIcon('edit')}</button> <button class="btn-sm btn-secondary" data-id="${p.id}" data-action="edit">${getIcon('edit')}</button>
@@ -636,7 +630,7 @@ function loadCustomPageList() {
`; `;
}); });
html += '</tbody></table></div>'; html += '</tbody></table></div>';
container.innerHTML = html; container.innerHTML = sanitizeHTML(html);
container.querySelectorAll('[data-action="edit"]').forEach(btn => { container.querySelectorAll('[data-action="edit"]').forEach(btn => {
btn.addEventListener('click', function() { btn.addEventListener('click', function() {
@@ -673,13 +667,13 @@ function openCustomPageEditor(page) {
<h2 style="margin-bottom:16px;">${isEdit ? getIcon('edit') + ' 编辑页面' : getIcon('add') + ' 添加页面'}</h2> <h2 style="margin-bottom:16px;">${isEdit ? getIcon('edit') + ' 编辑页面' : getIcon('add') + ' 添加页面'}</h2>
<div style="margin-bottom:12px;"> <div style="margin-bottom:12px;">
<label style="font-weight:600;font-size:14px;display:block;margin-bottom:4px;">页面名称</label> <label style="font-weight:600;font-size:14px;display:block;margin-bottom:4px;">页面名称</label>
<input type="text" id="editorPageName" value="${isEdit ? page.name : ''}" ${isEdit ? 'readonly style="background:var(--border-light);color:var(--text-light);"' : ''} <input type="text" id="editorPageName" value="${isEdit ? escapeHTML(page.name) : ''}" ${isEdit ? 'readonly style="background:var(--border-light);color:var(--text-light);"' : ''}
placeholder="about (用于 URL: ?custom=about)" style="width:100%;padding:8px 12px;border:1px solid var(--border);border-radius:4px;font-size:14px;background:var(--bg);color:var(--text);" /> placeholder="about (用于 URL: ?custom=about)" style="width:100%;padding:8px 12px;border:1px solid var(--border);border-radius:4px;font-size:14px;background:var(--bg);color:var(--text);" />
${isEdit ? '<div style="font-size:12px;color:var(--text-light);margin-top:2px;">⚠️ 名称不可修改</div>' : '<div style="font-size:12px;color:var(--text-light);margin-top:2px;">只允许字母、数字、短横线和下划线</div>'} ${isEdit ? '<div style="font-size:12px;color:var(--text-light);margin-top:2px;">⚠️ 名称不可修改</div>' : '<div style="font-size:12px;color:var(--text-light);margin-top:2px;">只允许字母、数字、短横线和下划线</div>'}
</div> </div>
<div style="margin-bottom:12px;"> <div style="margin-bottom:12px;">
<label style="font-weight:600;font-size:14px;display:block;margin-bottom:4px;">导航栏显示名称</label> <label style="font-weight:600;font-size:14px;display:block;margin-bottom:4px;">导航栏显示名称</label>
<input type="text" id="editorPageTitle" value="${isEdit ? page.title : ''}" <input type="text" id="editorPageTitle" value="${isEdit ? escapeHTML(page.title) : ''}"
placeholder="关于我们" style="width:100%;padding:8px 12px;border:1px solid var(--border);border-radius:4px;font-size:14px;background:var(--bg);color:var(--text);" /> placeholder="关于我们" style="width:100%;padding:8px 12px;border:1px solid var(--border);border-radius:4px;font-size:14px;background:var(--bg);color:var(--text);" />
</div> </div>
<div style="margin-bottom:12px;"> <div style="margin-bottom:12px;">
@@ -691,7 +685,7 @@ function openCustomPageEditor(page) {
</div> </div>
<div style="margin-bottom:12px;"> <div style="margin-bottom:12px;">
<label style="font-weight:600;font-size:14px;display:block;margin-bottom:4px;">页面内容(HTML + CSS + JS)</label> <label style="font-weight:600;font-size:14px;display:block;margin-bottom:4px;">页面内容(HTML + CSS + JS)</label>
<textarea id="editorContent" rows="12" style="width:100%;padding:8px 12px;border:1px solid var(--border);border-radius:4px;font-size:13px;font-family:monospace;background:var(--bg);color:var(--text);resize:vertical;">${isEdit ? page.content : ''}</textarea> <textarea id="editorContent" rows="12" style="width:100%;padding:8px 12px;border:1px solid var(--border);border-radius:4px;font-size:13px;font-family:monospace;background:var(--bg);color:var(--text);resize:vertical;">${isEdit ? escapeHTML(page.content) : ''}</textarea>
<div style="font-size:12px;color:var(--text-light);margin-top:2px;">支持 HTML、CSS(&lt;style&gt;)、JS(&lt;script&gt;),内容会在独立的沙盒中渲染</div> <div style="font-size:12px;color:var(--text-light);margin-top:2px;">支持 HTML、CSS(&lt;style&gt;)、JS(&lt;script&gt;),内容会在独立的沙盒中渲染</div>
</div> </div>
<button id="editorSaveBtn" class="btn-primary" style="padding:10px 24px;width:100%;">保存</button> <button id="editorSaveBtn" class="btn-primary" style="padding:10px 24px;width:100%;">保存</button>
-8
View File
@@ -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) { /* 静默失败 */ }
},
// ============================================================ // ============================================================
// 论坛设置 // 论坛设置
+36 -30
View File
@@ -19,7 +19,7 @@ function showToast(message, type = 'success', duration = 3000) {
toast.innerHTML = ` toast.innerHTML = `
<span class="toast-icon">${icons[type] || icons.success}</span> <span class="toast-icon">${icons[type] || icons.success}</span>
${message} ${escapeHTML(message)}
`; `;
document.body.appendChild(toast); document.body.appendChild(toast);
@@ -224,25 +224,30 @@ async function renderMessageList() {
const unread = c.unread_count || 0; const unread = c.unread_count || 0;
const lastMsg = c.last_message || '暂无消息'; const lastMsg = c.last_message || '暂无消息';
const time = c.last_message_time ? new Date(c.last_message_time).toLocaleString('zh-CN') : ''; const time = c.last_message_time ? new Date(c.last_message_time).toLocaleString('zh-CN') : '';
const avatar = c.other_avatar_url || 'https://ui-avatars.com/api/?name=' + encodeURIComponent(c.other_username) + '&background=6366f1&color=fff&size=64';
html += ` html += `
<div class="message-list-item" style="display:flex;align-items:center;gap:12px;padding:12px 16px;border-bottom:1px solid var(--border);cursor:pointer;transition:background 0.15s;" <div class="message-list-item" data-conversation-id="${escapeHTML(c.id)}" data-user-id="${escapeHTML(c.other_user_id)}" data-username="${escapeHTML(c.other_username)}" style="display:flex;align-items:center;gap:12px;padding:12px 16px;border-bottom:1px solid var(--border);cursor:pointer;transition:background 0.15s;">
onclick="openChat('${c.id}', '${c.other_user_id}', '${c.other_username}')"> <img src="${escapeHTML(safeURL(avatar, { image: true }))}"
<img src="${c.other_avatar_url || 'https://ui-avatars.com/api/?name=' + encodeURIComponent(c.other_username) + '&background=6366f1&color=fff&size=64'}"
style="width:40px;height:40px;border-radius:50%;object-fit:cover;" /> style="width:40px;height:40px;border-radius:50%;object-fit:cover;" />
<div style="flex:1;min-width:0;"> <div style="flex:1;min-width:0;">
<div style="display:flex;justify-content:space-between;align-items:center;"> <div style="display:flex;justify-content:space-between;align-items:center;">
<span style="font-weight:600;">${c.other_username}</span> <span style="font-weight:600;">${escapeHTML(c.other_username)}</span>
<span style="font-size:12px;color:var(--text-light);">${time}</span> <span style="font-size:12px;color:var(--text-light);">${time}</span>
</div> </div>
<div style="display:flex;justify-content:space-between;align-items:center;"> <div style="display:flex;justify-content:space-between;align-items:center;">
<span style="font-size:13px;color:var(--text-secondary);overflow:hidden;text-overflow:ellipsis;white-space:nowrap;max-width:200px;">${lastMsg}</span> <span style="font-size:13px;color:var(--text-secondary);overflow:hidden;text-overflow:ellipsis;white-space:nowrap;max-width:200px;">${escapeHTML(lastMsg)}</span>
${unread > 0 ? `<span style="background:#ef4444;color:#fff;border-radius:50%;padding:2px 8px;font-size:11px;font-weight:600;">${unread}</span>` : ''} ${unread > 0 ? `<span style="background:#ef4444;color:#fff;border-radius:50%;padding:2px 8px;font-size:11px;font-weight:600;">${unread}</span>` : ''}
</div> </div>
</div> </div>
</div> </div>
`; `;
}); });
container.innerHTML = html; container.innerHTML = sanitizeHTML(html);
container.querySelectorAll('.message-list-item').forEach(item => {
item.addEventListener('click', function() {
openChat(this.dataset.conversationId, this.dataset.userId, this.dataset.username);
});
});
} catch (err) { } catch (err) {
container.innerHTML = '<div style="text-align:center;color:#ef4444;padding:20px 0;">加载失败</div>'; container.innerHTML = '<div style="text-align:center;color:#ef4444;padding:20px 0;">加载失败</div>';
} }
@@ -294,12 +299,13 @@ async function renderMessages(conversationId, silent = false) {
messages.forEach(m => { messages.forEach(m => {
const isMine = m.sender_id === currentUser.id; const isMine = m.sender_id === currentUser.id;
const time = m.created_at ? new Date(m.created_at).toLocaleString('zh-CN') : ''; const time = m.created_at ? new Date(m.created_at).toLocaleString('zh-CN') : '';
const avatar = m.sender_avatar_url || 'https://ui-avatars.com/api/?name=' + encodeURIComponent(m.sender_username) + '&background=6366f1&color=fff&size=64';
html += ` html += `
<div style="display:flex;${isMine ? 'justify-content:flex-end;' : 'justify-content:flex-start;'} margin-bottom:12px;"> <div style="display:flex;${isMine ? 'justify-content:flex-end;' : 'justify-content:flex-start;'} margin-bottom:12px;">
${!isMine ? `<img src="${m.sender_avatar_url || 'https://ui-avatars.com/api/?name=' + encodeURIComponent(m.sender_username) + '&background=6366f1&color=fff&size=64'}" style="width:32px;height:32px;border-radius:50%;object-fit:cover;margin-right:8px;flex-shrink:0;" />` : ''} ${!isMine ? `<img src="${escapeHTML(safeURL(avatar, { image: true }))}" style="width:32px;height:32px;border-radius:50%;object-fit:cover;margin-right:8px;flex-shrink:0;" />` : ''}
<div style="max-width:70%;"> <div style="max-width:70%;">
<div style="background:${isMine ? 'var(--primary)' : 'var(--surface)'};color:${isMine ? '#fff' : 'var(--text)'};padding:10px 14px;border-radius:12px;border:${isMine ? 'none' : '1px solid var(--border)'};word-break:break-word;"> <div style="background:${isMine ? 'var(--primary)' : 'var(--surface)'};color:${isMine ? '#fff' : 'var(--text)'};padding:10px 14px;border-radius:12px;border:${isMine ? 'none' : '1px solid var(--border)'};word-break:break-word;">
${m.content} ${renderPlainText(m.content)}
</div> </div>
<div style="font-size:11px;color:var(--text-light);margin-top:4px;${isMine ? 'text-align:right;' : ''}"> <div style="font-size:11px;color:var(--text-light);margin-top:4px;${isMine ? 'text-align:right;' : ''}">
${time} ${isMine ? (m.is_read ? '✓✓' : '✓') : ''} ${time} ${isMine ? (m.is_read ? '✓✓' : '✓') : ''}
@@ -308,7 +314,7 @@ async function renderMessages(conversationId, silent = false) {
</div> </div>
`; `;
}); });
container.innerHTML = html; container.innerHTML = sanitizeHTML(html);
container.scrollTop = container.scrollHeight; container.scrollTop = container.scrollHeight;
} catch (err) { } catch (err) {
if (!silent) { if (!silent) {
@@ -452,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 allow-same-origin'; iframe.sandbox = 'allow-scripts allow-modals allow-top-navigation allow-same-origin allow-popups';
iframe.srcdoc = ` iframe.srcdoc = `
<!DOCTYPE html> <!DOCTYPE html>
<html> <html>
@@ -483,7 +489,7 @@ function showCustomPage(pageName) {
el.style.color = el.dataset.custom === pageName ? 'var(--primary)' : 'var(--text-secondary)'; el.style.color = el.dataset.custom === pageName ? 'var(--primary)' : 'var(--text-secondary)';
}); });
}).catch(err => { }).catch(err => {
container.innerHTML = '<div style="text-align:center;color:#ef4444;padding:40px 0;">页面加载失败:' + err.message + '</div>'; container.innerHTML = '<div style="text-align:center;color:#ef4444;padding:40px 0;">页面加载失败:' + escapeHTML(err.message) + '</div>';
}); });
} }
@@ -527,15 +533,15 @@ async function renderMessagesPage() {
<div style="display:flex;align-items:flex-start;gap:12px;padding:14px 16px;border-bottom:1px solid var(--border-light);background:var(--surface);border-radius:6px;margin-bottom:6px;"> <div style="display:flex;align-items:flex-start;gap:12px;padding:14px 16px;border-bottom:1px solid var(--border-light);background:var(--surface);border-radius:6px;margin-bottom:6px;">
<span style="font-size:20px;display:inline-flex;align-items:center;">${icon}</span> <span style="font-size:20px;display:inline-flex;align-items:center;">${icon}</span>
<div style="flex:1;min-width:0;"> <div style="flex:1;min-width:0;">
<div style="font-weight:600;font-size:14px;">${n.title}</div> <div style="font-weight:600;font-size:14px;">${escapeHTML(n.title)}</div>
<div style="color:var(--text-secondary);font-size:13px;margin-top:2px;">${n.content}</div> <div style="color:var(--text-secondary);font-size:13px;margin-top:2px;">${escapeHTML(n.content)}</div>
${n.link ? `<a href="${n.link}" style="color:var(--primary);font-size:13px;text-decoration:none;margin-top:4px;display:inline-block;">查看详情 →</a>` : ''} ${n.link ? `<a href="${escapeHTML(safeURL(n.link))}" style="color:var(--primary);font-size:13px;text-decoration:none;margin-top:4px;display:inline-block;">查看详情 →</a>` : ''}
<div style="font-size:12px;color:var(--text-light);margin-top:4px;">${time}</div> <div style="font-size:12px;color:var(--text-light);margin-top:4px;">${time}</div>
</div> </div>
</div> </div>
`; `;
}); });
container.innerHTML = html; container.innerHTML = sanitizeHTML(html);
} catch (err) { } catch (err) {
container.innerHTML = '<div style="text-align:center;color:#ef4444;padding:20px 0;">加载失败</div>'; container.innerHTML = '<div style="text-align:center;color:#ef4444;padding:20px 0;">加载失败</div>';
} }
@@ -579,9 +585,9 @@ function renderLinks() {
} else { } else {
let html = ''; let html = '';
links.forEach(l => { links.forEach(l => {
html += '<li><a href="' + l.url + '" target="_blank">' + l.title + '</a></li>'; html += '<li><a href="' + escapeHTML(safeURL(l.url, { allowRelative: false })) + '" target="_blank" rel="noopener noreferrer">' + escapeHTML(l.title) + '</a></li>';
}); });
ul.innerHTML = html; ul.innerHTML = sanitizeHTML(html);
} }
} }
@@ -593,9 +599,9 @@ function renderLinks() {
} else { } else {
let html = ''; let html = '';
links.forEach(l => { links.forEach(l => {
html += '<li><a href="' + l.url + '" target="_blank">' + l.title + '</a></li>'; html += '<li><a href="' + escapeHTML(safeURL(l.url, { allowRelative: false })) + '" target="_blank" rel="noopener noreferrer">' + escapeHTML(l.title) + '</a></li>';
}); });
ul2.innerHTML = html; ul2.innerHTML = sanitizeHTML(html);
} }
} }
}).catch(() => {}); }).catch(() => {});
@@ -640,15 +646,15 @@ async function renderSettingsPage(tab = 'profile') {
<!-- 头像 --> <!-- 头像 -->
<div style="text-align:center;margin-bottom:24px;"> <div style="text-align:center;margin-bottom:24px;">
<div style="position:relative;display:inline-block;"> <div style="position:relative;display:inline-block;">
<img id="avatarPreview" src="${user.avatar_url || 'https://ui-avatars.com/api/?name=' + encodeURIComponent(user.username) + '&background=6366f1&color=fff&size=128'}" <img id="avatarPreview" src="${escapeHTML(safeURL(user.avatar_url || 'https://ui-avatars.com/api/?name=' + encodeURIComponent(user.username) + '&background=6366f1&color=fff&size=128', { image: true }))}"
style="width:100px;height:100px;border-radius:50%;object-fit:cover;border:3px solid var(--primary);" /> style="width:100px;height:100px;border-radius:50%;object-fit:cover;border:3px solid var(--primary);" />
<button id="avatarUploadBtn" style="position:absolute;bottom:0;right:0;background:var(--primary);color:#fff;border:none;border-radius:50%;width:32px;height:32px;cursor:pointer;font-size:16px;display:flex;align-items:center;justify-content:center;box-shadow:0 2px 8px rgba(99,102,241,0.4);"> <button id="avatarUploadBtn" style="position:absolute;bottom:0;right:0;background:var(--primary);color:#fff;border:none;border-radius:50%;width:32px;height:32px;cursor:pointer;font-size:16px;display:flex;align-items:center;justify-content:center;box-shadow:0 2px 8px rgba(99,102,241,0.4);">
${getIcon('camera')} ${getIcon('camera')}
</button> </button>
</div> </div>
<input type="file" id="avatarFileInput" accept="image/*" style="display:none;" /> <input type="file" id="avatarFileInput" accept="image/*" style="display:none;" />
<h2 style="margin:12px 0 4px;">${user.username}</h2> <h2 style="margin:12px 0 4px;">${escapeHTML(user.username)}</h2>
<p style="color:var(--text-secondary);font-size:14px;">${user.bio || '这个人很懒,什么都没写'}</p> <p style="color:var(--text-secondary);font-size:14px;">${escapeHTML(user.bio || '这个人很懒,什么都没写')}</p>
<div style="display:flex;justify-content:center;gap:16px;margin-top:8px;font-size:13px;color:var(--text-secondary);flex-wrap:wrap;"> <div style="display:flex;justify-content:center;gap:16px;margin-top:8px;font-size:13px;color:var(--text-secondary);flex-wrap:wrap;">
<span>${getIcon('calendar')} 加入 ${user.created_at ? new Date(user.created_at).toLocaleDateString('zh-CN') : '未知'}</span> <span>${getIcon('calendar')} 加入 ${user.created_at ? new Date(user.created_at).toLocaleDateString('zh-CN') : '未知'}</span>
<span>${getIcon('file')} ${postCount} 帖</span> <span>${getIcon('file')} ${postCount} 帖</span>
@@ -661,15 +667,15 @@ async function renderSettingsPage(tab = 'profile') {
<div style="background:var(--surface);border:1px solid var(--border);border-radius:8px;padding:20px;"> <div style="background:var(--surface);border:1px solid var(--border);border-radius:8px;padding:20px;">
<div style="margin-bottom:16px;"> <div style="margin-bottom:16px;">
<label style="font-weight:600;font-size:14px;display:block;margin-bottom:4px;">用户名</label> <label style="font-weight:600;font-size:14px;display:block;margin-bottom:4px;">用户名</label>
<input type="text" id="settingsUsername" value="${user.username}" style="width:100%;padding:8px 12px;border:1px solid var(--border);border-radius:4px;font-size:14px;background:var(--bg);color:var(--text);" /> <input type="text" id="settingsUsername" value="${escapeHTML(user.username)}" style="width:100%;padding:8px 12px;border:1px solid var(--border);border-radius:4px;font-size:14px;background:var(--bg);color:var(--text);" />
</div> </div>
<div style="margin-bottom:16px;"> <div style="margin-bottom:16px;">
<label style="font-weight:600;font-size:14px;display:block;margin-bottom:4px;">个人简介</label> <label style="font-weight:600;font-size:14px;display:block;margin-bottom:4px;">个人简介</label>
<textarea id="settingsBio" rows="3" style="width:100%;padding:8px 12px;border:1px solid var(--border);border-radius:4px;font-size:14px;background:var(--bg);color:var(--text);resize:vertical;">${user.bio || ''}</textarea> <textarea id="settingsBio" rows="3" style="width:100%;padding:8px 12px;border:1px solid var(--border);border-radius:4px;font-size:14px;background:var(--bg);color:var(--text);resize:vertical;">${escapeHTML(user.bio || '')}</textarea>
</div> </div>
<div style="margin-bottom:16px;"> <div style="margin-bottom:16px;">
<label style="font-weight:600;font-size:14px;display:block;margin-bottom:4px;">帖子签名</label> <label style="font-weight:600;font-size:14px;display:block;margin-bottom:4px;">帖子签名</label>
<textarea id="settingsSignature" rows="2" placeholder="显示在每篇帖子底部,支持 Markdown" style="width:100%;padding:8px 12px;border:1px solid var(--border);border-radius:4px;font-size:13px;background:var(--bg);color:var(--text);resize:vertical;font-family:inherit;">${user.signature || ''}</textarea> <textarea id="settingsSignature" rows="2" placeholder="显示在每篇帖子底部,支持 Markdown" style="width:100%;padding:8px 12px;border:1px solid var(--border);border-radius:4px;font-size:13px;background:var(--bg);color:var(--text);resize:vertical;font-family:inherit;">${escapeHTML(user.signature || '')}</textarea>
<div style="font-size:12px;color:var(--text-light);margin-top:2px;">用 --- 分隔,支持 Markdown</div> <div style="font-size:12px;color:var(--text-light);margin-top:2px;">用 --- 分隔,支持 Markdown</div>
</div> </div>
<button id="settingsSaveBtn" class="btn-primary" style="width:100%;padding:10px;">保存设置</button> <button id="settingsSaveBtn" class="btn-primary" style="width:100%;padding:10px;">保存设置</button>
@@ -916,8 +922,8 @@ function openEditModal(postId, currentTitle, currentContent) {
<div class="modal-content" style="max-width:600px;"> <div class="modal-content" style="max-width:600px;">
<span class="close" style="position:absolute;top:12px;right:16px;font-size:24px;cursor:pointer;color:var(--text-light);">&times;</span> <span class="close" style="position:absolute;top:12px;right:16px;font-size:24px;cursor:pointer;color:var(--text-light);">&times;</span>
<h2 style="margin-bottom:16px;">${getIcon('edit')} 编辑帖子</h2> <h2 style="margin-bottom:16px;">${getIcon('edit')} 编辑帖子</h2>
<input type="text" id="editPostTitle" value="${currentTitle || ''}" placeholder="标题" style="width:100%;padding:10px 14px;border:1.5px solid var(--border);border-radius:6px;font-size:15px;font-weight:600;margin-bottom:12px;font-family:inherit;background:var(--bg);color:var(--text);" /> <input type="text" id="editPostTitle" value="${escapeHTML(currentTitle || '')}" placeholder="标题" style="width:100%;padding:10px 14px;border:1.5px solid var(--border);border-radius:6px;font-size:15px;font-weight:600;margin-bottom:12px;font-family:inherit;background:var(--bg);color:var(--text);" />
<textarea id="editPostContent" rows="6" style="width:100%;padding:12px;border:1.5px solid var(--border);border-radius:6px;font-size:15px;font-family:inherit;resize:vertical;background:var(--bg);color:var(--text);">${currentContent || ''}</textarea> <textarea id="editPostContent" rows="6" style="width:100%;padding:12px;border:1.5px solid var(--border);border-radius:6px;font-size:15px;font-family:inherit;resize:vertical;background:var(--bg);color:var(--text);">${escapeHTML(currentContent || '')}</textarea>
<button id="editPostSaveBtn" class="btn-primary" style="padding:10px 24px;margin-top:12px;width:100%;">保存修改</button> <button id="editPostSaveBtn" class="btn-primary" style="padding:10px 24px;margin-top:12px;width:100%;">保存修改</button>
</div> </div>
`; `;
@@ -1085,7 +1091,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');
@@ -1236,7 +1242,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();
+34 -44
View File
@@ -1,15 +1,3 @@
// ============================================================
// AUTH 对象(供其他模块使用)
// ============================================================
const AUTH = {
async getUserProfile(userId) {
const data = await apiFetch('/users/' + userId);
if (data.error) throw new Error(data.error);
return data;
}
};
// ============================================================ // ============================================================
// 🔐 认证 // 🔐 认证
// ============================================================ // ============================================================
@@ -30,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');
@@ -60,39 +47,42 @@ document.getElementById('registerSubmit').addEventListener('click', async () =>
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 {
const result = await API.register(email, password, username); await API.register(email, password, username);
document.getElementById('registerModal').classList.remove('active');
document.getElementById('regUsername').value = '';
document.getElementById('regEmail').value = '';
document.getElementById('regPassword').value = '';
document.getElementById('regCaptchaInput').value = '';
alert('注册成功!请登录');
// 生成恢复码
try {
const recoveryData = await API.generateRecoveryCodes();
if (recoveryData.codes) {
showRecoveryCodesModal(recoveryData.codes);
}
} catch (e) {
console.warn('恢复码生成失败:', e);
}
const loginResult = await API.login(email, password);
if (loginResult.user) {
const profile = await AUTH.getUserProfile(loginResult.user.id);
currentUser = { ...loginResult.user, ...profile };
API.logEvent('register').catch(() => {});
renderNav();
if (currentPage === 'admin' && currentUser.role !== 'admin') {
switchPage('feed');
} else if (currentPage === 'feed') {
renderFeed();
renderStats();
}
}
} catch (err) { } catch (err) {
alert('注册失败:' + err.message); alert('注册失败:' + err.message);
return;
}
document.getElementById('registerModal').classList.remove('active');
document.getElementById('regUsername').value = '';
document.getElementById('regEmail').value = '';
document.getElementById('regPassword').value = '';
document.getElementById('regCaptchaInput').value = '';
try {
await API.login(email, password);
currentUser = await API.getMe();
renderNav();
if (currentPage === 'admin' && currentUser.role !== 'admin') {
switchPage('feed');
} else if (currentPage === 'feed') {
renderFeed();
renderStats();
}
} catch (err) {
alert('注册成功,但自动登录失败,请手动登录:' + err.message);
return;
}
try {
const recoveryData = await API.generateRecoveryCodes();
if (recoveryData.codes?.length) {
showRecoveryCodesModal(recoveryData.codes);
}
} catch (err) {
console.warn('恢复码生成失败:', err);
alert('注册并登录成功,但恢复码生成失败。请稍后在设置中重新生成。');
} }
}); });
+24 -10
View File
@@ -38,18 +38,18 @@ function renderFeed() {
if (p.images && p.images.length > 0) { if (p.images && p.images.length > 0) {
imagesHtml = '<div class="post-images">'; imagesHtml = '<div class="post-images">';
p.images.forEach(img => { p.images.forEach(img => {
imagesHtml += '<img src="' + img + '" class="post-image" onclick="openImageViewer(this.src)" style="cursor:pointer;" />'; imagesHtml += '<img src="' + escapeHTML(safeURL(img, { image: true })) + '" class="post-image" style="cursor:pointer;" />';
}); });
imagesHtml += '</div>'; imagesHtml += '</div>';
} }
const replyCount = p.reply_count || 0; const replyCount = p.reply_count || 0;
const renderedContent = marked ? marked.parse(p.content || '') : (p.content || '').replace(/\n/g, '<br>'); const renderedContent = renderMarkdown(p.content || '');
// 签名渲染 // 签名渲染
let signatureHtml = ''; let signatureHtml = '';
if (p.signature) { if (p.signature) {
const sigContent = marked ? marked.parse(p.signature) : p.signature; const sigContent = renderMarkdown(p.signature);
signatureHtml = ` signatureHtml = `
<div style="margin-top:10px;padding-top:8px;border-top:1px solid var(--border-light);font-size:12px;color:var(--text-secondary);"> <div style="margin-top:10px;padding-top:8px;border-top:1px solid var(--border-light);font-size:12px;color:var(--text-secondary);">
${sigContent} ${sigContent}
@@ -61,12 +61,12 @@ function renderFeed() {
<div class="post-card" data-postid="${p.id}" style="cursor:pointer;"> <div class="post-card" data-postid="${p.id}" style="cursor:pointer;">
${p.is_pinned ? '<div style="font-size:12px;color:var(--primary);font-weight:600;margin-bottom:4px;">📌 置顶</div>' : ''} ${p.is_pinned ? '<div style="font-size:12px;color:var(--primary);font-weight:600;margin-bottom:4px;">📌 置顶</div>' : ''}
<div class="post-header"> <div class="post-header">
<img src="${avatar}" class="post-avatar" /> <img src="${escapeHTML(safeURL(avatar, { image: true }))}" class="post-avatar" />
<span class="post-username" style="cursor:pointer;color:var(--primary);" onclick="event.stopPropagation();switchPage('user','${username}')">${username}</span> <span class="post-username" data-username="${escapeHTML(username)}" style="cursor:pointer;color:var(--primary);">${escapeHTML(username)}</span>
<span class="post-time">${time}</span> <span class="post-time">${time}</span>
${p.edited_at ? '<span style="font-size:11px;color:var(--text-light);margin-left:6px;">(已编辑)</span>' : ''} ${p.edited_at ? '<span style="font-size:11px;color:var(--text-light);margin-left:6px;">(已编辑)</span>' : ''}
</div> </div>
<div class="post-title">${p.title || '无标题'}</div> <div class="post-title">${escapeHTML(p.title || '无标题')}</div>
<div class="post-content">${renderedContent}</div> <div class="post-content">${renderedContent}</div>
${imagesHtml} ${imagesHtml}
<div class="post-actions"> <div class="post-actions">
@@ -87,7 +87,7 @@ function renderFeed() {
</div> </div>
`; `;
}); });
container.innerHTML = html; container.innerHTML = sanitizeHTML(html);
// 分页控件 // 分页控件
if (totalPages > 1) { if (totalPages > 1) {
@@ -167,6 +167,20 @@ function renderFeed() {
}); });
}); });
container.querySelectorAll('.post-username').forEach(username => {
username.addEventListener('click', function(e) {
e.stopPropagation();
switchPage('user', this.dataset.username);
});
});
container.querySelectorAll('.post-image').forEach(image => {
image.addEventListener('click', function(e) {
e.stopPropagation();
openImageViewer(this.src);
});
});
container.querySelectorAll('.action-report').forEach(btn => { container.querySelectorAll('.action-report').forEach(btn => {
btn.addEventListener('click', function(e) { btn.addEventListener('click', function(e) {
e.stopPropagation(); e.stopPropagation();
@@ -187,7 +201,7 @@ function renderFeed() {
}); });
}); });
}).catch(err => { }).catch(err => {
container.innerHTML = '<div style="text-align:center;color:#ef4444;padding:40px 0;">加载失败:' + err.message + container.innerHTML = '<div style="text-align:center;color:#ef4444;padding:40px 0;">加载失败:' + escapeHTML(err.message) +
'</div>'; '</div>';
}); });
} }
@@ -210,9 +224,9 @@ function renderLinks() {
} }
let html = ''; let html = '';
links.forEach(l => { links.forEach(l => {
html += '<li><a href="' + l.url + '" target="_blank">' + l.title + '</a></li>'; html += '<li><a href="' + escapeHTML(safeURL(l.url, { allowRelative: false })) + '" target="_blank" rel="noopener noreferrer">' + escapeHTML(l.title) + '</a></li>';
}); });
ul.innerHTML = html; ul.innerHTML = sanitizeHTML(html);
}).catch(() => {}); }).catch(() => {});
} }
+24 -21
View File
@@ -49,26 +49,17 @@ async function renderPostDetail(postId) {
if (post.images && post.images.length > 0) { if (post.images && post.images.length > 0) {
imagesHtml = '<div class="post-images">'; imagesHtml = '<div class="post-images">';
post.images.forEach(img => { post.images.forEach(img => {
imagesHtml += '<img src="' + img + '" class="post-image" onclick="openImageViewer(this.src)" style="cursor:pointer;" />'; imagesHtml += '<img src="' + escapeHTML(safeURL(img, { image: true })) + '" class="post-image" style="cursor:pointer;" />';
}); });
imagesHtml += '</div>'; imagesHtml += '</div>';
} }
let renderedContent = post.content || ''; const renderedContent = renderMarkdown(post.content || '');
try {
if (typeof marked !== 'undefined' && marked.parse) {
renderedContent = marked.parse(renderedContent);
} else {
renderedContent = renderedContent.replace(/\n/g, '<br>');
}
} catch (e) {
renderedContent = renderedContent.replace(/\n/g, '<br>');
}
// 签名渲染 // 签名渲染
let signatureHtml = ''; let signatureHtml = '';
if (post.signature) { if (post.signature) {
const sigContent = marked ? marked.parse(post.signature) : post.signature; const sigContent = renderMarkdown(post.signature);
signatureHtml = ` signatureHtml = `
<div style="margin-top:16px;padding-top:12px;border-top:1px solid var(--border-light);font-size:12px;color:var(--text-secondary);"> <div style="margin-top:16px;padding-top:12px;border-top:1px solid var(--border-light);font-size:12px;color:var(--text-secondary);">
${sigContent} ${sigContent}
@@ -79,8 +70,8 @@ async function renderPostDetail(postId) {
let html = ` let html = `
<div class="post-detail-card"> <div class="post-detail-card">
<div class="post-header"> <div class="post-header">
<img src="${avatar}" class="post-avatar" /> <img src="${escapeHTML(safeURL(avatar, { image: true }))}" class="post-avatar" />
<span class="post-username" style="cursor:pointer;color:var(--primary);" onclick="switchPage('user','${username}')">${username}</span> <span class="post-username" data-username="${escapeHTML(username)}" style="cursor:pointer;color:var(--primary);">${escapeHTML(username)}</span>
<span class="post-time">${time}</span> <span class="post-time">${time}</span>
${post.edited_at ? `<span style="font-size:12px;color:var(--text-light);margin-left:8px;">(已编辑 ${new Date(post.edited_at).toLocaleString('zh-CN')})</span>` : ''} ${post.edited_at ? `<span style="font-size:12px;color:var(--text-light);margin-left:8px;">(已编辑 ${new Date(post.edited_at).toLocaleString('zh-CN')})</span>` : ''}
${post.is_pinned ? '<span style="font-size:12px;color:var(--primary);margin-left:8px;">📌 置顶</span>' : ''} ${post.is_pinned ? '<span style="font-size:12px;color:var(--primary);margin-left:8px;">📌 置顶</span>' : ''}
@@ -120,28 +111,40 @@ async function renderPostDetail(postId) {
html += ` html += `
<div class="reply-item" data-replyid="${r.id}"> <div class="reply-item" data-replyid="${r.id}">
<div class="reply-header"> <div class="reply-header">
<img src="${rAvatar}" class="reply-avatar" /> <img src="${escapeHTML(safeURL(rAvatar, { image: true }))}" class="reply-avatar" />
<span class="reply-username" style="cursor:pointer;color:var(--primary);" onclick="switchPage('user','${rUsername}')">${rUsername}</span> <span class="reply-username" data-username="${escapeHTML(rUsername)}" style="cursor:pointer;color:var(--primary);">${escapeHTML(rUsername)}</span>
<span class="reply-time">${rTime}</span> <span class="reply-time">${rTime}</span>
${currentUser && currentUser.id === r.user_id ? `<button class="btn-sm btn-danger reply-delete-btn" data-replyid="${r.id}"> ${currentUser && (currentUser.id === r.user_id || currentUser.role === 'admin') ? `<button class="btn-sm btn-danger reply-delete-btn" data-replyid="${r.id}">
<svg xmlns="http://www.w3.org/2000/svg" width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" style="display:inline;vertical-align:middle;"><polyline points="3 6 5 6 21 6"/><path d="M19 6v14a2 2 0 0 1-2 2H7a2 2 0 0 1-2-2V6m3 0V4a2 2 0 0 1 2-2h4a2 2 0 0 1 2 2v2"/></svg> <svg xmlns="http://www.w3.org/2000/svg" width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" style="display:inline;vertical-align:middle;"><polyline points="3 6 5 6 21 6"/><path d="M19 6v14a2 2 0 0 1-2 2H7a2 2 0 0 1-2-2V6m3 0V4a2 2 0 0 1 2-2h4a2 2 0 0 1 2 2v2"/></svg>
删除 删除
</button>` : ''} </button>` : ''}
</div> </div>
<div class="reply-content">${(r.content || '').replace(/\n/g, '<br>')}</div> <div class="reply-content">${renderPlainText(r.content || '')}</div>
</div> </div>
`; `;
}); });
} }
html += '</div>'; html += '</div>';
container.innerHTML = html; container.innerHTML = sanitizeHTML(html);
replyArea.style.display = 'block'; replyArea.style.display = 'block';
document.getElementById('replyContent').value = ''; document.getElementById('replyContent').value = '';
document.getElementById('replyCaptchaInput').value = ''; document.getElementById('replyCaptchaInput').value = '';
refreshCaptcha('reply'); refreshCaptcha('reply');
container.querySelectorAll('.post-username, .reply-username').forEach(usernameEl => {
usernameEl.addEventListener('click', function() {
switchPage('user', this.dataset.username);
});
});
container.querySelectorAll('.post-image').forEach(image => {
image.addEventListener('click', function() {
openImageViewer(this.src);
});
});
// 置顶按钮 // 置顶按钮
const pinBtn = document.getElementById('pinPostBtn'); const pinBtn = document.getElementById('pinPostBtn');
if (pinBtn) { if (pinBtn) {
@@ -210,7 +213,7 @@ async function renderPostDetail(postId) {
currentPostId = postId; currentPostId = postId;
} catch (err) { } catch (err) {
container.innerHTML = '<div style="text-align:center;color:#ef4444;padding:40px 0;">加载失败:' + err.message + container.innerHTML = '<div style="text-align:center;color:#ef4444;padding:40px 0;">加载失败:' + escapeHTML(err.message) +
'</div>'; '</div>';
replyArea.style.display = 'none'; replyArea.style.display = 'none';
} }
@@ -225,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();
+77
View File
@@ -0,0 +1,77 @@
// ============================================================
// Safe rendering helpers
// ============================================================
function escapeHTML(value) {
return String(value ?? '')
.replace(/&/g, '&amp;')
.replace(/</g, '&lt;')
.replace(/>/g, '&gt;')
.replace(/"/g, '&quot;')
.replace(/'/g, '&#39;');
}
function safeURL(value, { allowRelative = true, image = false } = {}) {
if (!value) return image ? '' : '#';
try {
const raw = String(value).trim();
const parsed = new URL(raw, window.location.origin);
const isRelative = parsed.origin === window.location.origin && !/^[a-z][a-z0-9+.-]*:/i.test(raw);
const allowedProtocol = parsed.protocol === 'http:' || parsed.protocol === 'https:';
if (!allowedProtocol || (!allowRelative && isRelative)) return image ? '' : '#';
return isRelative ? parsed.pathname + parsed.search + parsed.hash : parsed.href;
} catch (error) {
return image ? '' : '#';
}
}
function sanitizeHTML(html) {
const template = document.createElement('template');
template.innerHTML = String(html ?? '');
// Application templates contain legitimate controls. Raw user HTML is escaped
// before Markdown parsing, while this pass removes executable/embed elements.
const forbidden = 'script,iframe,object,embed,link,meta,base,style';
template.content.querySelectorAll(forbidden).forEach(node => node.remove());
template.content.querySelectorAll('*').forEach(node => {
for (const attribute of Array.from(node.attributes)) {
const name = attribute.name.toLowerCase();
if (name.startsWith('on') || name === 'srcdoc') {
node.removeAttribute(attribute.name);
}
}
if (node.hasAttribute('href')) {
const href = safeURL(node.getAttribute('href'));
if (href === '#') node.removeAttribute('href');
else node.setAttribute('href', href);
}
if (node.hasAttribute('src')) {
const src = safeURL(node.getAttribute('src'), { image: true });
if (!src) node.removeAttribute('src');
else node.setAttribute('src', src);
}
if (node.tagName === 'A' && node.getAttribute('target') === '_blank') {
node.setAttribute('rel', 'noopener noreferrer');
}
});
return template.innerHTML;
}
function renderMarkdown(value) {
const escaped = escapeHTML(value);
if (typeof marked !== 'undefined' && marked.parse) {
return sanitizeHTML(marked.parse(escaped));
}
return escaped.replace(/\r?\n/g, '<br>');
}
function renderPlainText(value) {
return escapeHTML(value).replace(/\r?\n/g, '<br>');
}
+14 -8
View File
@@ -24,9 +24,9 @@ async function renderUserProfile(username) {
let html = ` let html = `
<div style="background:var(--surface);border:1px solid var(--border);border-radius:8px;padding:32px;text-align:center;"> <div style="background:var(--surface);border:1px solid var(--border);border-radius:8px;padding:32px;text-align:center;">
<img src="${avatar}" style="width:96px;height:96px;border-radius:50%;object-fit:cover;border:3px solid var(--primary);" /> <img src="${escapeHTML(safeURL(avatar, { image: true }))}" style="width:96px;height:96px;border-radius:50%;object-fit:cover;border:3px solid var(--primary);" />
<h2 style="margin:16px 0 4px;font-size:24px;">${user.username}</h2> <h2 style="margin:16px 0 4px;font-size:24px;">${escapeHTML(user.username)}</h2>
<p style="color:var(--text-secondary);font-size:14px;">${user.bio || '这个人很懒,什么都没写'}</p> <p style="color:var(--text-secondary);font-size:14px;">${escapeHTML(user.bio || '这个人很懒,什么都没写')}</p>
<div style="display:flex;justify-content:center;gap:32px;margin-top:16px;font-size:14px;color:var(--text-secondary);flex-wrap:wrap;"> <div style="display:flex;justify-content:center;gap:32px;margin-top:16px;font-size:14px;color:var(--text-secondary);flex-wrap:wrap;">
<span>📅 加入于 ${user.created_at ? new Date(user.created_at).toLocaleDateString('zh-CN') : '未知'}</span> <span>📅 加入于 ${user.created_at ? new Date(user.created_at).toLocaleDateString('zh-CN') : '未知'}</span>
<span>📝 发了 ${posts.length} 个帖子</span> <span>📝 发了 ${posts.length} 个帖子</span>
@@ -48,16 +48,22 @@ async function renderUserProfile(username) {
posts.forEach(p => { posts.forEach(p => {
const time = p.created_at ? new Date(p.created_at).toLocaleString('zh-CN') : ''; const time = p.created_at ? new Date(p.created_at).toLocaleString('zh-CN') : '';
html += ` html += `
<div class="post-card" style="cursor:pointer;" onclick="switchToPost('${p.id}')"> <div class="post-card" data-postid="${escapeHTML(p.id)}" style="cursor:pointer;">
<div class="post-title" style="font-size:16px;font-weight:600;">${p.title || '无标题'}</div> <div class="post-title" style="font-size:16px;font-weight:600;">${escapeHTML(p.title || '无标题')}</div>
<div class="post-content" style="font-size:14px;color:var(--text-secondary);">${(p.content || '').substring(0, 100)}${(p.content || '').length > 100 ? '...' : ''}</div> <div class="post-content" style="font-size:14px;color:var(--text-secondary);">${escapeHTML((p.content || '').substring(0, 100))}${(p.content || '').length > 100 ? '...' : ''}</div>
<div style="font-size:12px;color:var(--text-light);margin-top:8px;">${time}</div> <div style="font-size:12px;color:var(--text-light);margin-top:8px;">${time}</div>
</div> </div>
`; `;
}); });
} }
container.innerHTML = html; container.innerHTML = sanitizeHTML(html);
container.querySelectorAll('.post-card[data-postid]').forEach(card => {
card.addEventListener('click', function() {
switchToPost(this.dataset.postid);
});
});
const dmBtn = document.getElementById('dmBtn'); const dmBtn = document.getElementById('dmBtn');
if (dmBtn) { if (dmBtn) {
@@ -67,7 +73,7 @@ async function renderUserProfile(username) {
} }
} catch (err) { } catch (err) {
container.innerHTML = '<div style="text-align:center;color:#ef4444;padding:40px 0;">加载失败:' + err.message + '</div>'; container.innerHTML = '<div style="text-align:center;color:#ef4444;padding:40px 0;">加载失败:' + escapeHTML(err.message) + '</div>';
} }
} }
+315 -618
View File
File diff suppressed because it is too large. Load diff
+14 -4
View File
@@ -3,16 +3,26 @@
"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",
"check": "node scripts/check-syntax.js",
"test": "node --test"
}, },
"dependencies": { "dependencies": {
"bcrypt": "^5.1.1", "bcryptjs": "3.0.3",
"cors": "^2.8.5", "cors": "^2.8.5",
"express": "^4.18.2", "express": "^4.18.2",
"express-rate-limit": "8.6.2",
"helmet": "8.1.0",
"jsonwebtoken": "^9.0.2", "jsonwebtoken": "^9.0.2",
"multer": "^1.4.5-lts.1", "multer": "2.2.0",
"pg": "^8.11.3" "pg": "^8.11.3"
},
"devDependencies": {
"supertest": "7.2.2"
} }
} }
+37 -1
View File
@@ -45,7 +45,7 @@ CREATE TABLE IF NOT EXISTS friendly_links (
-- 举报表 -- 举报表
CREATE TABLE IF NOT EXISTS reports ( CREATE TABLE IF NOT EXISTS reports (
id UUID PRIMARY KEY DEFAULT gen_random_uuid(), id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
post_id UUID NOT NULL REFERENCES posts(id) ON DELETE CASCADE, post_id UUID REFERENCES posts(id) ON DELETE SET NULL,
reporter_id UUID NOT NULL REFERENCES users(id) ON DELETE CASCADE, reporter_id UUID NOT NULL REFERENCES users(id) ON DELETE CASCADE,
reason VARCHAR(100) NOT NULL, reason VARCHAR(100) NOT NULL,
status VARCHAR(20) DEFAULT 'pending' CHECK (status IN ('pending', 'approved', 'rejected')), status VARCHAR(20) DEFAULT 'pending' CHECK (status IN ('pending', 'approved', 'rejected')),
@@ -55,15 +55,51 @@ CREATE TABLE IF NOT EXISTS reports (
handler_note TEXT handler_note TEXT
); );
-- Preserve moderation history when a reported post is deleted. This also
-- upgrades databases created with the previous ON DELETE CASCADE constraint.
DO $$
DECLARE
constraint_name TEXT;
BEGIN
SELECT con.conname INTO constraint_name
FROM pg_constraint con
JOIN pg_class rel ON rel.oid = con.conrelid
JOIN pg_attribute attr ON attr.attrelid = rel.oid AND attr.attnum = ANY(con.conkey)
WHERE rel.relname = 'reports'
AND con.contype = 'f'
AND attr.attname = 'post_id'
LIMIT 1;
IF constraint_name IS NOT NULL THEN
EXECUTE format('ALTER TABLE reports DROP CONSTRAINT %I', constraint_name);
END IF;
ALTER TABLE reports ALTER COLUMN post_id DROP NOT NULL;
ALTER TABLE reports
ADD CONSTRAINT reports_post_id_fkey
FOREIGN KEY (post_id) REFERENCES posts(id) ON DELETE SET NULL;
END $$;
-- 事件日志表 -- 事件日志表
CREATE TABLE IF NOT EXISTS event_logs ( CREATE TABLE IF NOT EXISTS event_logs (
id UUID PRIMARY KEY DEFAULT gen_random_uuid(), id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
user_id UUID REFERENCES users(id) ON DELETE SET NULL, user_id UUID REFERENCES users(id) ON DELETE SET NULL,
action VARCHAR(50) NOT NULL, action VARCHAR(50) NOT NULL,
ip VARCHAR(45), ip VARCHAR(45),
method VARCHAR(10),
path TEXT,
user_agent TEXT,
metadata JSONB NOT NULL DEFAULT '{}'::jsonb,
created_at TIMESTAMPTZ DEFAULT now() created_at TIMESTAMPTZ DEFAULT now()
); );
ALTER TABLE event_logs ADD COLUMN IF NOT EXISTS method VARCHAR(10);
ALTER TABLE event_logs ADD COLUMN IF NOT EXISTS path TEXT;
ALTER TABLE event_logs ADD COLUMN IF NOT EXISTS user_agent TEXT;
ALTER TABLE event_logs ADD COLUMN IF NOT EXISTS metadata JSONB NOT NULL DEFAULT '{}'::jsonb;
CREATE INDEX IF NOT EXISTS idx_event_logs_created_at ON event_logs(created_at DESC);
CREATE INDEX IF NOT EXISTS idx_event_logs_user_id ON event_logs(user_id);
-- ============================================================ -- ============================================================
-- 论坛设置表 -- 论坛设置表
-- ============================================================ -- ============================================================
+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.`);
+211 -45
View File
@@ -5,7 +5,9 @@
const express = require('express'); const express = require('express');
const cors = require('cors'); const cors = require('cors');
const bcrypt = require('bcrypt'); const helmet = require('helmet');
const { rateLimit } = require('express-rate-limit');
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');
@@ -19,7 +21,12 @@ const CONFIG = require('./config');
// 监听端口:环境变量 PORT 优先,其次 config.js 的 SERVER_PORT,最后默认 3000 // 监听端口:环境变量 PORT 优先,其次 config.js 的 SERVER_PORT,最后默认 3000
const PORT = process.env.PORT || CONFIG.SERVER_PORT || 3000; const PORT = process.env.PORT || CONFIG.SERVER_PORT || 3000;
const JWT_SECRET = process.env.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;
if (process.env.NODE_ENV === 'production' && JWT_SECRET === DEFAULT_JWT_SECRET) {
throw new Error('JWT_SECRET must be set to a unique value in production');
}
// ============================================================ // ============================================================
// 数据库 // 数据库
@@ -31,13 +38,118 @@ const pool = new Pool({
// ============================================================ // ============================================================
// 中间件 // 中间件
// ============================================================ // ============================================================
app.use(cors()); app.disable('x-powered-by');
app.use(express.json()); if (process.env.TRUST_PROXY === 'true') app.set('trust proxy', 1);
app.use(express.urlencoded({ extended: true }));
// The existing UI relies on inline styles/scripts and a CDN-hosted Markdown
// parser, so CSP is left for a dedicated frontend migration.
app.use(helmet({
contentSecurityPolicy: false,
crossOriginEmbedderPolicy: false,
}));
const allowedOrigins = (process.env.ALLOWED_ORIGINS || '')
.split(',')
.map(origin => origin.trim())
.filter(Boolean);
if (allowedOrigins.length > 0) {
app.use(cors({
origin(origin, callback) {
if (!origin || allowedOrigins.includes(origin)) return callback(null, true);
return callback(new Error('Origin is not allowed by CORS'));
},
}));
}
const apiLimiter = rateLimit({
windowMs: 15 * 60 * 1000,
limit: 300,
standardHeaders: 'draft-8',
legacyHeaders: false,
handler: (req, res) => res.status(429).json({ error: '请求过于频繁,请稍后重试' }),
});
const authLimiter = rateLimit({
windowMs: 15 * 60 * 1000,
limit: 20,
standardHeaders: 'draft-8',
legacyHeaders: false,
handler: (req, res) => res.status(429).json({ error: '尝试次数过多,请稍后重试' }),
});
app.use('/api', apiLimiter);
app.use(['/api/auth/login', '/api/auth/register', '/api/auth/reset-password'], authLimiter);
app.use(express.json({ limit: '100kb' }));
app.use(express.urlencoded({ extended: true, limit: '100kb' }));
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('uploads')); app.use('/uploads', express.static(path.join(__dirname, 'uploads'), {
dotfiles: 'deny',
fallthrough: false,
index: false,
}));
// ============================================================ // ============================================================
// 认证中间件 // 认证中间件
@@ -146,6 +258,9 @@ app.post('/api/auth/register', async (req, res) => {
[email, hash, username, avatar, role, ''] [email, hash, username, avatar, role, '']
); );
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: isFirstUser ? '🎉 你是第一个用户,已自动设为管理员!' : '注册成功'
@@ -180,6 +295,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 }, { id: user.id, email: user.email, role: user.role },
JWT_SECRET, JWT_SECRET,
@@ -752,34 +869,64 @@ app.post('/api/reports', auth, async (req, res) => {
app.put('/api/reports/:id', auth, admin, async (req, res) => { app.put('/api/reports/:id', auth, admin, async (req, res) => {
const { status, note } = req.body; const { status, note } = req.body;
if (!['pending', 'approved', 'rejected'].includes(status)) { if (!['approved', 'rejected'].includes(status)) {
return res.status(400).json({ error: '无效的状态' }); return res.status(400).json({ error: '无效的状态' });
} }
let client;
try { try {
const report = await pool.query('SELECT reporter_id, post_id FROM reports WHERE id = $1', [req.params.id]); client = await pool.connect();
await client.query('BEGIN');
const report = await client.query(
'SELECT reporter_id, post_id, status FROM reports WHERE id = $1 FOR UPDATE',
[req.params.id]
);
if (report.rows.length === 0) {
await client.query('ROLLBACK');
return res.status(404).json({ error: '举报不存在' });
}
if (report.rows[0].status !== 'pending') {
await client.query('ROLLBACK');
return res.status(409).json({ error: '该举报已处理' });
}
await pool.query( await client.query(
`UPDATE reports `UPDATE reports
SET status = $1, handled_at = NOW(), handler_id = $2, handler_note = $3 SET status = $1, handled_at = NOW(), handler_id = $2, handler_note = $3
WHERE id = $4`, WHERE id = $4`,
[status, req.user.id, note || '', req.params.id] [status, req.user.id, note || '', req.params.id]
); );
if (report.rows[0]) { if (status === 'approved' && report.rows[0].post_id) {
const statusText = status === 'approved' ? '已删除' : '已驳回'; await client.query('DELETE FROM posts WHERE id = $1', [report.rows[0].post_id]);
await createNotification( }
const statusText = status === 'approved' ? '已删除' : '已驳回';
await client.query(
`INSERT INTO notifications (user_id, type, title, content, link)
VALUES ($1, $2, $3, $4, $5)`,
[
report.rows[0].reporter_id, report.rows[0].reporter_id,
'report_handled', 'report_handled',
'你的举报已被处理', '你的举报已被处理',
`你举报的帖子已被管理员${statusText}`, `你举报的帖子已被管理员${statusText}`,
report.rows[0].post_id ? '/?post=' + report.rows[0].post_id : null status === 'rejected' && report.rows[0].post_id ? '/?post=' + report.rows[0].post_id : null,
); ]
} );
res.json({ success: true }); await client.query('COMMIT');
res.json({ success: true, post_deleted: status === 'approved' });
} catch (err) { } catch (err) {
if (client) {
try {
await client.query('ROLLBACK');
} catch (rollbackError) {
console.error('回滚举报处理事务失败:', rollbackError);
}
}
res.status(500).json({ error: '操作失败,请稍后重试' }); res.status(500).json({ error: '操作失败,请稍后重试' });
} finally {
if (client) client.release();
} }
}); });
@@ -886,21 +1033,6 @@ 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 });
}
});
// ============================================================ // ============================================================
// 图片上传 // 图片上传
// ============================================================ // ============================================================
@@ -1142,10 +1274,18 @@ 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', auth, async (req, res) => {
try { try {
await pool.query(` const result = await pool.query(`
UPDATE messages SET is_read = true UPDATE messages AS m SET is_read = true
WHERE id = $1 AND sender_id != $2 FROM conversations AS c
WHERE m.id = $1
AND m.sender_id != $2
AND c.id = m.conversation_id
AND (c.user1_id = $2 OR c.user2_id = $2)
RETURNING m.id
`, [req.params.id, req.user.id]); `, [req.params.id, req.user.id]);
if (result.rows.length === 0) {
return res.status(404).json({ error: '消息不存在或无权限' });
}
res.json({ success: true }); res.json({ success: true });
} catch (err) { } catch (err) {
res.status(500).json({ error: '服务器错误' }); res.status(500).json({ error: '服务器错误' });
@@ -1401,25 +1541,51 @@ app.post('/api/auth/reset-password', async (req, res) => {
}); });
// ============================================================ // ============================================================
// 托管前端文件 // 托管公开前端文件
// ============================================================ // ============================================================
app.use(express.static('.')); app.use('/js', express.static(path.join(__dirname, 'js'), {
dotfiles: 'deny',
fallthrough: false,
index: false,
}));
app.get('/style.css', (req, res) => res.sendFile(path.join(__dirname, 'style.css')));
app.get('/config.js', (req, res) => res.sendFile(path.join(__dirname, 'config.js')));
app.get('*', (req, res) => { app.get('*', (req, res) => {
if (!req.path.startsWith('/api')) { if (req.path.startsWith('/api')) {
res.sendFile(path.join(__dirname, 'index.html')); return res.status(404).json({ error: '接口不存在' });
} }
if (path.extname(req.path)) {
return res.status(404).send('Not found');
}
return res.sendFile(path.join(__dirname, 'index.html'));
});
app.use((err, req, res, next) => {
if (res.headersSent) return next(err);
if (err.type === 'entity.too.large') {
return res.status(413).json({ error: '请求内容过大' });
}
if (err.message === 'Origin is not allowed by CORS') {
return res.status(403).json({ error: '不允许的跨域来源' });
}
console.error(err);
return res.status(500).json({ error: '服务器错误' });
}); });
// ============================================================ // ============================================================
// 启动服务器 // 启动服务器
// ============================================================ // ============================================================
app.listen(PORT, '0.0.0.0', () => { if (require.main === module) {
console.log('========================================'); app.listen(PORT, '0.0.0.0', () => {
console.log(' 🌊 Forumlify 已启动'); console.log('========================================');
console.log(' 📡 http://localhost:' + PORT); console.log(' 🌊 Forumlify 已启动');
console.log(' 📡 API: http://localhost:' + PORT + '/api'); console.log(' 📡 http://localhost:' + PORT);
console.log('========================================'); console.log(' 📡 API: http://localhost:' + PORT + '/api');
}); console.log('========================================');
});
}
module.exports = { app, pool };
+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');
});