整理文档

This commit is contained in:
david_bai
2025-06-18 22:53:38 +08:00
parent 055da7888a
commit da88174846
6 changed files with 177 additions and 1112 deletions
+86
View File
@@ -0,0 +1,86 @@
# PrivyDrop(前 SecureShare) - 基于 WebRTC 的隐私安全文件分享工具
[![开源协议](https://img.shields.io/badge/license-MIT-blue.svg)](./LICENSE)
<!--[![版本](https://img.shields.io/badge/version-1.0.0-brightgreen.svg)]()-->
PrivyDrop 是一个基于 WebRTC 的隐私文件分享工具,支持点对点(P2P)文件和文本传输,无需服务器中转,确保数据传输的隐私性和安全性。
[**在线体验 »**](https://www.securityshare.xyz/)
---
<!-- (可选) 在这里放一张项目截图或 GIF 动图 -->
![PrivyDrop 界面截图](frontend/public/HowItWorks.gif)
## ✨ 主要特性
- 🔒 **端到端加密**: 所有文件通过 WebRTC 在浏览器之间直接传输,不经过服务器。
- 📂 **文件/文件夹传输**: 支持多文件和整个文件夹的传输,文件夹会自动打包。
-**实时高效**: 实时显示传输进度、自动计算传输速度。
- 📝 **富文本传输**: 支持在线编辑和发送格式化文本。
- 🔗 **便捷分享**: 通过链接或二维码轻松分享房间,建立连接。
- 📱 **多端支持**: 响应式设计,支持桌面和移动端浏览器。
- 🌐 **国际化**: 支持中文和英文界面。
## 🛠️ 技术栈
- **前端**: Next.js 14, React 18, TypeScript, Tailwind CSS, shadcn/ui
- **后端**: Node.js, Express.js, TypeScript
- **实时通信**: WebRTC, Socket.IO
- **数据存储**: Redis
- **部署**: PM2, Nginx, Docker[暂未支持]
## 🚀 快速上手 (本地全栈开发)
在开始之前,请确保你的开发环境已安装 [Node.js](https://nodejs.org/) (v18+), [npm](https://www.npmjs.com/) 以及一个正在运行的 [Redis](https://redis.io/) 实例。
1. **克隆项目**
```bash
git clone https://github.com/david-bai00/PrivyDrop.git
cd privydrop
```
2. **配置并启动后端服务**
```bash
cd backend
npm install
# 根据 backend/README.zh-CN.md 指引创建并配置 .env.development.local
npm run dev # 默认启动于 http://localhost:3001
```
3. **配置并启动前端应用** (在新的终端窗口中)
```bash
cd frontend
pnpm install
# 根据 frontend/README.zh-CN.md 指引创建并配置 .env.development.local
pnpm dev # 默认启动于 http://localhost:3000
```
4. **开始使用**
在浏览器中打开 `http://localhost:3000` 即可访问应用。
## 📚 文档
我们提供了详尽的文档来帮助你深入了解项目的设计和部署细节:
- [**项目整体架构**](./docs/ARCHITECTURE.zh-CN.md): 了解系统各个组件如何协同工作。
- [**前端架构详解**](./docs/FRONTEND_ARCHITECTURE.zh-CN.md): 深入探索前端的代码结构、状态管理和核心逻辑。
- [**后端架构详解**](./docs/BACKEND_ARCHITECTURE.zh-CN.md): 深入探索后端的代码结构、信令流程和 Redis 设计。
- [**部署指南**](./docs/DEPLOYMENT.zh-CN.md): 学习如何在生产环境部署完整的 PrivyDrop 应用。
## 🤝 参与贡献
我们欢迎任何形式的贡献!无论是报告 Bug、提出功能建议还是提交代码,都对我们帮助巨大。请阅读我们的 [**贡献指南**](./.github/CONTRIBUTING.md) 来开始你的贡献之旅。
## 📄 开源协议
本项目采用 MIT 协议,详情请见 [LICENSE](./LICENSE) 文件。
-202
View File
@@ -1,202 +0,0 @@
# Privydrop - Backend
This is the backend server for Privydrop, a WebRTC-based file-sharing application. It handles signaling for WebRTC connections, room management, API requests from the frontend, and other related backend logic.
## Features
- **WebRTC Signaling:** Uses Socket.IO to exchange SDP offers, answers, and ICE candidates to facilitate peer-to-peer connections.
- **Room Management:** Allows users to create and join unique rooms for file-sharing sessions. Room state and participant information are managed using Redis.
- **API Endpoints:** Provides HTTP APIs for frontend interaction (e.g., creating/joining rooms, checking room availability).
- **Real-time Communication:** Uses Socket.IO for instant messaging between clients and the server.
- **Rate Limiting:** Basic IP-based rate limiting on certain operations to prevent abuse.
- **Temporary Data Storage:** Utilizes Redis to store temporary data like room information and session details with automatic expiration.
- **Referrer Tracking:** Daily tracking of traffic sources (referrers).
## Tech Stack
- **Node.js:** JavaScript runtime environment.
- **Express.js:** Web application framework for Node.js.
- **TypeScript:** Superset of JavaScript for static type checking.
- **Socket.IO:** Library for real-time, bidirectional, event-based communication.
- **Redis:** In-memory data structure store, used as a cache, session manager, and message broker.
- **ioredis:** A robust Redis client for Node.js.
- **CORS:** Middleware for enabling Cross-Origin Resource Sharing.
- **dotenv:** Module for loading environment variables from an `.env` file.
- **PM2 (Ecosystem file provided):** Production process manager for Node.js applications.
## Project Structure
The backend source code is primarily located in the `src/` directory:
.
├── README.md
├── README.zh-CN.md
├── docker # Docker-related files (Dockerfile, Nginx/TURN configurations, etc.).
│ ├── Dockerfile
│ ├── env_install.log
│ ├── Nginx
│ │ ├── configure.sh
│ │ ├── default
│ │ ├── nginx.conf
│ │ ├── renew_ssl.sh
│ │ └── stop_clean-log.sh
│ └── TURN
│ ├── configure.sh
│ ├── turnserver_development.conf
│ └── turnserver_production.conf
├── docs
│ ├── DEPLOYMENT_GUIDE.en-US.md
│ └── DEPLOYMENT_GUIDE.zh-CN.md
├── ecosystem.config.js
├── package.json
├── package-lock.json
├── scripts
│ └── export-tracking-data.js
├── src
│ ├── config # Environment variables and server configuration (CORS).
│ │ ├── env.ts
│ │ └── server.ts
│ ├── routes # API route definitions (Express routes).
│ │ └── api.ts
│ ├── server.ts # Main application entry point: Express server and Socket.IO setup.
│ ├── services # Core business logic (room management, Redis interaction, rate limiting).
│ │ ├── rateLimit.ts
│ │ ├── redis.ts
│ │ └── room.ts
│ ├── socket # Socket.IO event handlers and signaling logic.
│ │ └── handlers.ts
│ └── types # TypeScript type definitions and interfaces.
│ ├── room.ts
│ └── socket.ts
└── tsconfig.json
## Prerequisites
- Node.js (v18.x or later recommended)
- npm
- A running Redis instance
For detailed installation and configuration of dependency services (like Redis, TURN/STUN server) and production deployment guidelines, please refer to the [Deployment Guide](./docs/DEPLOYMENT_GUIDE.en-US.md).
## Environment Variables
The application relies on environment variables to run. A simplified local development environment configuration is as follows:
Create a `.env.development.local` file in the `backend/` directory and populate it with the following basic variables:
```ini
# Server Configuration
PORT=3001
NODE_ENV=development # or production
CORS_ORIGIN=http://localhost:3000 # Your frontend application URL
# Redis Configuration
REDIS_HOST=127.0.0.1
REDIS_PORT=6379
# REDIS_PASSWORD=your_redis_password # Uncomment and set if your Redis is password-protected
```
**Note:**
- If `REDIS_HOST` or `REDIS_PORT` are not defined, the application will exit on startup.
- For more comprehensive environment variable configurations (including TURN server, production-specific settings, etc.), please refer to Section 4.3 of the [Deployment Guide](./docs/DEPLOYMENT_GUIDE.en-US.md).
## Getting Started (Local Development)
1. **Clone the repository.**
2. **Navigate to the `backend/` directory:**
```bash
cd path/to/your/project/privydrop/backend
```
3. **Install dependencies:**
```bash
npm install
```
4. **Ensure Redis is running** and accessible with the credentials provided in your `.env` file. For detailed Redis installation and configuration, refer to Section 3.1 of the [Deployment Guide](./docs/DEPLOYMENT_GUIDE.en-US.md).
5. **Create and configure your `.env.development.local` file** as described above.
6. **Run the development server:**
```bash
npm run dev
```
The server should start on the port specified by your `PORT` environment variable (defaults to 3001).
For **production deployment**, please refer to the detailed instructions on using PM2 in the [Deployment Guide](./docs/DEPLOYMENT_GUIDE.en-US.md) (Section 4.5).
## API Endpoints
All API endpoints are prefixed with `/api`.
- **`POST /api/create_room`**
- Creates a new room if the provided `roomId` is unique.
- Request Body: `{ "roomId": "string" }`
- Response: `{ "success": boolean, "message": "string" }`
- **`GET /api/get_room`**
- Generates a unique, available room ID and creates the room.
- Response: `{ "roomId": "string" }`
- **`POST /api/check_room`**
- Checks if the given `roomId` is available (i.e., does not exist).
- Request Body: `{ "roomId": "string" }`
- Response: `{ "available": boolean }`
- **`POST /api/set_track`**
- Tracks a referrer event. Stores daily stats in Redis with a 30-day TTL.
- Request Body: `{ "ref": "string", "timestamp": number, "path": "string" }`
- Response: `{ "success": boolean }`
- **`POST /api/logs_debug`** (For frontend debugging)
- Receives log messages from the frontend and prints them to the server console.
- Request Body: `{ "message": "string", "timestamp": number }`
- Response: `{ "success": boolean }`
## Socket.IO Events
The server listens for and emits the following Socket.IO events for WebRTC signaling and room communication:
**Client-to-Server Events:**
- **`join`**: Client requests to join a room.
- Data: `{ roomId: string }`
- **`offer`**: Client sends an SDP offer to a peer.
- Data: `{ peerId: string, offer: RTCSessionDescriptionInit, from?: string }`
- **`answer`**: Client sends an SDP answer to a peer.
- Data: `{ peerId: string, answer: RTCSessionDescriptionInit, from?: string }`
- **`ice-candidate`**: Client sends an ICE candidate to a peer.
- Data: `{ peerId: string, candidate: RTCIceCandidateInit, from?: string }`
- **`initiator-online`**: (Custom) Initiator signals online/ready status in the room.
- Data: `{ roomId: string }`
- **`recipient-ready`**: (Custom) Recipient signals ready status in the room.
- Data: `{ roomId: string, peerId: string }`
**Server-to-Client Events:**
- **`joinResponse`**: Response to a `join` request.
- Data: `{ success: boolean, message: string, roomId: string }`
- **`ready`**: Notifies clients in a room that a new peer has joined and is ready.
- Data: `{ peerId: string }` (ID of the new peer)
- **`offer`**: Forwards an SDP offer from one peer to another.
- Data: `{ offer: RTCSessionDescriptionInit, peerId: string }` (ID of the sender)
- **`answer`**: Forwards an SDP answer from one peer to another.
- Data: `{ answer: RTCSessionDescriptionInit, peerId: string }` (ID of the sender)
- **`ice-candidate`**: Forwards an ICE candidate from one peer to another.
- Data: `{ candidate: RTCIceCandidateInit, peerId: string }` (ID of the sender)
- **`initiator-online`**: (Custom) Broadcasts that the initiator is online in the room.
- Data: `{ roomId: string }`
- **`recipient-ready`**: (Custom) Broadcasts that a recipient is ready.
- Data: `{ peerId: string }` (ID of the ready recipient)
- **`peer-disconnected`**: Notifies clients in a room that a peer has disconnected.
- Data: `{ peerId: string }`
## Redis Data Usage Summary
Redis is used for:
- **Room Information (`room:<roomId>` - Hash):** Stores room creation time. TTL is managed.
- **Sockets in Room (`room:<roomId>:sockets` - Set):** Stores `socketId`s of clients in a room. TTL is tied to the room's TTL.
- **Socket to Room Mapping (`socket:<socketId>` - String):** Maps a `socketId` to its `roomId`. TTL is managed.
- **Rate Limiting (`ratelimit:join:<ipAddress>` - Sorted Set):** Tracks IP-based request timestamps for join operations for rate limiting. TTL is managed.
- **Referrer Tracking (`referrers:daily:<YYYY-MM-DD>` - Hash):** Stores daily referrer counts. TTL is 30 days.
## Contributing
(Placeholder for contribution guidelines - e.g., fork, branch, PR, coding standards)
## License
(Placeholder for license - e.g., MIT, Apache 2.0)
+45 -186
View File
@@ -1,207 +1,66 @@
# Privydrop - 后端
# PrivyDrop - 后端
这是 Privydrop 的后端服务器,一个基于 WebRTC 的文件共享应用程序。它处理 WebRTC 连接的信令、房间管理来自前端的 API 请求以及其他相关的后端逻辑
这是 PrivyDrop 的后端服务器。它使用 Node.js、Express 和 Socket.IO 构建,负责处理 WebRTC 连接的信令、房间管理来自前端的 API 请求。
## 功能特性
## 功能特性
- **WebRTC 信令:** 使用 Socket.IO 交换 SDP offers、answers 和 ICE candidates,以促进点对点连接
- **房间管理:** 允许用户创建和加入独特的房间进行文件共享会话。房间状态和参与者信息使用 Redis 进行管理
- **API 端点:** 提供 HTTP API 供前端交互(例如,创建/加入房间、检查房间可用性)
- **实时通信:** 使用 Socket.IO 实现客户端和服务器之间的即时消息传递
- **速率限制:** 对某些操作进行基本的基于 IP 的速率限制,以防止滥用。
- **临时数据存储:** 利用 Redis 存储临时数据,如房间信息和会话详情,并具有自动过期功能。
- **来源跟踪:** 每日基础的流量来源(referrers)跟踪。
- **WebRTC 信令:** 使用 Socket.IO 交换 SDP 和 ICE candidates。
- **房间管理:** 使用 Redis 高效地创建和管理临时文件共享房间
- **轻量级 API:** 提供核心的 HTTP 接口供前端交互。
- **临时数据存储:** 所有房间数据在 Redis 中都有自动过期时间
## 技术栈
## 🛠️ 技术栈
- **Node.js:** JavaScript 运行时环境。
- **Express.js:** Node.js 的 Web 应用程序框架。
- **TypeScript:** JavaScript 的超集,用于静态类型检查。
- **Socket.IO:** 用于实时、双向、基于事件的通信库。
- **Redis:** 内存数据结构存储,用作缓存、会话管理和消息代理。
- **ioredis:** Node.js 的一个健壮的 Redis 客户端。
- **CORS:** 用于启用跨域资源共享的中间件。
- **dotenv:** 用于从 `.env` 文件加载环境变量的模块。
- **PM2 (已提供 Ecosystem 文件):** Node.js 应用程序的生产流程管理器。
- **运行时**: Node.js
- **框架**: Express.js
- **语言**: TypeScript
- **实时通信**: Socket.IO
- **数据库**: Redis (使用 ioredis 客户端)
- **进程管理**: PM2
## 项目结构
## 🚀 入门 (本地开发)
后端源代码主要位于 `src/` 目录中:
.
├── README.md
├── README.zh-CN.md
├── docker # Docker 相关文件 (Dockerfile, Nginx/TURN 配置等)。
│ ├── Dockerfile
│ ├── env_install.log
│ ├── Nginx
│ │ ├── configure.sh
│ │ ├── default
│ │ ├── nginx.conf
│ │ ├── renew_ssl.sh
│ │ └── stop_clean-log.sh
│ └── TURN
│ ├── configure.sh
│ ├── turnserver_development.conf
│ └── turnserver_production.conf
├── docs
│ ├── DEPLOYMENT_GUIDE.en-US.md
│ └── DEPLOYMENT_GUIDE.zh-CN.md
├── ecosystem.config.js
├── package.json
├── package-lock.json
├── scripts
│ └── export-tracking-data.js
├── src
│ ├── config # 环境变量和服务器配置 (CORS)。
│ │ ├── env.ts
│ │ └── server.ts
│ ├── routes # API 路由定义 (Express 路由)。
│ │ └── api.ts
│ ├── server.ts # 主应用程序入口点:Express 服务器和 Socket.IO 设置。
│ ├── services # 核心业务逻辑 (房间管理, Redis 交互, 速率限制)。
│ │ ├── rateLimit.ts
│ │ ├── redis.ts
│ │ └── room.ts
│ ├── socket # Socket.IO 事件处理程序和信令逻辑。
│ │ └── handlers.ts
│ └── types # TypeScript 类型定义和接口。
│ ├── room.ts
│ └── socket.ts
└── tsconfig.json
1. **先决条件**
## 先决条件
- Node.js (v18.x 或更高版本)
- 一个正在运行的 Redis 实例
- Node.js (推荐 v18.x 或更高版本)
- npm
- 一个正在运行的 Redis 实例
2. **进入目录并安装依赖**
有关详细的依赖服务安装和配置(如 Redis, TURN/STUN 服务器)以及生产环境部署指南,请参阅 [部署指南](./docs/DEPLOYMENT_GUIDE.zh-CN.md)。
## 环境变量
应用程序的运行依赖于环境变量。
### 后端开发环境变量
`backend/` 目录中创建一个 `.env.development.local` 文件,并填充以下基本变量:
```ini
# 服务器配置
PORT=3001
NODE_ENV=development
CORS_ORIGIN=http://localhost:3000 # 你的前端应用程序 URL
# Redis 配置
REDIS_HOST=127.0.0.1
REDIS_PORT=6379
# REDIS_PASSWORD=your_redis_password # 如果 Redis 受密码保护,请取消注释并设置
```
**注意:**
- 如果未定义 `REDIS_HOST``REDIS_PORT`,应用程序将在启动时退出。
### 后端生产环境变量
更全面的后端环境变量配置(包括生产特定设置等)请参考 [部署指南](./docs/DEPLOYMENT_GUIDE.zh-CN.md)。
## 入门 (本地开发)
1. **克隆仓库。**
2. **导航到 `backend/` 目录:**
```bash
cd path/to/your/project/privydrop/backend
```
3. **安装依赖:**
```bash
cd backend
npm install
```
4. **确保 Redis 正在运行**,并且可以使用您在 `.env` 文件中提供的凭据进行访问。详细的 Redis 安装和配置,请参阅 [部署指南](./docs/DEPLOYMENT_GUIDE.zh-CN.md) 的第 3.1 节。
5. 如上所述,**创建并配置您的 `.env.development.local` 文件**
6. **运行开发服务器:**
3. **配置环境变量**
在 `backend/` 目录中创建一个 `.env.development.local` 文件,并填充以下变量:
```ini
# 服务器配置
PORT=3001
CORS_ORIGIN=http://localhost:3000 # 前端开发服务器的 URL
# Redis 配置
REDIS_HOST=127.0.0.1
REDIS_PORT=6379
# REDIS_PASSWORD=your_redis_password
```
4. **运行开发服务器**
```bash
npm run dev
```
服务器应在您 `PORT` 环境变量指定的端口上启动(默认为 3001)。
服务器将在 `PORT` 环境变量指定的端口上启动(默认为 3001)。
对于**生产环境部署**,请参考 [部署指南](./docs/DEPLOYMENT_GUIDE.zh-CN.md) 中关于使用 PM2 进行部署的详细说明(第 4.5 节)。
## 📖 API 与事件摘要
## API 端点
本服务提供了一系列 API 端点和 Socket.IO 事件来支持前端功能。
所有 API 端点都以 `/api` 为前缀
- **API 端点**: 主要包括房间创建 (`/api/get_room`)、加入和检查等
- **Socket.IO 事件**: 负责处理客户端加入房间 (`join`) 以及 WebRTC 信令的转发 (`offer`, `answer`, `ice-candidate`)。
- **`POST /api/create_room`**
- 如果提供的 `roomId` 是唯一的,则创建一个新房间。
- 请求体: `{ "roomId": "string" }`
- 响应: `{ "success": boolean, "message": "string" }`
- **`GET /api/get_room`**
- 生成一个唯一的、可用的房间 ID 并创建房间。
- 响应: `{ "roomId": "string" }`
- **`POST /api/check_room`**
- 检查给定的 `roomId` 是否可用(即不存在)。
- 请求体: `{ "roomId": "string" }`
- 响应: `{ "available": boolean }`
- **`POST /api/set_track`**
- 跟踪一个来源事件。在 Redis 中存储每日统计信息,TTL 为 30 天。
- 请求体: `{ "ref": "string", "timestamp": number, "path": "string" }`
- 响应: `{ "success": boolean }`
- **`POST /api/logs_debug`** (用于前端调试)
- 从前端接收日志消息并将其打印到服务器控制台。
- 请求体: `{ "message": "string", "timestamp": number }`
- 响应: `{ "success": boolean }`
## 📚 详细文档
## Socket.IO 事件
服务器侦听并发出以下 Socket.IO 事件,用于 WebRTC 信令和房间通信:
**客户端到服务器事件:**
- **`join`**: 客户端请求加入房间。
- 数据: `{ roomId: string }`
- **`offer`**: 客户端向对等方发送 SDP offer。
- 数据: `{ peerId: string, offer: RTCSessionDescriptionInit, from?: string }`
- **`answer`**: 客户端向对等方发送 SDP answer。
- 数据: `{ peerId: string, answer: RTCSessionDescriptionInit, from?: string }`
- **`ice-candidate`**: 客户端向对等方发送 ICE candidate。
- 数据: `{ peerId: string, candidate: RTCIceCandidateInit, from?: string }`
- **`initiator-online`**: (自定义) 发起者在房间内发出在线/就绪信号。
- 数据: `{ roomId: string }`
- **`recipient-ready`**: (自定义) 接收者在房间内发出就绪信号。
- 数据: `{ roomId: string, peerId: string }`
**服务器到客户端事件:**
- **`joinResponse`**: 对 `join` 请求的响应。
- 数据: `{ success: boolean, message: string, roomId: string }`
- **`ready`**: 通知房间内的客户端有新的对等方加入并准备就绪。
- 数据: `{ peerId: string }` (新对等方的 ID)
- **`offer`**: 将一个对等方的 SDP offer 转发给另一个对等方。
- 数据: `{ offer: RTCSessionDescriptionInit, peerId: string }` (发送方的 ID)
- **`answer`**: 将一个对等方的 SDP answer 转发给另一个对等方。
- 数据: `{ answer: RTCSessionDescriptionInit, peerId: string }` (发送方的 ID)
- **`ice-candidate`**: 将一个对等方的 ICE candidate 转发给另一个对等方。
- 数据: `{ candidate: RTCIceCandidateInit, peerId: string }` (发送方的 ID)
- **`initiator-online`**: (自定义) 广播房间内发起者在线。
- 数据: `{ roomId: string }`
- **`recipient-ready`**: (自定义) 广播接收者已准备就绪。
- 数据: `{ peerId: string }` (准备就绪的接收者的 ID)
- **`peer-disconnected`**: 通知房间内的客户端有对等方断开连接。
- 数据: `{ peerId: string }`
## Redis 数据使用摘要
Redis 用于:
- **房间信息 (`room:<roomId>` - Hash):** 存储房间创建时间。TTL 受管理。
- **房间内的套接字 (`room:<roomId>:sockets` - Set):** 存储房间内客户端的 `socketId`。TTL 与房间 TTL 绑定。
- **套接字到房间映射 (`socket:<socketId>` - String):** 将 `socketId` 映射到其 `roomId`。TTL 受管理。
- **速率限制 (`ratelimit:join:<ipAddress>` - Sorted Set):** 跟踪加入操作的基于 IP 的请求时间戳以进行速率限制。TTL 受管理。
- **来源跟踪 (`referrers:daily:<YYYY-MM-DD>` - Hash):** 存储每日来源计数。TTL 为 30 天。
## 贡献
(贡献指南占位符 - 例如:fork、branch、PR、编码标准)
## 许可证
(许可证占位符 - 例如:MIT、Apache 2.0)
- 要深入理解后端的代码结构、模块设计和 Redis 数据模型,请阅读 [**后端架构详解**](../docs/BACKEND_ARCHITECTURE.zh-CN.md)。
- 要了解项目前后端的整体协作方式,请参阅 [**项目整体架构**](../docs/ARCHITECTURE.zh-CN.md)。
- 有关生产环境的部署方法,请参考 [**部署指南**](../docs/DEPLOYMENT.zh-CN.md)。
-361
View File
@@ -1,361 +0,0 @@
# Privydrop Backend Deployment Guide
This guide provides comprehensive instructions for deploying the Privydrop backend application, including setting up necessary services like Redis, TURN, and Nginx (for production environments).
## 1. Introduction
This document will guide you through the steps of preparing your server environment, configuring dependencies, and deploying the Privydrop backend. Whether you are setting up a development/testing environment or a full production instance, this guide aims to cover the essential aspects.
## 2. Prerequisites
Before you begin, ensure your server environment meets the following requirements:
- **Operating System:** A Linux distribution (e.g., Ubuntu 20.04 LTS or later is recommended).
- **Node.js:** v18.x or later.
- **npm (or yarn):** Package manager for Node.js.
- **Root or Sudo Privileges:** Required for installing packages and configuring services.
- **Optional: Base Environment & Docker Image Reference:** If you need to start from a very clean system environment or want to understand the base dependencies used for Docker builds, you can refer to the `backend/docker/Dockerfile` file (for Docker image construction) and the `backend/docker/env_install.log` file (which may contain dependency installation records for specific environments). For most standard Linux distributions, following the subsequent steps in this guide will suffice.
## 3. Dependency Services Installation and Configuration
The Privydrop backend relies on several external services.
### 3.1. Redis Server
Redis is used for room management, session information, and caching.
**Installation (Ubuntu Example):**
```bash
sudo apt update
sudo apt install redis-server
```
**Configuration:**
- By default, Redis listens on `127.0.0.1:6379` and does not require a password.
In this case, add the default Redis configuration to your environment variable file:
REDIS_HOST='localhost'
REDIS_PORT=6379
- If your Redis instance is on a different host, port, or requires a password, you will need to update the environment variables accordingly (see Section 4.3).
- Ensure Redis is running:
```bash
sudo systemctl status redis-server
# Or for older systems
# /etc/init.d/redis-server status
```
- If Redis is not running, start it:
```bash
sudo systemctl start redis-server
# Or
# sudo /etc/init.d/redis-server start
```
### 3.2. TURN/STUN Server (Coturn)
A TURN server is crucial for WebRTC to traverse NATs and firewalls, ensuring reliable peer-to-peer connections. Coturn is a popular open-source TURN server implementation.
**Installation (Ubuntu Example):**
```bash
sudo apt update
sudo apt install coturn
```
**Configuration:**
1. **Enable Coturn Service:**
Edit `/etc/default/coturn` and uncomment the line:
```
TURNSERVER_ENABLED=1
```
2. **Coturn Configuration Files:**
`docker/TURN/turnserver_production.conf` and `docker/TURN/turnserver_development.conf` are template configuration files for production and development environments, respectively. You do not need to modify them manually; just add the corresponding fields to your environment variable file (see step 6 in this section).
3. **Firewall Configuration:**
Open the necessary ports on your server's firewall (e.g., using `ufw`):
- **TCP & UDP `3478`**: For STUN and TURN.
- **TCP & UDP `5349`**: For TURNS (TURN over TLS/DTLS) - **Primarily for production environments**.
- **UDP `49152-65533`**: Coturn's default relay port range (configurable with `min-port` and `max-port` in `turnserver.conf`).
```bash
sudo ufw allow 3478
sudo ufw allow 5349 # For TURNS in production
sudo ufw allow 49152:65535/udp
sudo ufw enable
sudo ufw status
```
**Note:** The following configurations regarding SSL certificates and TURNS (steps 4 and 5) are primarily for **production environments**. If you are only setting up a development or testing environment and using unencrypted TURN (`turn:your_server_public_ip:3478`), you can skip these steps and only configure the development environment variables in step 6.
4. **SSL Certificate for Production (TURNS): (Production Step)**
If deploying for production and using `TURNS` (TURN over TLS), you will need an SSL certificate for your TURN domain (e.g., `turn.yourdomain.com`).
- Ensure you have a DNS 'A' record pointing `turn.yourdomain.com` to your server's public IP.
- Obtain a certificate using Certbot:
```bash
sudo apt install certbot
sudo certbot certonly --standalone -d turn.yourdomain.com
```
The certificate and private key are typically stored in `/etc/letsencrypt/live/turn.yourdomain.com/`.
5. **SSL Certificate Permissions (Production): (Production Step)**
The Coturn process (usually running as user `turnserver`) needs permission to read the SSL certificate and key.
- Check current permissions:
```bash
sudo ls -lh /etc/letsencrypt/live/turn.yourdomain.com/fullchain.pem
sudo ls -ld /etc/letsencrypt/archive/
```
- If Coturn logs show permission errors:
Create a group (e.g., `ssl-cert`), add `turnserver` to it, and adjust permissions:
```bash
sudo groupadd -f ssl-cert
# Find the user coturn runs as, usually 'turnserver' or 'coturn'
# ps aux | grep turnserver
sudo usermod -a -G ssl-cert turnserver # Replace 'turnserver' if different
sudo chown -R root:ssl-cert /etc/letsencrypt/
sudo chmod -R 750 /etc/letsencrypt/
```
Verify the new permissions on `/etc/letsencrypt/archive/` and `/etc/letsencrypt/live/`.
6. **Add Configuration to Environment Variable File:**
Modify your TURN server configuration information in the appropriate `.env` file.
- For **development/testing environments** (e.g., add the following to `.env.development.local`):
```env
# TURN Server Configuration (Development)
TURN_EXTERNAL_IP=YourServerPublicIP # e.g., 123.123.456.567
TURN_REALM=YourServerPublicIP
TURN_USERNAME=YourTurnUsername
TURN_PASSWORD=YourTurnPassword
```
- For **production environments** (e.g., add the following to `.env.production.local`):
```env
# TURN Server Configuration (Production)
TURN_EXTERNAL_IP=YourServerPublicIP # e.g., 123.123.456.567
TURN_REALM=turn.yourdomain
TURN_USERNAME=YourTurnUsername
TURN_PASSWORD=YourTurnPassword
TURN_CERT_PATH=/etc/letsencrypt/live/turn.yourdomain/fullchain.pem
TURN_KEY_PATH=/etc/letsencrypt/live/turn.yourdomain/privkey.pem
```
7. **Start/Restart and Test Coturn:**
```bash
# Replace "your_env_file_path" with the appropriate environment file path
# e.g.: sudo bash ./docker/TURN/configure.sh .env.development.local
# or: sudo bash ./docker/TURN/configure.sh .env.production.local
sudo bash ./docker/TURN/configure.sh your_env_file_path
sudo systemctl status coturn
```
Check `/var/log/turnserver.log` (or your Coturn log file path) for any errors.
**Test your TURN server:**
Use an online tool like the Metered TURN Server Tester (https://www.metered.ca/turn-server-testing):
- **For Development/Testing (non-TLS):**
- TURN URL: `YourServerPublicIP`
- TURN Port: `3478`
- Username: `YourTurnUsername`
- Password: `YourTurnPassword`
- **For Production (TURNS) (if configured):**
- TURNS URL: `turn.yourdomain`
- TURNS Port: `5349`
- Username: `YourTurnUsername`
- Password: `YourTurnPassword`
Look for "Success" or "Reachable" messages.
### 3.3. Nginx (Reverse Proxy - Production Environment)
**Note: This section is entirely for production environments. If you are setting up a development or testing environment and not using Nginx as a reverse proxy, you can skip this entire Section 3.3.**
It is recommended to use Nginx as a reverse proxy in production environments to handle SSL termination, serve static files (if applicable), and enable HTTP/3.
**Installation (with HTTP/3 support, Ubuntu Example):**
Reference: https://nginx.org/en/linux_packages.html#Ubuntu
1. **Install prerequisites:**
```bash
sudo apt install curl gnupg2 ca-certificates lsb-release ubuntu-keyring
```
2. **Import Nginx signing key:**
```bash
curl https://nginx.org/keys/nginx_signing.key | gpg --dearmor \
| sudo tee /usr/share/keyrings/nginx-archive-keyring.gpg >/dev/null
```
3. **Verify the key:**
```bash
gpg --dry-run --quiet --no-keyring --import --import-options import-show /usr/share/keyrings/nginx-archive-keyring.gpg
# Expected fingerprint: 573BFD6B3D8FBC641079A6ABABF5BD827BD9BF62
```
4. **Set up the apt repository for stable Nginx packages:**
```bash
echo "deb [signed-by=/usr/share/keyrings/nginx-archive-keyring.gpg] \
http://nginx.org/packages/ubuntu `lsb_release -cs` nginx" \
| sudo tee /etc/apt/sources.list.d/nginx.list
```
5. **Set up repository pinning:**
```bash
echo -e "Package: *\nPin: origin nginx.org\nPin: release o=nginx\nPin-Priority: 900\n" \
| sudo tee /etc/apt/preferences.d/99nginx
```
6. **Install Nginx:**
```bash
sudo apt update
sudo apt install nginx
```
**Configuration (Production Environment):**
1. **Firewall Configuration:**
- TCP `80` (for HTTP, redirects to HTTPS)
- TCP `443` (for HTTPS)
- UDP `443` (for HTTP/3 QUIC)
```bash
sudo ufw allow 'Nginx Full' # Allows HTTP and HTTPS
sudo ufw allow 443/udp # For HTTP/3
sudo ufw status
```
2. **Main Domain SSL Certificate:**
Obtain SSL certificates for your main application domain (e.g., `yourdomain.com` and `www.yourdomain.com`).
```bash
# Ensure certbot is installed and configured to work with Nginx
sudo apt install python3-certbot-nginx
sudo certbot --nginx -d yourdomain.com -d www.yourdomain.com
```
Follow the prompts. This will also attempt to configure Nginx for SSL.
3. **Nginx Configuration:**
`docker/Nginx/default` is an Nginx configuration template. You do not need to modify this file manually. Instead, add the following configuration to your production environment file `.env.production.local`:
```env
# Nginx Configuration (Production)
NGINX_SERVER_NAME=yourdomain # Without www prefix, yourdomain includes the suffix
NGINX_SSL_CERT=/etc/letsencrypt/live/yourdomain/fullchain.pem
NGINX_SSL_KEY=/etc/letsencrypt/live/yourdomain/privkey.pem
NGINX_FRONTEND_ROOT=/path/to/your/frontend/build # Path to your frontend static build artifacts
```
4. **Apply Nginx Configuration and Restart:**
```bash
# This script will use the NGINX_* variables from .env.production.local to generate the Nginx config file
sudo bash docker/Nginx/configure.sh .env.production.local
```
## 4. Backend Application Deployment
### 4.1. Get the Code
Clone your repository to the server:
```bash
git clone <your-repository-url> privydrop
cd privydrop/backend
```
### 4.2. Install Dependencies
```bash
npm install
```
### 4.3. Environment Variable Configuration
The backend application relies on environment variables to run. Create and configure the appropriate `.env` file in the `privydrop/backend` directory based on your deployment environment (development/testing or production).
- **Development/Testing Environment**: Create an `.env.development.local` file.
- **Production Environment**: Create an `.env.production.local` file. **(Production Step)**
Add the following basic backend-related configurations to the corresponding `.env` file:
```env
NODE_ENV=development # or production
BACKEND_PORT=3001
CORS_ORIGIN=http://localhost:3000 # Development example, should be https://www.yourdomain for production
```
**Important:** Ensure that the Redis and TURN server related environment variables discussed in **Section 3.1 (Redis)** and **Section 3.2 (TURN Server)** have also been correctly added to the respective `.env.development.local` or `.env.production.local` file.
For the **production environment (`.env.production.local`)**, make sure all configurations (e.g., `NODE_ENV=production`, production TURN URL, production CORS origin, etc.) are set correctly.
### 4.4. Start Development/Test Server
After completing the development environment configuration (`.env.development.local`), you can start the backend service for development or testing using the following command:
```bash
# Ensure you are in the privydrop/backend directory
npm run dev
```
This command typically uses the configuration from `.env.development.local`.
### 4.5. Production Deployment (Using PM2)
**Note: This section describes how to deploy in a production environment using PM2. If you are only setting up a development/testing environment, you can skip this section.**
PM2 is a production process manager for Node.js applications and is recommended for production deployments.
1. **Install PM2 globally:**
```bash
sudo npm install -g pm2
```
2. **Start the application using the `ecosystem.config.js` file:**
The `backend/ecosystem.config.js` file in the project root is the configuration file for PM2.
```bash
# Ensure you are in the privydrop/backend directory
# cd /path/to/privydrop/backend
# Before starting, ensure .env.production.local is configured for production
sudo pm2 start ecosystem.config.js
```
If you have a previously running instance with the same name (e.g., `signaling-server` defined in `ecosystem.config.js`):
```bash
sudo pm2 stop signaling-server && sudo pm2 delete signaling-server
sudo pm2 start ecosystem.config.js
```
3. **Check application status and logs:**
```bash
sudo pm2 list
sudo pm2 logs signaling-server # Or the name defined in your ecosystem file
sudo pm2 monit
```
4. **Enable PM2 to start on boot:**
```bash
sudo pm2 startup
# Follow the instructions provided by the command (usually involves running another command it outputs)
sudo pm2 save # Save the current process list
```
## 5. Dockerized Deployment (Currently Not Fully Supported)
While this guide focuses on traditional deployment, you can also containerize the Privydrop backend. `backend/docker/Dockerfile` provides a record of the basic environment build process.
**Note:** This deployment method is currently mainly for reference, and official support is not yet complete. Docker deployment for production requires more detailed planning, including using `docker-compose` to orchestrate the backend application, Nginx (either within Docker or as a reverse proxy on the host), Redis, and potentially Coturn (although Coturn is often run directly on the host for better network access). Managing SSL certificates and network configurations in a Dockerized environment requires careful planning.
## 6. Security and Maintenance
- **SSL Certificate Renewal (Production Related):** You can refer to the `backend/docker/Nginx/renew_ssl.sh` script for automatic renewal.
- **Firewall:** Keep firewall rules strict, allowing only necessary ports.
## 7. Troubleshooting
- **Connection Issues:** Check firewall rules, Nginx proxy settings (production), `CORS_ORIGIN` in the backend `.env` file, and ensure all services (Redis, Coturn, Node.js app) are running and configured correctly.
- **Nginx Errors (Production):** `sudo nginx -t` will check configuration syntax. Check Nginx error logs (usually in `/var/log/nginx/error.log`).
- **PM2 Issues (Production):** Use `pm2 logs <app_name>` to view application errors.
- **Certificate Permissions (Production):** If Coturn or Nginx cannot read SSL certificates, double-check file permissions and user/group settings.
- **Coturn Logs:** Check `/var/log/turnserver.log` (or the Coturn log path on your system) for Coturn service-related errors.
-363
View File
@@ -1,363 +0,0 @@
# Privydrop 后端部署指南
本指南提供部署 Privydrop 后端应用程序的全面说明,包括设置 Redis、TURN 和 Nginx(用于生产环境)等必要服务。
## 1. 引言
本文档将引导您完成准备服务器环境、配置依赖项和部署 Privydrop 后端的步骤。无论您是设置开发/测试环境还是完整的生产实例,本指南都旨在涵盖基本方面。
## 2. 先决条件
在开始之前,请确保您的服务器环境满足以下要求:
- **操作系统:** Linux 发行版(例如,推荐 Ubuntu 20.04 LTS 或更高版本)。
- **Node.js** v18.x 或更高版本。
- **npm (或 yarn)** Node.js 的包管理器。
- **Root 或 Sudo 权限:** 安装软件包和配置服务所需。
- **可选:基础环境与 Docker 镜像参考:** 如果您需要从一个非常纯净的系统环境开始搭建,或者希望了解用于 Docker 构建的基础依赖,可以参考 `backend/docker/Dockerfile` 文件(用于 Docker 镜像构建)和 `backend/docker/env_install.log` 文件(可能包含特定环境下的依赖安装记录)。对于大多数标准 Linux 发行版,遵循本指南后续步骤即可。
## 3. 依赖服务安装与配置
Privydrop 后端依赖于多个外部服务。
### 3.1. Redis 服务器
Redis 用于房间管理、会话信息和缓存。
**安装 (Ubuntu 示例)**
```bash
sudo apt update
sudo apt install redis-server
```
**配置:**
- 默认情况下,Redis 监听 `127.0.0.1:6379` 并且不需要密码。
则将 redis 默认配置放到环境变量配置文件中,内容为:
REDIS_HOST='localhost'
REDIS_PORT=6379
- 如果您的 Redis 实例位于不同的主机、端口或需要密码,则需要相应地更新环境变量(参见第 4.3 节)。
- 确保 Redis 正在运行:
```bash
sudo systemctl status redis-server
# 或对于旧系统
# /etc/init.d/redis-server status
```
- 如果 Redis 未运行,则启动它:
```bash
sudo systemctl start redis-server
# 或
# sudo /etc/init.d/redis-server start
```
### 3.2. TURN/STUN 服务器 (Coturn)
**重要提示:本节为可选配置。** Privydrop 默认仅使用公共 STUN 服务器,在多数网络环境下足以建立连接。对于初次体验、开发测试,或部署于网络限制不严格的环境,**您可以跳过本节**。只有当您对 NAT 穿透成功率有极高要求时,才需要搭建自己的 TURN 服务器。
TURN 服务器对于 WebRTC 穿透 NAT 和防火墙至关重要,可确保可靠的点对点连接。Coturn 是一个流行的开源 TURN 服务器实现。
**安装 (Ubuntu 示例)**
```bash
sudo apt update
sudo apt install coturn
```
**配置:**
1. **启用 Coturn 服务:**
编辑 `/etc/default/coturn` 并取消注释该行:
```
TURNSERVER_ENABLED=1
```
2. **Coturn 配置文件:**
`docker/TURN/turnserver_production.conf` 和 `docker/TURN/turnserver_development.conf` 是生产和开发环境对应的模板配置文件,你不需要手动修改,只需要在环境变量配置文件中加入对应的字段就行(详见本节步骤 6)。
3. **防火墙配置:**
在服务器的防火墙上打开必要的端口 (例如,使用 `ufw`)
- **TCP & UDP `3478`**: 用于 STUN 和 TURN。
- **TCP & UDP `5349`**: 用于 TURNS (TURN over TLS/DTLS) - **主要用于生产环境**。
- **UDP `49152-65533`**: Coturn 的默认中继端口范围 (可在 `turnserver.conf` 中使用 `min-port` 和 `max-port` 配置)。
```bash
sudo ufw allow 3478
sudo ufw allow 5349 # 用于生产环境的 TURNS
sudo ufw allow 49152:65535/udp
sudo ufw enable
sudo ufw status
```
**注意:** 以下关于 SSL 证书和 TURNS 的配置(步骤 4 和步骤 5)主要针对**生产环境**。如果仅设置开发或测试环境,并使用非加密的 TURN (`turn:你的服务器公网IP:3478`),则可以跳过这些步骤,并在步骤 6 中仅配置开发环境所需的变量。
4. **生产环境的 SSL 证书 (TURNS)(生产环境步骤)**
如果为生产环境部署并使用 `TURNS` (TURN over TLS),您需要为您的 TURN 域名(例如 `turn.yourdomain.com`)准备 SSL 证书。
- 确保您有一个 DNS 'A' 记录将 `turn.yourdomain.com` 指向您服务器的公网 IP。
- 使用 Certbot 获取证书:
```bash
sudo apt install certbot
sudo certbot certonly --standalone -d turn.yourdomain.com
```
证书和私钥通常存储在 `/etc/letsencrypt/live/turn.yourdomain.com/`。
5. **SSL 证书权限 (生产环境):(生产环境步骤)**
Coturn 进程(通常以用户 `turnserver` 运行)需要读取 SSL 证书和密钥的权限。
- 检查当前权限:
```bash
sudo ls -lh /etc/letsencrypt/live/turn.yourdomain.com/fullchain.pem
sudo ls -ld /etc/letsencrypt/archive/
```
- 如果 Coturn 日志显示权限错误:
创建一个组(例如 `ssl-cert`),将 `turnserver` 添加到该组,并调整权限:
```bash
sudo groupadd -f ssl-cert
# 查找 coturn 运行的用户,通常是 'turnserver' 或 'coturn'
# ps aux | grep turnserver
sudo usermod -a -G ssl-cert turnserver # 如果不同,请替换 'turnserver'
sudo chown -R root:ssl-cert /etc/letsencrypt/
sudo chmod -R 750 /etc/letsencrypt/
```
验证 `/etc/letsencrypt/archive/` 和 `/etc/letsencrypt/live/` 上的新权限。
6. **填写配置到环境变量文件**
在相应的 `.env` 文件中修改您的 TURN 服务器配置信息。
- 对于**开发/测试环境** (例如,在 `.env.development.local` 文件中加入如下内容)
```env
# TURN Server Configuration (Development)
TURN_EXTERNAL_IP=YourServerPublicIP # 例如: 123.123.456.567
TURN_REALM=YourServerPublicIP
TURN_USERNAME=YourTurnUsername
TURN_PASSWORD=YourTurnPassword
```
- 对于**生产环境** (例如,在 `.env.production.local` 文件中加入如下内容)
```env
# TURN Server Configuration (Production)
TURN_EXTERNAL_IP=YourServerPublicIP # 例如: 123.123.456.567
TURN_REALM=turn.yourdomain
TURN_USERNAME=YourTurnUsername
TURN_PASSWORD=YourTurnPassword
TURN_CERT_PATH=/etc/letsencrypt/live/turn.yourdomain/fullchain.pem
TURN_KEY_PATH=/etc/letsencrypt/live/turn.yourdomain/privkey.pem
```
7. **启动/重启并测试 Coturn**
```bash
# 使用适当的环境变量文件路径替换 "your_env_file_path"
# 例如: sudo bash ./docker/TURN/configure.sh .env.development.local
# 或: sudo bash ./docker/TURN/configure.sh .env.production.local
sudo bash ./docker/TURN/configure.sh your_env_file_path
sudo systemctl status coturn
```
检查 `/var/log/turnserver.log` (或 Coturn 日志文件路径) 中是否有任何错误。
**测试您的 TURN 服务器:**
使用在线工具,如 Metered TURN Server Tester (https://www.metered.ca/turn-server-testing)
- **用于开发/测试 (非 TLS)**
- TURN URL: `你的服务器公网IP`
- TURN Port: `3478`
- 用户名: `你的Turn用户名`
- 密码: `你的Turn密码`
- **用于生产 (TURNS) (若已配置)**
- TURNS URL: `turn.yourdomain`
- TURNS Port: `5349`
- 用户名: `你的Turn用户名`
- 密码: `你的Turn密码`
查找 "Success" 或 "Reachable" 消息。
### 3.3. Nginx (反向代理 - 生产环境)
**注意:本节内容完全针对生产环境。如果您正在设置开发或测试环境,并且不使用 Nginx 作为反向代理,则可以跳过此整个 3.3 节。**
建议在生产环境中使用 Nginx 作为反向代理,处理 SSL 终止、提供静态文件(如果适用)并启用 HTTP/3。
**安装 (支持 HTTP/3Ubuntu 示例)**
参考: https://nginx.org/en/linux_packages.html#Ubuntu
1. **安装先决条件:**
```bash
sudo apt install curl gnupg2 ca-certificates lsb-release ubuntu-keyring
```
2. **导入 Nginx 签名密钥:**
```bash
curl https://nginx.org/keys/nginx_signing.key | gpg --dearmor \
| sudo tee /usr/share/keyrings/nginx-archive-keyring.gpg >/dev/null
```
3. **验证密钥:**
```bash
gpg --dry-run --quiet --no-keyring --import --import-options import-show /usr/share/keyrings/nginx-archive-keyring.gpg
# 期望指纹: 573BFD6B3D8FBC641079A6ABABF5BD827BD9BF62
```
4. **为稳定版 Nginx 包设置 apt 仓库:**
```bash
echo "deb [signed-by=/usr/share/keyrings/nginx-archive-keyring.gpg] \
http://nginx.org/packages/ubuntu `lsb_release -cs` nginx" \
| sudo tee /etc/apt/sources.list.d/nginx.list
```
5. **设置仓库 pinning**
```bash
echo -e "Package: *\nPin: origin nginx.org\nPin: release o=nginx\nPin-Priority: 900\n" \
| sudo tee /etc/apt/preferences.d/99nginx
```
6. **安装 Nginx**
```bash
sudo apt update
sudo apt install nginx
```
**配置 (生产环境)**
1. **防火墙配置:**
- TCP `80` (用于 HTTP,重定向到 HTTPS)
- TCP `443` (用于 HTTPS)
- UDP `443` (用于 HTTP/3 QUIC)
```bash
sudo ufw allow 'Nginx Full' # 允许 HTTP 和 HTTPS
sudo ufw allow 443/udp # 用于 HTTP/3
sudo ufw status
```
2. **主域名 SSL 证书:**
为您的主应用程序域名(例如 `yourdomain.com` 和 `www.yourdomain.com`)获取 SSL 证书。
```bash
# 确保已安装 certbot 并配置为与 Nginx 一起使用
sudo apt install python3-certbot-nginx
sudo certbot --nginx -d yourdomain.com -d www.yourdomain.com
```
按照提示操作。这也会尝试为 SSL 配置 Nginx。
3. **Nginx 配置:**
`docker/Nginx/default` 是 Nginx 配置模板。您不需要手动修改该文件,只需要将以下配置添加到生产环境变量文件 `.env.production.local` 中:
```env
# Nginx Configuration (Production)
NGINX_SERVER_NAME=yourdomain # 不带 www 前缀,yourdomain包含了后缀
NGINX_SSL_CERT=/etc/letsencrypt/live/yourdomain/fullchain.pem
NGINX_SSL_KEY=/etc/letsencrypt/live/yourdomain/privkey.pem
NGINX_FRONTEND_ROOT=/path/to/your/frontend/build # 前端静态文件构建产物的路径
```
4. **应用 Nginx 配置并重启:**
```bash
# 此脚本会使用 .env.production.local 中的 NGINX_* 变量来生成 Nginx 配置文件
sudo bash docker/Nginx/configure.sh .env.production.local
```
## 4. 后端应用部署
### 4.1. 获取代码
将您的仓库克隆到服务器:
```bash
git clone <your-repository-url> privydrop
cd privydrop/backend
```
### 4.2. 安装依赖
```bash
npm install
```
### 4.3. 环境变量配置
后端应用的运行依赖于环境变量。请根据您的部署环境(开发/测试或生产)在 `privydrop/backend` 目录下创建并配置相应的 `.env` 文件。
- **开发/测试环境**: 创建 `.env.development.local` 文件。
- **生产环境**: 创建 `.env.production.local` 文件。 **(生产环境步骤)**
在对应的 `.env` 文件中加入以下与后端相关的基本配置内容:
```env
NODE_ENV=development # 或 production
BACKEND_PORT=3001
CORS_ORIGIN=http://localhost:3000 # 开发环境示例, 生产环境应为 https://www.yourdomain
```
**重要提示:** 请确保之前在 **第 3.1 节 (Redis)** 和 **第 3.2 节 (TURN 服务器)** 中讨论的 Redis 和 TURN 服务器相关环境变量也已正确添加到相应的 `.env.development.local` 或 `.env.production.local` 文件中。
对于**生产环境 (`.env.production.local`)**,请务必确认所有配置(如 `NODE_ENV=production`,生产 TURN URL,生产 CORS origin 等)均已正确设置。
### 4.4. 启动开发/测试服务器
完成开发环境配置 (`.env.development.local`) 后,可以使用以下命令启动后端服务进行开发或测试:
```bash
# 确保您在 privydrop/backend 目录下
npm run dev
```
此命令通常会使用 `.env.development.local` 中的配置。
### 4.5. 生产环境部署 (使用 PM2)
**注意:本节介绍如何使用 PM2 进行生产环境部署。如果仅设置开发/测试环境,可以跳过此节。**
PM2 是 Node.js 应用程序的生产流程管理器,建议用于生产部署。
1. **全局安装 PM2**
```bash
sudo npm install -g pm2
```
2. **使用 `ecosystem.config.js` 文件启动应用程序:**
项目根目录下的 `backend/ecosystem.config.js` 是 PM2 的配置文件。
```bash
# 确保您在 privydrop/backend 目录下
# cd /path/to/privydrop/backend
# 启动前,请确保 .env.production.local 文件已按生产环境要求配置完毕
sudo pm2 start ecosystem.config.js
```
如果您先前运行的实例具有相同的名称(例如,在 `ecosystem.config.js` 中定义的 `signaling-server`):
```bash
sudo pm2 stop signaling-server && sudo pm2 delete signaling-server
sudo pm2 start ecosystem.config.js
```
3. **检查应用程序状态和日志:**
```bash
sudo pm2 list
sudo pm2 logs signaling-server # 或您 ecosystem 文件中定义的名称
sudo pm2 monit
```
4. **使 PM2 能够开机自启:**
```bash
sudo pm2 startup
# 遵循命令提供的说明 (通常涉及运行它输出的另一个命令)
sudo pm2 save # 保存当前进程列表
```
## 5. Docker 化部署 (目前暂不支持)
虽然本指南侧重于传统部署,但您也可以将 Privydrop 后端容器化。`backend/docker/Dockerfile` 提供了基本的环境构建过程记录。
**注意:** 此部署方式当前主要供参考,官方支持尚不完善。生产环境的 Docker 部署需要更详细的规划,包括使用 `docker-compose` 来编排后端应用程序、Nginx(作为 Docker 内或主机上的反向代理)、Redis 以及可能的 Coturn(尽管 Coturn 通常直接在主机上运行以获得更好的网络访问效果)。在 Docker 化环境中管理 SSL 证书和网络配置需要仔细规划。
## 6. 安全与维护
- **SSL 证书续订 (生产环境相关):** 可以参考 `backend/docker/Nginx/renew_ssl.sh` 脚本进行自动续订。
- **防火墙:** 保持防火墙规则严格,仅允许必要的端口。
## 7. 故障排除
- **连接问题:** 检查防火墙规则、Nginx 代理设置(生产环境)、后端 `.env` 文件中的 `CORS_ORIGIN`,并确保所有服务(Redis、Coturn、Node.js 应用)都在运行且配置正确。
- **Nginx 错误 (生产环境)** `sudo nginx -t` 将检查配置语法。检查 Nginx 错误日志 (通常在 `/var/log/nginx/error.log`)。
- **PM2 问题 (生产环境)** 使用 `pm2 logs <app_name>` 查看应用程序错误。
- **证书权限 (生产环境)** 如果 Coturn 或 Nginx 无法读取 SSL 证书,请仔细检查文件权限和用户/组设置。
- **Coturn 日志:** 检查 `/var/log/turnserver.log` (或您系统中 Coturn 的日志路径) 获取 Coturn 服务相关的错误信息。
+46
View File
@@ -0,0 +1,46 @@
# PrivyDrop - 前端
这是 PrivyDrop 的前端部分,一个使用 Next.js 构建的、基于 WebRTC 的隐私文件分享应用。
## 🛠️ 技术栈
- **前端框架**: Next.js 14 (App Router)
- **UI 框架**: React 18 + TypeScript
- **样式**: Tailwind CSS + shadcn/ui
- **P2P 传输**: WebRTC
- **信令服务客户端**: Socket.IO Client
- **国际化**: next-intl
## 🚀 本地开发
开始前,请确保你已经根据项目根目录 `README.md` 的指引,**安装并启动了后端服务**。
1. **进入目录**
```bash
# 假设你当前在项目根目录
cd frontend
```
2. **安装依赖**
```bash
pnpm install
```
3. **配置环境变量**
在 `frontend/` 目录下创建 `.env.development.local` 文件,并填入开发所需的环境变量,至少需要指定后端 API 的地址:
```ini
NEXT_PUBLIC_API_URL=http://localhost:3001
```
4. **启动开发服务器**
```bash
pnpm dev
```
5. 在浏览器中打开 `http://localhost:3000` 即可看到应用界面。
## 📚 详细文档
- 要了解完整的项目架构和组件协作方式,请参阅 [**项目整体架构**](../docs/ARCHITECTURE.zh-CN.md)。
- 要深入理解前端的代码结构、Hooks 设计和状态管理,请阅读 [**前端架构详解**](../docs/FRONTEND_ARCHITECTURE.zh-CN.md)。
- 有关生产环境的部署方法,请参考 [**部署指南**](../docs/DEPLOYMENT.zh-CN.md)。
## 🤝 参与贡献
我们欢迎任何形式的贡献!请阅读根目录下的 [**贡献指南**](../.github/CONTRIBUTING.md) 来开始。