Spaces:
Paused
Paused
Upload 8 files
Browse filesFiles changed (9)
- .gitattributes+1
- docs/DONATE.mdAdded+11
- docs/HUGGINGFACE_DEPLOY.mdAdded+130
- docs/HUGGINGFACE_DOCKER_SPACE.mdAdded+154
- docs/README_EN.mdAdded+822
- docs/币安.jpgAdded
- front/control_panel.htmlAdded
- front/control_panel_mobile.htmlAdded
- front/multi_user_auth_web.htmlAdded+762
32 unmodified lines33343532 unmodified lines*.zip filter=lfs diff=lfs merge=lfs -text*.zst filter=lfs diff=lfs merge=lfs -text*tfevents* filter=lfs diff=lfs merge=lfs -text32 unmodified lines3334353632 unmodified lines*.zip filter=lfs diff=lfs merge=lfs -text*.zst filter=lfs diff=lfs merge=lfs -text*tfevents* filter=lfs diff=lfs merge=lfs -textdocs/币安.jpg filter=lfs diff=lfs merge=lfs -text
1234567891011# 💰 支持项目发展
感谢您使用 gcli2api!如果这个项目对您有帮助,欢迎通过以下方式支持项目的持续发展:
## 💝 捐赠方式
### 币安捐赠

