File size: 17,278 Bytes
69b897d |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 |
# Claude Relay Service
<div align="center">
[](https://opensource.org/licenses/MIT)
[](https://nodejs.org/)
[](https://redis.io/)
[](https://www.docker.com/)
**๐ Self-hosted Claude API relay service with multi-account management**
[ไธญๆๆๆกฃ](README.md) โข [Preview](https://demo.pincc.ai/admin-next/login) โข [Telegram Channel](https://t.me/claude_relay_service)
</div>
---
## โญ If You Find It Useful, Please Give It a Star!
> Open source is not easy, your Star is my motivation to continue updating ๐
> Join [Telegram Channel](https://t.me/claude_relay_service) for the latest updates
---
## โ ๏ธ Important Notice
**Please read carefully before using this project:**
๐จ **Terms of Service Risk**: Using this project may violate Anthropic's terms of service. Please carefully read Anthropic's user agreement before use. All risks from using this project are borne by the user.
๐ **Disclaimer**: This project is for technical learning and research purposes only. The author is not responsible for any account bans, service interruptions, or other losses caused by using this project.
## ๐ค Is This Project Right for You?
- ๐ **Regional Restrictions**: Can't directly access Claude Code service in your region?
- ๐ **Privacy Concerns**: Worried about third-party mirror services logging or leaking your conversation content?
- ๐ฅ **Cost Sharing**: Want to share Claude Code Max subscription costs with friends?
- โก **Stability Issues**: Third-party mirror sites often fail and are unstable, affecting efficiency?
If you have any of these concerns, this project might be suitable for you.
### Suitable Scenarios
โ
**Cost Sharing with Friends**: 3-5 friends sharing Claude Code Max subscription, enjoying Opus freely
โ
**Privacy Sensitive**: Don't want third-party mirrors to see your conversation content
โ
**Technical Tinkering**: Have basic technical skills, willing to build and maintain yourself
โ
**Stability Needs**: Need long-term stable Claude access, don't want to be restricted by mirror sites
โ
**Regional Restrictions**: Cannot directly access Claude official service
### Unsuitable Scenarios
โ **Complete Beginner**: Don't understand technology at all, don't even know how to buy a server
โ **Occasional Use**: Use it only a few times a month, not worth the hassle
โ **Registration Issues**: Cannot register Claude account yourself
โ **Payment Issues**: No payment method to subscribe to Claude Code
**If you're just an ordinary user with low privacy requirements, just want to casually play around and quickly experience Claude, then choosing a mirror site you're familiar with would be more suitable.**
---
## ๐ญ Why Build Your Own?
### Potential Issues with Existing Mirror Sites
- ๐ต๏ธ **Privacy Risk**: Your conversation content is completely visible to others, forget about business secrets
- ๐ **Performance Instability**: Slow when many people use it, often crashes during peak hours
- ๐ฐ **Price Opacity**: Don't know the actual costs
### Benefits of Self-hosting
- ๐ **Data Security**: All API requests only go through your own server, direct connection to Anthropic API
- โก **Controllable Performance**: Only a few of you using it, Max $200 package basically allows you to enjoy Opus freely
- ๐ฐ **Cost Transparency**: Clear view of how many tokens used, specific costs calculated at official prices
- ๐ **Complete Monitoring**: Usage statistics, cost analysis, performance monitoring all available
---
## ๐ Core Features
> ๐ธ **[Click to view interface preview](docs/preview.md)** - See detailed screenshots of the Web management interface
### Basic Features
- โ
**Multi-account Management**: Add multiple Claude accounts for automatic rotation
- โ
**Custom API Keys**: Assign independent keys to each person
- โ
**Usage Statistics**: Detailed records of how many tokens each person used
### Advanced Features
- ๐ **Smart Switching**: Automatically switch to next account when one has issues
- ๐ **Performance Optimization**: Connection pooling, caching to reduce latency
- ๐ **Monitoring Dashboard**: Web interface to view all data
- ๐ก๏ธ **Security Control**: Access restrictions, rate limiting
- ๐ **Proxy Support**: Support for HTTP/SOCKS5 proxies
---
## ๐ Deployment Requirements
### Hardware Requirements (Minimum Configuration)
- **CPU**: 1 core is sufficient
- **Memory**: 512MB (1GB recommended)
- **Storage**: 30GB available space
- **Network**: Access to Anthropic API (recommend US region servers)
- **Recommendation**: 2 cores 4GB is basically enough, choose network with good return routes to your country (to improve speed, recommend not using proxy or setting server IP for direct connection)
### Software Requirements
- **Node.js** 18 or higher
- **Redis** 6 or higher
- **Operating System**: Linux recommended
### Cost Estimation
- **Server**: Light cloud server, $5-10 per month
- **Claude Subscription**: Depends on how you share costs
- **Others**: Domain name (optional)
---
## ๐ฆ Manual Deployment
### Step 1: Environment Setup
**Ubuntu/Debian users:**
```bash
# Install Node.js
curl -fsSL https://deb.nodesource.com/setup_18.x | sudo -E bash -
sudo apt-get install -y nodejs
# Install Redis
sudo apt update
sudo apt install redis-server
sudo systemctl start redis-server
```
**CentOS/RHEL users:**
```bash
# Install Node.js
curl -fsSL https://rpm.nodesource.com/setup_18.x | sudo bash -
sudo yum install -y nodejs
# Install Redis
sudo yum install redis
sudo systemctl start redis
```
### Step 2: Download and Configure
```bash
# Download project
git clone https://github.com/Wei-Shaw/claude-relay-service.git
cd claude-relay-service
# Install dependencies
npm install
# Copy configuration files (Important!)
cp config/config.example.js config/config.js
cp .env.example .env
```
### Step 3: Configuration File Setup
**Edit `.env` file:**
```bash
# Generate these two keys randomly, but remember them
JWT_SECRET=your-super-secret-key
ENCRYPTION_KEY=32-character-encryption-key-write-randomly
# Redis configuration
REDIS_HOST=localhost
REDIS_PORT=6379
REDIS_PASSWORD=
```
**Edit `config/config.js` file:**
```javascript
module.exports = {
server: {
port: 3000, // Service port, can be changed
host: '0.0.0.0' // Don't change
},
redis: {
host: '127.0.0.1', // Redis address
port: 6379 // Redis port
},
// Keep other configurations as default
}
```
### Step 4: Start Service
```bash
# Initialize
npm run setup # Will randomly generate admin account password info, stored in data/init.json
# Start service
npm run service:start:daemon # Run in background (recommended)
# Check status
npm run service:status
```
---
## ๐ฎ Getting Started
### 1. Open Management Interface
Browser visit: `http://your-server-IP:3000/web`
Default admin account: Look in data/init.json
### 2. Add Claude Account
This step is quite important, requires OAuth authorization:
1. Click "Claude Accounts" tab
2. If you're worried about multiple accounts sharing 1 IP getting banned, you can optionally set a static proxy IP
3. Click "Add Account"
4. Click "Generate Authorization Link", will open a new page
5. Complete Claude login and authorization in the new page
6. Copy the returned Authorization Code
7. Paste to page to complete addition
**Note**: If you're in China, this step may require VPN.
### 3. Create API Key
Assign a key to each user:
1. Click "API Keys" tab
2. Click "Create New Key"
3. Give the key a name, like "Zhang San's Key"
4. Set usage limits (optional)
5. Save, note down the generated key
### 4. Start Using Claude Code
Now you can replace the official API with your own service:
**Set environment variables:**
```bash
export ANTHROPIC_BASE_URL="http://127.0.0.1:3000/api/" # Fill in your server's IP address or domain according to actual situation
export ANTHROPIC_AUTH_TOKEN="API key created in the backend"
```
**Use claude:**
```bash
claude
```
---
## ๐ง Daily Maintenance
### Service Management
```bash
# Check service status
npm run service:status
# View logs
npm run service:logs
# Restart service
npm run service:restart:daemon
# Stop service
npm run service:stop
```
### Monitor Usage
- **Web Interface**: `http://your-domain:3000/web` - View usage statistics
- **Health Check**: `http://your-domain:3000/health` - Confirm service is normal
- **Log Files**: Various log files in `logs/` directory
### Upgrade Guide
When a new version is released, follow these steps to upgrade the service:
```bash
# 1. Navigate to project directory
cd claude-relay-service
# 2. Pull latest code
git pull origin main
# If you encounter package-lock.json conflicts, use the remote version
git checkout --theirs package-lock.json
git add package-lock.json
# 3. Install new dependencies (if any)
npm install
# 4. Restart service
npm run service:restart:daemon
# 5. Check service status
npm run service:status
```
**Important Notes:**
- Before upgrading, it's recommended to backup important configuration files (.env, config/config.js)
- Check the changelog to understand if there are any breaking changes
- Database structure changes will be migrated automatically if needed
### Common Issue Resolution
**Can't connect to Redis?**
```bash
# Check if Redis is running
redis-cli ping
# Should return PONG
```
**OAuth authorization failed?**
- Check if proxy settings are correct
- Ensure normal access to claude.ai
- Clear browser cache and retry
**API request failed?**
- Check if API Key is correct
- View log files for error information
- Confirm Claude account status is normal
---
## ๐ ๏ธ Advanced Usage
### Reverse Proxy Deployment Guide
For production environments, it is recommended to use a reverse proxy for automatic HTTPS, security headers, and performance optimization. Two common solutions are provided below: **Caddy** and **Nginx Proxy Manager (NPM)**.
---
## Caddy Solution
Caddy is a web server that automatically manages HTTPS certificates, with simple configuration and excellent performance, ideal for deployments without Docker environments.
**1. Install Caddy**
```bash
# Ubuntu/Debian
sudo apt install -y debian-keyring debian-archive-keyring apt-transport-https
curl -1sLf 'https://dl.cloudsmith.io/public/caddy/stable/gpg.key' | sudo gpg --dearmor -o /usr/share/keyrings/caddy-stable-archive-keyring.gpg
curl -1sLf 'https://dl.cloudsmith.io/public/caddy/stable/debian.deb.txt' | sudo tee /etc/apt/sources.list.d/caddy-stable.list
sudo apt update
sudo apt install caddy
# CentOS/RHEL/Fedora
sudo yum install yum-plugin-copr
sudo yum copr enable @caddy/caddy
sudo yum install caddy
```
**2. Caddy Configuration**
Edit `/etc/caddy/Caddyfile`:
```caddy
your-domain.com {
# Reverse proxy to local service
reverse_proxy 127.0.0.1:3000 {
# Support streaming responses or SSE
flush_interval -1
# Pass real IP
header_up X-Real-IP {remote_host}
header_up X-Forwarded-For {remote_host}
header_up X-Forwarded-Proto {scheme}
# Long read/write timeout configuration
transport http {
read_timeout 300s
write_timeout 300s
dial_timeout 30s
}
}
# Security headers
header {
Strict-Transport-Security "max-age=31536000; includeSubDomains"
X-Frame-Options "DENY"
X-Content-Type-Options "nosniff"
-Server
}
}
```
**3. Start Caddy**
```bash
sudo caddy validate --config /etc/caddy/Caddyfile
sudo systemctl start caddy
sudo systemctl enable caddy
sudo systemctl status caddy
```
**4. Service Configuration**
Since Caddy automatically manages HTTPS, you can restrict the service to listen locally only:
```javascript
// config/config.js
module.exports = {
server: {
port: 3000,
host: '127.0.0.1' // Listen locally only
}
}
```
**Caddy Features**
* ๐ Automatic HTTPS with zero-configuration certificate management
* ๐ก๏ธ Secure default configuration with modern TLS suites
* โก HTTP/2 and streaming support
* ๐ง Concise configuration files, easy to maintain
---
## Nginx Proxy Manager (NPM) Solution
Nginx Proxy Manager manages reverse proxies and HTTPS certificates through a graphical interface, deployed as a Docker container.
**1. Create a New Proxy Host in NPM**
Configure the Details as follows:
| Item | Setting |
| --------------------- | ------------------------ |
| Domain Names | relay.example.com |
| Scheme | http |
| Forward Hostname / IP | 192.168.0.1 (docker host IP) |
| Forward Port | 3000 |
| Block Common Exploits | โ๏ธ |
| Websockets Support | โ **Disable** |
| Cache Assets | โ **Disable** |
| Access List | Publicly Accessible |
> Note:
> - Ensure Claude Relay Service **listens on `0.0.0.0`, container IP, or host IP** to allow NPM internal network connections.
> - **Websockets Support and Cache Assets must be disabled**, otherwise SSE / streaming responses will fail.
**2. Custom locations**
No content needed, keep it empty.
**3. SSL Settings**
* **SSL Certificate**: Request a new SSL Certificate (Let's Encrypt) or existing certificate
* โ๏ธ **Force SSL**
* โ๏ธ **HTTP/2 Support**
* โ๏ธ **HSTS Enabled**
* โ๏ธ **HSTS Subdomains**
**4. Advanced Configuration**
Add the following to Custom Nginx Configuration:
```nginx
# Pass real user IP
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;
# Support WebSocket / SSE streaming
proxy_http_version 1.1;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection "upgrade";
proxy_buffering off;
# Long connection / timeout settings (for AI chat streaming)
proxy_read_timeout 300s;
proxy_send_timeout 300s;
proxy_connect_timeout 30s;
# ---- Security Settings ----
# Strict HTTPS policy (HSTS)
add_header Strict-Transport-Security "max-age=31536000; includeSubDomains" always;
# Block clickjacking and content sniffing
add_header X-Frame-Options "DENY" always;
add_header X-Content-Type-Options "nosniff" always;
# Referrer / Permissions restriction policies
add_header Referrer-Policy "no-referrer-when-downgrade" always;
add_header Permissions-Policy "camera=(), microphone=(), geolocation=()" always;
# Hide server information (equivalent to Caddy's `-Server`)
proxy_hide_header Server;
# ---- Performance Tuning ----
# Disable proxy caching for real-time responses (SSE / Streaming)
proxy_cache_bypass $http_upgrade;
proxy_no_cache $http_upgrade;
proxy_request_buffering off;
```
**5. Launch and Verify**
* After saving, wait for NPM to automatically request Let's Encrypt certificate (if applicable).
* Check Proxy Host status in Dashboard to ensure it shows "Online".
* Visit `https://relay.example.com`, if the green lock icon appears, HTTPS is working properly.
**NPM Features**
* ๐ Automatic certificate application and renewal
* ๐ง Graphical interface for easy multi-service management
* โก Native HTTP/2 / HTTPS support
* ๐ Ideal for Docker container deployments
---
Both solutions are suitable for production deployment. If you use a Docker environment, **Nginx Proxy Manager is more convenient**; if you want to keep software lightweight and automated, **Caddy is a better choice**.
---
## ๐ก Usage Recommendations
### Account Management
- **Regular Checks**: Check account status weekly, handle exceptions promptly
- **Reasonable Allocation**: Can assign different API keys to different people, analyze usage based on different API keys
### Security Recommendations
- **Use HTTPS**: Strongly recommend using Caddy reverse proxy (automatic HTTPS) to ensure secure data transmission
- **Regular Backups**: Back up important configurations and data
- **Monitor Logs**: Regularly check exception logs
- **Update Keys**: Regularly change JWT and encryption keys
- **Firewall Settings**: Only open necessary ports (80, 443), hide direct service ports
---
## ๐ What to Do When You Encounter Problems?
### Self-troubleshooting
1. **Check Logs**: Log files in `logs/` directory
2. **Check Configuration**: Confirm configuration files are set correctly
3. **Test Connectivity**: Use curl to test if API is normal
4. **Restart Service**: Sometimes restarting fixes it
### Seeking Help
- **GitHub Issues**: Submit detailed error information
- **Read Documentation**: Carefully read error messages and documentation
- **Community Discussion**: See if others have encountered similar problems
---
## ๐ License
This project uses the [MIT License](LICENSE).
---
<div align="center">
**โญ If you find it useful, please give it a Star, this is the greatest encouragement to the author!**
**๐ค Feel free to submit Issues for problems, welcome PRs for improvement suggestions**
</div> |