diff --git a/.dockerignore b/.dockerignore new file mode 100644 index 0000000..b2a2750 --- /dev/null +++ b/.dockerignore @@ -0,0 +1,10 @@ +.git +.github +.env +.env.* +!.env.example +node_modules +npm-debug.log* +uploads +coverage +*.md diff --git a/.env.example b/.env.example new file mode 100644 index 0000000..b86478d --- /dev/null +++ b/.env.example @@ -0,0 +1,4 @@ +# Copy to .env, then set both required secrets before running Docker Compose. +POSTGRES_PASSWORD= +JWT_SECRET= +PORT=3000 diff --git a/Dockerfile b/Dockerfile new file mode 100644 index 0000000..7c61282 --- /dev/null +++ b/Dockerfile @@ -0,0 +1,18 @@ +FROM node:22.23.2-bookworm-slim + +ENV NODE_ENV=production +WORKDIR /app + +COPY package.json package-lock.json ./ +RUN npm ci --omit=dev && npm cache clean --force + +COPY --chown=node:node . . +RUN mkdir -p /app/uploads && chown node:node /app/uploads + +USER node +EXPOSE 3000 + +HEALTHCHECK --interval=30s --timeout=5s --start-period=20s --retries=3 \ + CMD ["node", "scripts/healthcheck.js"] + +CMD ["sh", "-c", "npm run migrate && npm start"] diff --git a/README.md b/README.md index 10163a3..a39b984 100644 --- a/README.md +++ b/README.md @@ -39,11 +39,41 @@ Forumlify 提供了两个不同架构的分支版本,以满足不同部署环 ``` git clone https://github.com/furrium/forumlify.git cd forumlify -docker-compose up -d +cp .env.example .env +# 编辑 .env,为 POSTGRES_PASSWORD 和 JWT_SECRET 设置强随机值 +docker compose up --build -d ``` 应用默认运行在 `http://localhost:3000`。 +容器启动时会自动执行 `migrations/` 中尚未应用的 SQL 文件。可使用以下命令检查状态: + +```bash +docker compose ps +docker compose logs -f app +curl http://localhost:3000/health/live +curl http://localhost:3000/health/ready +``` + +- `/health/live` 表示 Node.js 服务正在运行。 +- `/health/ready` 仅在 PostgreSQL 可用时返回成功。 +- PostgreSQL 不再暴露到宿主机网络;应用通过 Compose 内部网络访问数据库。 +- 应用收到 `SIGTERM`/`SIGINT` 后会停止接收新连接并关闭数据库连接池。 + +升级代码后执行 `docker compose up --build -d`,应用会在启动前自动应用新增迁移。 + +#### Docker 数据备份 + +数据库与上传文件分别保存在 `db_data` 和 `uploads_data` 卷中。升级或删除容器前请备份: + +```bash +docker compose exec -T db pg_dump -U forumlify forumlify > forumlify.sql +docker run --rm -v forumlify_uploads_data:/data -v "$PWD":/backup alpine \ + tar czf /backup/forumlify-uploads.tar.gz -C /data . +``` + +`docker compose down` 会保留数据卷;只有明确执行 `docker compose down -v` 才会删除数据。 + --- > 如需部署 Next.js 版本,请前往 [forumlify/tree/next](https://github.com/furrium/forumlify/tree/next)。 @@ -77,19 +107,21 @@ psql -U postgres -c "CREATE DATABASE forumlify OWNER forumlify;" psql -U forumlify -d forumlify -f schema.sql ``` -3. **配置环境变量**(可选) +3. **配置环境变量** | 变量 | 默认值 | 说明 | |------|--------|------| | `DATABASE_URL` | `postgresql://forumlify:***@localhost:5432/forumlify` | PostgreSQL 连接串 | | `PORT` | `3000` | HTTP 监听端口 | -| `JWT_SECRET` | 本地开发使用内置值 | JWT 签名密钥;`NODE_ENV=production` 时必须显式设置 | +| `JWT_SECRET` | 本地开发使用内置值 | JWT 签名密钥;生产环境必须显式设置至少 32 个字符 | | `ALLOWED_ORIGINS` | 空 | 允许跨域访问的来源,多个值用逗号分隔;为空时仅支持同源访问 | | `TRUST_PROXY` | `false` | 位于可信反向代理后时设为 `true`,用于正确识别限流 IP | +| `PGHOST` / `PGPORT` / `PGUSER` / `PGPASSWORD` / `PGDATABASE` | PostgreSQL 客户端默认值 | 可替代 `DATABASE_URL`,Compose 使用这些变量避免密码 URL 编码问题 | -4. **启动** +4. **执行迁移并启动** ```bash +npm run migrate npm start ``` diff --git a/docker-compose.yml b/docker-compose.yml index 54673b5..534dd0d 100644 --- a/docker-compose.yml +++ b/docker-compose.yml @@ -1,27 +1,48 @@ -version: '3' services: db: - image: postgres:15 + image: postgres:16.14-alpine + restart: unless-stopped environment: POSTGRES_USER: forumlify - POSTGRES_PASSWORD: 123456 + POSTGRES_PASSWORD: ${POSTGRES_PASSWORD:?Set POSTGRES_PASSWORD in .env} POSTGRES_DB: forumlify volumes: - - ./schema.sql:/docker-entrypoint-initdb.d/schema.sql - db_data:/var/lib/postgresql/data - ports: - - "5432:5432" + healthcheck: + test: ["CMD-SHELL", "pg_isready -U forumlify -d forumlify"] + interval: 5s + timeout: 5s + retries: 10 + start_period: 10s app: - build: . + build: + context: . + dockerfile: Dockerfile + restart: unless-stopped ports: - - "3000:3000" + - "${PORT:-3000}:3000" depends_on: - - db + db: + condition: service_healthy environment: - DATABASE_URL: postgresql://forumlify:123456@db:5432/forumlify + NODE_ENV: production + PORT: 3000 + PGHOST: db + PGPORT: 5432 + PGUSER: forumlify + PGPASSWORD: ${POSTGRES_PASSWORD:?Set POSTGRES_PASSWORD in .env} + PGDATABASE: forumlify + JWT_SECRET: ${JWT_SECRET:?Set JWT_SECRET in .env} volumes: - - ./uploads:/app/uploads + - uploads_data:/app/uploads + healthcheck: + test: ["CMD", "node", "scripts/healthcheck.js"] + interval: 30s + timeout: 5s + retries: 3 + start_period: 30s volumes: db_data: + uploads_data: diff --git a/dockerfile b/dockerfile deleted file mode 100644 index 74507e4..0000000 --- a/dockerfile +++ /dev/null @@ -1,7 +0,0 @@ -FROM node:18-alpine -WORKDIR /app -COPY package*.json ./ -RUN npm install -COPY . . -EXPOSE 3000 -CMD ["npm", "start"] diff --git a/migrations/001_initial.sql b/migrations/001_initial.sql new file mode 100644 index 0000000..3ce81dd --- /dev/null +++ b/migrations/001_initial.sql @@ -0,0 +1,209 @@ +-- ============================================================ +-- Forumlify 数据库表结构 +-- ============================================================ + +-- 用户表 +CREATE TABLE IF NOT EXISTS users ( + id UUID PRIMARY KEY DEFAULT gen_random_uuid(), + email VARCHAR(255) UNIQUE NOT NULL, + password_hash VARCHAR(255) NOT NULL, + username VARCHAR(20) UNIQUE NOT NULL, + avatar_url TEXT, + bio TEXT DEFAULT '', + role VARCHAR(10) DEFAULT 'user' CHECK (role IN ('user', 'admin')), + created_at TIMESTAMPTZ DEFAULT now() +); + +-- 帖子表 +CREATE TABLE IF NOT EXISTS posts ( + id UUID PRIMARY KEY DEFAULT gen_random_uuid(), + user_id UUID NOT NULL REFERENCES users(id) ON DELETE CASCADE, + title VARCHAR(200) NOT NULL, + content TEXT NOT NULL, + images TEXT[] DEFAULT '{}', + created_at TIMESTAMPTZ DEFAULT now(), + updated_at TIMESTAMPTZ DEFAULT now() +); + +-- 回复表 +CREATE TABLE IF NOT EXISTS replies ( + id UUID PRIMARY KEY DEFAULT gen_random_uuid(), + post_id UUID NOT NULL REFERENCES posts(id) ON DELETE CASCADE, + user_id UUID NOT NULL REFERENCES users(id) ON DELETE CASCADE, + content TEXT NOT NULL, + created_at TIMESTAMPTZ DEFAULT now() +); + +-- 友情链接表 +CREATE TABLE IF NOT EXISTS friendly_links ( + id UUID PRIMARY KEY DEFAULT gen_random_uuid(), + title VARCHAR(100) NOT NULL, + url TEXT NOT NULL, + sort_order INT DEFAULT 0 +); + +-- 举报表 +CREATE TABLE IF NOT EXISTS reports ( + id UUID PRIMARY KEY DEFAULT gen_random_uuid(), + post_id UUID REFERENCES posts(id) ON DELETE SET NULL, + reporter_id UUID NOT NULL REFERENCES users(id) ON DELETE CASCADE, + reason VARCHAR(100) NOT NULL, + status VARCHAR(20) DEFAULT 'pending' CHECK (status IN ('pending', 'approved', 'rejected')), + created_at TIMESTAMPTZ DEFAULT now(), + handled_at TIMESTAMPTZ, + handler_id UUID REFERENCES users(id) ON DELETE SET NULL, + handler_note TEXT +); + +-- Preserve moderation history when a reported post is deleted. This also +-- upgrades databases created with the previous ON DELETE CASCADE constraint. +DO $$ +DECLARE + constraint_name TEXT; +BEGIN + SELECT con.conname INTO constraint_name + FROM pg_constraint con + JOIN pg_class rel ON rel.oid = con.conrelid + JOIN pg_attribute attr ON attr.attrelid = rel.oid AND attr.attnum = ANY(con.conkey) + WHERE rel.relname = 'reports' + AND con.contype = 'f' + AND attr.attname = 'post_id' + LIMIT 1; + + IF constraint_name IS NOT NULL THEN + EXECUTE format('ALTER TABLE reports DROP CONSTRAINT %I', constraint_name); + END IF; + + ALTER TABLE reports ALTER COLUMN post_id DROP NOT NULL; + ALTER TABLE reports + ADD CONSTRAINT reports_post_id_fkey + FOREIGN KEY (post_id) REFERENCES posts(id) ON DELETE SET NULL; +END $$; + +-- 事件日志表 +CREATE TABLE IF NOT EXISTS event_logs ( + id UUID PRIMARY KEY DEFAULT gen_random_uuid(), + user_id UUID REFERENCES users(id) ON DELETE SET NULL, + action VARCHAR(50) NOT NULL, + ip VARCHAR(45), + created_at TIMESTAMPTZ DEFAULT now() +); + +-- ============================================================ +-- 论坛设置表 +-- ============================================================ +CREATE TABLE IF NOT EXISTS settings ( + key VARCHAR(50) PRIMARY KEY, + value TEXT NOT NULL, + updated_at TIMESTAMPTZ DEFAULT now() +); + +INSERT INTO settings (key, value) VALUES ('forum_name', 'Forumlify') +ON CONFLICT (key) DO NOTHING; + +-- ============================================================ +-- 私信系统 +-- ============================================================ + +-- 私信会话表 +CREATE TABLE IF NOT EXISTS conversations ( + id UUID PRIMARY KEY DEFAULT gen_random_uuid(), + user1_id UUID NOT NULL REFERENCES users(id) ON DELETE CASCADE, + user2_id UUID NOT NULL REFERENCES users(id) ON DELETE CASCADE, + last_message_at TIMESTAMPTZ DEFAULT now(), + created_at TIMESTAMPTZ DEFAULT now(), + UNIQUE(user1_id, user2_id) +); + +-- 私信消息表 +CREATE TABLE IF NOT EXISTS messages ( + id UUID PRIMARY KEY DEFAULT gen_random_uuid(), + conversation_id UUID NOT NULL REFERENCES conversations(id) ON DELETE CASCADE, + sender_id UUID NOT NULL REFERENCES users(id) ON DELETE CASCADE, + content TEXT NOT NULL, + is_read BOOLEAN DEFAULT false, + created_at TIMESTAMPTZ DEFAULT now() +); + +CREATE INDEX IF NOT EXISTS idx_messages_conversation_id ON messages(conversation_id); +CREATE INDEX IF NOT EXISTS idx_messages_sender_id ON messages(sender_id); +CREATE INDEX IF NOT EXISTS idx_conversations_user1_id ON conversations(user1_id); +CREATE INDEX IF NOT EXISTS idx_conversations_user2_id ON conversations(user2_id); + +-- ============================================================ +-- 自定义页面表 +-- ============================================================ +CREATE TABLE IF NOT EXISTS custom_pages ( + id UUID PRIMARY KEY DEFAULT gen_random_uuid(), + name VARCHAR(50) NOT NULL UNIQUE, + title VARCHAR(100) NOT NULL, + content TEXT NOT NULL, + enabled BOOLEAN DEFAULT true, + created_at TIMESTAMPTZ DEFAULT now(), + updated_at TIMESTAMPTZ DEFAULT now() +); + +CREATE INDEX IF NOT EXISTS idx_custom_pages_name ON custom_pages(name); + +-- ============================================================ +-- 通知系统 +-- ============================================================ +CREATE TABLE IF NOT EXISTS notifications ( + id UUID PRIMARY KEY DEFAULT gen_random_uuid(), + user_id UUID NOT NULL REFERENCES users(id) ON DELETE CASCADE, + type VARCHAR(30) NOT NULL, + title VARCHAR(100) NOT NULL, + content TEXT NOT NULL, + link TEXT, + is_read BOOLEAN DEFAULT false, + created_at TIMESTAMPTZ DEFAULT now() +); + +CREATE INDEX IF NOT EXISTS idx_notifications_user_id ON notifications(user_id); +CREATE INDEX IF NOT EXISTS idx_notifications_is_read ON notifications(is_read); + +-- ============================================================ +-- 自动更新 updated_at 的触发器 +-- ============================================================ +CREATE OR REPLACE FUNCTION update_updated_at() +RETURNS TRIGGER AS $$ +BEGIN + NEW.updated_at = now(); + RETURN NEW; +END; +$$ LANGUAGE plpgsql; + +DROP TRIGGER IF EXISTS update_posts_updated_at ON posts; +CREATE TRIGGER update_posts_updated_at + BEFORE UPDATE ON posts + FOR EACH ROW EXECUTE FUNCTION update_updated_at(); + +ALTER TABLE posts ADD COLUMN IF NOT EXISTS edited_at TIMESTAMPTZ; + +-- ============================================================ +-- 恢复码表(密码重置用) +-- ============================================================ +CREATE TABLE IF NOT EXISTS recovery_codes ( + id UUID PRIMARY KEY DEFAULT gen_random_uuid(), + user_id UUID NOT NULL REFERENCES users(id) ON DELETE CASCADE, + code_hash VARCHAR(255) NOT NULL, + is_used BOOLEAN DEFAULT false, + created_at TIMESTAMPTZ DEFAULT now() +); + +CREATE INDEX IF NOT EXISTS idx_recovery_codes_user_id ON recovery_codes(user_id); + +-- 帖子表添加置顶字段 +ALTER TABLE posts ADD COLUMN IF NOT EXISTS is_pinned BOOLEAN DEFAULT false; +ALTER TABLE posts ADD COLUMN IF NOT EXISTS pinned_at TIMESTAMPTZ; + +-- 创建索引 +CREATE INDEX IF NOT EXISTS idx_posts_is_pinned ON posts(is_pinned); + +ALTER TABLE users ADD COLUMN IF NOT EXISTS signature TEXT DEFAULT ''; + +-- ============================================================ +-- 论坛默认设置 +-- ============================================================ +INSERT INTO settings (key, value) VALUES ('forum_name', 'Forumlify') +ON CONFLICT (key) DO NOTHING; diff --git a/package.json b/package.json index d44730c..3c703a9 100644 --- a/package.json +++ b/package.json @@ -5,7 +5,8 @@ "main": "server.js", "scripts": { "start": "node server.js", - "dev": "node server.js" + "dev": "node server.js", + "migrate": "node scripts/migrate.js" }, "dependencies": { "bcrypt": "^5.1.1", diff --git a/scripts/healthcheck.js b/scripts/healthcheck.js new file mode 100644 index 0000000..5e132d5 --- /dev/null +++ b/scripts/healthcheck.js @@ -0,0 +1,11 @@ +const port = process.env.PORT || 3000; +const url = `http://127.0.0.1:${port}/health/ready`; + +fetch(url, { signal: AbortSignal.timeout(4000) }) + .then(response => { + if (!response.ok) throw new Error(`readiness returned ${response.status}`); + }) + .catch(error => { + console.error(error.message); + process.exit(1); + }); diff --git a/scripts/migrate.js b/scripts/migrate.js new file mode 100644 index 0000000..d8d3202 --- /dev/null +++ b/scripts/migrate.js @@ -0,0 +1,59 @@ +const fs = require('node:fs/promises'); +const path = require('node:path'); +const { Pool } = require('pg'); + +const migrationsDir = path.join(__dirname, '..', 'migrations'); +if (!process.env.DATABASE_URL && !process.env.PGHOST) { + console.error('DATABASE_URL or PGHOST is required to run migrations.'); + process.exit(1); +} + +async function migrate() { + const pool = new Pool(); + const client = await pool.connect(); + + try { + await client.query(` + CREATE TABLE IF NOT EXISTS schema_migrations ( + filename TEXT PRIMARY KEY, + applied_at TIMESTAMPTZ NOT NULL DEFAULT NOW() + ) + `); + + const files = (await fs.readdir(migrationsDir)) + .filter(file => /^\d+.*\.sql$/.test(file)) + .sort(); + + const applied = await client.query('SELECT filename FROM schema_migrations'); + const appliedFiles = new Set(applied.rows.map(row => row.filename)); + + for (const filename of files) { + if (appliedFiles.has(filename)) continue; + + const sql = await fs.readFile(path.join(migrationsDir, filename), 'utf8'); + console.log(`Applying migration ${filename}`); + await client.query('BEGIN'); + try { + await client.query(sql); + await client.query( + 'INSERT INTO schema_migrations (filename) VALUES ($1)', + [filename] + ); + await client.query('COMMIT'); + } catch (error) { + await client.query('ROLLBACK'); + throw error; + } + } + + console.log('Database migrations are up to date.'); + } finally { + client.release(); + await pool.end(); + } +} + +migrate().catch(error => { + console.error('Database migration failed:', error); + process.exit(1); +}); diff --git a/server.js b/server.js index 268e813..661d845 100644 --- a/server.js +++ b/server.js @@ -24,16 +24,27 @@ const PORT = process.env.PORT || CONFIG.SERVER_PORT || 3000; 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'); +if (process.env.NODE_ENV === 'production') { + if (JWT_SECRET === DEFAULT_JWT_SECRET || JWT_SECRET.length < 32) { + throw new Error('JWT_SECRET must contain at least 32 unique characters in production'); + } + if (!process.env.DATABASE_URL && !process.env.PGHOST) { + throw new Error('DATABASE_URL or PGHOST must be configured in production'); + } } // ============================================================ // 数据库 // ============================================================ -const pool = new Pool({ - connectionString: process.env.DATABASE_URL || 'postgresql://forumlify:123456@localhost:5432/forumlify', -}); +const pool = new Pool(process.env.DATABASE_URL + ? { connectionString: process.env.DATABASE_URL } + : { + host: process.env.PGHOST || 'localhost', + port: Number(process.env.PGPORT || 5432), + user: process.env.PGUSER || 'forumlify', + password: process.env.PGPASSWORD || '123456', + database: process.env.PGDATABASE || 'forumlify', + }); // ============================================================ // 中间件 @@ -1492,6 +1503,19 @@ app.post('/api/auth/reset-password', async (req, res) => { // 托管公开前端文件 // ============================================================ +app.get('/health/live', (req, res) => { + res.json({ status: 'ok' }); +}); + +app.get('/health/ready', async (req, res) => { + try { + await pool.query('SELECT 1'); + res.json({ status: 'ready' }); + } catch (error) { + res.status(503).json({ status: 'not_ready' }); + } +}); + app.use('/js', express.static(path.join(__dirname, 'js'), { dotfiles: 'deny', fallthrough: false, @@ -1526,10 +1550,68 @@ app.use((err, req, res, next) => { // 启动服务器 // ============================================================ -app.listen(PORT, '0.0.0.0', () => { - console.log('========================================'); - console.log(' 🌊 Forumlify 已启动'); - console.log(' 📡 http://localhost:' + PORT); - console.log(' 📡 API: http://localhost:' + PORT + '/api'); - console.log('========================================'); -}); +let server = null; +let shuttingDown = false; + +function startServer() { + if (server) return server; + + server = app.listen(PORT, '0.0.0.0', () => { + console.log('========================================'); + console.log(' 🌊 Forumlify 已启动'); + console.log(' 📡 http://localhost:' + PORT); + console.log(' 📡 API: http://localhost:' + PORT + '/api'); + console.log('========================================'); + }); + return server; +} + +function shutdown(signal, { exitProcess = true } = {}) { + if (shuttingDown) return Promise.resolve(); + shuttingDown = true; + console.log(`${signal} received, shutting down gracefully`); + + return new Promise((resolve, reject) => { + const forceExit = exitProcess + ? setTimeout(() => process.exit(1), 10000) + : null; + if (forceExit) forceExit.unref(); + + const finish = async error => { + try { + await pool.end(); + if (error) throw error; + resolve(); + } catch (shutdownError) { + reject(shutdownError); + } finally { + if (forceExit) clearTimeout(forceExit); + server = null; + shuttingDown = false; + } + }; + + if (server) server.close(finish); + else finish(); + }).finally(() => { + if (exitProcess) process.exitCode = 0; + }); +} + +if (require.main === module) { + startServer(); + process.on('SIGTERM', () => { + shutdown('SIGTERM').catch(error => { + console.error('Graceful shutdown failed:', error); + process.exitCode = 1; + }); + }); + process.on('SIGINT', () => { + shutdown('SIGINT').catch(error => { + console.error('Graceful shutdown failed:', error); + process.exitCode = 1; + }); + }); +} + +module.exports = { app, pool, startServer, shutdown };