Compare commits

..

28 Commits

Author SHA1 Message Date
CJACK.
aa032540dc Merge pull request #11 from CJackHwang/codex/fix-vercel-deployment-adapt-issue-ota5s1
Stop committing WebUI build artifacts; add Vercel build + cache headers; remove committed static/admin files
2026-02-04 20:21:34 +08:00
CJACK.
b6062fdb0b Merge pull request #14 from CJackHwang/codex/update-vercel.json-build-configurations
Remove deprecated Vercel builds config
2026-02-04 20:19:17 +08:00
CJACK.
fda5f9339e Remove deprecated Vercel builds config 2026-02-04 20:17:51 +08:00
CJACK.
86ade10888 Fail build if WebUI output missing 2026-02-04 19:53:05 +08:00
CJACK.
063c5d2540 Build WebUI in Docker image 2026-02-04 19:40:34 +08:00
CJACK.
4e62292500 Merge pull request #12 from CJackHwang/revert-8-codex/fix-vercel-deployment-adapt-issue
Revert "Build WebUI during Vercel deployment and enforce Cache-Control for admin UI"
2026-02-04 18:25:43 +08:00
CJACK.
58d54adee2 Revert "Build WebUI during Vercel deployment and enforce Cache-Control for admin UI" 2026-02-04 18:25:04 +08:00
CJACK.
8ca5581171 Remove committed WebUI build artifacts 2026-02-04 18:05:57 +08:00
CJACK.
2007e0cde3 Merge pull request #8 from CJackHwang/codex/fix-vercel-deployment-adapt-issue
Build WebUI during Vercel deployment and enforce Cache-Control for admin UI
2026-02-04 14:25:41 +08:00
CJACK.
51f8d3c09f Clarify WebUI build ownership in docs 2026-02-04 14:19:27 +08:00
CJACK.
94238070d8 Update accounts module description 2026-02-04 14:12:42 +08:00
CJACK.
a917e19e9d Fix Vercel config routing properties 2026-02-04 14:00:19 +08:00
CJACK.
f65cf0c510 Build webui during Vercel deployment 2026-02-04 13:57:34 +08:00
github-actions[bot]
840042d301 chore: auto-build WebUI [skip ci] 2026-02-04 05:35:55 +00:00
CJACK.
16ea6b7a5a Merge pull request #7 from CJackHwang/codex/review-pr-for-docker-compatibility
Improve dev Docker reload, account token/session handling, and Vercel sync
2026-02-04 13:35:34 +08:00
CJACK.
d67b64633b Fix docker dev reload and token sync 2026-02-04 13:25:43 +08:00
CJACK.
a1b3f122a7 Merge pull request #6 from CJackHwang/cto-task-goal-ds2api-docker-docker-exploration-findings-files-examine
Add decoupled Docker support for ds2api
2026-02-04 01:10:54 +08:00
cto-new[bot]
43cb68cc1d Add decoupled Docker support with zero-intrusion design 2026-02-03 17:07:22 +00:00
CJACK.
06ae417dad Update README.MD
更新webui展示图片
2026-02-03 13:31:49 +08:00
CJACK.
28b70ca26c Update README.MD 2026-02-03 13:31:04 +08:00
CJACK
ee2dac28bd chore: remove debug logs 2026-02-01 21:47:23 +08:00
CJACK
db28b4e93e fix: simplify vercel.json and add debug logs for static file issues 2026-02-01 21:41:05 +08:00
CJACK
092532c625 feat: Add Vercel static builder and routes to serve admin assets. 2026-02-01 21:24:53 +08:00
CJACK
1a842c28d1 feat: Establish WebUI build process, update frontend assets, and add CI workflow. 2026-02-01 21:17:19 +08:00
CJACK.
ce0538fcd9 Merge pull request #4 from ronghuaxueleng/main
feat(webui): 添加 API 密钥自动生成和复制功能
2026-02-01 21:07:20 +08:00
qiangcao
eef4ec4a65 Merge branch 'CJackHwang:main' into main 2026-02-01 21:01:28 +08:00
CJACK
951c47f8c5 docs: Update copyright year to 2026 and generalize a feature description. 2026-02-01 20:41:46 +08:00
root
db80aebadc feat(webui): 添加 API 密钥自动生成和复制功能
- 添加密钥弹窗增加「生成」按钮,自动生成 sk-xxx 格式随机密钥
- 密钥列表添加复制按钮,点击复制完整密钥到剪贴板
- 复制成功显示内联 toast 提示
2026-02-01 20:32:59 +08:00
21 changed files with 3598 additions and 593 deletions

69
.dockerignore Normal file
View File

