cjovs commited on
Commit
1dce8cb
Β·
verified Β·
1 Parent(s): 9d3f59d

Update README.md

Browse files
Files changed (1) hide show
  1. README.md +583 -583
README.md CHANGED
@@ -1,6 +1,6 @@
1
  ---
2
- title: Sub2API
3
- emoji: "πŸš€"
4
  colorFrom: blue
5
  colorTo: green
6
  sdk: docker
@@ -10,93 +10,93 @@ license: mit
10
  ---
11
 
12
  # Sub2API
13
-
14
- <div align="center">
15
-
16
- [![Go](https://img.shields.io/badge/Go-1.25.7-00ADD8.svg)](https://golang.org/)
17
- [![Vue](https://img.shields.io/badge/Vue-3.4+-4FC08D.svg)](https://vuejs.org/)
18
- [![PostgreSQL](https://img.shields.io/badge/PostgreSQL-15+-336791.svg)](https://www.postgresql.org/)
19
- [![Redis](https://img.shields.io/badge/Redis-7+-DC382D.svg)](https://redis.io/)
20
- [![Docker](https://img.shields.io/badge/Docker-Ready-2496ED.svg)](https://www.docker.com/)
21
-
22
- <a href="https://trendshift.io/repositories/21823" target="_blank"><img src="https://trendshift.io/api/badge/repositories/21823" alt="Wei-Shaw%2Fsub2api | Trendshift" width="250" height="55"/></a>
23
-
24
- **AI API Gateway Platform for Subscription Quota Distribution**
25
-
26
- English | [δΈ­ζ–‡](README_CN.md)
27
-
28
- </div>
29
-
30
- > **Sub2API officially uses only the domains `sub2api.org` and `pincc.ai`. Other websites using the Sub2API name may be third-party deployments or services and are not affiliated with this project. Please verify and exercise your own judgment.**
31
-
32
- ---
33
-
34
- ## Demo
35
-
36
- Try Sub2API online: **[https://demo.sub2api.org/](https://demo.sub2api.org/)**
37
-
38
- Demo credentials (shared demo environment; **not** created automatically for self-hosted installs):
39
-
40
- | Email | Password |
41
- |-------|----------|
42
- | admin@sub2api.org | admin123 |
43
-
44
- ## Overview
45
-
46
- Sub2API is an AI API gateway platform designed to distribute and manage API quotas from AI product subscriptions. Users can access upstream AI services through platform-generated API Keys, while the platform handles authentication, billing, load balancing, and request forwarding.
47
-
48
- ## Features
49
-
50
- - **Multi-Account Management** - Support multiple upstream account types (OAuth, API Key)
51
- - **API Key Distribution** - Generate and manage API Keys for users
52
- - **Precise Billing** - Token-level usage tracking and cost calculation
53
- - **Smart Scheduling** - Intelligent account selection with sticky sessions
54
- - **Concurrency Control** - Per-user and per-account concurrency limits
55
- - **Rate Limiting** - Configurable request and token rate limits
56
- - **Admin Dashboard** - Web interface for monitoring and management
57
- - **External System Integration** - Embed external systems (e.g. payment, ticketing) via iframe to extend the admin dashboard
58
-
59
- ## Don't Want to Self-Host?
60
-
61
- <table>
62
- <tr>
63
- <td width="180" align="center" valign="middle"><a href="https://shop.pincc.ai/"><img src="assets/partners/logos/pincc-logo.png" alt="pincc" width="120"></a></td>
64
- <td valign="middle"><b><a href="https://shop.pincc.ai/">PinCC</a></b> is the official relay service built on Sub2API, offering stable access to Claude Code, Codex, Gemini and other popular models β€” ready to use, no deployment or maintenance required.</td>
65
- </tr>
66
- </table>
67
-
68
- ## Ecosystem
69
-
70
- Community projects that extend or integrate with Sub2API:
71
-
72
- | Project | Description | Features |
73
- |---------|-------------|----------|
74
- | [Sub2ApiPay](https://github.com/touwaeriol/sub2apipay) | Self-service payment system | Self-service top-up and subscription purchase; supports YiPay protocol, WeChat Pay, Alipay, Stripe; embeddable via iframe |
75
- | [sub2api-mobile](https://github.com/ckken/sub2api-mobile) | Mobile admin console | Cross-platform app (iOS/Android/Web) for user management, account management, monitoring dashboard, and multi-backend switching; built with Expo + React Native |
76
-
77
- ## Tech Stack
78
-
79
- | Component | Technology |
80
- |-----------|------------|
81
- | Backend | Go 1.25.7, Gin, Ent |
82
- | Frontend | Vue 3.4+, Vite 5+, TailwindCSS |
83
- | Database | PostgreSQL 15+ |
84
- | Cache/Queue | Redis 7+ |
85
-
86
- ---
87
-
88
- ## Nginx Reverse Proxy Note
89
-
90
- When using Nginx as a reverse proxy for Sub2API (or CRS) with Codex CLI, add the following to the `http` block in your Nginx configuration:
91
-
92
- ```nginx
93
- underscores_in_headers on;
94
- ```
95
-
96
- Nginx drops headers containing underscores by default (e.g. `session_id`), which breaks sticky session routing in multi-account setups.
97
-
98
- ---
99
-
100
  ## Deployment
101
 
102
  ### Method 0: Hugging Face Docker Space
@@ -129,497 +129,497 @@ TZ=Asia/Shanghai
129
  ```
130
 
131
  ### Method 1: Script Installation (Recommended)
132
-
133
- One-click installation script that downloads pre-built binaries from GitHub Releases.
134
-
135
- #### Prerequisites
136
-
137
- - Linux server (amd64 or arm64)
138
- - PostgreSQL 15+ (installed and running)
139
- - Redis 7+ (installed and running)
140
- - Root privileges
141
-
142
- #### Installation Steps
143
-
144
- ```bash
145
- curl -sSL https://raw.githubusercontent.com/Wei-Shaw/sub2api/main/deploy/install.sh | sudo bash
146
- ```
147
-
148
- The script will:
149
- 1. Detect your system architecture
150
- 2. Download the latest release
151
- 3. Install binary to `/opt/sub2api`
152
- 4. Create systemd service
153
- 5. Configure system user and permissions
154
-
155
- #### Post-Installation
156
-
157
- ```bash
158
- # 1. Start the service
159
- sudo systemctl start sub2api
160
-
161
- # 2. Enable auto-start on boot
162
- sudo systemctl enable sub2api
163
-
164
- # 3. Open Setup Wizard in browser
165
- # http://YOUR_SERVER_IP:8080
166
- ```
167
-
168
- The Setup Wizard will guide you through:
169
- - Database configuration
170
- - Redis configuration
171
- - Admin account creation
172
-
173
- #### Upgrade
174
-
175
- You can upgrade directly from the **Admin Dashboard** by clicking the **Check for Updates** button in the top-left corner.
176
-
177
- The web interface will:
178
- - Check for new versions automatically
179
- - Download and apply updates with one click
180
- - Support rollback if needed
181
-
182
- #### Useful Commands
183
-
184
- ```bash
185
- # Check status
186
- sudo systemctl status sub2api
187
-
188
- # View logs
189
- sudo journalctl -u sub2api -f
190
-
191
- # Restart service
192
- sudo systemctl restart sub2api
193
-
194
- # Uninstall
195
- curl -sSL https://raw.githubusercontent.com/Wei-Shaw/sub2api/main/deploy/install.sh | sudo bash -s -- uninstall -y
196
- ```
197
-
198
- ---
199
-
200
- ### Method 2: Docker Compose (Recommended)
201
-
202
- Deploy with Docker Compose, including PostgreSQL and Redis containers.
203
-
204
- #### Prerequisites
205
-
206
- - Docker 20.10+
207
- - Docker Compose v2+
208
-
209
- #### Quick Start (One-Click Deployment)
210
-
211
- Use the automated deployment script for easy setup:
212
-
213
- ```bash
214
- # Create deployment directory
215
- mkdir -p sub2api-deploy && cd sub2api-deploy
216
-
217
- # Download and run deployment preparation script
218
- curl -sSL https://raw.githubusercontent.com/Wei-Shaw/sub2api/main/deploy/docker-deploy.sh | bash
219
-
220
- # Start services
221
- docker compose up -d
222
-
223
- # View logs
224
- docker compose logs -f sub2api
225
- ```
226
-
227
- **What the script does:**
228
- - Downloads `docker-compose.local.yml` (saved as `docker-compose.yml`) and `.env.example`
229
- - Generates secure credentials (JWT_SECRET, TOTP_ENCRYPTION_KEY, POSTGRES_PASSWORD)
230
- - Creates `.env` file with auto-generated secrets
231
- - Creates data directories (uses local directories for easy backup/migration)
232
- - Displays generated credentials for your reference
233
-
234
- #### Manual Deployment
235
-
236
- If you prefer manual setup:
237
-
238
- ```bash
239
- # 1. Clone the repository
240
- git clone https://github.com/Wei-Shaw/sub2api.git
241
- cd sub2api/deploy
242
-
243
- # 2. Copy environment configuration
244
- cp .env.example .env
245
-
246
- # 3. Edit configuration (generate secure passwords)
247
- nano .env
248
- ```
249
-
250
- **Required configuration in `.env`:**
251
-
252
- ```bash
253
- # PostgreSQL password (REQUIRED)
254
- POSTGRES_PASSWORD=your_secure_password_here
255
-
256
- # JWT Secret (RECOMMENDED - keeps users logged in after restart)
257
- JWT_SECRET=your_jwt_secret_here
258
-
259
- # TOTP Encryption Key (RECOMMENDED - preserves 2FA after restart)
260
- TOTP_ENCRYPTION_KEY=your_totp_key_here
261
-
262
- # Optional: Admin account
263
- ADMIN_EMAIL=admin@example.com
264
- ADMIN_PASSWORD=your_admin_password
265
-
266
- # Optional: Custom port
267
- SERVER_PORT=8080
268
- ```
269
-
270
- **Generate secure secrets:**
271
- ```bash
272
- # Generate JWT_SECRET
273
- openssl rand -hex 32
274
-
275
- # Generate TOTP_ENCRYPTION_KEY
276
- openssl rand -hex 32
277
-
278
- # Generate POSTGRES_PASSWORD
279
- openssl rand -hex 32
280
- ```
281
-
282
- ```bash
283
- # 4. Create data directories (for local version)
284
- mkdir -p data postgres_data redis_data
285
-
286
- # 5. Start all services
287
- # Option A: Local directory version (recommended - easy migration)
288
- docker compose -f docker-compose.local.yml up -d
289
-
290
- # Option B: Named volumes version (simple setup)
291
- docker compose up -d
292
-
293
- # 6. Check status
294
- docker compose -f docker-compose.local.yml ps
295
-
296
- # 7. View logs
297
- docker compose -f docker-compose.local.yml logs -f sub2api
298
- ```
299
-
300
- #### Deployment Versions
301
-
302
- | Version | Data Storage | Migration | Best For |
303
- |---------|-------------|-----------|----------|
304
- | **docker-compose.local.yml** | Local directories | βœ… Easy (tar entire directory) | Production, frequent backups |
305
- | **docker-compose.yml** | Named volumes | ⚠️ Requires docker commands | Simple setup |
306
-
307
- **Recommendation:** Use `docker-compose.local.yml` (deployed by script) for easier data management.
308
-
309
- #### Access
310
-
311
- Open `http://YOUR_SERVER_IP:8080` in your browser.
312
-
313
- If admin password was auto-generated, find it in logs:
314
- ```bash
315
- docker compose -f docker-compose.local.yml logs sub2api | grep "admin password"
316
- ```
317
-
318
- #### Upgrade
319
-
320
- ```bash
321
- # Pull latest image and recreate container
322
- docker compose -f docker-compose.local.yml pull
323
- docker compose -f docker-compose.local.yml up -d
324
- ```
325
-
326
- #### Easy Migration (Local Directory Version)
327
-
328
- When using `docker-compose.local.yml`, migrate to a new server easily:
329
-
330
- ```bash
331
- # On source server
332
- docker compose -f docker-compose.local.yml down
333
- cd ..
334
- tar czf sub2api-complete.tar.gz sub2api-deploy/
335
-
336
- # Transfer to new server
337
- scp sub2api-complete.tar.gz user@new-server:/path/
338
-
339
- # On new server
340
- tar xzf sub2api-complete.tar.gz
341
- cd sub2api-deploy/
342
- docker compose -f docker-compose.local.yml up -d
343
- ```
344
-
345
- #### Useful Commands
346
-
347
- ```bash
348
- # Stop all services
349
- docker compose -f docker-compose.local.yml down
350
-
351
- # Restart
352
- docker compose -f docker-compose.local.yml restart
353
-
354
- # View all logs
355
- docker compose -f docker-compose.local.yml logs -f
356
-
357
- # Remove all data (caution!)
358
- docker compose -f docker-compose.local.yml down
359
- rm -rf data/ postgres_data/ redis_data/
360
- ```
361
-
362
- ---
363
-
364
- ### Method 3: Build from Source
365
-
366
- Build and run from source code for development or customization.
367
-
368
- #### Prerequisites
369
-
370
- - Go 1.21+
371
- - Node.js 18+
372
- - PostgreSQL 15+
373
- - Redis 7+
374
-
375
- #### Build Steps
376
-
377
- ```bash
378
- # 1. Clone the repository
379
- git clone https://github.com/Wei-Shaw/sub2api.git
380
- cd sub2api
381
-
382
- # 2. Install pnpm (if not already installed)
383
- npm install -g pnpm
384
-
385
- # 3. Build frontend
386
- cd frontend
387
- pnpm install
388
- pnpm run build
389
- # Output will be in ../backend/internal/web/dist/
390
-
391
- # 4. Build backend with embedded frontend
392
- cd ../backend
393
- go build -tags embed -o sub2api ./cmd/server
394
-
395
- # 5. Create configuration file
396
- cp ../deploy/config.example.yaml ./config.yaml
397
-
398
- # 6. Edit configuration
399
- nano config.yaml
400
- ```
401
-
402
- > **Note:** The `-tags embed` flag embeds the frontend into the binary. Without this flag, the binary will not serve the frontend UI.
403
-
404
- **Key configuration in `config.yaml`:**
405
-
406
- ```yaml
407
- server:
408
- host: "0.0.0.0"
409
- port: 8080
410
- mode: "release"
411
-
412
- database:
413
- host: "localhost"
414
- port: 5432
415
- user: "postgres"
416
- password: "your_password"
417
- dbname: "sub2api"
418
-
419
- redis:
420
- host: "localhost"
421
- port: 6379
422
- password: ""
423
-
424
- jwt:
425
- secret: "change-this-to-a-secure-random-string"
426
- expire_hour: 24
427
-
428
- default:
429
- user_concurrency: 5
430
- user_balance: 0
431
- api_key_prefix: "sk-"
432
- rate_multiplier: 1.0
433
- ```
434
-
435
- ### Sora Status (Temporarily Unavailable)
436
-
437
- > ⚠️ Sora-related features are temporarily unavailable due to technical issues in upstream integration and media delivery.
438
- > Please do not rely on Sora in production at this time.
439
- > Existing `gateway.sora_*` configuration keys are reserved and may not take effect until these issues are resolved.
440
-
441
- Additional security-related options are available in `config.yaml`:
442
-
443
- - `cors.allowed_origins` for CORS allowlist
444
- - `security.url_allowlist` for upstream/pricing/CRS host allowlists
445
- - `security.url_allowlist.enabled` to disable URL validation (use with caution)
446
- - `security.url_allowlist.allow_insecure_http` to allow HTTP URLs when validation is disabled
447
- - `security.url_allowlist.allow_private_hosts` to allow private/local IP addresses
448
- - `security.response_headers.enabled` to enable configurable response header filtering (disabled uses default allowlist)
449
- - `security.csp` to control Content-Security-Policy headers
450
- - `billing.circuit_breaker` to fail closed on billing errors
451
- - `server.trusted_proxies` to enable X-Forwarded-For parsing
452
- - `turnstile.required` to require Turnstile in release mode
453
-
454
- **⚠️ Security Warning: HTTP URL Configuration**
455
-
456
- When `security.url_allowlist.enabled=false`, the system performs minimal URL validation by default, **rejecting HTTP URLs** and only allowing HTTPS. To allow HTTP URLs (e.g., for development or internal testing), you must explicitly set:
457
-
458
- ```yaml
459
- security:
460
- url_allowlist:
461
- enabled: false # Disable allowlist checks
462
- allow_insecure_http: true # Allow HTTP URLs (⚠️ INSECURE)
463
- ```
464
-
465
- **Or via environment variable:**
466
-
467
- ```bash
468
- SECURITY_URL_ALLOWLIST_ENABLED=false
469
- SECURITY_URL_ALLOWLIST_ALLOW_INSECURE_HTTP=true
470
- ```
471
-
472
- **Risks of allowing HTTP:**
473
- - API keys and data transmitted in **plaintext** (vulnerable to interception)
474
- - Susceptible to **man-in-the-middle (MITM) attacks**
475
- - **NOT suitable for production** environments
476
-
477
- **When to use HTTP:**
478
- - βœ… Development/testing with local servers (http://localhost)
479
- - βœ… Internal networks with trusted endpoints
480
- - βœ… Testing account connectivity before obtaining HTTPS
481
- - ❌ Production environments (use HTTPS only)
482
-
483
- **Example error without this setting:**
484
- ```
485
- Invalid base URL: invalid url scheme: http
486
- ```
487
-
488
- If you disable URL validation or response header filtering, harden your network layer:
489
- - Enforce an egress allowlist for upstream domains/IPs
490
- - Block private/loopback/link-local ranges
491
- - Enforce TLS-only outbound traffic
492
- - Strip sensitive upstream response headers at the proxy
493
-
494
- ```bash
495
- # 6. Run the application
496
- ./sub2api
497
- ```
498
-
499
- #### Development Mode
500
-
501
- ```bash
502
- # Backend (with hot reload)
503
- cd backend
504
- go run ./cmd/server
505
-
506
- # Frontend (with hot reload)
507
- cd frontend
508
- pnpm run dev
509
- ```
510
-
511
- #### Code Generation
512
-
513
- When editing `backend/ent/schema`, regenerate Ent + Wire:
514
-
515
- ```bash
516
- cd backend
517
- go generate ./ent
518
- go generate ./cmd/server
519
- ```
520
-
521
- ---
522
-
523
- ## Simple Mode
524
-
525
- Simple Mode is designed for individual developers or internal teams who want quick access without full SaaS features.
526
-
527
- - Enable: Set environment variable `RUN_MODE=simple`
528
- - Difference: Hides SaaS-related features and skips billing process
529
- - Security note: In production, you must also set `SIMPLE_MODE_CONFIRM=true` to allow startup
530
-
531
- ---
532
-
533
- ## Antigravity Support
534
-
535
- Sub2API supports [Antigravity](https://antigravity.so/) accounts. After authorization, dedicated endpoints are available for Claude and Gemini models.
536
-
537
- ### Dedicated Endpoints
538
-
539
- | Endpoint | Model |
540
- |----------|-------|
541
- | `/antigravity/v1/messages` | Claude models |
542
- | `/antigravity/v1beta/` | Gemini models |
543
-
544
- ### Claude Code Configuration
545
-
546
- ```bash
547
- export ANTHROPIC_BASE_URL="http://localhost:8080/antigravity"
548
- export ANTHROPIC_AUTH_TOKEN="sk-xxx"
549
- ```
550
-
551
- ### Hybrid Scheduling Mode
552
-
553
- Antigravity accounts support optional **hybrid scheduling**. When enabled, the general endpoints `/v1/messages` and `/v1beta/` will also route requests to Antigravity accounts.
554
-
555
- > **⚠️ Warning**: Anthropic Claude and Antigravity Claude **cannot be mixed within the same conversation context**. Use groups to isolate them properly.
556
-
557
- ### Known Issues
558
-
559
- In Claude Code, Plan Mode cannot exit automatically. (Normally when using the native Claude API, after planning is complete, Claude Code will pop up options for users to approve or reject the plan.)
560
-
561
- **Workaround**: Press `Shift + Tab` to manually exit Plan Mode, then type your response to approve or reject the plan.
562
-
563
- ---
564
-
565
- ## Project Structure
566
-
567
- ```
568
- sub2api/
569
- β”œβ”€β”€ backend/ # Go backend service
570
- οΏ½οΏ½οΏ½ β”œβ”€β”€ cmd/server/ # Application entry
571
- β”‚ β”œβ”€β”€ internal/ # Internal modules
572
- β”‚ β”‚ β”œβ”€β”€ config/ # Configuration
573
- β”‚ β”‚ β”œβ”€β”€ model/ # Data models
574
- β”‚ β”‚ β”œβ”€β”€ service/ # Business logic
575
- β”‚ β”‚ β”œβ”€β”€ handler/ # HTTP handlers
576
- β”‚ β”‚ └── gateway/ # API gateway core
577
- β”‚ └── resources/ # Static resources
578
- β”‚
579
- β”œβ”€β”€ frontend/ # Vue 3 frontend
580
- β”‚ └── src/
581
- β”‚ β”œβ”€β”€ api/ # API calls
582
- β”‚ β”œβ”€β”€ stores/ # State management
583
- β”‚ β”œβ”€β”€ views/ # Page components
584
- β”‚ └── components/ # Reusable components
585
- β”‚
586
- └── deploy/ # Deployment files
587
- β”œβ”€β”€ docker-compose.yml # Docker Compose configuration
588
- β”œβ”€β”€ .env.example # Environment variables for Docker Compose
589
- β”œβ”€β”€ config.example.yaml # Full config file for binary deployment
590
- └── install.sh # One-click installation script
591
- ```
592
-
593
- ## Disclaimer
594
-
595
- > **Please read carefully before using this project:**
596
- >
597
- > :rotating_light: **Terms of Service Risk**: Using this project may violate Anthropic's Terms of Service. Please read Anthropic's user agreement carefully before use. All risks arising from the use of this project are borne solely by the user.
598
- >
599
- > :book: **Disclaimer**: This project is for technical learning and research purposes only. The author assumes no responsibility for account suspension, service interruption, or any other losses caused by the use of this project.
600
-
601
- ---
602
-
603
- ## Star History
604
-
605
- <a href="https://star-history.com/#Wei-Shaw/sub2api&Date">
606
- <picture>
607
- <source media="(prefers-color-scheme: dark)" srcset="https://api.star-history.com/svg?repos=Wei-Shaw/sub2api&type=Date&theme=dark" />
608
- <source media="(prefers-color-scheme: light)" srcset="https://api.star-history.com/svg?repos=Wei-Shaw/sub2api&type=Date" />
609
- <img alt="Star History Chart" src="https://api.star-history.com/svg?repos=Wei-Shaw/sub2api&type=Date" />
610
- </picture>
611
- </a>
612
-
613
- ---
614
-
615
- ## License
616
-
617
- MIT License
618
-
619
- ---
620
-
621
- <div align="center">
622
-
623
- **If you find this project useful, please give it a star!**
624
-
625
- </div>
 
1
  ---
2
+ title: XAPI
3
+ emoji: πŸš€
4
  colorFrom: blue
5
  colorTo: green
6
  sdk: docker
 
10
  ---
11
 
12
  # Sub2API
13
+
14
+ <div align="center">
15
+
16
+ [![Go](https://img.shields.io/badge/Go-1.25.7-00ADD8.svg)](https://golang.org/)
17
+ [![Vue](https://img.shields.io/badge/Vue-3.4+-4FC08D.svg)](https://vuejs.org/)
18
+ [![PostgreSQL](https://img.shields.io/badge/PostgreSQL-15+-336791.svg)](https://www.postgresql.org/)
19
+ [![Redis](https://img.shields.io/badge/Redis-7+-DC382D.svg)](https://redis.io/)
20
+ [![Docker](https://img.shields.io/badge/Docker-Ready-2496ED.svg)](https://www.docker.com/)
21
+
22
+ <a href="https://trendshift.io/repositories/21823" target="_blank"><img src="https://trendshift.io/api/badge/repositories/21823" alt="Wei-Shaw%2Fsub2api | Trendshift" width="250" height="55"/></a>
23
+
24
+ **AI API Gateway Platform for Subscription Quota Distribution**
25
+
26
+ English | [δΈ­ζ–‡](README_CN.md)
27
+
28
+ </div>
29
+
30
+ > **Sub2API officially uses only the domains `sub2api.org` and `pincc.ai`. Other websites using the Sub2API name may be third-party deployments or services and are not affiliated with this project. Please verify and exercise your own judgment.**
31
+
32
+ ---
33
+
34
+ ## Demo
35
+
36
+ Try Sub2API online: **[https://demo.sub2api.org/](https://demo.sub2api.org/)**
37
+
38
+ Demo credentials (shared demo environment; **not** created automatically for self-hosted installs):
39
+
40
+ | Email | Password |
41
+ |-------|----------|
42
+ | admin@sub2api.org | admin123 |
43
+
44
+ ## Overview
45
+
46
+ Sub2API is an AI API gateway platform designed to distribute and manage API quotas from AI product subscriptions. Users can access upstream AI services through platform-generated API Keys, while the platform handles authentication, billing, load balancing, and request forwarding.
47
+
48
+ ## Features
49
+
50
+ - **Multi-Account Management** - Support multiple upstream account types (OAuth, API Key)
51
+ - **API Key Distribution** - Generate and manage API Keys for users
52
+ - **Precise Billing** - Token-level usage tracking and cost calculation
53
+ - **Smart Scheduling** - Intelligent account selection with sticky sessions
54
+ - **Concurrency Control** - Per-user and per-account concurrency limits
55
+ - **Rate Limiting** - Configurable request and token rate limits
56
+ - **Admin Dashboard** - Web interface for monitoring and management
57
+ - **External System Integration** - Embed external systems (e.g. payment, ticketing) via iframe to extend the admin dashboard
58
+
59
+ ## Don't Want to Self-Host?
60
+
61
+ <table>
62
+ <tr>
63
+ <td width="180" align="center" valign="middle"><a href="https://shop.pincc.ai/"><img src="assets/partners/logos/pincc-logo.png" alt="pincc" width="120"></a></td>
64
+ <td valign="middle"><b><a href="https://shop.pincc.ai/">PinCC</a></b> is the official relay service built on Sub2API, offering stable access to Claude Code, Codex, Gemini and other popular models β€” ready to use, no deployment or maintenance required.</td>
65
+ </tr>
66
+ </table>
67
+
68
+ ## Ecosystem
69
+
70
+ Community projects that extend or integrate with Sub2API:
71
+
72
+ | Project | Description | Features |
73
+ |---------|-------------|----------|
74
+ | [Sub2ApiPay](https://github.com/touwaeriol/sub2apipay) | Self-service payment system | Self-service top-up and subscription purchase; supports YiPay protocol, WeChat Pay, Alipay, Stripe; embeddable via iframe |
75
+ | [sub2api-mobile](https://github.com/ckken/sub2api-mobile) | Mobile admin console | Cross-platform app (iOS/Android/Web) for user management, account management, monitoring dashboard, and multi-backend switching; built with Expo + React Native |
76
+
77
+ ## Tech Stack
78
+
79
+ | Component | Technology |
80
+ |-----------|------------|
81
+ | Backend | Go 1.25.7, Gin, Ent |
82
+ | Frontend | Vue 3.4+, Vite 5+, TailwindCSS |
83
+ | Database | PostgreSQL 15+ |
84
+ | Cache/Queue | Redis 7+ |
85
+
86
+ ---
87
+
88
+ ## Nginx Reverse Proxy Note
89
+
90
+ When using Nginx as a reverse proxy for Sub2API (or CRS) with Codex CLI, add the following to the `http` block in your Nginx configuration:
91
+
92
+ ```nginx
93
+ underscores_in_headers on;
94
+ ```
95
+
96
+ Nginx drops headers containing underscores by default (e.g. `session_id`), which breaks sticky session routing in multi-account setups.
97
+
98
+ ---
99
+
100
  ## Deployment
101
 
102
  ### Method 0: Hugging Face Docker Space
 
129
  ```
130
 
131
  ### Method 1: Script Installation (Recommended)
132
+
133
+ One-click installation script that downloads pre-built binaries from GitHub Releases.
134
+
135
+ #### Prerequisites
136
+
137
+ - Linux server (amd64 or arm64)
138
+ - PostgreSQL 15+ (installed and running)
139
+ - Redis 7+ (installed and running)
140
+ - Root privileges
141
+
142
+ #### Installation Steps
143
+
144
+ ```bash
145
+ curl -sSL https://raw.githubusercontent.com/Wei-Shaw/sub2api/main/deploy/install.sh | sudo bash
146
+ ```
147
+
148
+ The script will:
149
+ 1. Detect your system architecture
150
+ 2. Download the latest release
151
+ 3. Install binary to `/opt/sub2api`
152
+ 4. Create systemd service
153
+ 5. Configure system user and permissions
154
+
155
+ #### Post-Installation
156
+
157
+ ```bash
158
+ # 1. Start the service
159
+ sudo systemctl start sub2api
160
+
161
+ # 2. Enable auto-start on boot
162
+ sudo systemctl enable sub2api
163
+
164
+ # 3. Open Setup Wizard in browser
165
+ # http://YOUR_SERVER_IP:8080
166
+ ```
167
+
168
+ The Setup Wizard will guide you through:
169
+ - Database configuration
170
+ - Redis configuration
171
+ - Admin account creation
172
+
173
+ #### Upgrade
174
+
175
+ You can upgrade directly from the **Admin Dashboard** by clicking the **Check for Updates** button in the top-left corner.
176
+
177
+ The web interface will:
178
+ - Check for new versions automatically
179
+ - Download and apply updates with one click
180
+ - Support rollback if needed
181
+
182
+ #### Useful Commands
183
+
184
+ ```bash
185
+ # Check status
186
+ sudo systemctl status sub2api
187
+
188
+ # View logs
189
+ sudo journalctl -u sub2api -f
190
+
191
+ # Restart service
192
+ sudo systemctl restart sub2api
193
+
194
+ # Uninstall
195
+ curl -sSL https://raw.githubusercontent.com/Wei-Shaw/sub2api/main/deploy/install.sh | sudo bash -s -- uninstall -y
196
+ ```
197
+
198
+ ---
199
+
200
+ ### Method 2: Docker Compose (Recommended)
201
+
202
+ Deploy with Docker Compose, including PostgreSQL and Redis containers.
203
+
204
+ #### Prerequisites
205
+
206
+ - Docker 20.10+
207
+ - Docker Compose v2+
208
+
209
+ #### Quick Start (One-Click Deployment)
210
+
211
+ Use the automated deployment script for easy setup:
212
+
213
+ ```bash
214
+ # Create deployment directory
215
+ mkdir -p sub2api-deploy && cd sub2api-deploy
216
+
217
+ # Download and run deployment preparation script
218
+ curl -sSL https://raw.githubusercontent.com/Wei-Shaw/sub2api/main/deploy/docker-deploy.sh | bash
219
+
220
+ # Start services
221
+ docker compose up -d
222
+
223
+ # View logs
224
+ docker compose logs -f sub2api
225
+ ```
226
+
227
+ **What the script does:**
228
+ - Downloads `docker-compose.local.yml` (saved as `docker-compose.yml`) and `.env.example`
229
+ - Generates secure credentials (JWT_SECRET, TOTP_ENCRYPTION_KEY, POSTGRES_PASSWORD)
230
+ - Creates `.env` file with auto-generated secrets
231
+ - Creates data directories (uses local directories for easy backup/migration)
232
+ - Displays generated credentials for your reference
233
+
234
+ #### Manual Deployment
235
+
236
+ If you prefer manual setup:
237
+
238
+ ```bash
239
+ # 1. Clone the repository
240
+ git clone https://github.com/Wei-Shaw/sub2api.git
241
+ cd sub2api/deploy
242
+
243
+ # 2. Copy environment configuration
244
+ cp .env.example .env
245
+
246
+ # 3. Edit configuration (generate secure passwords)
247
+ nano .env
248
+ ```
249
+
250
+ **Required configuration in `.env`:**
251
+
252
+ ```bash
253
+ # PostgreSQL password (REQUIRED)
254
+ POSTGRES_PASSWORD=your_secure_password_here
255
+
256
+ # JWT Secret (RECOMMENDED - keeps users logged in after restart)
257
+ JWT_SECRET=your_jwt_secret_here
258
+
259
+ # TOTP Encryption Key (RECOMMENDED - preserves 2FA after restart)
260
+ TOTP_ENCRYPTION_KEY=your_totp_key_here
261
+
262
+ # Optional: Admin account
263
+ ADMIN_EMAIL=admin@example.com
264
+ ADMIN_PASSWORD=your_admin_password
265
+
266
+ # Optional: Custom port
267
+ SERVER_PORT=8080
268
+ ```
269
+
270
+ **Generate secure secrets:**
271
+ ```bash
272
+ # Generate JWT_SECRET
273
+ openssl rand -hex 32
274
+
275
+ # Generate TOTP_ENCRYPTION_KEY
276
+ openssl rand -hex 32
277
+
278
+ # Generate POSTGRES_PASSWORD
279
+ openssl rand -hex 32
280
+ ```
281
+
282
+ ```bash
283
+ # 4. Create data directories (for local version)
284
+ mkdir -p data postgres_data redis_data
285
+
286
+ # 5. Start all services
287
+ # Option A: Local directory version (recommended - easy migration)
288
+ docker compose -f docker-compose.local.yml up -d
289
+
290
+ # Option B: Named volumes version (simple setup)
291
+ docker compose up -d
292
+
293
+ # 6. Check status
294
+ docker compose -f docker-compose.local.yml ps
295
+
296
+ # 7. View logs
297
+ docker compose -f docker-compose.local.yml logs -f sub2api
298
+ ```
299
+
300
+ #### Deployment Versions
301
+
302
+ | Version | Data Storage | Migration | Best For |
303
+ |---------|-------------|-----------|----------|
304
+ | **docker-compose.local.yml** | Local directories | βœ… Easy (tar entire directory) | Production, frequent backups |
305
+ | **docker-compose.yml** | Named volumes | ⚠️ Requires docker commands | Simple setup |
306
+
307
+ **Recommendation:** Use `docker-compose.local.yml` (deployed by script) for easier data management.
308
+
309
+ #### Access
310
+
311
+ Open `http://YOUR_SERVER_IP:8080` in your browser.
312
+
313
+ If admin password was auto-generated, find it in logs:
314
+ ```bash
315
+ docker compose -f docker-compose.local.yml logs sub2api | grep "admin password"
316
+ ```
317
+
318
+ #### Upgrade
319
+
320
+ ```bash
321
+ # Pull latest image and recreate container
322
+ docker compose -f docker-compose.local.yml pull
323
+ docker compose -f docker-compose.local.yml up -d
324
+ ```
325
+
326
+ #### Easy Migration (Local Directory Version)
327
+
328
+ When using `docker-compose.local.yml`, migrate to a new server easily:
329
+
330
+ ```bash
331
+ # On source server
332
+ docker compose -f docker-compose.local.yml down
333
+ cd ..
334
+ tar czf sub2api-complete.tar.gz sub2api-deploy/
335
+
336
+ # Transfer to new server
337
+ scp sub2api-complete.tar.gz user@new-server:/path/
338
+
339
+ # On new server
340
+ tar xzf sub2api-complete.tar.gz
341
+ cd sub2api-deploy/
342
+ docker compose -f docker-compose.local.yml up -d
343
+ ```
344
+
345
+ #### Useful Commands
346
+
347
+ ```bash
348
+ # Stop all services
349
+ docker compose -f docker-compose.local.yml down
350
+
351
+ # Restart
352
+ docker compose -f docker-compose.local.yml restart
353
+
354
+ # View all logs
355
+ docker compose -f docker-compose.local.yml logs -f
356
+
357
+ # Remove all data (caution!)
358
+ docker compose -f docker-compose.local.yml down
359
+ rm -rf data/ postgres_data/ redis_data/
360
+ ```
361
+
362
+ ---
363
+
364
+ ### Method 3: Build from Source
365
+
366
+ Build and run from source code for development or customization.
367
+
368
+ #### Prerequisites
369
+
370
+ - Go 1.21+
371
+ - Node.js 18+
372
+ - PostgreSQL 15+
373
+ - Redis 7+
374
+
375
+ #### Build Steps
376
+
377
+ ```bash
378
+ # 1. Clone the repository
379
+ git clone https://github.com/Wei-Shaw/sub2api.git
380
+ cd sub2api
381
+
382
+ # 2. Install pnpm (if not already installed)
383
+ npm install -g pnpm
384
+
385
+ # 3. Build frontend
386
+ cd frontend
387
+ pnpm install
388
+ pnpm run build
389
+ # Output will be in ../backend/internal/web/dist/
390
+
391
+ # 4. Build backend with embedded frontend
392
+ cd ../backend
393
+ go build -tags embed -o sub2api ./cmd/server
394
+
395
+ # 5. Create configuration file
396
+ cp ../deploy/config.example.yaml ./config.yaml
397
+
398
+ # 6. Edit configuration
399
+ nano config.yaml
400
+ ```
401
+
402
+ > **Note:** The `-tags embed` flag embeds the frontend into the binary. Without this flag, the binary will not serve the frontend UI.
403
+
404
+ **Key configuration in `config.yaml`:**
405
+
406
+ ```yaml
407
+ server:
408
+ host: "0.0.0.0"
409
+ port: 8080
410
+ mode: "release"
411
+
412
+ database:
413
+ host: "localhost"
414
+ port: 5432
415
+ user: "postgres"
416
+ password: "your_password"
417
+ dbname: "sub2api"
418
+
419
+ redis:
420
+ host: "localhost"
421
+ port: 6379
422
+ password: ""
423
+
424
+ jwt:
425
+ secret: "change-this-to-a-secure-random-string"
426
+ expire_hour: 24
427
+
428
+ default:
429
+ user_concurrency: 5
430
+ user_balance: 0
431
+ api_key_prefix: "sk-"
432
+ rate_multiplier: 1.0
433
+ ```
434
+
435
+ ### Sora Status (Temporarily Unavailable)
436
+
437
+ > ⚠️ Sora-related features are temporarily unavailable due to technical issues in upstream integration and media delivery.
438
+ > Please do not rely on Sora in production at this time.
439
+ > Existing `gateway.sora_*` configuration keys are reserved and may not take effect until these issues are resolved.
440
+
441
+ Additional security-related options are available in `config.yaml`:
442
+
443
+ - `cors.allowed_origins` for CORS allowlist
444
+ - `security.url_allowlist` for upstream/pricing/CRS host allowlists
445
+ - `security.url_allowlist.enabled` to disable URL validation (use with caution)
446
+ - `security.url_allowlist.allow_insecure_http` to allow HTTP URLs when validation is disabled
447
+ - `security.url_allowlist.allow_private_hosts` to allow private/local IP addresses
448
+ - `security.response_headers.enabled` to enable configurable response header filtering (disabled uses default allowlist)
449
+ - `security.csp` to control Content-Security-Policy headers
450
+ - `billing.circuit_breaker` to fail closed on billing errors
451
+ - `server.trusted_proxies` to enable X-Forwarded-For parsing
452
+ - `turnstile.required` to require Turnstile in release mode
453
+
454
+ **⚠️ Security Warning: HTTP URL Configuration**
455
+
456
+ When `security.url_allowlist.enabled=false`, the system performs minimal URL validation by default, **rejecting HTTP URLs** and only allowing HTTPS. To allow HTTP URLs (e.g., for development or internal testing), you must explicitly set:
457
+
458
+ ```yaml
459
+ security:
460
+ url_allowlist:
461
+ enabled: false # Disable allowlist checks
462
+ allow_insecure_http: true # Allow HTTP URLs (⚠️ INSECURE)
463
+ ```
464
+
465
+ **Or via environment variable:**
466
+
467
+ ```bash
468
+ SECURITY_URL_ALLOWLIST_ENABLED=false
469
+ SECURITY_URL_ALLOWLIST_ALLOW_INSECURE_HTTP=true
470
+ ```
471
+
472
+ **Risks of allowing HTTP:**
473
+ - API keys and data transmitted in **plaintext** (vulnerable to interception)
474
+ - Susceptible to **man-in-the-middle (MITM) attacks**
475
+ - **NOT suitable for production** environments
476
+
477
+ **When to use HTTP:**
478
+ - βœ… Development/testing with local servers (http://localhost)
479
+ - βœ… Internal networks with trusted endpoints
480
+ - βœ… Testing account connectivity before obtaining HTTPS
481
+ - ❌ Production environments (use HTTPS only)
482
+
483
+ **Example error without this setting:**
484
+ ```
485
+ Invalid base URL: invalid url scheme: http
486
+ ```
487
+
488
+ If you disable URL validation or response header filtering, harden your network layer:
489
+ - Enforce an egress allowlist for upstream domains/IPs
490
+ - Block private/loopback/link-local ranges
491
+ - Enforce TLS-only outbound traffic
492
+ - Strip sensitive upstream response headers at the proxy
493
+
494
+ ```bash
495
+ # 6. Run the application
496
+ ./sub2api
497
+ ```
498
+
499
+ #### Development Mode
500
+
501
+ ```bash
502
+ # Backend (with hot reload)
503
+ cd backend
504
+ go run ./cmd/server
505
+
506
+ # Frontend (with hot reload)
507
+ cd frontend
508
+ pnpm run dev
509
+ ```
510
+
511
+ #### Code Generation
512
+
513
+ When editing `backend/ent/schema`, regenerate Ent + Wire:
514
+
515
+ ```bash
516
+ cd backend
517
+ go generate ./ent
518
+ go generate ./cmd/server
519
+ ```
520
+
521
+ ---
522
+
523
+ ## Simple Mode
524
+
525
+ Simple Mode is designed for individual developers or internal teams who want quick access without full SaaS features.
526
+
527
+ - Enable: Set environment variable `RUN_MODE=simple`
528
+ - Difference: Hides SaaS-related features and skips billing process
529
+ - Security note: In production, you must also set `SIMPLE_MODE_CONFIRM=true` to allow startup
530
+
531
+ ---
532
+
533
+ ## Antigravity Support
534
+
535
+ Sub2API supports [Antigravity](https://antigravity.so/) accounts. After authorization, dedicated endpoints are available for Claude and Gemini models.
536
+
537
+ ### Dedicated Endpoints
538
+
539
+ | Endpoint | Model |
540
+ |----------|-------|
541
+ | `/antigravity/v1/messages` | Claude models |
542
+ | `/antigravity/v1beta/` | Gemini models |
543
+
544
+ ### Claude Code Configuration
545
+
546
+ ```bash
547
+ export ANTHROPIC_BASE_URL="http://localhost:8080/antigravity"
548
+ export ANTHROPIC_AUTH_TOKEN="sk-xxx"
549
+ ```
550
+
551
+ ### Hybrid Scheduling Mode
552
+
553
+ Antigravity accounts support optional **hybrid scheduling**. When enabled, the general endpoints `/v1/messages` and `/v1beta/` will also route requests to Antigravity accounts.
554
+
555
+ > **⚠️ Warning**: Anthropic Claude and Antigravity Claude **cannot be mixed within the same conversation context**. Use groups to isolate them properly.
556
+
557
+ ### Known Issues
558
+
559
+ In Claude Code, Plan Mode cannot exit automatically. (Normally when using the native Claude API, after planning is complete, Claude Code will pop up options for users to approve or reject the plan.)
560
+
561
+ **Workaround**: Press `Shift + Tab` to manually exit Plan Mode, then type your response to approve or reject the plan.
562
+
563
+ ---
564
+
565
+ ## Project Structure
566
+
567
+ ```
568
+ sub2api/
569
+ β”œβ”€β”€ backend/ # Go backend service
570
+ β”‚ β”œβ”€β”€ cmd/server/ # Application entry
571
+ β”‚ β”œβ”€β”€ internal/ # Internal modules
572
+ β”‚ β”‚ β”œβ”€β”€ config/ # Configuration
573
+ β”‚ β”‚ β”œβ”€β”€ model/ # Data models
574
+ β”‚ β”‚ β”œβ”€β”€ service/ # Business logic
575
+ β”‚ β”‚ β”œβ”€β”€ handler/ # HTTP handlers
576
+ β”‚ β”‚ └── gateway/ # API gateway core
577
+ β”‚ └── resources/ # Static resources
578
+ β”‚
579
+ β”œβ”€β”€ frontend/ # Vue 3 frontend
580
+ β”‚ └── src/
581
+ β”‚ β”œβ”€β”€ api/ # API calls
582
+ β”‚ β”œβ”€β”€ stores/ # State management
583
+ β”‚ β”œβ”€β”€ views/ # Page components
584
+ β”‚ └── components/ # Reusable components
585
+ β”‚
586
+ └── deploy/ # Deployment files
587
+ β”œβ”€β”€ docker-compose.yml # Docker Compose configuration
588
+ β”œβ”€β”€ .env.example # Environment variables for Docker Compose
589
+ β”œβ”€β”€ config.example.yaml # Full config file for binary deployment
590
+ └── install.sh # One-click installation script
591
+ ```
592
+
593
+ ## Disclaimer
594
+
595
+ > **Please read carefully before using this project:**
596
+ >
597
+ > :rotating_light: **Terms of Service Risk**: Using this project may violate Anthropic's Terms of Service. Please read Anthropic's user agreement carefully before use. All risks arising from the use of this project are borne solely by the user.
598
+ >
599
+ > :book: **Disclaimer**: This project is for technical learning and research purposes only. The author assumes no responsibility for account suspension, service interruption, or any other losses caused by the use of this project.
600
+
601
+ ---
602
+
603
+ ## Star History
604
+
605
+ <a href="https://star-history.com/#Wei-Shaw/sub2api&Date">
606
+ <picture>
607
+ <source media="(prefers-color-scheme: dark)" srcset="https://api.star-history.com/svg?repos=Wei-Shaw/sub2api&type=Date&theme=dark" />
608
+ <source media="(prefers-color-scheme: light)" srcset="https://api.star-history.com/svg?repos=Wei-Shaw/sub2api&type=Date" />
609
+ <img alt="Star History Chart" src="https://api.star-history.com/svg?repos=Wei-Shaw/sub2api&type=Date" />
610
+ </picture>
611
+ </a>
612
+
613
+ ---
614
+
615
+ ## License
616
+
617
+ MIT License
618
+
619
+ ---
620
+
621
+ <div align="center">
622
+
623
+ **If you find this project useful, please give it a star!**
624
+
625
+ </div>