更新文档
This commit is contained in:
+46
-62
@@ -1,36 +1,36 @@
|
||||
# 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.
|
||||
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:** Facilitates peer-to-peer connections using Socket.IO for exchanging SDP offers, answers, and ICE candidates.
|
||||
- **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 the frontend to interact with (e.g., creating/joining rooms, checking room availability).
|
||||
- **Real-time Communication:** Uses Socket.IO for instant messaging between clients and server.
|
||||
- **Rate Limiting:** Basic IP-based rate limiting for certain operations to prevent abuse.
|
||||
- **Ephemeral Data Storage:** Leverages Redis for storing temporary data like room information and session details, with automatic expiry.
|
||||
- **Referrer Tracking:** Basic daily tracking of traffic sources (referrers).
|
||||
- **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 typing.
|
||||
- **Socket.IO:** Library for real-time, bidirectional event-based communication.
|
||||
- **Redis:** In-memory data structure store, used for caching, session management, and message brokering.
|
||||
- **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 to load environment variables from a `.env` file.
|
||||
- **dotenv:** Module for loading environment variables from an `.env` file.
|
||||
- **PM2 (Ecosystem file provided):** Production process manager for Node.js applications.
|
||||
- **Docker:** Containerization platform.
|
||||
|
||||
## Project Structure
|
||||
|
||||
The backend source code is primarily located in the `src/` directory:
|
||||
.
|
||||
├── DEPLOYMENT.md
|
||||
├── docker # Docker related files (Dockerfile, Nginx/TURN configs if used).
|
||||
├── README.md
|
||||
├── README.zh-CN.md
|
||||
├── docker # Docker-related files (Dockerfile, Nginx/TURN configurations, etc.).
|
||||
│ ├── Dockerfile
|
||||
│ ├── env_install.log
|
||||
│ ├── Nginx
|
||||
@@ -44,25 +44,23 @@ The backend source code is primarily located in the `src/` directory:
|
||||
│ ├── turnserver_development.conf
|
||||
│ └── turnserver_production.conf
|
||||
├── docs
|
||||
│ ├── host_preparation.md
|
||||
│ └── turn_nginx_notes.md
|
||||
│ ├── DEPLOYMENT_GUIDE.en-US.md
|
||||
│ └── DEPLOYMENT_GUIDE.zh-CN.md
|
||||
├── ecosystem.config.js
|
||||
├── package.json
|
||||
├── package-lock.json
|
||||
├── readme.md
|
||||
├── README.md
|
||||
├── scripts
|
||||
│ ├── del_logs.js
|
||||
│ ├── export-tracking-data.js
|
||||
│ └── redis-monitor.js
|
||||
├── src
|
||||
│ ├── config # Environment variables and server configurations (CORS).
|
||||
│ ├── config # Environment variables and server configuration (CORS).
|
||||
│ │ ├── env.ts
|
||||
│ │ └── server.ts
|
||||
│ ├── routes # API route definitions (Express routers).
|
||||
│ ├── 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 interactions, rate limiting).
|
||||
│ ├── services # Core business logic (room management, Redis interaction, rate limiting).
|
||||
│ │ ├── rateLimit.ts
|
||||
│ │ ├── redis.ts
|
||||
│ │ └── room.ts
|
||||
@@ -79,23 +77,30 @@ The backend source code is primarily located in the `src/` directory:
|
||||
- npm or yarn
|
||||
- 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
|
||||
|
||||
Create a `.env.development.local` file in the `backend/` directory for local development (or `.env.production.local` for production-like environments). Populate it with the following 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 # URL of your frontend application
|
||||
CORS_ORIGIN=http://localhost:3000 # Your frontend application URL
|
||||
|
||||
# Redis Configuration
|
||||
REDIS_HOST=127.0.0.1 # Or your Redis server host
|
||||
REDIS_PORT=6379 # Or your Redis server port
|
||||
# REDIS_PASSWORD=your_redis_password # Optional: if your Redis is password protected (code needs adjustment to use this)
|
||||
REDIS_HOST=127.0.0.1
|
||||
REDIS_PORT=6379
|
||||
# REDIS_PASSWORD=your_redis_password # Uncomment and set if your Redis is password-protected
|
||||
```
|
||||
|
||||
**Note:** The application will exit on startup if `REDIS_HOST` or `REDIS_PORT` are not defined.
|
||||
**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)
|
||||
|
||||
@@ -110,36 +115,15 @@ REDIS_PORT=6379 # Or your Redis server port
|
||||
# or
|
||||
yarn install
|
||||
```
|
||||
4. **Ensure Redis is running** and accessible with the credentials provided in your `.env` file.
|
||||
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 in your `PORT` environment variable (defaults to 3001).
|
||||
The server should start on the port specified by your `PORT` environment variable (defaults to 3001).
|
||||
|
||||
## Docker Deployment
|
||||
|
||||
1. **Navigate to the `backend/` directory.** (This assumes your `Dockerfile` is in `backend/docker/Dockerfile` but the build context is `backend/`)
|
||||
2. **Build the Docker image:**
|
||||
```bash
|
||||
docker build -t privydrop-backend -f docker/Dockerfile .
|
||||
```
|
||||
3. **Run the Docker container:**
|
||||
```bash
|
||||
docker run -d \
|
||||
-p 3001:3001 \
|
||||
--name privydrop-backend-container \
|
||||
-e PORT=3001 \
|
||||
-e NODE_ENV=production \
|
||||
-e CORS_ORIGIN="http://your-frontend-domain.com" \
|
||||
-e REDIS_HOST="your-redis-host" \
|
||||
-e REDIS_PORT="your-redis-port" \
|
||||
privydrop-backend
|
||||
```
|
||||
- Adjust `-p` if your internal `PORT` differs or you want to map to a different host port.
|
||||
- Replace placeholder values for environment variables (`-e`).
|
||||
- For a production setup, you'll likely use Docker Compose and might run Nginx as a reverse proxy and a TURN server. Refer to configurations in the `backend/docker/nginx/` and `backend/docker/turn/` directories (if you structure them as suggested) and potentially a `docker-compose.yml` file.
|
||||
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
|
||||
|
||||
@@ -153,11 +137,11 @@ All API endpoints are prefixed with `/api`.
|
||||
- Generates a unique, available room ID and creates the room.
|
||||
- Response: `{ "roomId": "string" }`
|
||||
- **`POST /api/check_room`**
|
||||
- Checks if a given `roomId` is available (i.e., does not exist).
|
||||
- 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 statistics in Redis with a 30-day TTL.
|
||||
- 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)
|
||||
@@ -179,9 +163,9 @@ The server listens for and emits the following Socket.IO events for WebRTC signa
|
||||
- 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 it's online/ready in a room.
|
||||
- **`initiator-online`**: (Custom) Initiator signals online/ready status in the room.
|
||||
- Data: `{ roomId: string }`
|
||||
- **`recipient-ready`**: (Custom) Recipient signals it's ready in a room.
|
||||
- **`recipient-ready`**: (Custom) Recipient signals ready status in the room.
|
||||
- Data: `{ roomId: string, peerId: string }`
|
||||
|
||||
**Server-to-Client Events:**
|
||||
@@ -196,7 +180,7 @@ The server listens for and emits the following Socket.IO events for WebRTC signa
|
||||
- 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 an initiator is online in the room.
|
||||
- **`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)
|
||||
@@ -207,11 +191,11 @@ The server listens for and emits the following Socket.IO events for WebRTC signa
|
||||
|
||||
Redis is used for:
|
||||
|
||||
- **Room Information (`room:<roomId>` - Hash):** Stores room creation time. TTL managed.
|
||||
- **Sockets in Room (`room:<roomId>:sockets` - Set):** Stores `socketId`s of clients in a room. TTL tied to room TTL.
|
||||
- **Socket to Room Mapping (`socket:<socketId>` - String):** Maps a `socketId` to its `roomId`. TTL managed.
|
||||
- **Rate Limiting (`ratelimit:join:<ipAddress>` - Sorted Set):** Tracks request timestamps for IP-based rate limiting on join operations. TTL managed.
|
||||
- **Referrer Tracking (`referrers:daily:<YYYY-MM-DD>` - Hash):** Stores daily counts of referrers. TTL of 30 days.
|
||||
- **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
|
||||
|
||||
|
||||
+19
-35
@@ -23,13 +23,13 @@
|
||||
- **CORS:** 用于启用跨域资源共享的中间件。
|
||||
- **dotenv:** 用于从 `.env` 文件加载环境变量的模块。
|
||||
- **PM2 (已提供 Ecosystem 文件):** Node.js 应用程序的生产流程管理器。
|
||||
- **Docker:** 容器化平台。
|
||||
|
||||
## 项目结构
|
||||
|
||||
后端源代码主要位于 `src/` 目录中:
|
||||
.
|
||||
├── DEPLOYMENT.md
|
||||
├── README.md
|
||||
├── README.zh-CN.md
|
||||
├── docker # Docker 相关文件 (Dockerfile, Nginx/TURN 配置等)。
|
||||
│ ├── Dockerfile
|
||||
│ ├── env_install.log
|
||||
@@ -44,13 +44,11 @@
|
||||
│ ├── turnserver_development.conf
|
||||
│ └── turnserver_production.conf
|
||||
├── docs
|
||||
│ ├── host_preparation.md
|
||||
│ └── turn_nginx_notes.md
|
||||
│ ├── DEPLOYMENT_GUIDE.en-US.md
|
||||
│ └── DEPLOYMENT_GUIDE.zh-CN.md
|
||||
├── ecosystem.config.js
|
||||
├── package.json
|
||||
├── package-lock.json
|
||||
├── readme.md
|
||||
├── README.md
|
||||
├── scripts
|
||||
│ ├── del_logs.js
|
||||
│ ├── export-tracking-data.js
|
||||
@@ -79,9 +77,13 @@
|
||||
- npm 或 yarn
|
||||
- 一个正在运行的 Redis 实例
|
||||
|
||||
有关详细的依赖服务安装和配置(如 Redis, TURN/STUN 服务器)以及生产环境部署指南,请参阅 [部署指南](./docs/DEPLOYMENT_GUIDE.zh-CN.md)。
|
||||
|
||||
## 环境变量
|
||||
|
||||
在 `backend/` 目录中创建一个 `.env.development.local` 文件用于本地开发(或为类生产环境创建 `.env.production.local` 文件)。用以下变量填充它:
|
||||
应用程序的运行依赖于环境变量。简化的本地开发环境配置如下:
|
||||
|
||||
在 `backend/` 目录中创建一个 `.env.development.local` 文件,并填充以下基本变量:
|
||||
|
||||
```ini
|
||||
# 服务器配置
|
||||
@@ -90,12 +92,15 @@ NODE_ENV=development # 或 production
|
||||
CORS_ORIGIN=http://localhost:3000 # 你的前端应用程序 URL
|
||||
|
||||
# Redis 配置
|
||||
REDIS_HOST=127.0.0.1 # 或者你的 Redis 服务器主机
|
||||
REDIS_PORT=6379 # 或者你的 Redis 服务器端口
|
||||
# REDIS_PASSWORD=your_redis_password # 可选:如果你的 Redis 受密码保护(代码需要调整才能使用)
|
||||
REDIS_HOST=127.0.0.1
|
||||
REDIS_PORT=6379
|
||||
# REDIS_PASSWORD=your_redis_password # 如果 Redis 受密码保护,请取消注释并设置
|
||||
```
|
||||
|
||||
**注意:** 如果未定义 `REDIS_HOST` 或 `REDIS_PORT`,应用程序将在启动时退出。
|
||||
**注意:**
|
||||
|
||||
- 如果未定义 `REDIS_HOST` 或 `REDIS_PORT`,应用程序将在启动时退出。
|
||||
- 更全面的环境变量配置(包括 TURN 服务器、生产特定设置等)请参考 [部署指南](./docs/DEPLOYMENT_GUIDE.zh-CN.md) 的第 4.3 节。
|
||||
|
||||
## 入门 (本地开发)
|
||||
|
||||
@@ -110,7 +115,7 @@ REDIS_PORT=6379 # 或者你的 Redis 服务器端口
|
||||
# 或
|
||||
yarn install
|
||||
```
|
||||
4. **确保 Redis 正在运行**,并且可以使用您在 `.env` 文件中提供的凭据进行访问。
|
||||
4. **确保 Redis 正在运行**,并且可以使用您在 `.env` 文件中提供的凭据进行访问。详细的 Redis 安装和配置,请参阅 [部署指南](./docs/DEPLOYMENT_GUIDE.zh-CN.md) 的第 3.1 节。
|
||||
5. 如上所述,**创建并配置您的 `.env.development.local` 文件**。
|
||||
6. **运行开发服务器:**
|
||||
```bash
|
||||
@@ -118,28 +123,7 @@ REDIS_PORT=6379 # 或者你的 Redis 服务器端口
|
||||
```
|
||||
服务器应在您 `PORT` 环境变量指定的端口上启动(默认为 3001)。
|
||||
|
||||
## Docker 部署
|
||||
|
||||
1. **导航到 `backend/` 目录。** (这假设您的 `Dockerfile` 位于 `backend/docker/Dockerfile`,但构建上下文是 `backend/`)
|
||||
2. **构建 Docker 镜像:**
|
||||
```bash
|
||||
docker build -t privydrop-backend -f docker/Dockerfile .
|
||||
```
|
||||
3. **运行 Docker 容器:**
|
||||
```bash
|
||||
docker run -d \
|
||||
-p 3001:3001 \
|
||||
--name privydrop-backend-container \
|
||||
-e PORT=3001 \
|
||||
-e NODE_ENV=production \
|
||||
-e CORS_ORIGIN="http://your-frontend-domain.com" \
|
||||
-e REDIS_HOST="your-redis-host" \
|
||||
-e REDIS_PORT="your-redis-port" \
|
||||
privydrop-backend
|
||||
```
|
||||
- 如果您的内部 `PORT` 不同或您想映射到不同的主机端口,请调整 `-p`。
|
||||
- 替换环境变量 (`-e`) 的占位符值。
|
||||
- 对于生产设置,您可能需要使用 Docker Compose,并可能将 Nginx 作为反向代理和 TURN 服务器运行。请参考 `backend/docker/nginx/` 和 `backend/docker/turn/` 目录中的配置(如果您按建议构建它们)以及可能的 `docker-compose.yml` 文件。
|
||||
对于**生产环境部署**,请参考 [部署指南](./docs/DEPLOYMENT_GUIDE.zh-CN.md) 中关于使用 PM2 进行部署的详细说明(第 4.5 节)。
|
||||
|
||||
## API 端点
|
||||
|
||||
@@ -219,4 +203,4 @@ Redis 用于:
|
||||
|
||||
## 许可证
|
||||
|
||||
(许可证占位符 - 例如:MIT、Apache 2.0)
|
||||
(许可证占位符 - 例如:MIT、Apache 2.0)
|
||||
|
||||
@@ -0,0 +1,359 @@
|
||||
# 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: `turn:YourServerPublicIP:3478`
|
||||
- Username: `YourTurnUsername`
|
||||
- Password: `YourTurnPassword`
|
||||
- **For Production (TURNS) (if configured):**
|
||||
- TURNS URL: `turns:turn.yourdomain: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.
|
||||
@@ -1,483 +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).
|
||||
|
||||
## 1. Introduction
|
||||
|
||||
This document will walk you through the steps to prepare your server environment, configure dependencies, and deploy 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.
|
||||
* **Git:** For cloning the repository.
|
||||
* **Curl, GnuPG, etc.:** For installing Nginx or other dependencies.
|
||||
* **Root or Sudo Access:** Required for installing packages and configuring services.
|
||||
|
||||
## 3. Dependent 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 requires no password.
|
||||
- If your Redis instance is on a different host, port, or requires a password, you will need to update the backend application's 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
|
||||
```
|
||||
- To start Redis if it's not running:
|
||||
```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 File (`/etc/turnserver.conf`):**
|
||||
This is the main configuration file. Below is a comprehensive example. Adapt it to your needs.
|
||||
|
||||
* **For Testing/Development (using IP, no TLS):**
|
||||
```conf
|
||||
# Listening IP address(es) for STUN/TURN. Use your server's private/local IP if behind NAT,
|
||||
# and ensure your TURN_EXTERNAL_IP environment variable for the backend uses the public IP.
|
||||
# If your server has a public IP directly, you can use that.
|
||||
listening-ip=YOUR_SERVER_PRIVATE_OR_PUBLIC_IP
|
||||
|
||||
# External IP address of the server.
|
||||
# This is the IP that clients will use to connect to the TURN server from the internet.
|
||||
# It MUST be set if the server is behind NAT.
|
||||
external-ip=YOUR_SERVER_PUBLIC_IP
|
||||
|
||||
# Realm for the TURN server
|
||||
realm=YOUR_SERVER_PUBLIC_IP # Or your domain for production
|
||||
|
||||
# User for TURN authentication
|
||||
user=YourTurnUsername:YourTurnPassword
|
||||
|
||||
# Listening port for STUN/TURN (UDP and TCP)
|
||||
listening-port=3478
|
||||
|
||||
# Further listening ports for STUN/TURN (UDP and TCP)
|
||||
# alt-listening-port=3479 # Optional
|
||||
|
||||
# Log file
|
||||
log-file=/var/log/turnserver.log
|
||||
verbose
|
||||
|
||||
# Deny TLS/DTLS for non-secure connections if you don't have SSL certs for testing
|
||||
no-tls
|
||||
no-dtls
|
||||
|
||||
# Other recommended settings
|
||||
lt-cred-mech # Use long-term credential mechanism
|
||||
fingerprint # Use fingerprint for STUN messages
|
||||
```
|
||||
|
||||
* **For Production (using Domain, with TLS for TURNS):**
|
||||
```conf
|
||||
# Listening IP address(es)
|
||||
listening-ip=YOUR_SERVER_PRIVATE_OR_PUBLIC_IP
|
||||
|
||||
# External IP address of the server if behind NAT
|
||||
external-ip=YOUR_SERVER_PUBLIC_IP # Must be the public IP
|
||||
|
||||
# Realm for the TURN server - MUST match your domain used for SSL cert
|
||||
realm=turn.yourdomain.com
|
||||
|
||||
# User for TURN authentication
|
||||
user=YourTurnUsername:YourTurnPassword
|
||||
|
||||
# Listening port for STUN/TURN (UDP and TCP) - standard non-TLS
|
||||
listening-port=3478
|
||||
|
||||
# Listening port for TURNS (TLS-TCP)
|
||||
tls-listening-port=5349
|
||||
|
||||
# SSL Certificate and Key for TURNS
|
||||
cert=/etc/letsencrypt/live/turn.yourdomain.com/fullchain.pem
|
||||
pkey=/etc/letsencrypt/live/turn.yourdomain.com/privkey.pem
|
||||
|
||||
# Log file
|
||||
log-file=/var/log/turnserver.log
|
||||
verbose
|
||||
|
||||
# Other recommended settings
|
||||
lt-cred-mech
|
||||
fingerprint
|
||||
# Specify a cipher list if needed, e.g., for older clients, but modern defaults are usually fine.
|
||||
# cipher-list="DEFAULT"
|
||||
```
|
||||
|
||||
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) - *Production*.
|
||||
* **UDP `49152-65533`**: Default relay port range for Coturn (configurable with `min-port` and `max-port` in `turnserver.conf`).
|
||||
```bash
|
||||
sudo ufw allow 3478
|
||||
sudo ufw allow 5349 # For production
|
||||
sudo ufw allow 49152:65535/udp
|
||||
sudo ufw enable
|
||||
sudo ufw status
|
||||
```
|
||||
|
||||
4. **SSL Certificate for Production (TURNS):**
|
||||
If deploying for production and using `TURNS` (TURN over TLS), you 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.
|
||||
* Use Certbot to obtain a certificate:
|
||||
```bash
|
||||
sudo apt install certbot
|
||||
sudo certbot certonly --standalone -d turn.yourdomain.com
|
||||
```
|
||||
The certificate and private key will typically be stored in `/etc/letsencrypt/live/turn.yourdomain.com/`.
|
||||
|
||||
5. **Permissions for SSL Certificates (Production):**
|
||||
The Coturn process (usually runs 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 it's 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. **Start/Restart and Test Coturn:**
|
||||
```bash
|
||||
sudo systemctl restart coturn
|
||||
sudo systemctl status coturn
|
||||
```
|
||||
Check `/var/log/turnserver.log` for any errors.
|
||||
|
||||
**Testing your TURN server:**
|
||||
Use an online tool like Metered TURN Server Tester (https://www.metered.ca/turn-server-testing):
|
||||
* **For testing (non-TLS):**
|
||||
* TURN URL: `turn:YOUR_SERVER_PUBLIC_IP:3478`
|
||||
* Username: `YourTurnUsername`
|
||||
* Password: `YourTurnPassword`
|
||||
* **For production (TURNS):**
|
||||
* TURNS URL: `turns:turn.yourdomain.com:5349`
|
||||
* Username: `YourTurnUsername`
|
||||
* Password: `YourTurnPassword`
|
||||
Look for "Success" or "Reachable" messages.
|
||||
|
||||
### 3.3. Nginx (Reverse Proxy - Production Environment)
|
||||
|
||||
Nginx is recommended for production environments to act as a reverse proxy, handle SSL termination, serve static files (if applicable), and enable HTTP/3.
|
||||
|
||||
**Installation (with HTTP/3 support, Ubuntu Example):**
|
||||
Ref: 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 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:**
|
||||
|
||||
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. **SSL Certificate for Your Main Domain:**
|
||||
Obtain an SSL certificate 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 (`/etc/nginx/nginx.conf` and server blocks in `/etc/nginx/conf.d/`):**
|
||||
You'll need to configure Nginx to:
|
||||
* Listen on port 80 and redirect to HTTPS.
|
||||
* Listen on port 443 (TCP and UDP for HTTP/3).
|
||||
* Use your SSL certificates.
|
||||
* Proxy pass requests to your backend Node.js application (running on e.g., `localhost:3001`).
|
||||
* Handle WebSocket connections for Socket.IO.
|
||||
* (Optionally) Serve your frontend static files if they are on the same server.
|
||||
|
||||
A basic example server block for your application (`/etc/nginx/conf.d/privydrop.conf`):
|
||||
```nginx
|
||||
map $http_upgrade $connection_upgrade {
|
||||
default upgrade;
|
||||
'' close;
|
||||
}
|
||||
|
||||
server {
|
||||
listen 80;
|
||||
server_name yourdomain.com www.yourdomain.com;
|
||||
# Redirect all HTTP requests to HTTPS
|
||||
return 301 https://$host$request_uri;
|
||||
}
|
||||
|
||||
server {
|
||||
listen 443 ssl http2;
|
||||
listen [::]:443 ssl http2;
|
||||
# For HTTP/3 (QUIC)
|
||||
listen 443 quic reuseport;
|
||||
listen [::]:443 quic reuseport;
|
||||
|
||||
server_name yourdomain.com www.yourdomain.com;
|
||||
|
||||
ssl_certificate /etc/letsencrypt/live/yourdomain.com/fullchain.pem;
|
||||
ssl_certificate_key /etc/letsencrypt/live/yourdomain.com/privkey.pem;
|
||||
include /etc/letsencrypt/options-ssl-nginx.conf; # Recommended SSL settings from Certbot
|
||||
ssl_dhparam /etc/letsencrypt/ssl-dhparams.pem; # Recommended SSL settings from Certbot
|
||||
|
||||
# HTTP/3 specific headers
|
||||
# Tell the browser that HTTP/3 is available
|
||||
add_header Alt-Svc 'h3=":443"; ma=86400';
|
||||
# For 0-RTT
|
||||
# add_header Alt-Svc 'h3=":443"; ma=86400, h3-29=":443"; ma=86400'; # If supporting older h3 drafts
|
||||
# ssl_early_data on; # Nginx 1.15.4+
|
||||
|
||||
# (Optional) If serving frontend from Nginx
|
||||
# root /path/to/your/frontend/build;
|
||||
# index index.html index.htm;
|
||||
|
||||
location / {
|
||||
# If serving frontend:
|
||||
# try_files $uri $uri/ /index.html;
|
||||
|
||||
# If only backend, or for API calls when frontend is separate:
|
||||
proxy_pass http://localhost:3001; # Assuming backend runs on port 3001
|
||||
proxy_http_version 1.1;
|
||||
proxy_set_header Upgrade $http_upgrade;
|
||||
proxy_set_header Connection $connection_upgrade;
|
||||
proxy_set_header Host $host;
|
||||
proxy_set_header X-Real-IP $remote_addr;
|
||||
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
|
||||
proxy_set_header X-Forwarded-Proto $scheme;
|
||||
proxy_set_header X-Forwarded-Host $host;
|
||||
proxy_set_header X-Forwarded-Port $server_port;
|
||||
proxy_read_timeout 86400s; # For potentially long file transfers
|
||||
proxy_send_timeout 86400s;
|
||||
}
|
||||
|
||||
# Socket.IO specific location (ensure path matches your Socket.IO path)
|
||||
location /socket.io/ {
|
||||
proxy_pass http://localhost:3001; # Assuming backend runs on port 3001
|
||||
proxy_http_version 1.1;
|
||||
proxy_set_header Upgrade $http_upgrade;
|
||||
proxy_set_header Connection $connection_upgrade;
|
||||
proxy_set_header Host $host;
|
||||
}
|
||||
|
||||
# Add other security headers, logging, etc. as needed
|
||||
}
|
||||
```
|
||||
* **Important:** The `nginx.conf` main file should have an `http` block that enables QUIC:
|
||||
```nginx
|
||||
# In /etc/nginx/nginx.conf, inside the http {} block:
|
||||
http {
|
||||
# ... other settings ...
|
||||
quic_retry on; # Nginx 1.25.0+
|
||||
# ... other settings ...
|
||||
}
|
||||
```
|
||||
Ensure your Nginx version supports QUIC and `quic_retry`. The official Nginx packages usually do.
|
||||
|
||||
4. **Test Nginx Configuration and Restart:**
|
||||
```bash
|
||||
sudo nginx -t
|
||||
sudo systemctl restart nginx
|
||||
```
|
||||
|
||||
## 4. Backend Application Deployment
|
||||
|
||||
### 4.1. Get the Code
|
||||
Clone your repository to your server:
|
||||
```bash
|
||||
git clone <your-repository-url> privydrop
|
||||
cd privydrop/backend
|
||||
```
|
||||
|
||||
### 4.2. Install Dependencies
|
||||
```bash
|
||||
npm install
|
||||
```
|
||||
|
||||
### 4.3. Environment Variables
|
||||
|
||||
Create a `.env.production.local` file in the `backend/` directory. This file contains sensitive information and configurations.
|
||||
|
||||
```ini
|
||||
# Server Configuration
|
||||
PORT=3001 # The port your Node.js app will listen on (Nginx will proxy to this)
|
||||
NODE_ENV=production
|
||||
CORS_ORIGIN=https://yourdomain.com # URL of your frontend application
|
||||
|
||||
# Redis Configuration
|
||||
REDIS_HOST=127.0.0.1
|
||||
REDIS_PORT=6379
|
||||
# REDIS_PASSWORD=your_redis_password # If applicable
|
||||
|
||||
# TURN Server Configuration
|
||||
# These are used by the backend to inform clients about the TURN server.
|
||||
# For Testing (if using non-TLS TURN)
|
||||
# TURN_EXTERNAL_IP=YOUR_SERVER_PUBLIC_IP
|
||||
# TURN_REALM=YOUR_SERVER_PUBLIC_IP
|
||||
# TURN_USERNAME=YourTurnUsername
|
||||
# TURN_PASSWORD=YourTurnPassword
|
||||
|
||||
# For Production (if using TURNS)
|
||||
TURN_EXTERNAL_IP=YOUR_SERVER_PUBLIC_IP # The public IP of your TURN server
|
||||
TURN_REALM=turn.yourdomain.com # The realm, usually your TURN domain
|
||||
TURN_USERNAME=YourTurnUsername
|
||||
TURN_PASSWORD=YourTurnPassword
|
||||
TURN_CERT_PATH=/etc/letsencrypt/live/turn.yourdomain.com/fullchain.pem # Path to TURN SSL cert
|
||||
TURN_KEY_PATH=/etc/letsencrypt/live/turn.yourdomain.com/privkey.pem # Path to TURN SSL key
|
||||
# Note: The backend itself doesn't directly use TURN_CERT_PATH/TURN_KEY_PATH
|
||||
# for its own operations but might pass this info or use it for internal validation
|
||||
# if you extend its functionality. The primary user of these paths is Coturn itself.
|
||||
# The backend primarily needs to know the correct TURN URL (derived from these settings)
|
||||
# to send to clients.
|
||||
|
||||
# Nginx Related (Used by helper scripts if any, or for reference)
|
||||
# NGINX_SERVER_NAME=yourdomain.com
|
||||
# NGINX_SSL_CERT=/etc/letsencrypt/live/yourdomain.com/fullchain.pem
|
||||
# NGINX_SSL_KEY=/etc/letsencrypt/live/yourdomain.com/privkey.pem
|
||||
# NGINX_FRONTEND_ROOT=/path/to/your/frontend/build # If Nginx serves frontend
|
||||
```
|
||||
**Important:**
|
||||
* Ensure `CORS_ORIGIN` is correctly set to your frontend's domain for production.
|
||||
* The `TURN_*` variables are critical for the backend to correctly inform clients how to connect to your TURN server.
|
||||
|
||||
### 4.4. Process Management with PM2
|
||||
|
||||
PM2 is a production process manager for Node.js applications.
|
||||
|
||||
1. **Install PM2 globally:**
|
||||
```bash
|
||||
sudo npm install -g pm2
|
||||
```
|
||||
2. **Start the application using the `ecosystem.config.js` file:**
|
||||
The `ecosystem.config.js` file (usually in your project root) defines how PM2 should run your application.
|
||||
```bash
|
||||
# Navigate to your backend directory if not already there
|
||||
# cd /path/to/privydrop/backend
|
||||
|
||||
sudo pm2 start ecosystem.config.js
|
||||
```
|
||||
If you have a previous instance running with the same name (e.g., `signaling-server` as 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 system boot:**
|
||||
```bash
|
||||
sudo pm2 startup
|
||||
# Follow the instructions provided by the command (usually involves running another command it outputs)
|
||||
sudo pm2 save # Save current process list
|
||||
```
|
||||
|
||||
### 4.5. Firewall for Backend Application
|
||||
If your backend application's port (`3001` by default) is not proxied by Nginx for all access (e.g., health checks directly to the app), ensure it's open in the firewall. However, for typical production setups with Nginx, only Nginx ports (80, 443) need to be publicly accessible.
|
||||
```bash
|
||||
# Only if direct access to Node.js app is needed and not through Nginx
|
||||
# sudo ufw allow 3001/tcp
|
||||
```
|
||||
|
||||
## 5. Dockerized Deployment (Advanced/Optional)
|
||||
|
||||
While this guide focuses on a traditional deployment, you can also containerize the Privydrop backend. Refer to the `Dockerfile` in the `backend/docker/` directory and the Docker deployment section in `README.md` for basic Docker build and run commands.
|
||||
|
||||
For a production Docker setup, consider using `docker-compose` to orchestrate the backend application, Nginx (as a reverse proxy within Docker or on the host), Redis, and potentially Coturn (though Coturn often runs better directly on the host for network access). Managing SSL certificates and network configurations requires careful planning in a Dockerized environment.
|
||||
|
||||
## 6. Security and Maintenance
|
||||
|
||||
* **Regular Updates:** Keep your server's OS, Nginx, Node.js, PM2, and all other software packages updated.
|
||||
* **SSL Certificate Renewal:** Certbot usually sets up automatic renewal. You can test it with `sudo certbot renew --dry-run`. Ensure the renewal process has permissions to restart Nginx if needed.
|
||||
* **Log Management:** Regularly monitor logs for Nginx (`/var/log/nginx/`), Coturn (`/var/log/turnserver.log`), and your application (via PM2). Set up log rotation.
|
||||
* **Firewall:** Keep your firewall rules strict, only allowing necessary ports.
|
||||
* **Application Dependencies:** Regularly update Node.js dependencies (`npm update`) and test thoroughly.
|
||||
|
||||
## 7. Troubleshooting
|
||||
|
||||
* **Connection Issues:** Check firewall rules, Nginx proxy settings, `CORS_ORIGIN` in your backend .env file, and ensure all services (Redis, Coturn, Node.js app) are running.
|
||||
* **WebRTC Failures:** Use `chrome://webrtc-internals` (or Firefox equivalent) for debugging. Test your TURN server independently. Ensure `TURN_EXTERNAL_IP` and `TURN_REALM` are correctly set.
|
||||
* **Nginx Errors:** `sudo nginx -t` will check configuration syntax. Examine Nginx error logs.
|
||||
* **PM2 Issues:** Use `pm2 logs <app_name>` to see application errors.
|
||||
* **Certificate Permissions:** If Coturn or Nginx can't read SSL certificates, double-check file permissions and group memberships.
|
||||
|
||||
---
|
||||
This is a draft and can be expanded with more details, specific configurations for different Linux distributions, or more advanced topics.
|
||||
@@ -14,8 +14,8 @@
|
||||
- **Node.js:** v18.x 或更高版本。
|
||||
- **npm (或 yarn):** Node.js 的包管理器。
|
||||
- **Root 或 Sudo 权限:** 安装软件包和配置服务所需。
|
||||
- **可选:基础环境与 Docker 镜像参考:** 如果您需要从一个非常纯净的系统环境开始搭建,或者希望了解用于 Docker 构建的基础依赖,可以参考 `backend/docker/Dockerfile` 文件(用于 Docker 镜像构建)和 `backend/docker/env_install.log` 文件(可能包含特定环境下的依赖安装记录)。对于大多数标准 Linux 发行版,遵循本指南后续步骤即可。
|
||||
|
||||
基础镜像或基础依赖安装:请参考 backend/docker/Dockerfile 或 backend/docker/env_install.log
|
||||
|
||||
## 3. 依赖服务安装与配置
|
||||
|
||||
|
||||
Reference in New Issue
Block a user