*扫描上方二维码,使用币安进行捐赠*123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130# Hugging Face Spaces 部署指南
本文档介绍如何将 GCLI2API 部署到 Hugging Face Spaces。
## 1. 部署方式选择
推荐使用 **Gradio (Python) Space** 进行部署。
## 2. 必要文件说明
已添加以下适配文件:
| 文件 | 作用 || ---- | ---- || `app.py` | Hugging Face Space 启动入口,启动 FastAPI 服务并提供 Gradio 信息页 || `README_HF.md` | Hugging Face Space 展示 README,用于空间首页说明 || `requirements.txt` | 依赖列表,已加入 gradio 与 requests || `.env.example` | 环境变量示例文件 || `README.md` | 已添加 front matter 以支持 HF Metadata |
## 3. 创建 Hugging Face Space
1. 打开 https://huggingface.co/spaces2. 点击 "Create new Space"3. 选择技术栈:`Gradio`4. 填写名称,例如:`your-username/gcli2api`5. 选择可见性:`Public` 或 `Private`6. 创建后,将当前仓库代码推送到新建 Space 或在 Space 内手动上传文件
## 4. 设置环境变量 (Settings → Variables)
最少需要配置:
| 名称 | 说明 | 是否必需 || ---- | ---- | -------- || `API_PASSWORD` | API 请求认证密码 | 是(或用 PASSWORD) || `PANEL_PASSWORD` | 控制面板登录密码 | 是(或用 PASSWORD) || `PASSWORD` | 通用密码(设置后覆盖上面两个) | 否 || `AUTO_LOAD_ENV_CREDS` | 是否自动加载环境变量凭证 | 否 |
凭证(任选其一方式):
1. 在 Web 控制面板上传 credential JSON 文件2. 设置 `AUTO_LOAD_ENV_CREDS=true` 并添加: ```bash GCLI_CREDS_1={"client_id":"...","client_secret":"...","refresh_token":"...","token_uri":"https://oauth2.googleapis.com/token","project_id":"your-project"} GCLI_CREDS_2={"client_id":"...","project_id":"..."} ```
可选优化参数:```bashCALLS_PER_ROTATION=10RETRY_429_ENABLED=trueRETRY_429_MAX_RETRIES=5COMPATIBILITY_MODE=trueANTI_TRUNCATION_MAX_ATTEMPTS=3```
## 5. Space 启动后访问
| 功能 | URL 示例 || ---- | -------- || 控制面板 | `https://<space-id>.hf.space/auth` || OpenAI 模型列表 | `https://<space-id>.hf.space/v1/models` || 健康检测 | `https://<space-id>.hf.space/keepalive` |
## 6. 示例请求
```bashcurl -X POST "https://<space-id>.hf.space/v1/chat/completions" \ -H "Authorization: Bearer ${API_PASSWORD}" \ -H "Content-Type: application/json" \ -d '{ "model": "gemini-2.5-pro", "messages": [ {"role": "user", "content": "你好"} ] }'```
## 7. 常见问题与解决
| 问题 | 可能原因 | 解决方案 || ---- | -------- | -------- || 401 Unauthorized | 密码错误 | 检查 `API_PASSWORD` 或 `PASSWORD` || 503 Service Unavailable | 无有效凭证 | 上传或配置 GCLI_CREDS_* || 模型列表为空 | 未正确认证 | 确认凭证刷新成功 || 流式不输出 | 客户端不支持 SSE | 使用假流式模型 `假流式/` 前缀 |
## 8. 模型命名速查
| 模式 | 示例 || ---- | ---- || 基础 | `gemini-2.5-pro` || 假流式 | `假流式/gemini-2.5-pro` || 抗截断流式 | `流式抗截断/gemini-2.5-pro` || 最大思考 | `gemini-2.5-pro-maxthinking` || 无思考 | `gemini-2.5-pro-nothinking` || 搜索增强 | `gemini-2.5-pro-search` |
可组合:`流式抗截断/gemini-2.5-pro-maxthinking`
## 9. 安全建议
- 使用随机长密码(>=24字符)- Private Space 存放敏感凭证- 不要在公共 README 中泄露密码- 定期轮换凭证与刷新 token
## 10. 维护操作
| 操作 | 方法 || ---- | ---- || 更新代码 | 推送到 Space 触发重建 || 查看日志 | Space Logs 面板 + Web 面板实时日志 || 清空日志 | 面板中提供清空按钮 || 添加凭证 | 面板上传或新增环境变量 |
## 11. 自定义扩展 (可选)
如果需要自定义依赖或系统级库,可切换到 **Docker Space**,并使用项目中现有 `Dockerfile`(如需精简可自行裁剪)。
## 12. 版本升级策略
- 关注上游仓库 release- 使用 Git Submodule 或定期同步- 修改前备份 `creds/` 与持久化数据库
---如需进一步自动化(CI 自动推送 Space),可添加 GitHub Actions,构建并同步至 Hugging Face。123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154# Hugging Face Docker Space 部署指南
本文档说明如何使用 Hugging Face 的 Docker Space 技术栈部署 GCLI2API。
## 1. 选择 Docker 方式的适用场景
选择 **Docker** 而不是 Gradio 技术栈的场景:- 需要完全自定义运行环境- 需要更快的冷启动或更可控的依赖- 不需要额外 UI,仅提供 API 服务- 需要使用系统级扩展、构建工具或自定义脚本
## 2. 准备代码仓库
仓库已包含优化后的 `Dockerfile`,特点:- 多阶段构建(减小最终镜像体积)- 使用 `tini` 作为 init 进程,优雅处理信号- 非 root 用户运行(安全)- 支持 Hugging Face 自动注入的 `PORT` 环境变量- 支持健康检查(`/keepalive`)
## 3. 创建 Docker Space
1. 打开 https://huggingface.co/spaces2. Create New Space → 选择 `Docker` 技术栈3. 填写 Space 名称与可见性4. 创建后把本项目代码推送到该 Space(或者直接在 Space 网页上传文件)
## 4. Dockerfile 说明
当前项目内的 `Dockerfile` 默认启动命令:```dockerfileCMD ["python","app.py"]```app.py 会:- 启动 FastAPI 主应用 (web.py)- 提供可选的 Gradio 信息界面(若需要)
如仅需 API,可改为:```dockerfileCMD ["python","web.py"]```
## 5. 配置环境变量
在 Space 设置(Settings → Variables)中添加:
| 变量 | 说明 | 是否必需 || ---- | ---- | -------- || API_PASSWORD | API 访问密码 | 是 || PANEL_PASSWORD | 控制面板密码 | 是(或使用 PASSWORD) || AUTO_LOAD_ENV_CREDS | 启用环境变量凭证载入 | 否 || GCLI_CREDS_* | 提供 Google OAuth 凭证 | 依使用方式决定 |
可选性能优化:```bashCALLS_PER_ROTATION=10RETRY_429_ENABLED=trueRETRY_429_MAX_RETRIES=5ANTI_TRUNCATION_MAX_ATTEMPTS=3COMPATIBILITY_MODE=true```
## 6. 初次部署流程
1. 推送代码后 Space 会自动构建镜像2. 构建完成后自动运行容器3. 查看 Logs 确认输出中包含:`GCLI2API Lightspeed - Hugging Face Spaces Edition`4. 访问:`https://<space-id>.hf.space/auth` 登录控制台5. 上传或配置凭证6. 通过 `/v1/models` 验证 API 可用
## 7. API 访问示例
```bashcurl -X POST "https://<space-id>.hf.space/v1/chat/completions" \ -H "Authorization: Bearer ${API_PASSWORD}" \ -H "Content-Type: application/json" \ -d '{ "model": "gemini-2.5-pro", "messages": [ {"role": "user", "content": "介绍一下你自己"} ] }'```
健康检查:```bashcurl -I "https://<space-id>.hf.space/keepalive"```
## 8. 自定义与扩展
### 更换 Python 版本修改 `FROM python:3.13-slim` 为其他受支持版本(建议 >=3.11)。
### 添加系统依赖在 `Base Stage` 中:```dockerfileRUN apt-get update && apt-get install -y --no-install-recommends \ ffmpeg libmagic1 && rm -rf /var/lib/apt/lists/*```
### 修改启动参数使用环境变量:```bashPORT=7860 HOST=0.0.0.0 LOG_LEVEL=INFO```
或修改 Dockerfile:```dockerfileCMD ["python","-m","web"]```
## 9. 故障排查
| 症状 | 可能原因 | 解决方案 || ---- | -------- | -------- || Space 构建失败 | 依赖缺失/语法错误 | 查看构建日志,确认 requirements 正常安装 || 401 Unauthorized | 密码错误 | 确认 API_PASSWORD 与请求头一致 || 503 Service Unavailable | 无有效凭证 | 上传 Google OAuth 凭证或配置 GCLI_CREDS_* || 模型名称报错 | 模型名带前缀/后缀拼写错误 | 参考 README_HF.md 中模型命名规则 || 流式响应无输出 | 客户端不支持 SSE | 使用 假流式/ 前缀模型 || 截断 | 输出过长 | 使用 流式抗截断/ 前缀模型 |
## 10. 升级策略
更新代码并推送 -> Space 自动重建 -> 验证功能。如需保留持久凭证,可改用外部数据库(Redis/MongoDB/Postgres)。
## 11. 使用外部 Redis (示例)
在 Variables 中配置:```bashREDIS_URI=rediss://default:token@xxx.upstash.io:6379REDIS_DATABASE=0```
## 12. 使用 MongoDB Atlas (示例)```bashMONGODB_URI=mongodb+srv://user:pass@cluster.mongodb.netMONGODB_DATABASE=gcli2api```
## 13. 切换到 web.py 纯 API 模式
编辑 Dockerfile:```dockerfileCMD ["python","web.py"]```并删除 `app.py` 中的 Gradio 依赖(如不需要 UI)。
---如需 CI 自动同步到 Space,可添加 GitHub Action 使用 `huggingface-cli` 推送更新。123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822# GeminiCLI to API
**Convert GeminiCLI to OpenAI and GEMINI API interfaces**
[中文](../README.md) | English
## 🚀 Quick Deploy
[](https://zeabur.com/templates/2QLQC2?referralCode=su-kaka)---
## ⚠️ License Declaration
**This project is licensed under the Cooperative Non-Commercial License (CNC-1.0)**
This is a strict anti-commercial open source license. Please refer to the [LICENSE](../LICENSE) file for details.
### ✅ Permitted Uses:- Personal learning, research, and educational purposes- Non-profit organization use- Open source project integration (must comply with the same license)- Academic research and publication
### ❌ Prohibited Uses:- Any form of commercial use- Enterprise use with annual revenue exceeding $1 million- Venture capital-backed or publicly traded companies- Providing paid services or products- Commercial competitive use
---
## Core Features
### 🔄 API Endpoints and Format Support
**Multi-endpoint Dual Format Support**- **OpenAI Compatible Endpoints**: `/v1/chat/completions` and `/v1/models` - Supports standard OpenAI format (messages structure) - Supports Gemini native format (contents structure) - Automatic format detection and conversion, no manual switching required - Supports multimodal input (text + images)- **Gemini Native Endpoints**: `/v1/models/{model}:generateContent` and `streamGenerateContent` - Supports complete Gemini native API specifications - Multiple authentication methods: Bearer Token, x-goog-api-key header, URL parameter key
### 🔐 Authentication and Security Management
**Flexible Password Management**- **Separate Password Support**: API password (chat endpoints) and control panel password can be set independently- **Multiple Authentication Methods**: Supports Authorization Bearer, x-goog-api-key header, URL parameters, etc.- **JWT Token Authentication**: Control panel supports JWT token authentication- **User Email Retrieval**: Automatically retrieves and displays Google account email addresses
### 📊 Intelligent Credential Management System
**Advanced Credential Management**- Multiple Google OAuth credential automatic rotation- Enhanced stability through redundant authentication- Load balancing and concurrent request support- Automatic failure detection and credential disabling- Credential usage statistics and quota management- Support for manual enable/disable credential files- Batch credential file operations (enable, disable, delete)
**Credential Status Monitoring**- Real-time credential health checks- Error code tracking (429, 403, 500, etc.)- Automatic banning mechanism (configurable)- Credential rotation strategy (based on call count)- Usage statistics and quota monitoring
### 🌊 Streaming and Response Processing
**Multiple Streaming Support**- True real-time streaming responses- Fake streaming mode (for compatibility)- Streaming anti-truncation feature (prevents answer truncation)- Asynchronous task management and timeout handling
**Response Optimization**- Thinking chain content separation- Reasoning process (reasoning_content) handling- Multi-turn conversation context management- Compatibility mode (converts system messages to user messages)
### 🎛️ Web Management Console
**Full-featured Web Interface**- OAuth authentication flow management- Credential file upload, download, and management- Real-time log viewing (WebSocket)- System configuration management- Usage statistics and monitoring dashboard- Mobile-friendly interface
**Batch Operation Support**- ZIP file batch credential upload- Batch enable/disable/delete credentials- Batch user email retrieval- Batch configuration management
### 📈 Usage Statistics and Monitoring
**Detailed Usage Statistics**- Call count statistics by credential file- Gemini 2.5 Pro model specific statistics- Daily quota management (UTC+7 reset)- Aggregated statistics and analysis- Custom daily limit configuration
**Real-time Monitoring**- WebSocket real-time log streams- System status monitoring- Credential health status- API call success rate statistics
### 🔧 Advanced Configuration and Customization
**Network and Proxy Configuration**- HTTP/HTTPS proxy support- Proxy endpoint configuration (OAuth, Google APIs, metadata service)- Timeout and retry configuration- Network error handling and recovery
**Performance and Stability Configuration**- 429 error automatic retry (configurable interval and attempts)- Anti-truncation maximum retry attempts- Credential rotation strategy- Concurrent request management
**Logging and Debugging**- Multi-level logging system (DEBUG, INFO, WARNING, ERROR)- Log file management- Real-time log streams- Log download and clearing
### 🔄 Environment Variables and Configuration Management
**Flexible Configuration Methods**- TOML configuration file support- Environment variable configuration- Hot configuration updates (partial configuration items)- Configuration locking (environment variable priority)
**Environment Variable Credential Support**- `GCLI_CREDS_*` format environment variable import- Automatic loading of environment variable credentials- Base64 encoded credential support- Docker container friendly
## Supported Models
All models have 1M context window capacity. Each credential file provides 1000 request quota.
### 🤖 Base Models- `gemini-2.5-pro`- `gemini-2.5-pro-preview-06-05` - `gemini-2.5-pro-preview-05-06`
### 🧠 Thinking Models- `gemini-2.5-pro-maxthinking`: Maximum thinking budget mode- `gemini-2.5-pro-nothinking`: No thinking mode- Supports custom thinking budget configuration- Automatic separation of thinking content and final answers
### 🔍 Search-Enhanced Models- `gemini-2.5-pro-search`: Model with integrated search functionality
### 🌊 Special Feature Variants- **Fake Streaming Mode**: Add `-假流式` suffix to any model name - Example: `gemini-2.5-pro-假流式` - For scenarios requiring streaming responses but server doesn't support true streaming- **Streaming Anti-truncation Mode**: Add `流式抗截断/` prefix to model name - Example: `流式抗截断/gemini-2.5-pro` - Automatically detects response truncation and retries to ensure complete answers
### 🔧 Automatic Model Feature Detection- System automatically recognizes feature identifiers in model names- Transparently handles feature mode transitions- Supports feature combination usage
---
## Installation Guide
### Termux Environment
**Initial Installation**```bashcurl -o termux-install.sh "https://raw.githubusercontent.com/su-kaka/gcli2api/refs/heads/master/termux-install.sh" && chmod +x termux-install.sh && ./termux-install.sh```
**Restart Service**```bashcd gcli2apibash termux-start.sh```
### Windows Environment
**Initial Installation**```powershelliex (iwr "https://raw.githubusercontent.com/su-kaka/gcli2api/refs/heads/master/install.ps1" -UseBasicParsing).Content```
**Restart Service**Double-click to execute `start.bat`
### Linux Environment
**Initial Installation**```bashcurl -o install.sh "https://raw.githubusercontent.com/su-kaka/gcli2api/refs/heads/master/install.sh" && chmod +x install.sh && ./install.sh```
**Restart Service**```bashcd gcli2apibash start.sh```
### Docker Environment
**Docker Run Command**```bash# Using universal passworddocker run -d --name gcli2api --network host -e PASSWORD=pwd -e PORT=7861 -v $(pwd)/data/creds:/app/creds ghcr.io/su-kaka/gcli2api:latest
# Using separate passwordsdocker run -d --name gcli2api --network host -e API_PASSWORD=api_pwd -e PANEL_PASSWORD=panel_pwd -e PORT=7861 -v $(pwd)/data/creds:/app/creds ghcr.io/su-kaka/gcli2api:latest```
**Docker Compose Run Command**1. Save the following content as `docker-compose.yml` file: ```yaml version: '3.8'
services: gcli2api: image: ghcr.io/su-kaka/gcli2api:latest container_name: gcli2api restart: unless-stopped network_mode: host environment: # Using universal password (recommended for simple deployment) - PASSWORD=pwd - PORT=7861 # Or use separate passwords (recommended for production) # - API_PASSWORD=your_api_password # - PANEL_PASSWORD=your_panel_password volumes: - ./data/creds:/app/creds healthcheck: test: ["CMD-SHELL", "python -c \"import sys, urllib.request, os; port = os.environ.get('PORT', '7861'); req = urllib.request.Request(f'http://localhost:{port}/v1/models', headers={'Authorization': 'Bearer ' + os.environ.get('PASSWORD', 'pwd')}); sys.exit(0 if urllib.request.urlopen(req, timeout=5).getcode() == 200 else 1)\""] interval: 30s timeout: 10s retries: 3 start_period: 40s ```2. Start the service: ```bash docker-compose up -d ```
---
## ⚠️ Important Notes
- The current OAuth authentication process **only supports localhost access**, meaning authentication must be completed through `http://127.0.0.1:7861/auth` (default port 7861, modifiable via PORT environment variable).- **For deployment on cloud servers or other remote environments, please first run the service locally and complete OAuth authentication to obtain the generated json credential files (located in the `./geminicli/creds` directory), then upload these files via the auth panel.**- **Please strictly comply with usage restrictions, only for personal learning and non-commercial purposes**
---
## Configuration Instructions
1. Visit `http://127.0.0.1:7861/auth` (default port, modifiable via PORT environment variable)2. Complete OAuth authentication flow (default password: `pwd`, modifiable via environment variables)3. Configure client:
**OpenAI Compatible Client:** - **Endpoint Address**: `http://127.0.0.1:7861/v1` - **API Key**: `pwd` (default value, modifiable via API_PASSWORD or PASSWORD environment variables)
**Gemini Native Client:** - **Endpoint Address**: `http://127.0.0.1:7861` - **Authentication Methods**: - `Authorization: Bearer your_api_password` - `x-goog-api-key: your_api_password` - URL parameter: `?key=your_api_password`
## 💾 Distributed Storage Mode
### 🌟 Storage Backend Priority
gcli2api supports multiple storage backends, automatically selecting by priority: **Redis > Postgres > MongoDB > Local Files**
### ⚡ Redis Distributed Storage Mode
### ⚙️ Enable Redis Mode
**Step 1: Configure Redis Connection**```bash# Local Redisexport REDIS_URI="redis://localhost:6379"
# Redis with passwordexport REDIS_URI="redis://:password@localhost:6379"
# SSL connection (recommended for production)export REDIS_URI="rediss://default:password@host:6380"
# Upstash Redis (free cloud service)export REDIS_URI="rediss://default:token@your-host.upstash.io:6379"
# Optional: Custom database index (default: 0)export REDIS_DATABASE="1"```
**Step 2: Start Application**```bash# Application will automatically detect Redis configuration and prioritize Redis storagepython web.py```
### 🐘 Postgres Distributed Storage Mode
If Redis is not configured, or you prefer a relational database, gcli2api also supports Postgres (it is checked after Redis and before MongoDB).
⚙️ Enable Postgres Mode
Step 1: Configure Postgres DSN```bash# Example DSN:export POSTGRES_DSN="postgresql://user:password@localhost:5432/gcli2api"```
Step 2: Start Application```bash# Application will detect POSTGRES_DSN and use Postgres when Redis is not availablepython web.py```
### 🍃 MongoDB Distributed Storage Mode
### 🌟 Alternative Storage Solution
If Redis is not configured, gcli2api will attempt to use **MongoDB storage mode**.
### ⚙️ Enable MongoDB Mode
**Step 1: Configure MongoDB Connection**```bash# Local MongoDBexport MONGODB_URI="mongodb://localhost:27017"
# MongoDB Atlas cloud serviceexport MONGODB_URI="mongodb+srv://username:password@cluster.mongodb.net"
# MongoDB with authenticationexport MONGODB_URI="mongodb://admin:password@localhost:27017/admin"
# Optional: Custom database name (default: gcli2api)export MONGODB_DATABASE="my_gcli_db"```
**Step 2: Start Application**```bash# Application will automatically detect MongoDB configuration and use MongoDB storagepython web.py```
**Docker Environment using MongoDB**```bash# Single MongoDB deploymentdocker run -d --name gcli2api \ -e MONGODB_URI="mongodb://mongodb:27017" \ -e API_PASSWORD=your_password \ --network your_network \ ghcr.io/su-kaka/gcli2api:latest
# Using MongoDB Atlasdocker run -d --name gcli2api \ -e MONGODB_URI="mongodb+srv://user:pass@cluster.mongodb.net/gcli2api" \ -e API_PASSWORD=your_password \ -p 7861:7861 \ ghcr.io/su-kaka/gcli2api:latest```
**Docker Compose Example**```yamlversion: '3.8'
services: mongodb: image: mongo:7 container_name: gcli2api-mongodb restart: unless-stopped environment: MONGO_INITDB_ROOT_USERNAME: admin MONGO_INITDB_ROOT_PASSWORD: password123 volumes: - mongodb_data:/data/db ports: - "27017:27017"
gcli2api: image: ghcr.io/su-kaka/gcli2api:latest container_name: gcli2api restart: unless-stopped depends_on: - mongodb environment: - MONGODB_URI=mongodb://admin:password123@mongodb:27017/admin - MONGODB_DATABASE=gcli2api - API_PASSWORD=your_api_password - PORT=7861 ports: - "7861:7861"
volumes: mongodb_data:```
### 🛠️ Troubleshooting
**Common Issue Solutions**
```bash# Check MongoDB connectionpython mongodb_setup.py check
# View detailed status informationpython mongodb_setup.py status
# Verify data migration resultspython -c "import asynciofrom src.storage_adapter import get_storage_adapter
async def test(): storage = await get_storage_adapter() info = await storage.get_backend_info() print(f'Current mode: {info[\"backend_type\"]}') if info['backend_type'] == 'mongodb': print(f'Database: {info.get(\"database_name\", \"Unknown\")}')
asyncio.run(test())"```
**Migration Failure Handling**```bash# If migration is interrupted, re-runpython mongodb_setup.py migrate
# To rollback to file mode, remove MONGODB_URI environment variableunset MONGODB_URI# Then export data from MongoDBpython mongodb_setup.py export```
### 🔧 Advanced Configuration
**MongoDB Connection Optimization**```bash# Connection pool and timeout configurationexport MONGODB_URI="mongodb://localhost:27017?maxPoolSize=10&serverSelectionTimeoutMS=5000"
# Replica set configurationexport MONGODB_URI="mongodb://host1:27017,host2:27017,host3:27017/gcli2api?replicaSet=myReplicaSet"
# Read-write separation configurationexport MONGODB_URI="mongodb://localhost:27017/gcli2api?readPreference=secondaryPreferred"```
## 🏗️ Technical Architecture
### Core Module Description
**Authentication and Credential Management** (`src/auth.py`, `src/credential_manager.py`)- OAuth 2.0 authentication flow management- Multi-credential file status management and rotation- Automatic failure detection and recovery- JWT token generation and validation
**API Routing and Conversion** (`src/openai_router.py`, `src/gemini_router.py`, `src/openai_transfer.py`)- OpenAI and Gemini format bidirectional conversion- Multimodal input processing (text+images)- Thinking chain content separation and processing- Streaming response management
**Network and Proxy** (`src/httpx_client.py`, `src/google_chat_api.py`)- Unified HTTP client management- Proxy configuration and hot update support- Timeout and retry strategies- Asynchronous request pool management
**State Management** (`src/state_manager.py`, `src/usage_stats.py`)- Atomic state operations- Usage statistics and quota management- File locking and concurrency safety- Data persistence (TOML format)
**Task Management** (`src/task_manager.py`)- Global asynchronous task lifecycle management- Resource cleanup and memory management- Graceful shutdown and exception handling
**Web Console** (`src/web_routes.py`)- RESTful API endpoints- WebSocket real-time communication- Mobile device adaptation detection- Batch operation support
### Advanced Feature Implementation
**Streaming Anti-truncation Mechanism** (`src/anti_truncation.py`)- Response truncation pattern detection- Automatic retry and state recovery- Context connection management
**Format Detection and Conversion** (`src/format_detector.py`)- Automatic request format detection (OpenAI vs Gemini)- Seamless format conversion- Parameter mapping and validation
**User Agent Simulation** (`src/utils.py`)- GeminiCLI format user agent generation- Platform detection and client metadata- API compatibility guarantee
### Environment Variable Configuration
**Basic Configuration**- `PORT`: Service port (default: 7861)- `HOST`: Server listen address (default: 0.0.0.0)
**Password Configuration**- `API_PASSWORD`: Chat API access password (default: inherits PASSWORD or pwd)- `PANEL_PASSWORD`: Control panel access password (default: inherits PASSWORD or pwd) - `PASSWORD`: Universal password, overrides the above two when set (default: pwd)
**Performance and Stability Configuration**- `CALLS_PER_ROTATION`: Number of calls before each credential rotation (default: 10)- `RETRY_429_ENABLED`: Enable 429 error automatic retry (default: true)- `RETRY_429_MAX_RETRIES`: Maximum retry attempts for 429 errors (default: 3)- `RETRY_429_INTERVAL`: Retry interval for 429 errors, in seconds (default: 1.0)- `ANTI_TRUNCATION_MAX_ATTEMPTS`: Maximum retry attempts for anti-truncation (default: 3)
**Network and Proxy Configuration**- `PROXY`: HTTP/HTTPS proxy address (format: `http://host:port`)- `OAUTH_PROXY_URL`: OAuth authentication proxy endpoint- `GOOGLEAPIS_PROXY_URL`: Google APIs proxy endpoint- `METADATA_SERVICE_URL`: Metadata service proxy endpoint
**Automation Configuration**- `AUTO_BAN`: Enable automatic credential banning (default: true)- `AUTO_LOAD_ENV_CREDS`: Automatically load environment variable credentials at startup (default: false)
**Compatibility Configuration**- `COMPATIBILITY_MODE`: Enable compatibility mode, converts system messages to user messages (default: false)
**Logging Configuration**- `LOG_LEVEL`: Log level (DEBUG/INFO/WARNING/ERROR, default: INFO)- `LOG_FILE`: Log file path (default: gcli2api.log)
**Storage Configuration (by priority)**
**Redis Configuration (Highest Priority)**- `REDIS_URI`: Redis connection string (enables Redis mode when set) - Local: `redis://localhost:6379` - With password: `redis://:password@host:6379` - SSL: `rediss://default:password@host:6380`- `REDIS_DATABASE`: Redis database index (0-15, default: 0)
**MongoDB Configuration (Second Priority)**- `MONGODB_URI`: MongoDB connection string (enables MongoDB mode when set)- `MONGODB_DATABASE`: MongoDB database name (default: gcli2api)
**Credential Configuration**
Support importing multiple credentials using `GCLI_CREDS_*` environment variables:
#### Credential Environment Variable Usage Examples
**Method 1: Numbered Format**```bashexport GCLI_CREDS_1='{"client_id":"your-client-id","client_secret":"your-secret","refresh_token":"your-token","token_uri":"https://oauth2.googleapis.com/token","project_id":"your-project"}'export GCLI_CREDS_2='{"client_id":"...","project_id":"..."}'```
**Method 2: Project Name Format**```bashexport GCLI_CREDS_myproject='{"client_id":"...","project_id":"myproject",...}'export GCLI_CREDS_project2='{"client_id":"...","project_id":"project2",...}'```
**Enable Automatic Loading**```bashexport AUTO_LOAD_ENV_CREDS=true # Automatically import environment variable credentials at program startup```
**Docker Usage Example**```bash# Using universal passworddocker run -d --name gcli2api \ -e PASSWORD=mypassword \ -e PORT=8080 \ -e GOOGLE_CREDENTIALS="$(cat credential.json | base64 -w 0)" \ ghcr.io/su-kaka/gcli2api:latest
# Using separate passwordsdocker run -d --name gcli2api \ -e API_PASSWORD=my_api_password \ -e PANEL_PASSWORD=my_panel_password \ -e PORT=8080 \ -e GOOGLE_CREDENTIALS="$(cat credential.json | base64 -w 0)" \ ghcr.io/su-kaka/gcli2api:latest```
Note: When credential environment variables are set, the system will prioritize using credentials from environment variables and ignore files in the `creds` directory.
### API Usage Methods
This service supports two complete sets of API endpoints:
#### 1. OpenAI Compatible Endpoints
**Endpoint:** `/v1/chat/completions` **Authentication:** `Authorization: Bearer your_api_password`
Supports two request formats with automatic detection and processing:
**OpenAI Format:**```json{ "model": "gemini-2.5-pro", "messages": [ {"role": "system", "content": "You are a helpful assistant"}, {"role": "user", "content": "Hello"} ], "temperature": 0.7, "stream": true}```
**Gemini Native Format:**```json{ "model": "gemini-2.5-pro", "contents": [ {"role": "user", "parts": [{"text": "Hello"}]} ], "systemInstruction": {"parts": [{"text": "You are a helpful assistant"}]}, "generationConfig": { "temperature": 0.7 }}```
#### 2. Gemini Native Endpoints
**Non-streaming Endpoint:** `/v1/models/{model}:generateContent` **Streaming Endpoint:** `/v1/models/{model}:streamGenerateContent` **Model List:** `/v1/models`
**Authentication Methods (choose one):**- `Authorization: Bearer your_api_password`- `x-goog-api-key: your_api_password` - URL parameter: `?key=your_api_password`
**Request Examples:**```bash# Using x-goog-api-key headercurl -X POST "http://127.0.0.1:7861/v1/models/gemini-2.5-pro:generateContent" \ -H "x-goog-api-key: your_api_password" \ -H "Content-Type: application/json" \ -d '{ "contents": [ {"role": "user", "parts": [{"text": "Hello"}]} ] }'
# Using URL parametercurl -X POST "http://127.0.0.1:7861/v1/models/gemini-2.5-pro:streamGenerateContent?key=your_api_password" \ -H "Content-Type: application/json" \ -d '{ "contents": [ {"role": "user", "parts": [{"text": "Hello"}]} ] }'```
**Notes:**- OpenAI endpoints return OpenAI-compatible format- Gemini endpoints return Gemini native format- Both endpoints use the same API password
## 📋 Complete API Reference
### Web Console API
**Authentication Endpoints**- `POST /auth/login` - User login- `POST /auth/start` - Start OAuth authentication- `POST /auth/callback` - Handle OAuth callback- `GET /auth/status/{project_id}` - Check authentication status
**Credential Management Endpoints**- `GET /creds/status` - Get all credential statuses- `POST /creds/action` - Single credential operation (enable/disable/delete)- `POST /creds/batch-action` - Batch credential operations- `POST /auth/upload` - Batch upload credential files (supports ZIP)- `GET /creds/download/{filename}` - Download credential file- `GET /creds/download-all` - Package download all credentials- `POST /creds/fetch-email/{filename}` - Get user email- `POST /creds/refresh-all-emails` - Batch refresh user emails
**Configuration Management Endpoints**- `GET /config/get` - Get current configuration- `POST /config/save` - Save configuration
**Environment Variable Credential Endpoints**- `POST /auth/load-env-creds` - Load environment variable credentials- `DELETE /auth/env-creds` - Clear environment variable credentials- `GET /auth/env-creds-status` - Get environment variable credential status
**Log Management Endpoints**- `POST /auth/logs/clear` - Clear logs- `GET /auth/logs/download` - Download log file- `WebSocket /auth/logs/stream` - Real-time log stream
**Usage Statistics Endpoints**- `GET /usage/stats` - Get usage statistics- `GET /usage/aggregated` - Get aggregated statistics- `POST /usage/update-limits` - Update usage limits- `POST /usage/reset` - Reset usage statistics
### Chat API Features
**Multimodal Support**```json{ "model": "gemini-2.5-pro", "messages": [ { "role": "user", "content": [ {"type": "text", "text": "Describe this image"}, { "type": "image_url", "image_url": { "url": "data:image/jpeg;base64,/9j/4AAQSkZJRgABA..." } } ] } ]}```
**Thinking Mode Support**```json{ "model": "gemini-2.5-pro-maxthinking", "messages": [ {"role": "user", "content": "Complex math problem"} ]}```
Response will include separated thinking content:```json{ "choices": [{ "message": { "role": "assistant", "content": "Final answer", "reasoning_content": "Detailed thought process..." } }]}```
**Streaming Anti-truncation Usage**```json{ "model": "流式抗截断/gemini-2.5-pro", "messages": [ {"role": "user", "content": "Write a long article"} ], "stream": true}```
**Compatibility Mode**```bash# Enable compatibility modeexport COMPATIBILITY_MODE=true```In this mode, all `system` messages are converted to `user` messages, improving compatibility with certain clients.
---
## Support the Project
If this project has been helpful to you, we welcome your support for the project's continued development!
For detailed donation information, please see: [📖 Donation Documentation](DONATE.md)
---
## License and Disclaimer
This project is for learning and research purposes only. Using this project indicates that you agree to:- Not use this project for any commercial purposes- Bear all risks and responsibilities of using this project- Comply with relevant terms of service and legal regulations
The project authors are not responsible for any direct or indirect losses arising from the use of this project.123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762<!DOCTYPE html><html lang="zh-CN"><head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Google OAuth 认证</title> <style> body { font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, Arial, sans-serif; max-width: 700px; margin: 0 auto; padding: 20px; background: linear-gradient(135deg, #667eea 0%, #764ba2 100%); min-height: 100vh; display: flex; align-items: center; justify-content: center; } .container { background: white; padding: 40px; border-radius: 15px; box-shadow: 0 20px 40px rgba(0,0,0,0.1); width: 100%; max-width: 600px; } h1 { color: #333; text-align: center; margin-bottom: 30px; font-size: 28px; font-weight: 300; } .logo { text-align: center; margin-bottom: 30px; } .logo svg { width: 60px; height: 60px; } .form-group { margin-bottom: 25px; } label { display: block; margin-bottom: 8px; font-weight: 600; color: #555; font-size: 14px; } input[type="text"], input[type="password"] { width: 100%; padding: 12px 16px; border: 2px solid #e1e5e9; border-radius: 8px; font-size: 16px; box-sizing: border-box; transition: all 0.3s ease; } input[type="text"]:focus, input[type="password"]:focus { border-color: #4285f4; outline: none; box-shadow: 0 0 0 3px rgba(66, 133, 244, 0.1); } .btn { background: linear-gradient(135deg, #4285f4, #34a853); color: white; padding: 14px 30px; border: none; border-radius: 8px; font-size: 16px; cursor: pointer; width: 100%; margin-bottom: 15px; font-weight: 600; transition: all 0.3s ease; } .btn:hover { transform: translateY(-2px); box-shadow: 0 10px 20px rgba(66, 133, 244, 0.3); } .btn:active { transform: translateY(0); } .btn:disabled { background: #ccc; cursor: not-allowed; transform: none; box-shadow: none; } .btn.secondary { background: linear-gradient(135deg, #34a853, #fbbc04); } .btn.download { background: linear-gradient(135deg, #ea4335, #ff6900); } .auth-url { background: #f8f9fa; border: 2px solid #e1e4e8; border-radius: 8px; padding: 20px; margin: 25px 0; word-break: break-all; border-left: 4px solid #4285f4; } .auth-url a { color: #4285f4; text-decoration: none; font-weight: 600; } .auth-url a:hover { text-decoration: underline; } .credentials { background: #f0f8ff; border: 2px solid #b0d4ff; border-radius: 8px; padding: 20px; margin: 25px 0; font-family: 'Consolas', 'Monaco', 'Courier New', monospace; font-size: 12px; white-space: pre-wrap; word-break: break-all; max-height: 400px; overflow-y: auto; border-left: 4px solid #34a853; } .status { padding: 15px 20px; border-radius: 8px; margin: 20px 0; font-weight: 500; } .status.success { background: #d4edda; border: 2px solid #c3e6cb; color: #155724; border-left: 4px solid #28a745; } .status.error { background: #f8d7da; border: 2px solid #f5c6cb; color: #721c24; border-left: 4px solid #dc3545; } .status.info { background: #d1ecf1; border: 2px solid #bee5eb; color: #0c5460; border-left: 4px solid #17a2b8; } .status.warning { background: #fff3cd; border: 2px solid #ffeaa7; color: #856404; border-left: 4px solid #ffc107; } .hidden { display: none; } .loading { text-align: center; color: #666; } .login-form { text-align: center; padding: 20px 0; } .steps { background: #f8f9fa; border-radius: 8px; padding: 20px; margin: 25px 0; border-left: 4px solid #ffc107; } .steps h4 { margin-top: 0; color: #333; font-size: 16px; } .steps ol { margin: 15px 0; padding-left: 20px; } .steps li { margin-bottom: 8px; color: #555; line-height: 1.5; } .api-warning { background: #fff3cd; border: 2px solid #ffeaa7; border-radius: 8px; padding: 20px; margin: 25px 0; border-left: 4px solid #ffc107; } .api-warning h4 { color: #856404; margin-top: 0; display: flex; align-items: center; gap: 8px; } .api-warning a { color: #4285f4; text-decoration: none; font-weight: 600; } .api-warning a:hover { text-decoration: underline; } .progress-bar { background: #e9ecef; border-radius: 10px; height: 8px; margin: 15px 0; overflow: hidden; } .progress-fill { background: linear-gradient(135deg, #28a745, #20c997); height: 100%; width: 0%; transition: width 0.3s ease; } .footer { text-align: center; margin-top: 30px; padding-top: 20px; border-top: 1px solid #e1e5e9; color: #666; font-size: 14px; } @media (max-width: 768px) { body { padding: 10px; } .container { padding: 20px; } } /* 下载按钮动画 */ .download-animation { animation: downloadPulse 2s infinite; } @keyframes downloadPulse { 0% { transform: scale(1); } 50% { transform: scale(1.05); } 100% { transform: scale(1); } } </style></head><body> <div class="container"> <!-- 登录界面 --> <div id="loginSection"> <div class="logo"> <svg viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg"> <path d="M22.56 12.25c0-.78-.07-1.53-.2-2.25H12v4.26h5.92c-.26 1.37-1.04 2.53-2.21 3.31v2.77h3.57c2.08-1.92 3.28-4.74 3.28-8.09z" fill="#4285F4"/> <path d="M12 23c2.97 0 5.46-.98 7.28-2.66l-3.57-2.77c-.98.66-2.23 1.06-3.71 1.06-2.86 0-5.29-1.93-6.16-4.53H2.18v2.84C3.99 20.53 7.7 23 12 23z" fill="#34A853"/> <path d="M5.84 14.09c-.22-.66-.35-1.36-.35-2.09s.13-1.43.35-2.09V7.07H2.18C1.43 8.55 1 10.22 1 12s.43 3.45 1.18 4.93l2.85-2.22.81-.62z" fill="#FBBC05"/> <path d="M12 5.38c1.62 0 3.06.56 4.21 1.64l3.15-3.15C17.45 2.09 14.97 1 12 1 7.7 1 3.99 3.47 2.18 7.07l3.66 2.84c.87-2.6 3.3-4.53 6.16-4.53z" fill="#EA4335"/> </svg> </div> <h1>Google OAuth 认证</h1> <div class="login-form"> <div class="form-group"> <input type="password" id="password" placeholder="请输入访问密码" onkeypress="handlePasswordEnter(event)" /> </div> <button class="btn" onclick="login()">登录</button> </div> </div>
<!-- 主界面 --> <div id="mainSection" class="hidden"> <h1>Google OAuth 认证</h1> <!-- API 自动启用说明 --> <div class="status info"> <h4>✨ 自动化优化</h4> <p style="margin: 15px 0;">系统现在会在认证成功后自动为您的项目启用以下必需的API服务:</p> <ul style="margin: 15px 0; padding-left: 20px;"> <li><strong>Gemini Cloud Assist API</strong></li> <li><strong>Gemini for Google Cloud API</strong></li> </ul> <p style="margin: 15px 0; color: #0c5460;"><strong>说明:</strong>无需手动启用API,系统会自动处理这些配置步骤。</p> </div>
<!-- 折叠式 Project ID 输入框 --> <div class="form-group"> <div style="cursor: pointer; user-select: none; padding: 12px; border: 2px solid #e1e5e9; border-radius: 8px; background: #f8f9fa; display: flex; justify-content: space-between; align-items: center;" onclick="toggleProjectIdSection()"> <span style="font-weight: 600; color: #555;">📁 高级选项:Google Cloud Project ID (不用管,直接点击获取链接即可)</span> <span id="projectIdToggleIcon" style="font-size: 14px; color: #666; transition: transform 0.3s ease;">▶</span> </div> <div id="projectIdSection" style="display: none; margin-top: 15px; padding: 15px; border: 2px solid #e1e5e9; border-top: none; border-radius: 0 0 8px 8px; background: #ffffff;"> <label for="projectId" style="display: block; margin-bottom: 8px; font-weight: 600; color: #555; font-size: 14px;">Google Cloud Project ID (可选):</label> <input type="text" id="projectId" style="width: 100%; padding: 12px 16px; border: 2px solid #e1e5e9; border-radius: 8px; font-size: 16px; box-sizing: border-box; transition: all 0.3s ease;" placeholder="留空将尝试自动检测,或手动输入项目ID" /> <small style="color: #666; font-size: 12px; margin-top: 5px; display: block;"> 💡 提示:如果你不懂这是什么,可以留空此字段让系统自动检测项目ID </small> </div> </div> <button class="btn" id="getAuthBtn" onclick="startAuth()">获取认证链接</button> <div id="authUrlSection" class="hidden"> <h3>步骤一:认证链接</h3> <div class="auth-url"> <a id="authUrl" href="#" target="_blank">点击此链接进行 OAuth 认证</a> </div> <div class="steps"> <h4>认证步骤:</h4> <ol> <li>点击上方认证链接,在新窗口中完成 Google 登录</li> <li>授权应用访问您的 Google Cloud 项目</li> <li>看到 "OAuth authentication successful!" 页面后,关闭该窗口</li> <li>返回本页面,点击下方"获取认证文件"按钮</li> </ol> <div class="status warning" style="margin-top: 20px;"> <h4>⚠️ 注意</h4> <p>当回源时,网页访问会显示报错。这时请手动将浏览器地址栏的 <code>localhost</code> 修改为 <code>gcli-auth.sukaka.top</code>,然后重新访问即可。</p> </div> </div> <!-- 快捷回调URL输入选项 --> <div style="margin: 20px 0; padding: 15px; border: 2px solid #e8f4fd; border-radius: 8px; background: #f8fcff;"> <div style="cursor: pointer; user-select: none; display: flex; justify-content: space-between; align-items: center; margin-bottom: 10px;" onclick="toggleCallbackUrlSection()"> <span style="font-weight: 600; color: #0066cc; font-size: 16px;">🚀 无法回源?试试快捷方式</span> <span id="callbackUrlToggleIcon" style="font-size: 14px; color: #666; transition: transform 0.3s ease;">▼</span> </div> <div id="callbackUrlSection" style="display: none;"> <div style="background: #fff3cd; border: 1px solid #ffeaa7; border-radius: 6px; padding: 12px; margin-bottom: 12px;"> <div style="color: #856404; font-size: 14px; font-weight: bold; margin-bottom: 6px;">📚 适用场景:</div> <ul style="color: #856404; font-size: 13px; margin: 0; padding-left: 18px; line-height: 1.5;"> <li>云服务器、VPS等非本地环境</li> <li>防火墙阻止了回调端口访问</li> <li>网络环境无法正常回源</li> <li>Docker容器端口映射问题</li> </ul> </div> <div style="color: #666; font-size: 13px; margin-bottom: 12px; line-height: 1.6;"> <strong style="color: #0066cc;">🔍 什么是回调URL?</strong><br> 完成Google OAuth授权后,浏览器地址栏显示的完整URL,通常看起来像这样:<br> <code style="background: #f1f3f4; padding: 2px 6px; border-radius: 3px; font-size: 12px; word-break: break-all; display: block; margin-top: 4px;"> http://localhost:8080/?state=abc123...&code=4/0AVMBsJ...&scope=email%20profile... </code> </div> <div style="background: #e7f3ff; border: 1px solid #b3d9ff; border-radius: 6px; padding: 10px; margin-bottom: 12px;"> <div style="color: #0066cc; font-size: 13px; font-weight: bold; margin-bottom: 4px;">📋 使用步骤:</div> <ol style="color: #0066cc; font-size: 12px; margin: 0; padding-left: 18px; line-height: 1.4;"> <li>点击上方认证链接,完成Google授权</li> <li>授权成功后,复制浏览器地址栏的<strong>完整URL</strong></li> <li>粘贴到下方输入框,点击获取凭证即可</li> </ol> </div> <div style="margin-bottom: 12px;"> <input type="url" id="callbackUrlInput" placeholder="粘贴完整的回调URL,例如:http://localhost:8080/?state=xxx&code=xxx&scope=xxx..." style="width: 100%; padding: 10px; border: 2px solid #ddd; border-radius: 4px; font-size: 13px; box-sizing: border-box;"> </div> <button class="btn" style="background: #28a745; border-color: #28a745;" onclick="processCallbackUrl()"> 从回调URL获取凭证 </button> </div> </div> <button class="btn secondary" id="getCredsBtn" onclick="getCredentials()">获取认证文件</button> </div> <div id="credentialsSection" class="hidden"> <h3>步骤二:认证成功!</h3> <div class="status success"> <strong>✅ OAuth 认证成功完成!</strong><br> 认证文件已生成,您可以下载保存或复制使用。 </div> <div class="credentials" id="credentialsContent"></div> <button class="btn download download-animation" id="downloadBtn" onclick="downloadCredentials()"> 📥 下载认证文件 </button> <button class="btn" onclick="resetForm()">认证其他项目</button> </div>
<div id="statusSection"></div> <div class="footer"> <p>🔒 您的认证信息将安全保存,仅用于访问指定的 Google Cloud 项目</p> <!-- 项目信息 --> <div style="background-color: #f8f9fa; border: 1px solid #dee2e6; border-radius: 8px; padding: 15px; margin-top: 20px; text-align: center; border-left: 4px solid #17a2b8;"> <p style="margin: 6px 0; font-size: 15px; color: #495057;">GitHub: <a href="https://github.com/su-kaka/gcli2api" target="_blank" style="color: #17a2b8; text-decoration: none; font-weight: 500;">https://github.com/su-kaka/gcli2api</a></p> <p style="margin: 6px 0; font-size: 15px; color: #dc3545; font-weight: 500;">⚠️ 禁止商业用途和倒卖 - 仅供学习使用 ⚠️</p> </div> </div> </div> </div>
<script> let currentProjectId = ''; let authInProgress = false; let authToken = ''; let currentCredentials = null;
function showStatus(message, type = 'info') { const statusSection = document.getElementById('statusSection'); if (statusSection) { statusSection.innerHTML = `<div class="status ${type}">${message}</div>`; // 自动滚动到状态消息 statusSection.scrollIntoView({ behavior: 'smooth', block: 'nearest' }); } }
// 登录相关函数 async function login() { const password = document.getElementById('password').value; if (!password) { showStatus('请输入密码', 'error'); return; }
try { const response = await fetch('/auth/login', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ password: password }) });
const data = await response.json(); if (response.ok) { authToken = data.token; document.getElementById('loginSection').classList.add('hidden'); document.getElementById('mainSection').classList.remove('hidden'); showStatus('登录成功', 'success'); } else { showStatus(`登录失败: ${data.detail || data.error || '密码错误'}`, 'error'); } } catch (error) { showStatus(`网络错误: ${error.message}`, 'error'); } }
function handlePasswordEnter(event) { if (event.key === 'Enter') { login(); } }
// 获取认证头 function getAuthHeaders() { return { 'Content-Type': 'application/json', 'Authorization': `Bearer ${authToken}` }; }
async function startAuth() { const projectId = document.getElementById('projectId').value.trim(); // 项目ID现在是可选的 currentProjectId = projectId || null; const btn = document.getElementById('getAuthBtn'); btn.disabled = true; btn.textContent = '正在生成认证链接...';
try { const requestBody = {}; if (projectId) { requestBody.project_id = projectId; showStatus('使用指定的项目ID生成认证链接...', 'info'); } else { showStatus('将尝试自动检测项目ID,正在生成认证链接...', 'info'); }
const response = await fetch('/auth/start', { method: 'POST', headers: getAuthHeaders(), body: JSON.stringify(requestBody) });
const data = await response.json(); if (response.ok) { document.getElementById('authUrl').href = data.auth_url; document.getElementById('authUrl').textContent = data.auth_url; document.getElementById('authUrlSection').classList.remove('hidden'); if (data.auto_project_detection) { showStatus('认证链接已生成(将在认证完成后自动检测项目ID),请点击链接完成 OAuth 授权', 'info'); } else { showStatus(`认证链接已生成(项目ID: ${data.detected_project_id}),请点击链接完成 OAuth 授权`, 'info'); } authInProgress = true; } else { showStatus(`生成认证链接失败: ${data.error || '未知错误'}`, 'error'); } } catch (error) { showStatus(`网络错误: ${error.message}`, 'error'); } finally { btn.disabled = false; btn.textContent = '获取认证链接'; } }
async function getCredentials() { if (!authInProgress) { showStatus('请先获取认证链接并完成 OAuth 授权', 'error'); return; }
const btn = document.getElementById('getCredsBtn'); btn.disabled = true; btn.textContent = '等待 OAuth 回调...';
try { showStatus('正在等待 OAuth 回调,请确保已完成浏览器中的授权...', 'info'); const requestBody = {}; if (currentProjectId) { requestBody.project_id = currentProjectId; } const response = await fetch('/auth/callback', { method: 'POST', headers: getAuthHeaders(), body: JSON.stringify(requestBody) });
const data = await response.json(); if (response.ok) { currentCredentials = data.credentials; document.getElementById('credentialsContent').textContent = JSON.stringify(data.credentials, null, 2); document.getElementById('credentialsSection').classList.remove('hidden'); if (data.auto_detected_project) { showStatus(`认证成功!项目ID已自动检测为: ${data.credentials.project_id},文件已保存到服务器: ${data.file_path}`, 'success'); } else { showStatus(`认证成功!文件已保存到服务器: ${data.file_path}`, 'success'); } authInProgress = false; // 隐藏前面的步骤,突出显示成功结果 document.getElementById('authUrlSection').style.opacity = '0.6'; } else { // 检查是否需要项目选择 if (data.requires_project_selection && data.available_projects) { let projectOptions = "请选择一个项目:\n\n"; data.available_projects.forEach((project, index) => { projectOptions += `${index + 1}. ${project.name} (${project.projectId})\n`; }); projectOptions += `\n请输入序号 (1-${data.available_projects.length}):`; const selection = prompt(projectOptions); const projectIndex = parseInt(selection) - 1; if (projectIndex >= 0 && projectIndex < data.available_projects.length) { const selectedProject = data.available_projects[projectIndex]; currentProjectId = selectedProject.projectId; btn.textContent = '重新尝试获取认证文件'; showStatus(`使用选择的项目 ${selectedProject.name} (${selectedProject.projectId}) 重新尝试...`, 'info'); setTimeout(() => getCredentials(), 1000); return; } else { showStatus('无效的选择,请重新开始认证', 'error'); } } // 检查是否需要手动输入项目ID else if (data.requires_manual_project_id) { const userProjectId = prompt('无法自动检测项目ID,请手动输入您的Google Cloud项目ID:'); if (userProjectId && userProjectId.trim()) { // 重新尝试,使用用户输入的项目ID currentProjectId = userProjectId.trim(); btn.textContent = '重新尝试获取认证文件'; showStatus('使用手动输入的项目ID重新尝试...', 'info'); setTimeout(() => getCredentials(), 1000); return; } else { showStatus('需要项目ID才能完成认证,请重新开始并输入正确的项目ID', 'error'); } } else { showStatus(`认证失败: ${data.error || '获取认证文件失败'}`, 'error'); if (data.error && data.error.includes('未接收到授权回调')) { showStatus('提示:请确保已完成浏览器中的 OAuth 认证,并看到了"OAuth authentication successful"页面', 'warning'); } } } } catch (error) { showStatus(`网络错误: ${error.message}`, 'error'); } finally { btn.disabled = false; btn.textContent = '获取认证文件'; } }
function downloadCredentials() { if (!currentCredentials) { showStatus('没有可下载的认证文件', 'error'); return; }
const filename = `${currentProjectId}-credentials.json`; const content = JSON.stringify(currentCredentials, null, 2); const blob = new Blob([content], { type: 'application/json' }); const url = window.URL.createObjectURL(blob); const a = document.createElement('a'); a.style.display = 'none'; a.href = url; a.download = filename; document.body.appendChild(a); a.click(); window.URL.revokeObjectURL(url); document.body.removeChild(a); showStatus(`认证文件已下载: ${filename}`, 'success'); }
function resetForm() { // 重置表单 document.getElementById('projectId').value = ''; document.getElementById('authUrlSection').classList.add('hidden'); document.getElementById('credentialsSection').classList.add('hidden'); document.getElementById('authUrlSection').style.opacity = '1'; // 重置状态 currentProjectId = ''; authInProgress = false; currentCredentials = null; showStatus('请输入新的 Project ID 开始认证', 'info'); }
// Project ID 折叠切换函数 function toggleProjectIdSection() { const section = document.getElementById('projectIdSection'); const icon = document.getElementById('projectIdToggleIcon'); if (section.style.display === 'none') { section.style.display = 'block'; icon.style.transform = 'rotate(90deg)'; icon.textContent = '▼'; } else { section.style.display = 'none'; icon.style.transform = 'rotate(0deg)'; icon.textContent = '▶'; } }
// 回调URL输入区域折叠切换函数 function toggleCallbackUrlSection() { const section = document.getElementById('callbackUrlSection'); const icon = document.getElementById('callbackUrlToggleIcon');
if (section.style.display === 'none') { section.style.display = 'block'; icon.style.transform = 'rotate(180deg)'; icon.textContent = '▲'; } else { section.style.display = 'none'; icon.style.transform = 'rotate(0deg)'; icon.textContent = '▼'; } }
// 处理回调URL的函数 async function processCallbackUrl() { const callbackUrlInput = document.getElementById('callbackUrlInput'); const callbackUrl = callbackUrlInput.value.trim();
if (!callbackUrl) { showStatus('请输入回调URL', 'error'); return; }
// 简单验证URL格式 if (!callbackUrl.startsWith('http://') && !callbackUrl.startsWith('https://')) { showStatus('请输入有效的URL(以http://或https://开头)', 'error'); return; }
// 检查是否包含必要参数 if (!callbackUrl.includes('code=') || !callbackUrl.includes('state=')) { showStatus('❌ 这不是有效的回调URL!请确保:\n1. 已完成Google OAuth授权\n2. 复制的是浏览器地址栏的完整URL\n3. URL包含code和state参数', 'error'); return; }
showStatus('正在从回调URL获取凭证...', 'info');
try { // 获取当前项目ID设置(如果有的话) const projectIdInput = document.getElementById('projectId'); const projectId = projectIdInput ? projectIdInput.value.trim() : null;
const response = await fetch('/auth/callback-url', { method: 'POST', headers: getAuthHeaders(), body: JSON.stringify({ callback_url: callbackUrl, project_id: projectId || null }) });
const result = await response.json();
if (result.credentials) { // 显示成功信息 showStatus(result.message || '从回调URL获取凭证成功!', 'success'); // 隐藏认证URL区域,显示凭证内容 document.getElementById('authUrlSection').classList.add('hidden'); document.getElementById('credentialsSection').classList.remove('hidden'); // 显示凭证内容 document.getElementById('credentialsContent').innerHTML = '<pre>' + JSON.stringify(result.credentials, null, 2) + '</pre>'; // 设置全局变量供下载使用 window.currentCredentials = result.credentials; // 清空输入框 callbackUrlInput.value = ''; } else if (result.requires_manual_project_id) { showStatus('需要手动指定项目ID,请在高级选项中填入Google Cloud项目ID后重试', 'error'); } else if (result.requires_project_selection) { let projectOptions = '\n\n可用项目:\n'; result.available_projects.forEach(project => { projectOptions += `• ${project.name} (ID: ${project.projectId})\n`; }); showStatus('检测到多个项目,请在高级选项中指定项目ID:' + projectOptions, 'error'); } else { showStatus(result.error || '从回调URL获取凭证失败', 'error'); } } catch (error) { console.error('从回调URL获取凭证时出错:', error); showStatus(`从回调URL获取凭证失败: ${error.message}`, 'error'); } }
// 页面加载时的初始化 window.onload = function() { showStatus('请输入密码登录以开始 OAuth 认证', 'info'); // 自动聚焦到密码输入框 document.getElementById('password').focus(); }; </script></body></html>.gitattributes+1
docs/DONATE.mdAdded+11
docs/HUGGINGFACE_DEPLOY.mdAdded+130
docs/HUGGINGFACE_DOCKER_SPACE.mdAdded+154
docs/README_EN.mdAdded+822
docs/币安.jpgAdded

Large File Pointer Details
- SHA256: dda43355858a13738dcb9023374aefc303ec846dd21f7c4b60c37bea5165852b
- Pointer size: 131 Bytes
- Size of remote file: 106 kB
front/control_panel.htmlAdded
front/control_panel_mobile.htmlAdded
front/multi_user_auth_web.htmlAdded+762