@@ -0,0 +1,69 @@
# Git
.git
.gitignore
# Python
__pycache__
*.py[cod]
*$py.class
*.so
.Python
build/
develop-eggs/
dist/
downloads/
eggs/
.eggs/
lib/
lib64/
parts/
sdist/
var/
wheels/
*.egg-info/
.installed.cfg
*.egg
# 虚拟环境
venv/
env/
ENV/
.venv
# 环境配置(通过 docker-compose 挂载或环境变量传递)
.env
.env.local
.env.*.local
config.json
# 开发工具
.vscode/
.idea/
*.swp
*.swo
*~
# 测试
tests/
.pytest_cache/
.coverage
htmlcov/
# Node.js / WebUI 开发依赖
node_modules/
webui/node_modules/
npm-debug.log*
yarn-debug.log*
yarn-error.log*
# 文档
*.md
!README*.md
# CI/CD
.github/
.releaserc.json
# 其他
.DS_Store
Thumbs.db

View File

@@ -17,4 +17,8 @@
#### 📝 补充信息 | Additional Information
<!-- Add any other context about the Pull Request here. -->
<!-- Add any other context about the Pull Request here. -->
---
> 💡 **提示**:如果修改了 `webui/` 目录下的文件PR 合并后 CI 会自动构建并提交产物,无需手动构建。

5
.gitignore vendored
View File

