Compare commits

..

22 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
18 changed files with 412 additions and 656 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

@@ -1,76 +0,0 @@
# 自动构建 WebUI 并提交构建产物
# 触发条件webui 目录下的文件变更
name: Build WebUI
on:
push:
branches:
- main
paths:
- 'webui/**'
- '.github/workflows/build-webui.yml'
pull_request:
branches:
- main
paths:
- 'webui/**'
# 允许手动触发
workflow_dispatch:
jobs:
build:
runs-on: ubuntu-latest
# 只在主仓库运行,避免 fork 仓库运行
if: github.repository == 'CJackHwang/ds2api'
permissions:
contents: write
steps:
- name: Checkout repository
uses: actions/checkout@v4
with:
token: ${{ secrets.GITHUB_TOKEN }}
- name: Setup Node.js
uses: actions/setup-node@v4
with:
node-version: '20'
cache: 'npm'
cache-dependency-path: webui/package-lock.json
- name: Install dependencies
working-directory: webui
run: npm ci
- name: Build WebUI
working-directory: webui
run: npm run build
- name: Check for changes
id: check_changes
run: |
git add static/admin
if git diff --staged --quiet; then
echo "changed=false" >> $GITHUB_OUTPUT
else
echo "changed=true" >> $GITHUB_OUTPUT
fi
- name: Commit and push changes
if: steps.check_changes.outputs.changed == 'true' && github.event_name == 'push'
run: |
git config --local user.email "github-actions[bot]@users.noreply.github.com"
git config --local user.name "github-actions[bot]"
git commit -m "chore: auto-build WebUI [skip ci]"
git push
- name: Upload build artifacts (for PR review)
if: github.event_name == 'pull_request'
uses: actions/upload-artifact@v4
with:
name: webui-build
path: static/admin
retention-days: 7

2
.gitignore vendored
View File

@@ -64,6 +64,8 @@ pnpm-lock.yaml
*.tsbuildinfo
.cache/
.parcel-cache/
static/admin/*
!static/admin/.gitkeep
# Environment
.env.local

166
DEPLOY.md
View File

@@ -7,6 +7,7 @@
## 目录
- [Vercel 部署(推荐)](#vercel-部署推荐)
- [Docker 部署(推荐)](#docker-部署推荐)
- [本地开发](#本地开发)
- [生产环境部署](#生产环境部署)
- [常见问题](#常见问题)
@@ -130,8 +131,9 @@ WebUI 开发服务器会启动在 `http://localhost:5173`,并自动代理 API
WebUI 构建产物位于 `static/admin/` 目录。
**自动构建(推荐)**
- `webui/` 目录下的文件变更并推送到 `main` 分支时GitHub Actions 会自动构建并提交产物
- PR 合并时会自动触发构建
-前由 Vercel 在部署时执行 WebUI 构建(见 `vercel.json``buildCommand`
- GitHub Actions 的 WebUI 自动构建流程已关闭
- `static/admin/` 构建产物不再提交到仓库
**手动构建**
```bash
@@ -144,7 +146,110 @@ npm install
npm run build
```
> **贡献者注意**:修改 WebUI 后无需手动构建,CI 会自动处理
> **贡献者注意**:修改 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
```
---
@@ -231,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
```
---
## 常见问题
@@ -312,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,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

@@ -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)

View File

@@ -18,5 +18,10 @@ 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-C7aw1GYL.js"></script>
<link rel="stylesheet" crossorigin href="/admin/assets/index-D9_KYhGM.css">
</head>
<body>
<div id="root"></div>
</body>
</html>

View File

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

View File

@@ -2,12 +2,8 @@ import { useState, useEffect } from 'react'
import {
Plus,
Trash2,
RefreshCw,
CheckCircle2,
AlertCircle,
Search,
Play,
MoreHorizontal,
X,
Server,
ShieldCheck,
@@ -23,8 +19,6 @@ export default function AccountManager({ config, onRefresh, onMessage, authFetch
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: [] })
@@ -133,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 {
@@ -347,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"
@@ -372,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">
@@ -430,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"

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,
}),