@@ -55,7 +55,8 @@ webui/node_modules/
webui/dist/
.npm
.pnpm-store/
package-lock.json
# 保留 webui/package-lock.json 用于 CI 缓存
# package-lock.json # 如果有根目录的可以忽略
yarn.lock
pnpm-lock.yaml
@@ -63,6 +64,8 @@ pnpm-lock.yaml
*.tsbuildinfo
.cache/
.parcel-cache/
static/admin/*
!static/admin/.gitkeep
# Environment
.env.local

90
CONTRIBUTING.md Normal file
View File

@@ -0,0 +1,90 @@
# 贡献指南
感谢你对 DS2API 的贡献!
## 开发环境设置
### 后端
```bash
# 1. 克隆仓库
git clone https://github.com/CJackHwang/ds2api.git
cd ds2api
# 2. 创建虚拟环境(推荐)
python -m venv venv
source venv/bin/activate # Windows: venv\Scripts\activate
# 3. 安装依赖
pip install -r requirements.txt
# 4. 配置
cp config.example.json config.json
# 编辑 config.json
# 5. 启动
python dev.py
```
### 前端 (WebUI)
```bash
cd webui
npm install
npm run dev
```
## 代码规范
- **Python**: 遵循 PEP 8使用 4 空格缩进
- **JavaScript/React**: 使用 4 空格缩进,使用函数组件
- **提交信息**: 使用语义化提交格式(如 `feat:`, `fix:`, `docs:`
## 提交 PR
1. Fork 本仓库
2. 创建功能分支 (`git checkout -b feature/xxx`)
3. 提交更改 (`git commit -m 'feat: 添加xxx功能'`)
4. 推送分支 (`git push origin feature/xxx`)
5. 创建 Pull Request
## WebUI 构建
> **重要**: 修改 `webui/` 目录后 **无需手动构建**
当 PR 合并到 `main` 分支后GitHub Actions 会自动:
1. 构建 WebUI
2. 提交构建产物到 `static/admin/`
如果需要本地构建(测试用):
```bash
./scripts/build-webui.sh
```
## 项目结构
```
ds2api/
├── app.py # FastAPI 应用入口
├── dev.py # 开发服务器
├── core/ # 核心模块
│ ├── auth.py # 账号认证与轮询
│ ├── config.py # 配置管理
│ ├── deepseek.py # DeepSeek API 调用
│ ├── models.py # 模型定义
│ ├── pow.py # PoW 计算
│ └── sse_parser.py # SSE 解析
├── routes/ # API 路由
│ ├── openai.py # OpenAI 兼容接口
│ ├── claude.py # Claude 兼容接口
│ ├── home.py # 首页路由
│ └── admin/ # 管理接口
├── webui/ # React WebUI 源码
├── static/admin/ # WebUI 构建产物(自动生成)
└── scripts/ # 辅助脚本
```
## 问题反馈
- 使用 [GitHub Issues](https://github.com/CJackHwang/ds2api/issues) 报告问题
- 提供详细的复现步骤和日志信息

181
DEPLOY.md
View File

@@ -7,6 +7,7 @@
## 目录
- [Vercel 部署(推荐)](#vercel-部署推荐)
- [Docker 部署(推荐)](#docker-部署推荐)
- [本地开发](#本地开发)
- [生产环境部署](#生产环境部署)
- [常见问题](#常见问题)
@@ -125,6 +126,131 @@ npm run dev
WebUI 开发服务器会启动在 `http://localhost:5173`,并自动代理 API 请求到后端 `http://localhost:5001`
### WebUI 构建
WebUI 构建产物位于 `static/admin/` 目录。
**自动构建(推荐)**
- 当前由 Vercel 在部署时执行 WebUI 构建(见 `vercel.json``buildCommand`
- GitHub Actions 的 WebUI 自动构建流程已关闭
- `static/admin/` 构建产物不再提交到仓库
**手动构建**
```bash
# 方式1使用脚本
./scripts/build-webui.sh
# 方式2直接执行
cd webui
npm install
npm run build
```
> **贡献者注意**:修改 WebUI 后无需手动构建Vercel 部署会自动构建。
---
## Docker 部署(推荐)
Docker 部署采用**零侵入、解耦设计**
- Dockerfile 仅执行标准 Python 项目操作,不硬编码任何项目特定配置
- 构建镜像时会一并构建 WebUI便于非 Vercel 部署直接访问管理面板)
- 所有配置通过环境变量和 `.env` 文件管理
- **主代码更新时只需重新构建镜像,无需修改 Docker 配置**
### 快速开始Docker Compose
```bash
# 1. 复制环境变量模板
cp .env.example .env
# 编辑 .env填写 DS2API_ADMIN_KEY 和 DS2API_CONFIG_JSON
# 2. 启动服务
docker-compose up -d
# 3. 查看日志
docker-compose logs -f
# 4. 主代码更新后重新构建
docker-compose up -d --build
```
### 配置文件挂载方式
如需使用 `config.json` 而非环境变量:
```yaml
# docker-compose.yml
services:
ds2api:
build: .
ports:
- "5001:5001"
environment:
- DS2API_ADMIN_KEY=your-admin-key
volumes:
- ./config.json:/app/config.json:ro
restart: unless-stopped
```
### Docker 命令行部署
```bash
# 构建镜像
docker build -t ds2api:latest .
# 使用环境变量运行
docker run -d \
--name ds2api \
-p 5001:5001 \
-e DS2API_ADMIN_KEY=your-admin-key \
-e DS2API_CONFIG_JSON='{"keys":["api-key"],"accounts":[...]}' \
--restart unless-stopped \
ds2api:latest
# 或使用配置文件挂载
docker run -d \
--name ds2api \
-p 5001:5001 \
-e DS2API_ADMIN_KEY=your-admin-key \
-v $(pwd)/config.json:/app/config.json:ro \
--restart unless-stopped \
ds2api:latest
```
### 开发模式(热重载)
```bash
# 使用开发配置启动,代码修改实时生效
docker-compose -f docker-compose.dev.yml up
```
开发模式特性:
- 源代码挂载到容器,修改即时生效
- 日志级别设为 DEBUG
- 自动读取本地 `config.json`
### 维护命令
```bash
# 查看容器状态
docker-compose ps
# 查看日志
docker-compose logs -f ds2api
# 重启服务
docker-compose restart
# 停止服务
docker-compose down
# 完全重建(清除缓存)
docker-compose down
docker-compose build --no-cache
docker-compose up -d
```
---
## 生产环境部署
@@ -210,52 +336,6 @@ server {
}
```
### Docker 部署(可选)
```dockerfile
# Dockerfile
FROM python:3.11-slim
WORKDIR /app
COPY requirements.txt .
RUN pip install --no-cache-dir -r requirements.txt
COPY . .
EXPOSE 5001
CMD ["python", "app.py"]
```
```bash
# 构建镜像
docker build -t ds2api .
# 运行容器
docker run -d \
--name ds2api \
-p 5001:5001 \
-e DS2API_ADMIN_KEY=your-admin-key \
-e DS2API_CONFIG_JSON='{"keys":["api-key"],"accounts":[...]}' \
ds2api
```
### Docker Compose
```yaml
# docker-compose.yml
version: '3.8'
services:
ds2api:
build: .
ports:
- "5001:5001"
environment:
- DS2API_ADMIN_KEY=${DS2API_ADMIN_KEY}
- DS2API_CONFIG_JSON=${DS2API_CONFIG_JSON}
restart: unless-stopped
```
---
## 常见问题
@@ -291,6 +371,15 @@ pip install -r requirements.txt
# 重启服务
```
**Docker 部署**:
```bash
# 拉取最新代码
git pull origin main
# 重新构建并启动(无需修改 Docker 配置)
docker-compose up -d --build
```
**Vercel 部署**:
- 项目会自动从 GitHub 同步更新
- 或在 Vercel 控制台手动触发重新部署

33
Dockerfile Normal file
View File

@@ -0,0 +1,33 @@
# DS2API Docker 镜像
# 采用极简、零侵入设计,所有配置通过环境变量传递
# 主代码更新时只需重新构建镜像,无需修改 Dockerfile
FROM node:20 AS webui-builder
WORKDIR /app/webui
COPY webui/package.json webui/package-lock.json ./
RUN npm ci
COPY webui ./
RUN npm run build
FROM python:3.11-slim
WORKDIR /app
# 安装依赖(利用 Docker 缓存层)
COPY requirements.txt .
RUN pip install --no-cache-dir -r requirements.txt
# 复制整个项目(保留原始目录结构)
COPY . .
# 拷贝 WebUI 构建产物(非 Vercel / Docker 部署可直接使用)
COPY --from=webui-builder /app/static/admin /app/static/admin
# 暴露服务端口
EXPOSE 5001
# 启动命令(依赖项目自身的启动逻辑)
CMD ["python", "app.py"]

View File

@@ -4,9 +4,18 @@
![Stars](https://img.shields.io/github/stars/CJackHwang/ds2api.svg)
![Forks](https://img.shields.io/github/forks/CJackHwang/ds2api.svg)
[![Version](https://img.shields.io/badge/version-1.6.11-blue.svg)](version.txt)
[![Docker](https://img.shields.io/badge/docker-ready-blue.svg)](DEPLOY.md#docker-部署推荐)
将 DeepSeek 免费对话版转换为 **OpenAI & Claude 兼容 API**,支持多账号轮询、自动 Token 刷新、可视化管理界面。
![p1](https://github.com/user-attachments/assets/07296a50-50d4-4f05-a9e5-280df14e9532)
![p2](https://github.com/user-attachments/assets/03b4a763-766f-4050-aea8-1a183e70ae6a)
![p3](https://github.com/user-attachments/assets/beb9e41d-4c12-45d1-a26c-154280211185)
![p4](https://github.com/user-attachments/assets/fc8b9836-11e3-4c38-a684-eb2c79b80fe9)
![p5](https://github.com/user-attachments/assets/513e9ca7-aa9e-45a6-8f7e-f362b1650675)
## ✨ 特性
- 🔄 **双协议兼容** - 同时支持 OpenAI 和 Claude (Anthropic) API 格式
@@ -184,17 +193,26 @@ location / {
}
```
### Docker 部署(可选)
### 方式三:Docker 部署
```bash
# 使用环境变量配置
docker run -d \
-p 5001:5001 \
-e DS2API_ADMIN_KEY=your-admin-key \
-e DS2API_CONFIG_JSON='{"keys":["api-key"],"accounts":[...]}' \
ds2api
# 1. 克隆仓库并进入目录
git clone https://github.com/CJackHwang/ds2api.git
cd ds2api
# 2. 配置环境变量
cp .env.example .env
# 编辑 .env填写 DS2API_ADMIN_KEY 和 DS2API_CONFIG_JSON
# 3. 启动服务
docker-compose up -d
# 4. 查看日志
docker-compose logs -f
```
> **Docker 优势**:零侵入设计,主代码更新只需 `docker-compose up -d --build`,无需修改 Docker 配置。详见 [DEPLOY.md](DEPLOY.md#docker-部署推荐)。
## ⚠️ 免责声明
**本项目基于逆向工程实现,服务稳定性无法保证。**

45
docker-compose.dev.yml Normal file
View File

@@ -0,0 +1,45 @@
# DS2API 开发环境配置
# 特性:
# - 源代码挂载(热重载)
# - 调试日志级别
# - 自动重启
#
# 使用说明:
# docker-compose -f docker-compose.dev.yml up
services:
ds2api:
build: .
image: ds2api:dev
container_name: ds2api-dev
command: [
"uvicorn",
"app:app",
"--host",
"0.0.0.0",
"--port",
"5001",
"--reload",
"--reload-dir",
"/app",
"--log-level",
"debug"
]
ports:
- "${PORT:-5001}:5001"
env_file:
- .env
environment:
- HOST=0.0.0.0
- LOG_LEVEL=DEBUG
volumes:
# 源代码挂载(开发时实时生效)
- ./app.py:/app/app.py:ro
- ./core:/app/core:ro
- ./routes:/app/routes:ro
- ./static:/app/static:ro
# 配置文件挂载(便于本地修改)
- ./config.json:/app/config.json
restart: "no"
stdin_open: true
tty: true

29
docker-compose.yml Normal file
View File

@@ -0,0 +1,29 @@
# DS2API 生产环境配置
# 使用说明:
# 1. 复制 .env.example 为 .env 并填写配置
# 2. docker-compose up -d
# 3. 主代码更新后docker-compose up -d --build
#
# 设计原则:
# - 零侵入:所有项目配置通过 .env 文件传递
# - 易维护:主代码更新只需重新构建镜像
services:
ds2api:
build: .
image: ds2api:latest
container_name: ds2api
ports:
- "${PORT:-5001}:5001"
env_file:
- .env
environment:
# 确保容器内使用正确的主机绑定
- HOST=0.0.0.0
restart: unless-stopped
healthcheck:
test: ["CMD", "python", "-c", "import urllib.request; urllib.request.urlopen('http://localhost:5001/v1/models')"]
interval: 30s
timeout: 10s
retries: 3
start_period: 10s

View File

@@ -1,19 +1,24 @@
# DS2API 依赖
# 安装命令: pip install -r requirements.txt
# Python 版本要求: >=3.9
# Web 框架
# ===== Web 框架 =====
fastapi>=0.110.0,<1.0.0
uvicorn[standard]>=0.24.0,<1.0.0
# HTTP 客户端
# ===== HTTP 客户端 =====
# curl_cffi: 支持 TLS 指纹模拟,绕过 Cloudflare 等防护
curl_cffi>=0.7.0
# httpx: 异步 HTTP 客户端,用于 Vercel API 调用
httpx>=0.25.0
# 模板引擎
# ===== 模板引擎 =====
jinja2>=3.1.0,<4.0.0
# Tokenizer(用于 token 计数)
# ===== Tokenizer =====
# 用于 token 计数(可选,不安装则使用估算方式)
transformers>=4.39.0,<5.0.0
# WASM 运行时(用于 PoW 计算)
# ===== WASM 运行时 =====
# 用于 DeepSeek PoW (Proof of Work) 计算
wasmtime>=14.0.0

View File

@@ -1,5 +1,5 @@
# -*- coding: utf-8 -*-
"""Admin 账号管理模块 - 账号验证和测试"""
"""Admin 账号管理模块 - 账号测试与导入"""
import asyncio
import json
import base64
@@ -24,93 +24,6 @@ from .auth import verify_admin
router = APIRouter()
# ----------------------------------------------------------------------
# 账号验证
# ----------------------------------------------------------------------
async def validate_single_account(account: dict) -> dict:
"""验证单个账号的有效性"""
acc_id = get_account_identifier(account)
result = {
"account": acc_id,
"valid": False,
"has_token": bool(account.get("token", "").strip()),
"message": "",
}
try:
if result["has_token"]:
result["valid"] = True
result["message"] = "已有有效 token"
else:
try:
login_deepseek_via_account(account)
result["valid"] = True
result["has_token"] = True
result["message"] = "登录成功"
except Exception as e:
result["valid"] = False
result["message"] = f"登录失败: {str(e)}"
except Exception as e:
result["message"] = f"验证出错: {str(e)}"
return result
@router.post("/accounts/validate")
async def validate_account(request: Request, _: bool = Depends(verify_admin)):
"""验证单个账号"""
data = await request.json()
identifier = data.get("identifier", "").strip()
if not identifier:
raise HTTPException(status_code=400, detail="需要账号标识email 或 mobile")
account = None
for acc in CONFIG.get("accounts", []):
if acc.get("email") == identifier or acc.get("mobile") == identifier:
account = acc
break
if not account:
raise HTTPException(status_code=404, detail="账号不存在")
result = await validate_single_account(account)
if result["valid"] and result["has_token"]:
save_config(CONFIG)
return JSONResponse(content=result)
@router.post("/accounts/validate-all")
async def validate_all_accounts(_: bool = Depends(verify_admin)):
"""批量验证所有账号"""
accounts = CONFIG.get("accounts", [])
if not accounts:
return JSONResponse(content={
"total": 0, "valid": 0, "invalid": 0, "results": [],
})
results = []
valid_count = 0
for acc in accounts:
result = await validate_single_account(acc)
results.append(result)
if result["valid"]:
valid_count += 1
await asyncio.sleep(0.5)
save_config(CONFIG)
return JSONResponse(content={
"total": len(accounts),
"valid": valid_count,
"invalid": len(accounts) - valid_count,
"results": results,
})
# ----------------------------------------------------------------------
# 账号 API 测试
# ----------------------------------------------------------------------
@@ -134,38 +47,68 @@ async def test_account_api(account: dict, model: str = "deepseek-chat", message:
start_time = time.time()
def _is_token_invalid(status_code: int, data: dict) -> bool:
msg = (data.get("msg") or data.get("message") or "").lower()
code = data.get("code")
return status_code in {401, 403} or code in {40001, 40002, 40003} or "token" in msg or "unauthorized" in msg
def _create_session(token: str) -> dict:
headers = {**BASE_HEADERS, "authorization": f"Bearer {token}"}
try:
session_resp = cffi_requests.post(
DEEPSEEK_CREATE_SESSION_URL,
headers=headers,
json={"agent": "chat"},
impersonate="safari15_3",
timeout=15,
)
except Exception as e:
return {"success": False, "message": f"请求异常: {e}", "status_code": 0, "data": {}}
try:
session_data = session_resp.json()
except Exception:
session_data = {}
finally:
session_resp.close()
if session_resp.status_code == 200 and session_data.get("code") == 0:
return {
"success": True,
"session_id": session_data.get("data", {}).get("biz_data", {}).get("id"),
"status_code": session_resp.status_code,
"data": session_data,
}
return {
"success": False,
"message": session_data.get("msg") or f"HTTP {session_resp.status_code}",
"status_code": session_resp.status_code,
"data": session_data,
}
try:
token = account.get("token", "").strip()
if not token:
session_result = None
if token:
session_result = _create_session(token)
if not token or (session_result and not session_result["success"] and _is_token_invalid(session_result["status_code"], session_result["data"])):
try:
account["token"] = ""
login_deepseek_via_account(account)
token = account.get("token", "")
session_result = _create_session(token)
except Exception as e:
result["message"] = f"登录失败: {str(e)}"
return result
if not session_result or not session_result["success"]:
result["message"] = f"创建会话失败: {session_result['message'] if session_result else 'Unknown error'}"
return result
session_id = session_result["session_id"]
headers = {**BASE_HEADERS, "authorization": f"Bearer {token}"}
session_resp = cffi_requests.post(
DEEPSEEK_CREATE_SESSION_URL,
headers=headers,
json={"agent": "chat"},
impersonate="safari15_3",
timeout=15,
)
if session_resp.status_code != 200:
result["message"] = f"创建会话失败: HTTP {session_resp.status_code}"
return result
session_data = session_resp.json()
if session_data.get("code") != 0:
result["message"] = f"创建会话失败: {session_data.get('msg', 'Unknown error')}"
account["token"] = ""
return result
session_id = session_data.get("data", {}).get("biz_data", {}).get("id")
if not message.strip():
result["success"] = True
result["message"] = "API 测试成功(仅会话创建)"

View File

@@ -253,7 +253,7 @@ WELCOME_HTML = """<!DOCTYPE html>
<div class="feature-card">
<span class="feature-icon">🧠</span>
<h3>深度思考</h3>
<p>完整支持 DeepSeek-R1 推理过程输出,让思考可见。</p>
<p>完整支持 推理过程输出,让思考可见。</p>
</div>
<div class="feature-card">
<span class="feature-icon">🔍</span>
@@ -263,7 +263,7 @@ WELCOME_HTML = """<!DOCTYPE html>
</div>
<footer>
<p>&copy; 2024 DS2API Project. Designed for flexibility & performance.</p>
<p>&copy; 2026 DS2API Project. Designed for flexibility & performance.</p>
</footer>
</div>
</body>
@@ -290,12 +290,19 @@ async def webui(request: Request, path: str = ""):
if path and "." in path:
file_path = os.path.join(STATIC_ADMIN_DIR, path)
if os.path.isfile(file_path):
return FileResponse(file_path)
cache_control = "public, max-age=31536000, immutable"
if path.startswith("assets/"):
headers = {"Cache-Control": cache_control}
else:
headers = {"Cache-Control": "no-store, must-revalidate"}
return FileResponse(file_path, headers=headers)
return HTMLResponse(content="Not Found", status_code=404)
# 否则返回 index.htmlSPA 路由)
index_path = os.path.join(STATIC_ADMIN_DIR, "index.html")
if os.path.isfile(index_path):
return FileResponse(index_path)
headers = {"Cache-Control": "no-store, must-revalidate"}
return FileResponse(index_path, headers=headers)
return HTMLResponse(content="index.html not found", status_code=404)

27
scripts/build-webui.sh Executable file
View File

@@ -0,0 +1,27 @@
#!/bin/bash
# WebUI 构建脚本
# 用法: ./scripts/build-webui.sh
set -e
echo "🔨 Building WebUI..."
cd "$(dirname "$0")/../webui"
# 检查 node_modules
if [ ! -d "node_modules" ]; then
echo "📦 Installing dependencies..."
npm install
fi
# 构建
echo "🏗️ Running build..."
npm run build
if [ ! -f "../static/admin/index.html" ]; then
echo "❌ WebUI build failed: static/admin/index.html not found"
exit 1
fi
echo "✅ WebUI built successfully!"
echo "📁 Output: static/admin/"

1
static/admin/.gitkeep Normal file
View File

@@ -0,0 +1 @@

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

View File

@@ -1,43 +0,0 @@
<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<!-- SEO Meta Tags -->
<title>DS2API - DeepSeek API 管理面板</title>
<meta name="description" content="DS2API 管理面板 - 轻松管理 DeepSeek 账号、测试 API、同步 Vercel 配置" />
<meta name="keywords" content="DeepSeek, API, OpenAI, 管理面板, DS2API" />
<meta name="author" content="CJackHwang" />
<meta name="robots" content="noindex, nofollow" />
<!-- Open Graph / Social -->
<meta property="og:type" content="website" />
<meta property="og:title" content="DS2API - DeepSeek API 管理面板" />
<meta property="og:description" content="轻松管理 DeepSeek 账号、测试 API、同步 Vercel 配置" />
<meta property="og:site_name" content="DS2API" />
<!-- PWA / Mobile -->
<meta name="theme-color" content="#f59e0b" />
<meta name="apple-mobile-web-app-capable" content="yes" />
<meta name="apple-mobile-web-app-status-bar-style" content="black-translucent" />
<meta name="apple-mobile-web-app-title" content="DS2API" />
<!-- Favicon - using data URI for orange-yellow gradient icon -->
<link rel="icon" type="image/svg+xml"
href="data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 100 100'%3E%3Cdefs%3E%3ClinearGradient id='g' x1='0%25' y1='0%25' x2='100%25' y2='100%25'%3E%3Cstop offset='0%25' stop-color='%23f59e0b'/%3E%3Cstop offset='100%25' stop-color='%23ef4444'/%3E%3C/linearGradient%3E%3C/defs%3E%3Crect rx='20' width='100' height='100' fill='url(%23g)'/%3E%3Ctext x='50' y='68' font-family='Arial,sans-serif' font-size='48' font-weight='bold' fill='white' text-anchor='middle'%3EDS%3C/text%3E%3C/svg%3E" />
<!-- Fonts -->
<link rel="preconnect" href="https://fonts.googleapis.com">
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
<link href="https://fonts.googleapis.com/css2?family=Inter:wght@100..900&display=swap" rel="stylesheet">
<script type="module" crossorigin src="/admin/assets/index-Da8PBvaf.js"></script>
<link rel="stylesheet" crossorigin href="/admin/assets/index-BzdNSWuo.css">
</head>
<body>
<div id="root"></div>
</body>
</html>

View File

@@ -1,15 +1,30 @@
{
"version": 2,
"builds": [
"buildCommand": "bash scripts/build-webui.sh",
"rewrites": [
{
"src": "app.py",
"use": "@vercel/python"
"source": "/(.*)",
"destination": "/app.py"
}
],
"routes": [
"headers": [
{
"src": "/(.*)",
"dest": "app.py"
"source": "/admin/assets/(.*)",
"headers": [
{
"key": "Cache-Control",
"value": "public, max-age=31536000, immutable"
}
]
},
{
"source": "/admin/(.*)",
"headers": [
{
"key": "Cache-Control",
"value": "no-store, must-revalidate"
}
]
}
]
}
}

2986
webui/package-lock.json generated Normal file

File diff suppressed because it is too large Load Diff

View File

@@ -2,15 +2,13 @@ import { useState, useEffect } from 'react'
import {
Plus,
Trash2,
RefreshCw,
CheckCircle2,
AlertCircle,
Search,
Play,
MoreHorizontal,
X,
Server,
ShieldCheck
ShieldCheck,
Copy,
Check
} from 'lucide-react'
import clsx from 'clsx'
@@ -18,10 +16,9 @@ export default function AccountManager({ config, onRefresh, onMessage, authFetch
const [showAddKey, setShowAddKey] = useState(false)
const [showAddAccount, setShowAddAccount] = useState(false)
const [newKey, setNewKey] = useState('')
const [copiedKey, setCopiedKey] = useState(null)
const [newAccount, setNewAccount] = useState({ email: '', mobile: '', password: '' })
const [loading, setLoading] = useState(false)
const [validating, setValidating] = useState({})
const [validatingAll, setValidatingAll] = useState(false)
const [testing, setTesting] = useState({})
const [testingAll, setTestingAll] = useState(false)
const [batchProgress, setBatchProgress] = useState({ current: 0, total: 0, results: [] })
@@ -130,60 +127,6 @@ export default function AccountManager({ config, onRefresh, onMessage, authFetch
}
}
const validateAccount = async (identifier) => {
setValidating(prev => ({ ...prev, [identifier]: true }))
try {
const res = await apiFetch('/admin/accounts/validate', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ identifier }),
})
const data = await res.json()
onMessage(data.valid ? 'success' : 'error', `${identifier}: ${data.message}`)
onRefresh()
} catch (e) {
onMessage('error', 'Validation failed: ' + e.message)
} finally {
setValidating(prev => ({ ...prev, [identifier]: false }))
}
}
const validateAllAccounts = async () => {
if (!confirm('校验所有账号?这可能需要一些时间。')) return
const accounts = config.accounts || []
if (accounts.length === 0) return
setValidatingAll(true)
setBatchProgress({ current: 0, total: accounts.length, results: [] })
let validCount = 0
const results = []
for (let i = 0; i < accounts.length; i++) {
const acc = accounts[i]
const id = acc.email || acc.mobile
try {
const res = await apiFetch('/admin/accounts/validate', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ identifier: id }),
})
const data = await res.json()
results.push({ id, success: data.valid, message: data.message })
if (data.valid) validCount++
} catch (e) {
results.push({ id, success: false, message: e.message })
}
setBatchProgress({ current: i + 1, total: accounts.length, results: [...results] })
}
onMessage('success', `Completed: ${validCount}/${accounts.length} valid`)
onRefresh()
setValidatingAll(false)
}
const testAccount = async (identifier) => {
setTesting(prev => ({ ...prev, [identifier]: true }))
try {
@@ -298,15 +241,34 @@ export default function AccountManager({ config, onRefresh, onMessage, authFetch
{config.keys?.length > 0 ? (
config.keys.map((key, i) => (
<div key={i} className="p-4 flex items-center justify-between hover:bg-muted/50 transition-colors group">
<div className="font-mono text-sm bg-muted/50 px-3 py-1 rounded inline-block">
{key.slice(0, 16)}****
<div className="flex items-center gap-2">
<div className="font-mono text-sm bg-muted/50 px-3 py-1 rounded inline-block">
{key.slice(0, 16)}****
</div>
{copiedKey === key && (
<span className="text-xs text-green-500 animate-pulse">已复制</span>
)}
</div>
<div className="flex items-center gap-1">
<button
onClick={() => {
navigator.clipboard.writeText(key)
setCopiedKey(key)
setTimeout(() => setCopiedKey(null), 2000)
}}
className="p-2 text-muted-foreground hover:text-primary hover:bg-primary/10 rounded-md transition-colors opacity-0 group-hover:opacity-100"
title="复制密钥"
>
{copiedKey === key ? <Check className="w-4 h-4 text-green-500" /> : <Copy className="w-4 h-4" />}
</button>
<button
onClick={() => deleteKey(key)}
className="p-2 text-muted-foreground hover:text-destructive hover:bg-destructive/10 rounded-md transition-colors opacity-0 group-hover:opacity-100"
title="删除密钥"
>
<Trash2 className="w-4 h-4" />
</button>
</div>
<button
onClick={() => deleteKey(key)}
className="p-2 text-muted-foreground hover:text-destructive hover:bg-destructive/10 rounded-md transition-colors opacity-0 group-hover:opacity-100"
>
<Trash2 className="w-4 h-4" />
</button>
</div>
))
) : (
@@ -325,20 +287,12 @@ export default function AccountManager({ config, onRefresh, onMessage, authFetch
<div className="flex flex-wrap gap-2">
<button
onClick={testAllAccounts}
disabled={testingAll || validatingAll || !config.accounts?.length}
disabled={testingAll || !config.accounts?.length}
className="flex items-center px-3 py-2 bg-secondary text-secondary-foreground rounded-lg hover:bg-secondary/80 transition-colors text-xs font-medium border border-border disabled:opacity-50"
>
{testingAll ? <span className="animate-spin mr-2"></span> : <Play className="w-3 h-3 mr-2" />}
测试全部
</button>
<button
onClick={validateAllAccounts}
disabled={validatingAll || testingAll || !config.accounts?.length}
className="flex items-center px-3 py-2 bg-secondary text-secondary-foreground rounded-lg hover:bg-secondary/80 transition-colors text-xs font-medium border border-border disabled:opacity-50"
>
{validatingAll ? <span className="animate-spin mr-2"></span> : <CheckCircle2 className="w-3 h-3 mr-2" />}
校验全部
</button>
<button
onClick={() => setShowAddAccount(true)}
className="flex items-center gap-2 px-4 py-2 bg-primary text-primary-foreground rounded-lg hover:bg-primary/90 transition-colors font-medium text-sm shadow-sm"
@@ -350,10 +304,10 @@ export default function AccountManager({ config, onRefresh, onMessage, authFetch
</div>
{/* Batch Progress */}
{(testingAll || validatingAll) && batchProgress.total > 0 && (
{testingAll && batchProgress.total > 0 && (
<div className="p-4 border-b border-border bg-muted/30">
<div className="flex items-center justify-between text-sm mb-2">
<span className="font-medium">{testingAll ? '正在测试所有账号...' : '正在校验所有账号...'}</span>
<span className="font-medium">正在测试所有账号...</span>
<span className="text-muted-foreground">{batchProgress.current} / {batchProgress.total}</span>
</div>
<div className="w-full bg-muted rounded-full h-2 overflow-hidden mb-4">
@@ -408,13 +362,6 @@ export default function AccountManager({ config, onRefresh, onMessage, authFetch
>
{testing[id] ? '正在测试...' : '测试'}
</button>
<button
onClick={() => validateAccount(id)}
disabled={validating[id]}
className="px-2 lg:px-3 py-1 lg:py-1.5 text-[10px] lg:text-xs font-medium border border-border rounded-md hover:bg-secondary transition-colors disabled:opacity-50"
>
{validating[id] ? '正在校验...' : '校验'}
</button>
<button
onClick={() => deleteAccount(id)}
className="p-1 lg:p-1.5 text-muted-foreground hover:text-destructive hover:bg-destructive/10 rounded-md transition-colors"
@@ -445,14 +392,24 @@ export default function AccountManager({ config, onRefresh, onMessage, authFetch
<div className="p-6 space-y-4">
<div>
<label className="block text-sm font-medium mb-1.5">新密钥值</label>
<input
type="text"
className="input-field bg-[#09090b]"
placeholder="输入自定义 API 密钥"
value={newKey}
onChange={e => setNewKey(e.target.value)}
autoFocus
/>
<div className="flex gap-2">
<input
type="text"
className="input-field bg-[#09090b] flex-1"
placeholder="输入自定义 API 密钥"
value={newKey}
onChange={e => setNewKey(e.target.value)}
autoFocus
/>
<button
type="button"
onClick={() => setNewKey('sk-' + crypto.randomUUID().replace(/-/g, ''))}
className="px-3 py-2 bg-secondary text-secondary-foreground rounded-lg hover:bg-secondary/80 transition-colors text-sm font-medium border border-border whitespace-nowrap"
>
生成
</button>
</div>
<p className="text-xs text-muted-foreground mt-1.5">点击生成自动创建随机密钥</p>
</div>
<div className="flex justify-end gap-2 pt-2">
<button onClick={() => setShowAddKey(false)} className="px-4 py-2 rounded-lg border border-border hover:bg-secondary transition-colors text-sm font-medium">取消</button>

View File

@@ -47,7 +47,7 @@ export default function VercelSync({ onMessage, authFetch }) {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
vercel_token: vercelToken,
vercel_token: tokenToUse,
project_id: projectId,
team_id: teamId || undefined,
}),