Upload 42 files
Browse filesFiles changed (23)
- .env.exampleAdded+15
- .gitignore+3-1
- Dockerfile+3
- README.md+231-49
- cmd/server/main.go+80-1
- go.mod+50-37
- go.sum+118-92
- internal/handler/auth.goAdded+125
- internal/handler/cookies.goAdded+320
- internal/handler/messages.go+34
- internal/middleware/auth.goAdded+53
- internal/model/cookie.goAdded+64
- internal/model/db.goAdded+69
- internal/model/user.goAdded+92
- internal/service/auth_service.goAdded+190
- internal/service/cookie_service.goAdded+125
- internal/service/rotator.goAdded+167
- internal/service/validator.goAdded+141
- internal/types/common.go+55-4
- web/static/app.jsAdded+484
- web/static/dashboard.htmlAdded+196
- web/static/index.htmlAdded+27
- web/static/styles.cssAdded+447
123456789101112131415# PostgreSQL 数据库连接(必需,Hugging Face Spaces 中通过 Secrets 配置)
DATABASE_URL=postgresql://user:password@host:5432/dbname
# JWT 签名密钥(必需,生产环境请使用强密码)
JWT_SECRET=your-secret-key-change-in-production
# 默认管理员账号(首次启动时创建)
DEFAULT_ADMIN_USERNAME=admin
DEFAULT_ADMIN_PASSWORD=admin
# Cookie 验证配置
COOKIE_MAX_ERROR_COUNT=3
# 轮询策略:round_robin, priority, least_used
ROTATION_STRATEGY=priority38 unmodified lines3940414238 unmodified lines# Build artifactsdist/build/38 unmodified lines39404142434438 unmodified lines# Build artifactsdist/build/.env
34 unmodified lines35363738394034 unmodified lines# Copy Python startup scriptCOPY app.py .# Create logs directoryRUN mkdir -p /app/logs34 unmodified lines35363738394041424334 unmodified lines# Copy Python startup scriptCOPY app.py .# Copy web static filesCOPY --from=builder /app/web ./web# Create logs directoryRUN mkdir -p /app/logs
6 unmodified lines789101112131415161718192021222324252627282930313233346 unmodified lines41424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091106 unmodified linesapp_port: 7860---# Opus API一个用于 API 消息格式转换的服务,将 Claude API 格式转换为其他格式。## 功能特性- ✨ Claude API 消息格式转换- 🔄 流式响应支持- 🛠️ 工具调用处理- 📊 Token 计数- 💾 请求/响应日志记录(调试模式)## API 端点### 1. 消息转换接口```POST /v1/messages```将 Claude API 格式的消息转换为目标格式。**请求示例:**```bashcurl -X POST https://your-space.hf.space/v1/messages \-H "Content-Type: application/json" \6 unmodified lines}'```### 2. 健康检查接口```GET /health```检查服务运行状态。**响应示例:**```json{"status": "healthy","timestamp": "2024-01-01T00:00:00Z"}```## 技术栈- **后端**: Go 1.21- **Web 框架**: Gin- **Token 计数**: tiktoken-go- **容器化**: Docker- **部署平台**: Hugging Face Spaces## 环境变量- `PORT`: 服务端口(默认: 7860)- `DEBUG_MODE`: 调试模式开关- `LOG_DIR`: 日志目录路径## 本地开发### 使用 Go 直接运行```bashgo run cmd/server/main.go```### 使用 Docker```bashdocker build -t opus-api .docker run -p 7860:7860 opus-api```## 项目结构```opus-api/├── cmd/server/ # 主程序入口├── internal/│ ├── converter/ # 格式转换逻辑│ ├── handler/ # HTTP 处理器│ ├── logger/ # 日志管理│ ├── parser/ # 消息解析│ ├── stream/ # 流式处理│ ├── tokenizer/ # Token 计数│ └── types/ # 类型定义├── app.py # Python 启动脚本├── Dockerfile # Docker 构建文件└── go.mod # Go 依赖管理```## 许可证本项目遵循开源协议。## 联系方式如有问题或建议,欢迎提交 Issue。6 unmodified lines7891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031046 unmodified lines1111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912926 unmodified linesapp_port: 7860---# Opus API - 账号管理系统一个用于 API 消息格式转换的服务,将 Claude API 格式转换为其他格式,支持多账号 Cookie 管理和轮询。## ✨ 功能特性- 🔄 Claude API 消息格式转换- 📊 Token 计数统计- 🎯 **账号管理系统**- 用户登录认证(JWT)- 多 Morph 账号 Cookie 管理- Cookie 有效性检测(手动/自动)- Cookie 轮询策略(轮询/优先级/最少使用)- Web 管理界面- 🛠️ 工具调用处理- 💾 请求/响应日志记录(调试模式)- 🔌 支持客户端 Cookie/Authorization 请求头覆盖## 🚀 快速开始### 部署到 Hugging Face Spaces1. **创建 Space**- 在 Hugging Face 上创建新 Space- 选择 **Docker SDK**- Space 名称例如:`your-username/opus-api`2. **配置环境变量**在 Space 的 **Settings → Repository secrets** 中添加:| Secret 名称 | 说明 | 示例值 ||-------------|------|--------|| `DATABASE_URL` | PostgreSQL 数据库连接 | `postgresql://user:password@host:5432/dbname` || `JWT_SECRET` | JWT 签名密钥 | `your-random-secret-key-here` || `DEFAULT_ADMIN_PASSWORD` | 管理员密码 | `changeme123` |3. **推送代码**```bashgit remote add hf https://huggingface.co/spaces/YOUR_USERNAME/YOUR_SPACE_NAMEgit push hf main```4. **访问管理界面**- 访问 `https://YOUR_USERNAME-YOUR_SPACE_NAME.hf.space`- 使用默认账号登录:- 用户名:`admin`- 密码:你设置的 `DEFAULT_ADMIN_PASSWORD`## 📡 API 端点### 认证 API```POST /api/auth/login # 用户登录POST /api/auth/logout # 用户登出GET /api/auth/me # 获取当前用户信息```### Cookie 管理 API(需要认证)```GET /api/cookies # 获取 Cookie 列表POST /api/cookies # 添加 CookieGET /api/cookies/:id # 获取单个 CookiePUT /api/cookies/:id # 更新 CookieDELETE /api/cookies/:id # 删除 CookiePOST /api/cookies/:id/validate # 验证单个 CookiePOST /api/cookies/validate/all # 批量验证所有 CookieGET /api/cookies/stats # 获取统计信息```### 消息转换 API```POST /v1/messages # 消息转换接口(支持客户端 Cookie 覆盖)GET /health # 健康检查接口```## 🔧 使用方法### 1. Web 管理界面访问 `/dashboard` 或 `/static/dashboard.html`,登录后可以:- 查看 Cookie 统计信息- 添加/编辑/删除 Cookie- 手动或批量验证 Cookie 有效性- 设置 Cookie 优先级### 2. 调用消息 API**基础请求:**```bashcurl -X POST https://your-space.hf.space/v1/messages \-H "Content-Type: application/json" \6 unmodified lines}'```**使用自定义 Cookie(覆盖轮询):**```bashcurl -X POST https://your-space.hf.space/v1/messages \-H "Content-Type: application/json" \-H "Cookie: _gcl_aw=GCL.17692..." \-d '{"model": "claude-opus-4-20250514","max_tokens": 1024,"messages": [{"role": "user", "content": "Hello!"}]}'```## 🗄️ 数据库结构### users 表```sqlCREATE TABLE users (id SERIAL PRIMARY KEY,username VARCHAR(50) UNIQUE NOT NULL,password_hash VARCHAR(255) NOT NULL,created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP);```### morph_cookies 表```sqlCREATE TABLE morph_cookies (id SERIAL PRIMARY KEY,user_id INTEGER REFERENCES users(id) ON DELETE CASCADE,name VARCHAR(100) NOT NULL,api_key TEXT NOT NULL,session_key TEXT,is_valid BOOLEAN DEFAULT true,last_validated TIMESTAMP,last_used TIMESTAMP,priority INTEGER DEFAULT 0,usage_count BIGINT DEFAULT 0,error_count INTEGER DEFAULT 0,created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP);```### user_sessions 表```sqlCREATE TABLE user_sessions (id SERIAL PRIMARY KEY,user_id INTEGER REFERENCES users(id) ON DELETE CASCADE,token_hash VARCHAR(255) UNIQUE NOT NULL,expires_at TIMESTAMP NOT NULL,created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP);```## 🔄 Cookie 轮询策略系统支持三种轮询策略,通过环境变量 `ROTATION_STRATEGY` 配置:| 策略 | 说明 ||------|------|| `priority` | 按优先级(数字越大越优先,默认) || `round_robin` | 轮询(按顺序循环使用) || `least_used` | 使用次数最少的优先 |## 🔐 环境变量配置| 变量名 | 说明 | 默认值 | 必需 ||--------|------|--------|------|| `DATABASE_URL` | PostgreSQL 连接字符串 | - | ✅ || `JWT_SECRET` | JWT 签名密钥 | - | ✅ || `DEFAULT_ADMIN_USERNAME` | 默认管理员用户名 | `admin` | ❌ || `DEFAULT_ADMIN_PASSWORD` | 默认管理员密码 | `changeme123` | ❌ || `COOKIE_MAX_ERROR_COUNT` | Cookie 失败阈值 | `3` | ❌ || `ROTATION_STRATEGY` | 轮询策略 | `priority` | ❌ || `DEBUG_MODE` | 调试模式 | `false` | ❌ |## 🛠️ 本地开发### 前置要求- Go 1.21+- PostgreSQL 14+- Python 3.9+(用于 Hugging Face 部署)### 安装依赖```bashgo mod download```### 配置环境变量```bashcp .env.example .env# 编辑 .env 文件,设置数据库连接等```### 运行服务```bash# 使用 Go 直接运行go run cmd/server/main.go# 或使用 Dockerdocker build -t opus-api .docker run -p 7860:7860 \-e DATABASE_URL="postgresql://..." \-e JWT_SECRET="your-secret" \opus-api```## 📁 项目结构```opus-api/├── cmd/server/ # 主程序入口│ └── main.go├── internal/│ ├── converter/ # 格式转换逻辑│ ├── handler/ # HTTP 处理器│ │ ├── messages.go # 消息处理│ │ ├── health.go # 健康检查│ │ ├── auth.go # 认证处理│ │ └── cookies.go # Cookie 管理│ ├── middleware/ # 中间件│ │ └── auth.go # JWT 认证│ ├── model/ # 数据模型│ │ ├── db.go # 数据库连接│ │ ├── user.go # 用户模型│ │ └── cookie.go # Cookie 模型│ ├── service/ # 业务逻辑│ │ ├── auth_service.go # 认证服务│ │ ├── cookie_service.go# Cookie 服务│ │ ├── validator.go # Cookie 验证│ │ └── rotator.go # Cookie 轮询│ ├── logger/ # 日志管理│ ├── parser/ # 消息解析│ ├── stream/ # 流式处理│ ├── tokenizer/ # Token 计数│ ├── types/ # 类型定义│ └── converter/ # 格式转换├── web/static/ # 前端静态文件│ ├── index.html # 登录页│ ├── dashboard.html # 管理面板│ ├── styles.css # 样式│ └── app.js # 前端逻辑├── migrations/ # 数据库迁移(可选)├── .env.example # 环境变量示例├── app.py # Python 启动脚本├── Dockerfile # Docker 构建文件└── go.mod # Go 依赖管理```## 📝 技术栈- **后端**: Go 1.21, Gin- **数据库**: PostgreSQL, GORM- **认证**: JWT- **前端**: HTML, CSS, Vanilla JavaScript- **容器化**: Docker- **部署平台**: Hugging Face Spaces## 🔐 安全建议1. **首次登录后立即修改默认密码**2. **生产环境使用强 JWT_SECRET**3. **定期更新 Cookie**(Morph Cookie 可能会过期)4. **使用 HTTPS**(Hugging Face Spaces 自动提供)## 📄 许可证本项目遵循开源协议。## ���� 贡献欢迎提交 Issue 和 Pull Request。## 📞 联系方式如有问题或建议,欢迎提交 Issue。
4 unmodified lines567891011121314151617189 unmodified lines282930313233343536373839404142434 unmodified lines4849505152534 unmodified lines"log""opus-api/internal/handler""opus-api/internal/logger""opus-api/internal/tokenizer""opus-api/internal/types""os""github.com/gin-gonic/gin")func main() {// Create logs directoryif err := os.MkdirAll(types.LogDir, 0755); err != nil {log.Fatalf("Failed to create logs directory: %v", err)9 unmodified lineslog.Printf("[WARN] Failed to initialize tokenizer: %v (will use fallback)", err)}// Set Gin modegin.SetMode(gin.ReleaseMode)// Create Gin routerrouter := gin.Default()// Register routesrouter.POST("/v1/messages", handler.HandleMessages)router.GET("/health", handler.HandleHealth)// Start server// Hugging Face Spaces uses port 7860port := 78604 unmodified lineslog.Printf("Server running on http://0.0.0.0:%d", port)log.Printf("Debug mode: %v", types.DebugMode)log.Printf("Log directory: %s", types.LogDir)if err := router.Run(addr); err != nil {log.Fatalf("Failed to start server: %v", err)4 unmodified lines5678910111213141516171819202122232425262728299 unmodified lines394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201214 unmodified lines1261271281291301311324 unmodified lines"log""opus-api/internal/handler""opus-api/internal/logger""opus-api/internal/middleware""opus-api/internal/model""opus-api/internal/service""opus-api/internal/tokenizer""opus-api/internal/types""os""github.com/gin-gonic/gin""github.com/joho/godotenv")func main() {// Load .env fileif err := godotenv.Load(); err != nil {log.Printf("[INFO] No .env file found or error loading it: %v", err)} else {log.Printf("[INFO] .env file loaded successfully")}// Create logs directoryif err := os.MkdirAll(types.LogDir, 0755); err != nil {log.Fatalf("Failed to create logs directory: %v", err)9 unmodified lineslog.Printf("[WARN] Failed to initialize tokenizer: %v (will use fallback)", err)}// Initialize databaseif err := model.InitDB(); err != nil {log.Printf("[WARN] Failed to initialize database: %v (running without database)", err)} else {// Create default admin userif err := model.CreateDefaultAdmin(model.DB); err != nil {log.Printf("[WARN] Failed to create default admin: %v", err)}}// Initialize servicesvar authService *service.AuthServicevar cookieService *service.CookieServicevar cookieValidator *service.CookieValidatorvar cookieRotator *service.CookieRotatorif model.DB != nil {authService = service.NewAuthService(model.DB)cookieService = service.NewCookieService(model.DB)cookieValidator = service.NewCookieValidator(cookieService)cookieRotator = service.NewCookieRotator(cookieService, service.StrategyRoundRobin)// Store rotator in types for use in messages handlertypes.CookieRotatorInstance = cookieRotator}// Set Gin modegin.SetMode(gin.ReleaseMode)// Create Gin routerrouter := gin.Default()// Serve static filesrouter.Static("/static", "./web/static")// Redirect root to login page or dashboardrouter.GET("/", func(c *gin.Context) {c.Redirect(302, "/static/index.html")})// Dashboard redirectrouter.GET("/dashboard", func(c *gin.Context) {c.Redirect(302, "/static/dashboard.html")})// Register API routesrouter.POST("/v1/messages", handler.HandleMessages)router.GET("/health", handler.HandleHealth)// Auth routes (only if database is available)if authService != nil {authHandler := handler.NewAuthHandler(authService)router.POST("/api/auth/login", authHandler.Login)router.POST("/api/auth/logout", authHandler.Logout)// Protected routesauthGroup := router.Group("/api")authGroup.Use(middleware.AuthMiddleware(authService)){authGroup.GET("/auth/me", authHandler.Me)authGroup.PUT("/auth/password", authHandler.ChangePassword)// Cookie management routesif cookieService != nil && cookieValidator != nil {cookieHandler := handler.NewCookieHandler(cookieService, cookieValidator)authGroup.GET("/cookies", cookieHandler.ListCookies)authGroup.GET("/cookies/stats", cookieHandler.GetStats)authGroup.POST("/cookies", cookieHandler.CreateCookie)authGroup.GET("/cookies/:id", cookieHandler.GetCookie)authGroup.PUT("/cookies/:id", cookieHandler.UpdateCookie)authGroup.DELETE("/cookies/:id", cookieHandler.DeleteCookie)authGroup.POST("/cookies/:id/validate", cookieHandler.ValidateCookie)authGroup.POST("/cookies/validate/all", cookieHandler.ValidateAllCookies)}}}// Start server// Hugging Face Spaces uses port 7860port := 78604 unmodified lineslog.Printf("Server running on http://0.0.0.0:%d", port)log.Printf("Debug mode: %v", types.DebugMode)log.Printf("Log directory: %s", types.LogDir)log.Printf("Database connected: %v", model.DB != nil)if err := router.Run(addr); err != nil {log.Fatalf("Failed to start server: %v", err)
12345678910111213141516171819202122232425262728293031323334353637module opus-apigo 1.21require (github.com/gin-gonic/gin v1.9.1github.com/google/uuid v1.6.0github.com/pkoukk/tiktoken-go v0.1.8)require (github.com/bytedance/sonic v1.9.1 // indirectgithub.com/chenzhuoyu/base64x v0.0.0-20221115062448-fe3a3abad311 // indirectgithub.com/dlclark/regexp2 v1.10.0 // indirectgithub.com/gabriel-vasile/mimetype v1.4.2 // indirectgithub.com/gin-contrib/sse v0.1.0 // indirectgithub.com/go-playground/locales v0.14.1 // indirectgithub.com/go-playground/universal-translator v0.18.1 // indirectgithub.com/go-playground/validator/v10 v10.14.0 // indirectgithub.com/goccy/go-json v0.10.2 // indirectgithub.com/json-iterator/go v1.1.12 // indirectgithub.com/klauspost/cpuid/v2 v2.2.4 // indirectgithub.com/leodido/go-urn v1.2.4 // indirectgithub.com/mattn/go-isatty v0.0.19 // indirectgithub.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd // indirectgithub.com/modern-go/reflect2 v1.0.2 // indirectgithub.com/pelletier/go-toml/v2 v2.0.8 // indirectgithub.com/twitchyliquid64/golang-asm v0.15.1 // indirectgithub.com/ugorji/go/codec v1.2.11 // indirectgolang.org/x/arch v0.3.0 // indirectgolang.org/x/crypto v0.9.0 // indirectgolang.org/x/net v0.10.0 // indirectgolang.org/x/sys v0.8.0 // indirectgolang.org/x/text v0.9.0 // indirectgoogle.golang.org/protobuf v1.30.0 // indirectgopkg.in/yaml.v3 v3.0.1 // indirect)1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950module opus-apigo 1.23toolchain go1.24.5require (github.com/gin-gonic/gin v1.9.1github.com/golang-jwt/jwt/v5 v5.2.0github.com/google/uuid v1.6.0github.com/pkoukk/tiktoken-go v0.1.8golang.org/x/crypto v0.18.0gorm.io/driver/postgres v1.5.4gorm.io/gorm v1.25.5)require (github.com/bytedance/sonic v1.9.1 // indirectgithub.com/chenzhuoyu/base64x v0.0.0-20221115062448-fe3a3abad311 // indirectgithub.com/dlclark/regexp2 v1.10.0 // indirectgithub.com/gabriel-vasile/mimetype v1.4.2 // indirectgithub.com/gin-contrib/sse v0.1.0 // indirectgithub.com/go-playground/locales v0.14.1 // indirectgithub.com/go-playground/universal-translator v0.18.1 // indirectgithub.com/go-playground/validator/v10 v10.14.0 // indirectgithub.com/goccy/go-json v0.10.2 // indirectgithub.com/jackc/pgpassfile v1.0.0 // indirectgithub.com/jackc/pgservicefile v0.0.0-20221227161230-091c0ba34f0a // indirectgithub.com/jackc/pgx/v5 v5.4.3 // indirectgithub.com/jinzhu/inflection v1.0.0 // indirectgithub.com/jinzhu/now v1.1.5 // indirectgithub.com/joho/godotenv v1.5.1 // indirectgithub.com/json-iterator/go v1.1.12 // indirectgithub.com/klauspost/cpuid/v2 v2.2.4 // indirectgithub.com/kr/text v0.2.0 // indirectgithub.com/leodido/go-urn v1.2.4 // indirectgithub.com/mattn/go-isatty v0.0.19 // indirectgithub.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd // indirectgithub.com/modern-go/reflect2 v1.0.2 // indirectgithub.com/pelletier/go-toml/v2 v2.0.8 // indirectgithub.com/rogpeppe/go-internal v1.14.1 // indirectgithub.com/twitchyliquid64/golang-asm v0.15.1 // indirectgithub.com/ugorji/go/codec v1.2.11 // indirectgolang.org/x/arch v0.3.0 // indirectgolang.org/x/net v0.10.0 // indirectgolang.org/x/sys v0.26.0 // indirectgolang.org/x/text v0.14.0 // indirectgoogle.golang.org/protobuf v1.30.0 // indirectgopkg.in/yaml.v3 v3.0.1 // indirect)
1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192github.com/bytedance/sonic v1.5.0/go.mod h1:ED5hyg4y6t3/9Ku1R6dU/4KyJ48DZ4jPhfY1O2AihPM=github.com/bytedance/sonic v1.9.1 h1:6iJ6NqdoxCDr6mbY8h18oSO+cShGSMRGCEo7F2h0x8s=github.com/bytedance/sonic v1.9.1/go.mod h1:i736AoUSYt75HyZLoJW9ERYxcy6eaN6h4BZXU064P/U=github.com/chenzhuoyu/base64x v0.0.0-20211019084208-fb5309c8db06/go.mod h1:DH46F32mSOjUmXrMHnKwZdA8wcEefY7UVqBKYGjpdQY=github.com/chenzhuoyu/base64x v0.0.0-20221115062448-fe3a3abad311 h1:qSGYFH7+jGhDF8vLC+iwCD4WpbV1EBDSzWkJODFLams=github.com/chenzhuoyu/base64x v0.0.0-20221115062448-fe3a3abad311/go.mod h1:b583jCggY9gE99b6G5LEC39OIiVsWj+R97kbl5odCEk=github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c=github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=github.com/dlclark/regexp2 v1.10.0 h1:+/GIL799phkJqYW+3YbOd8LCcbHzT0Pbo8zl70MHsq0=github.com/dlclark/regexp2 v1.10.0/go.mod h1:DHkYz0B9wPfa6wondMfaivmHpzrQ3v9q8cnmRbL6yW8=github.com/gabriel-vasile/mimetype v1.4.2 h1:w5qFW6JKBz9Y393Y4q372O9A7cUSequkh1Q7OhCmWKU=github.com/gabriel-vasile/mimetype v1.4.2/go.mod h1:zApsH/mKG4w07erKIaJPFiX0Tsq9BFQgN3qGY5GnNgA=github.com/gin-contrib/sse v0.1.0 h1:Y/yl/+YNO8GZSjAhjMsSuLt29uWRFHdHYUb5lYOV9qE=github.com/gin-contrib/sse v0.1.0/go.mod h1:RHrZQHXnP2xjPF+u1gW/2HnVO7nvIa9PG3Gm+fLHvGI=github.com/gin-gonic/gin v1.9.1 h1:4idEAncQnU5cB7BeOkPtxjfCSye0AAm1R0RVIqJ+Jmg=github.com/gin-gonic/gin v1.9.1/go.mod h1:hPrL7YrpYKXt5YId3A/Tnip5kqbEAP+KLuI3SUcPTeU=github.com/go-playground/assert/v2 v2.2.0 h1:JvknZsQTYeFEAhQwI4qEt9cyV5ONwRHC+lYKSsYSR8s=github.com/go-playground/assert/v2 v2.2.0/go.mod h1:VDjEfimB/XKnb+ZQfWdccd7VUvScMdVu0Titje2rxJ4=github.com/go-playground/locales v0.14.1 h1:EWaQ/wswjilfKLTECiXz7Rh+3BjFhfDFKv/oXslEjJA=github.com/go-playground/locales v0.14.1/go.mod h1:hxrqLVvrK65+Rwrd5Fc6F2O76J/NuW9t0sjnWqG1slY=github.com/go-playground/universal-translator v0.18.1 h1:Bcnm0ZwsGyWbCzImXv+pAJnYK9S473LQFuzCbDbfSFY=github.com/go-playground/universal-translator v0.18.1/go.mod h1:xekY+UJKNuX9WP91TpwSH2VMlDf28Uj24BCp08ZFTUY=github.com/go-playground/validator/v10 v10.14.0 h1:vgvQWe3XCz3gIeFDm/HnTIbj6UGmg/+t63MyGU2n5js=github.com/go-playground/validator/v10 v10.14.0/go.mod h1:9iXMNT7sEkjXb0I+enO7QXmzG6QCsPWY4zveKFVRSyU=github.com/goccy/go-json v0.10.2 h1:CrxCmQqYDkv1z7lO7Wbh2HN93uovUHgrECaO5ZrCXAU=github.com/goccy/go-json v0.10.2/go.mod h1:6MelG93GURQebXPDq3khkgXZkazVtN9CRI+MGFi0w8I=github.com/golang/protobuf v1.5.0/go.mod h1:FsONVRAS9T7sI+LIUmWTfcYkHO4aIWwzhcaSAoJOfIk=github.com/google/go-cmp v0.5.5 h1:Khx7svrCpmxxtHBq5j2mp/xVjsi8hQMfNLvJFAlrGgU=github.com/google/go-cmp v0.5.5/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE=github.com/google/gofuzz v1.0.0/go.mod h1:dBl0BpW6vV/+mYPU4Po3pmUjxk6FQPldtuIdl/M65Eg=github.com/google/uuid v1.6.0 h1:NIvaJDMOsjHA8n1jAhLSgzrAzy1Hgr+hNrb57e+94F0=github.com/google/uuid v1.6.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo=github.com/json-iterator/go v1.1.12 h1:PV8peI4a0ysnczrg+LtxykD8LfKY9ML6u2jnxaEnrnM=github.com/json-iterator/go v1.1.12/go.mod h1:e30LSqwooZae/UwlEbR2852Gd8hjQvJoHmT4TnhNGBo=github.com/klauspost/cpuid/v2 v2.0.9/go.mod h1:FInQzS24/EEf25PyTYn52gqo7WaD8xa0213Md/qVLRg=github.com/klauspost/cpuid/v2 v2.2.4 h1:acbojRNwl3o09bUq+yDCtZFc1aiwaAAxtcn8YkZXnvk=github.com/klauspost/cpuid/v2 v2.2.4/go.mod h1:RVVoqg1df56z8g3pUjL/3lE5UfnlrJX8tyFgg4nqhuY=github.com/leodido/go-urn v1.2.4 h1:XlAE/cm/ms7TE/VMVoduSpNBoyc2dOxHs5MZSwAN63Q=github.com/leodido/go-urn v1.2.4/go.mod h1:7ZrI8mTSeBSHl/UaRyKQW1qZeMgak41ANeCNaVckg+4=github.com/mattn/go-isatty v0.0.19 h1:JITubQf0MOLdlGRuRq+jtsDlekdYPia9ZFsB8h/APPA=github.com/mattn/go-isatty v0.0.19/go.mod h1:W+V8PltTTMOvKvAeJH7IuucS94S2C6jfK/D7dTCTo3Y=github.com/modern-go/concurrent v0.0.0-20180228061459-e0a39a4cb421/go.mod h1:6dJC0mAP4ikYIbvyc7fijjWJddQyLn8Ig3JB5CqoB9Q=github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd h1:TRLaZ9cD/w8PVh93nsPXa1VrQ6jlwL5oN8l14QlcNfg=github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd/go.mod h1:6dJC0mAP4ikYIbvyc7fijjWJddQyLn8Ig3JB5CqoB9Q=github.com/modern-go/reflect2 v1.0.2 h1:xBagoLtFs94CBntxluKeaWgTMpvLxC4ur3nMaC9Gz0M=github.com/modern-go/reflect2 v1.0.2/go.mod h1:yWuevngMOJpCy52FWWMvUC8ws7m/LJsjYzDa0/r8luk=github.com/pelletier/go-toml/v2 v2.0.8 h1:0ctb6s9mE31h0/lhu+J6OPmVeDxJn+kYnJc2jZR9tGQ=github.com/pelletier/go-toml/v2 v2.0.8/go.mod h1:vuYfssBdrU2XDZ9bYydBu6t+6a6PYNcZljzZR9VXg+4=github.com/pkoukk/tiktoken-go v0.1.8 h1:85ENo+3FpWgAACBaEUVp+lctuTcYUO7BtmfhlN/QTRo=github.com/pkoukk/tiktoken-go v0.1.8/go.mod h1:9NiV+i9mJKGj1rYOT+njbv+ZwA/zJxYdewGl6qVatpg=github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM=github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME=github.com/stretchr/objx v0.4.0/go.mod h1:YvHI0jy2hoMjB+UWwv71VJQ9isScKT/TqJzVSSt89Yw=github.com/stretchr/objx v0.5.0/go.mod h1:Yh+to48EsGEfYuaHDzXPcE3xhTkx73EhmCGUpEOglKo=github.com/stretchr/testify v1.3.0/go.mod h1:M5WIy9Dh21IEIfnGCwXGc5bZfKNJtfHm1UVUgZn+9EI=github.com/stretchr/testify v1.7.0/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg=github.com/stretchr/testify v1.7.1/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg=github.com/stretchr/testify v1.8.0/go.mod h1:yNjHg4UonilssWZ8iaSj1OCr/vHnekPRkoO+kdMU+MU=github.com/stretchr/testify v1.8.1/go.mod h1:w2LPCIKwWwSfY2zedu0+kehJoqGctiVI29o6fzry7u4=github.com/stretchr/testify v1.8.2/go.mod h1:w2LPCIKwWwSfY2zedu0+kehJoqGctiVI29o6fzry7u4=github.com/stretchr/testify v1.8.3 h1:RP3t2pwF7cMEbC1dqtB6poj3niw/9gnV4Cjg5oW5gtY=github.com/stretchr/testify v1.8.3/go.mod h1:sz/lmYIOXD/1dqDmKjjqLyZ2RngseejIcXlSw2iwfAo=github.com/twitchyliquid64/golang-asm v0.15.1 h1:SU5vSMR7hnwNxj24w34ZyCi/FmDZTkS4MhqMhdFk5YI=github.com/twitchyliquid64/golang-asm v0.15.1/go.mod h1:a1lVb/DtPvCB8fslRZhAngC2+aY1QWCk3Cedj/Gdt08=github.com/ugorji/go/codec v1.2.11 h1:BMaWp1Bb6fHwEtbplGBGJ498wD+LKlNSl25MjdZY4dU=github.com/ugorji/go/codec v1.2.11/go.mod h1:UNopzCgEMSXjBc6AOMqYvWC1ktqTAfzJZUZgYf6w6lg=golang.org/x/arch v0.0.0-20210923205945-b76863e36670/go.mod h1:5om86z9Hs0C8fWVUuoMHwpExlXzs5Tkyp9hOrfG7pp8=golang.org/x/arch v0.3.0 h1:02VY4/ZcO/gBOH6PUaoiptASxtXU10jazRCP865E97k=golang.org/x/arch v0.3.0/go.mod h1:5om86z9Hs0C8fWVUuoMHwpExlXzs5Tkyp9hOrfG7pp8=golang.org/x/crypto v0.9.0 h1:LF6fAI+IutBocDJ2OT0Q1g8plpYljMZ4+lty+dsqw3g=golang.org/x/crypto v0.9.0/go.mod h1:yrmDGqONDYtNj3tH8X9dzUun2m2lzPa9ngI6/RUPGR0=golang.org/x/net v0.10.0 h1:X2//UzNDwYmtCLn7To6G58Wr6f5ahEAQgKNzv9Y951M=golang.org/x/net v0.10.0/go.mod h1:0qNGK6F8kojg2nk9dLZ2mShWaEBan6FAoqfSigmmuDg=golang.org/x/sys v0.0.0-20220704084225-05e143d24a9e/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=golang.org/x/sys v0.6.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=golang.org/x/sys v0.8.0 h1:EBmGv8NaZBZTWvrbjNoL6HVt+IVy3QDQpJs7VRIw3tU=golang.org/x/sys v0.8.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=golang.org/x/text v0.9.0 h1:2sjJmO8cDvYveuX97RDLsxlyUxLl+GHoLxBiRdHllBE=golang.org/x/text v0.9.0/go.mod h1:e1OnstbJyHTd6l/uOt8jFFHp6TRDWZR/bV3emEE/zU8=golang.org/x/xerrors v0.0.0-20191204190536-9bdfabe68543 h1:E7g+9GITq07hpfrRu66IVDexMakfv52eLZ2CXBWiKr4=golang.org/x/xerrors v0.0.0-20191204190536-9bdfabe68543/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0=google.golang.org/protobuf v1.26.0-rc.1/go.mod h1:jlhhOSvTdKEhbULTjvd4ARK9grFBp09yW+WbY/TyQbw=google.golang.org/protobuf v1.30.0 h1:kPPoIgf3TsEvrm0PFe15JQ+570QVxYzEvvHqChK+cng=google.golang.org/protobuf v1.30.0/go.mod h1:HV8QOd/L58Z+nl8r43ehVNZIU/HEI6OcFqwMG9pJV4I=gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405 h1:yhCVgyC4o1eVCa2tZl7eS0r+SDo693bJlVdllGtEeKM=gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA=gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=rsc.io/pdf v0.1.1/go.mod h1:n8OzWcQ6Sp37PL01nO98y4iUCRdTGarVfzxY20ICaU4=123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118github.com/bytedance/sonic v1.5.0/go.mod h1:ED5hyg4y6t3/9Ku1R6dU/4KyJ48DZ4jPhfY1O2AihPM=github.com/bytedance/sonic v1.9.1 h1:6iJ6NqdoxCDr6mbY8h18oSO+cShGSMRGCEo7F2h0x8s=github.com/bytedance/sonic v1.9.1/go.mod h1:i736AoUSYt75HyZLoJW9ERYxcy6eaN6h4BZXU064P/U=github.com/chenzhuoyu/base64x v0.0.0-20211019084208-fb5309c8db06/go.mod h1:DH46F32mSOjUmXrMHnKwZdA8wcEefY7UVqBKYGjpdQY=github.com/chenzhuoyu/base64x v0.0.0-20221115062448-fe3a3abad311 h1:qSGYFH7+jGhDF8vLC+iwCD4WpbV1EBDSzWkJODFLams=github.com/chenzhuoyu/base64x v0.0.0-20221115062448-fe3a3abad311/go.mod h1:b583jCggY9gE99b6G5LEC39OIiVsWj+R97kbl5odCEk=github.com/creack/pty v1.1.9/go.mod h1:oKZEueFk5CKHvIhNR5MUki03XCEU+Q6VDXinZuGJ33E=github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c=github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=github.com/dlclark/regexp2 v1.10.0 h1:+/GIL799phkJqYW+3YbOd8LCcbHzT0Pbo8zl70MHsq0=github.com/dlclark/regexp2 v1.10.0/go.mod h1:DHkYz0B9wPfa6wondMfaivmHpzrQ3v9q8cnmRbL6yW8=github.com/gabriel-vasile/mimetype v1.4.2 h1:w5qFW6JKBz9Y393Y4q372O9A7cUSequkh1Q7OhCmWKU=github.com/gabriel-vasile/mimetype v1.4.2/go.mod h1:zApsH/mKG4w07erKIaJPFiX0Tsq9BFQgN3qGY5GnNgA=github.com/gin-contrib/sse v0.1.0 h1:Y/yl/+YNO8GZSjAhjMsSuLt29uWRFHdHYUb5lYOV9qE=github.com/gin-contrib/sse v0.1.0/go.mod h1:RHrZQHXnP2xjPF+u1gW/2HnVO7nvIa9PG3Gm+fLHvGI=github.com/gin-gonic/gin v1.9.1 h1:4idEAncQnU5cB7BeOkPtxjfCSye0AAm1R0RVIqJ+Jmg=github.com/gin-gonic/gin v1.9.1/go.mod h1:hPrL7YrpYKXt5YId3A/Tnip5kqbEAP+KLuI3SUcPTeU=github.com/go-playground/assert/v2 v2.2.0 h1:JvknZsQTYeFEAhQwI4qEt9cyV5ONwRHC+lYKSsYSR8s=github.com/go-playground/assert/v2 v2.2.0/go.mod h1:VDjEfimB/XKnb+ZQfWdccd7VUvScMdVu0Titje2rxJ4=github.com/go-playground/locales v0.14.1 h1:EWaQ/wswjilfKLTECiXz7Rh+3BjFhfDFKv/oXslEjJA=github.com/go-playground/locales v0.14.1/go.mod h1:hxrqLVvrK65+Rwrd5Fc6F2O76J/NuW9t0sjnWqG1slY=github.com/go-playground/universal-translator v0.18.1 h1:Bcnm0ZwsGyWbCzImXv+pAJnYK9S473LQFuzCbDbfSFY=github.com/go-playground/universal-translator v0.18.1/go.mod h1:xekY+UJKNuX9WP91TpwSH2VMlDf28Uj24BCp08ZFTUY=github.com/go-playground/validator/v10 v10.14.0 h1:vgvQWe3XCz3gIeFDm/HnTIbj6UGmg/+t63MyGU2n5js=github.com/go-playground/validator/v10 v10.14.0/go.mod h1:9iXMNT7sEkjXb0I+enO7QXmzG6QCsPWY4zveKFVRSyU=github.com/goccy/go-json v0.10.2 h1:CrxCmQqYDkv1z7lO7Wbh2HN93uovUHgrECaO5ZrCXAU=github.com/goccy/go-json v0.10.2/go.mod h1:6MelG93GURQebXPDq3khkgXZkazVtN9CRI+MGFi0w8I=github.com/golang-jwt/jwt/v5 v5.2.0 h1:d/ix8ftRUorsN+5eMIlF4T6J8CAt9rch3My2winC1Jw=github.com/golang-jwt/jwt/v5 v5.2.0/go.mod h1:pqrtFR0X4osieyHYxtmOUWsAWrfe1Q5UVIyoH402zdk=github.com/golang/protobuf v1.5.0/go.mod h1:FsONVRAS9T7sI+LIUmWTfcYkHO4aIWwzhcaSAoJOfIk=github.com/google/go-cmp v0.5.5 h1:Khx7svrCpmxxtHBq5j2mp/xVjsi8hQMfNLvJFAlrGgU=github.com/google/go-cmp v0.5.5/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE=github.com/google/gofuzz v1.0.0/go.mod h1:dBl0BpW6vV/+mYPU4Po3pmUjxk6FQPldtuIdl/M65Eg=github.com/google/uuid v1.6.0 h1:NIvaJDMOsjHA8n1jAhLSgzrAzy1Hgr+hNrb57e+94F0=github.com/google/uuid v1.6.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo=github.com/jackc/pgpassfile v1.0.0 h1:/6Hmqy13Ss2zCq62VdNG8tM1wchn8zjSGOBJ6icpsIM=github.com/jackc/pgpassfile v1.0.0/go.mod h1:CEx0iS5ambNFdcRtxPj5JhEz+xB6uRky5eyVu/W2HEg=github.com/jackc/pgservicefile v0.0.0-20221227161230-091c0ba34f0a h1:bbPeKD0xmW/Y25WS6cokEszi5g+S0QxI/d45PkRi7Nk=github.com/jackc/pgservicefile v0.0.0-20221227161230-091c0ba34f0a/go.mod h1:5TJZWKEWniPve33vlWYSoGYefn3gLQRzjfDlhSJ9ZKM=github.com/jackc/pgx/v5 v5.4.3 h1:cxFyXhxlvAifxnkKKdlxv8XqUf59tDlYjnV5YYfsJJY=github.com/jackc/pgx/v5 v5.4.3/go.mod h1:Ig06C2Vu0t5qXC60W8sqIthScaEnFvojjj9dSljmHRA=github.com/jinzhu/inflection v1.0.0 h1:K317FqzuhWc8YvSVlFMCCUb36O/S9MCKRDI7QkRKD/E=github.com/jinzhu/inflection v1.0.0/go.mod h1:h+uFLlag+Qp1Va5pdKtLDYj+kHp5pxUVkryuEj+Srlc=github.com/jinzhu/now v1.1.5 h1:/o9tlHleP7gOFmsnYNz3RGnqzefHA47wQpKrrdTIwXQ=github.com/jinzhu/now v1.1.5/go.mod h1:d3SSVoowX0Lcu0IBviAWJpolVfI5UJVZZ7cO71lE/z8=github.com/joho/godotenv v1.5.1 h1:7eLL/+HRGLY0ldzfGMeQkb7vMd0as4CfYvUVzLqw0N0=github.com/joho/godotenv v1.5.1/go.mod h1:f4LDr5Voq0i2e/R5DDNOoa2zzDfwtkZa6DnEwAbqwq4=github.com/json-iterator/go v1.1.12 h1:PV8peI4a0ysnczrg+LtxykD8LfKY9ML6u2jnxaEnrnM=github.com/json-iterator/go v1.1.12/go.mod h1:e30LSqwooZae/UwlEbR2852Gd8hjQvJoHmT4TnhNGBo=github.com/klauspost/cpuid/v2 v2.0.9/go.mod h1:FInQzS24/EEf25PyTYn52gqo7WaD8xa0213Md/qVLRg=github.com/klauspost/cpuid/v2 v2.2.4 h1:acbojRNwl3o09bUq+yDCtZFc1aiwaAAxtcn8YkZXnvk=github.com/klauspost/cpuid/v2 v2.2.4/go.mod h1:RVVoqg1df56z8g3pUjL/3lE5UfnlrJX8tyFgg4nqhuY=github.com/kr/pretty v0.3.0 h1:WgNl7dwNpEZ6jJ9k1snq4pZsg7DOEN8hP9Xw0Tsjwk0=github.com/kr/pretty v0.3.0/go.mod h1:640gp4NfQd8pI5XOwp5fnNeVWj67G7CFk/SaSQn7NBk=github.com/kr/text v0.2.0 h1:5Nx0Ya0ZqY2ygV366QzturHI13Jq95ApcVaJBhpS+AY=github.com/kr/text v0.2.0/go.mod h1:eLer722TekiGuMkidMxC/pM04lWEeraHUUmBw8l2grE=github.com/leodido/go-urn v1.2.4 h1:XlAE/cm/ms7TE/VMVoduSpNBoyc2dOxHs5MZSwAN63Q=github.com/leodido/go-urn v1.2.4/go.mod h1:7ZrI8mTSeBSHl/UaRyKQW1qZeMgak41ANeCNaVckg+4=github.com/mattn/go-isatty v0.0.19 h1:JITubQf0MOLdlGRuRq+jtsDlekdYPia9ZFsB8h/APPA=github.com/mattn/go-isatty v0.0.19/go.mod h1:W+V8PltTTMOvKvAeJH7IuucS94S2C6jfK/D7dTCTo3Y=github.com/modern-go/concurrent v0.0.0-20180228061459-e0a39a4cb421/go.mod h1:6dJC0mAP4ikYIbvyc7fijjWJddQyLn8Ig3JB5CqoB9Q=github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd h1:TRLaZ9cD/w8PVh93nsPXa1VrQ6jlwL5oN8l14QlcNfg=github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd/go.mod h1:6dJC0mAP4ikYIbvyc7fijjWJddQyLn8Ig3JB5CqoB9Q=github.com/modern-go/reflect2 v1.0.2 h1:xBagoLtFs94CBntxluKeaWgTMpvLxC4ur3nMaC9Gz0M=github.com/modern-go/reflect2 v1.0.2/go.mod h1:yWuevngMOJpCy52FWWMvUC8ws7m/LJsjYzDa0/r8luk=github.com/pelletier/go-toml/v2 v2.0.8 h1:0ctb6s9mE31h0/lhu+J6OPmVeDxJn+kYnJc2jZR9tGQ=github.com/pelletier/go-toml/v2 v2.0.8/go.mod h1:vuYfssBdrU2XDZ9bYydBu6t+6a6PYNcZljzZR9VXg+4=github.com/pkoukk/tiktoken-go v0.1.8 h1:85ENo+3FpWgAACBaEUVp+lctuTcYUO7BtmfhlN/QTRo=github.com/pkoukk/tiktoken-go v0.1.8/go.mod h1:9NiV+i9mJKGj1rYOT+njbv+ZwA/zJxYdewGl6qVatpg=github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM=github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=github.com/rogpeppe/go-internal v1.14.1 h1:UQB4HGPB6osV0SQTLymcB4TgvyWu6ZyliaW0tI/otEQ=github.com/rogpeppe/go-internal v1.14.1/go.mod h1:MaRKkUm5W0goXpeCfT7UZI6fk/L7L7so1lCWt35ZSgc=github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME=github.com/stretchr/objx v0.4.0/go.mod h1:YvHI0jy2hoMjB+UWwv71VJQ9isScKT/TqJzVSSt89Yw=github.com/stretchr/objx v0.5.0/go.mod h1:Yh+to48EsGEfYuaHDzXPcE3xhTkx73EhmCGUpEOglKo=github.com/stretchr/testify v1.3.0/go.mod h1:M5WIy9Dh21IEIfnGCwXGc5bZfKNJtfHm1UVUgZn+9EI=github.com/stretchr/testify v1.7.0/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg=github.com/stretchr/testify v1.7.1/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg=github.com/stretchr/testify v1.8.0/go.mod h1:yNjHg4UonilssWZ8iaSj1OCr/vHnekPRkoO+kdMU+MU=github.com/stretchr/testify v1.8.1/go.mod h1:w2LPCIKwWwSfY2zedu0+kehJoqGctiVI29o6fzry7u4=github.com/stretchr/testify v1.8.2/go.mod h1:w2LPCIKwWwSfY2zedu0+kehJoqGctiVI29o6fzry7u4=github.com/stretchr/testify v1.8.3 h1:RP3t2pwF7cMEbC1dqtB6poj3niw/9gnV4Cjg5oW5gtY=github.com/stretchr/testify v1.8.3/go.mod h1:sz/lmYIOXD/1dqDmKjjqLyZ2RngseejIcXlSw2iwfAo=github.com/twitchyliquid64/golang-asm v0.15.1 h1:SU5vSMR7hnwNxj24w34ZyCi/FmDZTkS4MhqMhdFk5YI=github.com/twitchyliquid64/golang-asm v0.15.1/go.mod h1:a1lVb/DtPvCB8fslRZhAngC2+aY1QWCk3Cedj/Gdt08=github.com/ugorji/go/codec v1.2.11 h1:BMaWp1Bb6fHwEtbplGBGJ498wD+LKlNSl25MjdZY4dU=github.com/ugorji/go/codec v1.2.11/go.mod h1:UNopzCgEMSXjBc6AOMqYvWC1ktqTAfzJZUZgYf6w6lg=golang.org/x/arch v0.0.0-20210923205945-b76863e36670/go.mod h1:5om86z9Hs0C8fWVUuoMHwpExlXzs5Tkyp9hOrfG7pp8=golang.org/x/arch v0.3.0 h1:02VY4/ZcO/gBOH6PUaoiptASxtXU10jazRCP865E97k=golang.org/x/arch v0.3.0/go.mod h1:5om86z9Hs0C8fWVUuoMHwpExlXzs5Tkyp9hOrfG7pp8=golang.org/x/crypto v0.18.0 h1:PGVlW0xEltQnzFZ55hkuX5+KLyrMYhHld1YHO4AKcdc=golang.org/x/crypto v0.18.0/go.mod h1:R0j02AL6hcrfOiy9T4ZYp/rcWeMxM3L6QYxlOuEG1mg=golang.org/x/net v0.10.0 h1:X2//UzNDwYmtCLn7To6G58Wr6f5ahEAQgKNzv9Y951M=golang.org/x/net v0.10.0/go.mod h1:0qNGK6F8kojg2nk9dLZ2mShWaEBan6FAoqfSigmmuDg=golang.org/x/sys v0.0.0-20220704084225-05e143d24a9e/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=golang.org/x/sys v0.6.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=golang.org/x/sys v0.26.0 h1:KHjCJyddX0LoSTb3J+vWpupP9p0oznkqVk/IfjymZbo=golang.org/x/sys v0.26.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA=golang.org/x/text v0.14.0 h1:ScX5w1eTa3QqT8oi6+ziP7dTV1S2+ALU0bI+0zXKWiQ=golang.org/x/text v0.14.0/go.mod h1:18ZOQIKpY8NJVqYksKHtTdi31H5itFRjB5/qKTNYzSU=golang.org/x/xerrors v0.0.0-20191204190536-9bdfabe68543 h1:E7g+9GITq07hpfrRu66IVDexMakfv52eLZ2CXBWiKr4=golang.org/x/xerrors v0.0.0-20191204190536-9bdfabe68543/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0=google.golang.org/protobuf v1.26.0-rc.1/go.mod h1:jlhhOSvTdKEhbULTjvd4ARK9grFBp09yW+WbY/TyQbw=google.golang.org/protobuf v1.30.0 h1:kPPoIgf3TsEvrm0PFe15JQ+570QVxYzEvvHqChK+cng=google.golang.org/protobuf v1.30.0/go.mod h1:HV8QOd/L58Z+nl8r43ehVNZIU/HEI6OcFqwMG9pJV4I=gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c h1:Hei/4ADfdWqJk1ZMxUNpqntNwaWcugrBjAiHlqqRiVk=gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c/go.mod h1:JHkPIbrfpd72SG/EVd6muEfDQjcINNoR0C8j2r3qZ4Q=gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA=gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=gorm.io/driver/postgres v1.5.4 h1:Iyrp9Meh3GmbSuyIAGyjkN+n9K+GHX9b9MqsTL4EJCo=gorm.io/driver/postgres v1.5.4/go.mod h1:Bgo89+h0CRcdA33Y6frlaHHVuTdOf87pmyzwW9C/BH0=gorm.io/gorm v1.25.5 h1:zR9lOiiYf09VNh5Q1gphfyia1JpiClIWG9hQaxB/mls=gorm.io/gorm v1.25.5/go.mod h1:hbnx/Oo0ChWMn1BIhpy1oYozzpM15i4YPuHDmfYtwg8=rsc.io/pdf v0.1.1/go.mod h1:n8OzWcQ6Sp37PL01nO98y4iUCRdTGarVfzxY20ICaU4=
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125package handler
import (
"net/http"
"opus-api/internal/middleware"
"opus-api/internal/service"
"opus-api/internal/types"
"github.com/gin-gonic/gin"
)
// AuthHandler 认证处理器
type AuthHandler struct {
authService *service.AuthService
}
// NewAuthHandler 创建认证处理器
func NewAuthHandler(authService *service.AuthService) *AuthHandler {
return &AuthHandler{authService: authService}
}
// LoginRequest 登录请求
type LoginRequest struct {
Username string `json:"username" binding:"required"`
Password string `json:"password" binding:"required"`
}
// LoginResponse 登录响应
type LoginResponse struct {
Token string `json:"token"`
User User `json:"user"`
}
// User 用户信息
type User struct {
ID uint `json:"id"`
Username string `json:"username"`
}
// Login 登录
func (h *AuthHandler) Login(c *gin.Context) {
var req LoginRequest
if err := c.ShouldBindJSON(&req); err != nil {
c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
return
}
user, token, err := h.authService.Login(req.Username, req.Password)
if err != nil {
c.JSON(http.StatusUnauthorized, gin.H{"error": "invalid username or password"})
return
}
c.JSON(http.StatusOK, LoginResponse{
Token: token,
User: User{
ID: user.ID,
Username: user.Username,
},
})
}
// Logout 登出
func (h *AuthHandler) Logout(c *gin.Context) {
userID, ok := middleware.GetUserID(c)
if !ok {
c.JSON(http.StatusUnauthorized, gin.H{"error": "unauthorized"})
return
}
if err := h.authService.Logout(userID); err != nil {
c.JSON(http.StatusInternalServerError, gin.H{"error": "failed to logout"})
return
}
c.JSON(http.StatusOK, gin.H{"message": "logged out successfully"})
}
// Me 获取当前用户信息
func (h *AuthHandler) Me(c *gin.Context) {
userID, ok := middleware.GetUserID(c)
if !ok {
c.JSON(http.StatusUnauthorized, gin.H{"error": "unauthorized"})
return
}
user, err := h.authService.GetUserByID(userID)
if err != nil {
c.JSON(http.StatusNotFound, gin.H{"error": "user not found"})
return
}
c.JSON(http.StatusOK, User{
ID: user.ID,
Username: user.Username,
})
}
// ChangePassword 修改密码
func (h *AuthHandler) ChangePassword(c *gin.Context) {
var req types.ChangePasswordRequest
if err := c.ShouldBindJSON(&req); err != nil {
c.JSON(http.StatusBadRequest, gin.H{"error": "请求参数错误: " + err.Error()})
return
}
// 从上下文获取当前用户ID
userID, ok := middleware.GetUserID(c)
if !ok {
c.JSON(http.StatusUnauthorized, gin.H{"error": "unauthorized"})
return
}
// 修改密码
if err := h.authService.ChangePassword(userID, req.OldPassword, req.NewPassword); err != nil {
if err == service.ErrInvalidCredentials {
c.JSON(http.StatusBadRequest, gin.H{"error": "原密码错误"})
return
}
c.JSON(http.StatusInternalServerError, gin.H{"error": "密码修改失败"})
return
}
c.JSON(http.StatusOK, gin.H{"message": "密码修改成功"})
}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320package handler
import (
"net/http"
"opus-api/internal/middleware"
"opus-api/internal/model"
"opus-api/internal/service"
"strconv"
"github.com/gin-gonic/gin"
)
// CookieHandler Cookie 管理处理器
type CookieHandler struct {
cookieService *service.CookieService
validator *service.CookieValidator
}
// NewCookieHandler 创建 Cookie 处理器
func NewCookieHandler(cookieService *service.CookieService, validator *service.CookieValidator) *CookieHandler {
return &CookieHandler{
cookieService: cookieService,
validator: validator,
}
}
// CreateCookieRequest 创建 Cookie 请求
type CreateCookieRequest struct {
Name string `json:"name" binding:"required"`
APIKey string `json:"api_key" binding:"required"`
SessionKey string `json:"session_key"`
Priority int `json:"priority"`
}
// UpdateCookieRequest 更新 Cookie 请求
type UpdateCookieRequest struct {
Name string `json:"name"`
APIKey string `json:"api_key"`
SessionKey string `json:"session_key"`
Priority *int `json:"priority"`
IsValid *bool `json:"is_valid"`
}
// CookieResponse Cookie 响应
type CookieResponse struct {
ID uint `json:"id"`
Name string `json:"name"`
APIKey string `json:"api_key"`
SessionKey string `json:"session_key"`
IsValid bool `json:"is_valid"`
Priority int `json:"priority"`
UsageCount int64 `json:"usage_count"`
ErrorCount int `json:"error_count"`
LastUsed string `json:"last_used,omitempty"`
LastValidated string `json:"last_validated,omitempty"`
CreatedAt string `json:"created_at"`
UpdatedAt string `json:"updated_at"`
}
// ListCookies 获取 Cookie 列表
func (h *CookieHandler) ListCookies(c *gin.Context) {
userID, ok := middleware.GetUserID(c)
if !ok {
c.JSON(http.StatusUnauthorized, gin.H{"error": "unauthorized"})
return
}
cookies, err := h.cookieService.ListCookies(userID)
if err != nil {
c.JSON(http.StatusInternalServerError, gin.H{"error": "failed to list cookies"})
return
}
responses := make([]CookieResponse, len(cookies))
for i, cookie := range cookies {
responses[i] = toCookieResponse(&cookie)
}
c.JSON(http.StatusOK, responses)
}
// GetCookie 获取单个 Cookie
func (h *CookieHandler) GetCookie(c *gin.Context) {
userID, ok := middleware.GetUserID(c)
if !ok {
c.JSON(http.StatusUnauthorized, gin.H{"error": "unauthorized"})
return
}
idStr := c.Param("id")
id, err := strconv.ParseUint(idStr, 10, 32)
if err != nil {
c.JSON(http.StatusBadRequest, gin.H{"error": "invalid id"})
return
}
cookie, err := h.cookieService.GetCookie(uint(id), userID)
if err != nil {
if err == service.ErrCookieNotFound {
c.JSON(http.StatusNotFound, gin.H{"error": "cookie not found"})
return
}
c.JSON(http.StatusInternalServerError, gin.H{"error": "failed to get cookie"})
return
}
c.JSON(http.StatusOK, toCookieResponse(cookie))
}
// CreateCookie 创建 Cookie
func (h *CookieHandler) CreateCookie(c *gin.Context) {
userID, ok := middleware.GetUserID(c)
if !ok {
c.JSON(http.StatusUnauthorized, gin.H{"error": "unauthorized"})
return
}
var req CreateCookieRequest
if err := c.ShouldBindJSON(&req); err != nil {
c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
return
}
cookie := &model.MorphCookie{
UserID: userID,
Name: req.Name,
APIKey: req.APIKey,
SessionKey: req.SessionKey,
Priority: req.Priority,
IsValid: true, // 默认有效,可以通过验证接口验证
}
if err := h.cookieService.CreateCookie(cookie); err != nil {
c.JSON(http.StatusInternalServerError, gin.H{"error": "failed to create cookie"})
return
}
c.JSON(http.StatusCreated, toCookieResponse(cookie))
}
// UpdateCookie 更新 Cookie
func (h *CookieHandler) UpdateCookie(c *gin.Context) {
userID, ok := middleware.GetUserID(c)
if !ok {
c.JSON(http.StatusUnauthorized, gin.H{"error": "unauthorized"})
return
}
idStr := c.Param("id")
id, err := strconv.ParseUint(idStr, 10, 32)
if err != nil {
c.JSON(http.StatusBadRequest, gin.H{"error": "invalid id"})
return
}
cookie, err := h.cookieService.GetCookie(uint(id), userID)
if err != nil {
if err == service.ErrCookieNotFound {
c.JSON(http.StatusNotFound, gin.H{"error": "cookie not found"})
return
}
c.JSON(http.StatusInternalServerError, gin.H{"error": "failed to get cookie"})
return
}
var req UpdateCookieRequest
if err := c.ShouldBindJSON(&req); err != nil {
c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
return
}
// 更新字段
if req.Name != "" {
cookie.Name = req.Name
}
if req.APIKey != "" {
cookie.APIKey = req.APIKey
}
if req.SessionKey != "" {
cookie.SessionKey = req.SessionKey
}
if req.Priority != nil {
cookie.Priority = *req.Priority
}
if req.IsValid != nil {
cookie.IsValid = *req.IsValid
}
if err := h.cookieService.UpdateCookie(cookie); err != nil {
c.JSON(http.StatusInternalServerError, gin.H{"error": "failed to update cookie"})
return
}
c.JSON(http.StatusOK, toCookieResponse(cookie))
}
// DeleteCookie 删除 Cookie
func (h *CookieHandler) DeleteCookie(c *gin.Context) {
userID, ok := middleware.GetUserID(c)
if !ok {
c.JSON(http.StatusUnauthorized, gin.H{"error": "unauthorized"})
return
}
idStr := c.Param("id")
id, err := strconv.ParseUint(idStr, 10, 32)
if err != nil {
c.JSON(http.StatusBadRequest, gin.H{"error": "invalid id"})
return
}
if err := h.cookieService.DeleteCookie(uint(id), userID); err != nil {
if err == service.ErrCookieNotFound {
c.JSON(http.StatusNotFound, gin.H{"error": "cookie not found"})
return
}
c.JSON(http.StatusInternalServerError, gin.H{"error": "failed to delete cookie"})
return
}
c.JSON(http.StatusOK, gin.H{"message": "cookie deleted successfully"})
}
// ValidateCookie 验证单个 Cookie
func (h *CookieHandler) ValidateCookie(c *gin.Context) {
userID, ok := middleware.GetUserID(c)
if !ok {
c.JSON(http.StatusUnauthorized, gin.H{"error": "unauthorized"})
return
}
idStr := c.Param("id")
id, err := strconv.ParseUint(idStr, 10, 32)
if err != nil {
c.JSON(http.StatusBadRequest, gin.H{"error": "invalid id"})
return
}
cookie, err := h.cookieService.GetCookie(uint(id), userID)
if err != nil {
if err == service.ErrCookieNotFound {
c.JSON(http.StatusNotFound, gin.H{"error": "cookie not found"})
return
}
c.JSON(http.StatusInternalServerError, gin.H{"error": "failed to get cookie"})
return
}
isValid := h.validator.ValidateCookie(cookie)
c.JSON(http.StatusOK, gin.H{
"id": cookie.ID,
"is_valid": isValid,
})
}
// ValidateAllCookies 验证所有 Cookie
func (h *CookieHandler) ValidateAllCookies(c *gin.Context) {
userID, ok := middleware.GetUserID(c)
if !ok {
c.JSON(http.StatusUnauthorized, gin.H{"error": "unauthorized"})
return
}
results := h.validator.ValidateAllCookies(userID)
c.JSON(http.StatusOK, gin.H{
"results": results,
})
}
// GetStats 获取统计信息
func (h *CookieHandler) GetStats(c *gin.Context) {
userID, ok := middleware.GetUserID(c)
if !ok {
c.JSON(http.StatusUnauthorized, gin.H{"error": "unauthorized"})
return
}
stats, err := h.cookieService.GetStats(userID)
if err != nil {
c.JSON(http.StatusInternalServerError, gin.H{"error": "failed to get stats"})
return
}
c.JSON(http.StatusOK, stats)
}
// toCookieResponse 转换为响应格式
func toCookieResponse(cookie *model.MorphCookie) CookieResponse {
resp := CookieResponse{
ID: cookie.ID,
Name: cookie.Name,
APIKey: maskAPIKey(cookie.APIKey),
SessionKey: cookie.SessionKey,
IsValid: cookie.IsValid,
Priority: cookie.Priority,
UsageCount: cookie.UsageCount,
ErrorCount: cookie.ErrorCount,
CreatedAt: cookie.CreatedAt.Format("2006-01-02 15:04:05"),
UpdatedAt: cookie.UpdatedAt.Format("2006-01-02 15:04:05"),
}
if cookie.LastUsed != nil {
resp.LastUsed = cookie.LastUsed.Format("2006-01-02 15:04:05")
}
if cookie.LastValidated != nil {
resp.LastValidated = cookie.LastValidated.Format("2006-01-02 15:04:05")
}
return resp
}
// maskAPIKey 隐藏 API Key 中间部分
func maskAPIKey(apiKey string) string {
if len(apiKey) <= 8 {
return "****"
}
return apiKey[:4] + "****" + apiKey[len(apiKey)-4:]
}8 unmodified lines9101112131420 unmodified lines35363738394023 unmodified lines646566676869708 unmodified lines"net/http""opus-api/internal/converter""opus-api/internal/logger""opus-api/internal/stream""opus-api/internal/tokenizer""opus-api/internal/types"20 unmodified linesreturn}// Log Point 1: Claude requestvar logFolder stringif types.DebugMode {23 unmodified lines}// Set headersfor key, value := range types.MorphHeaders {req.Header.Set(key, value)}8 unmodified lines910111213141520 unmodified lines363738394041424344454647484950515223 unmodified lines7677787980818283848586878889909192939495969798991001011021031048 unmodified lines"net/http""opus-api/internal/converter""opus-api/internal/logger""opus-api/internal/model""opus-api/internal/stream""opus-api/internal/tokenizer""opus-api/internal/types"20 unmodified linesreturn}// 验证模型是否支持if claudeReq.Model == "" {claudeReq.Model = types.DefaultModel}if !types.IsModelSupported(claudeReq.Model) {c.JSON(http.StatusBadRequest, gin.H{"error": fmt.Sprintf("Model '%s' is not supported. Supported models: %v", claudeReq.Model, types.SupportedModels),})return}// Log Point 1: Claude requestvar logFolder stringif types.DebugMode {23 unmodified lines}// Set headersheaders := make(map[string]string)for key, value := range types.MorphHeaders {headers[key] = value}// 如果启用了 Cookie 轮询器,使用轮询的 Cookieif types.CookieRotatorInstance != nil {cookieInterface, err := types.CookieRotatorInstance.NextCookie()if err == nil && cookieInterface != nil {// 类型断言为 *model.MorphCookieif cookie, ok := cookieInterface.(*model.MorphCookie); ok {headers["cookie"] = cookie.APIKeylog.Printf("[INFO] Using rotated cookie (ID: %d, Priority: %d)", cookie.ID, cookie.Priority)} else {log.Printf("[WARN] Cookie type assertion failed, using default")}} else {log.Printf("[WARN] Failed to get rotated cookie: %v, using default", err)}}// 应用所有请求头for key, value := range headers {req.Header.Set(key, value)}
1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253package middleware
import (
"net/http"
"opus-api/internal/service"
"strings"
"github.com/gin-gonic/gin"
)
// AuthMiddleware JWT 认证中间件
func AuthMiddleware(authService *service.AuthService) gin.HandlerFunc {
return func(c *gin.Context) {
authHeader := c.GetHeader("Authorization")
if authHeader == "" {
c.JSON(http.StatusUnauthorized, gin.H{"error": "missing authorization header"})
c.Abort()
return
}
// 解析 Bearer token
parts := strings.SplitN(authHeader, " ", 2)
if len(parts) != 2 || parts[0] != "Bearer" {
c.JSON(http.StatusUnauthorized, gin.H{"error": "invalid authorization header format"})
c.Abort()
return
}
token := parts[1]
// 验证 token
userID, err := authService.ValidateToken(token)
if err != nil {
c.JSON(http.StatusUnauthorized, gin.H{"error": "invalid or expired token"})
c.Abort()
return
}
// 将用户 ID 存储到上下文
c.Set("user_id", userID)
c.Next()
}
}
// GetUserID 从上下文获取用户 ID
func GetUserID(c *gin.Context) (uint, bool) {
userID, exists := c.Get("user_id")
if !exists {
return 0, false
}
id, ok := userID.(uint)
return id, ok
}12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364package model
import (
"time"
)
// MorphCookie Morph Cookie 模型
type MorphCookie struct {
ID uint `gorm:"primaryKey" json:"id"`
UserID uint `gorm:"not null;index" json:"user_id"`
User User `gorm:"foreignKey:UserID;constraint:OnDelete:CASCADE" json:"-"`
Name string `gorm:"size:100;not null" json:"name"`
APIKey string `gorm:"column:api_key;type:text;not null" json:"api_key"`
SessionKey string `gorm:"column:session_key;type:text" json:"session_key"`
IsValid bool `gorm:"default:true;index" json:"is_valid"`
LastValidated *time.Time `gorm:"column:last_validated" json:"last_validated"`
LastUsed *time.Time `gorm:"column:last_used" json:"last_used"`
Priority int `gorm:"default:0;index" json:"priority"`
UsageCount int64 `gorm:"default:0" json:"usage_count"`
ErrorCount int `gorm:"default:0" json:"error_count"`
CreatedAt time.Time `json:"created_at"`
UpdatedAt time.Time `json:"updated_at"`
}
// CookieStats Cookie 统计信息
type CookieStats struct {
TotalCount int64 `json:"total_count"`
ValidCount int64 `json:"valid_count"`
InvalidCount int64 `json:"invalid_count"`
TotalUsage int64 `json:"total_usage"`
}
// TableName 指定表名
func (MorphCookie) TableName() string {
return "morph_cookies"
}
// MarkUsed 标记 Cookie 已使用
func (c *MorphCookie) MarkUsed() {
now := time.Now()
c.LastUsed = &now
c.UsageCount++
c.ErrorCount = 0 // 成功使用后重置错误计数
}
// MarkError 标记 Cookie 错误
func (c *MorphCookie) MarkError() {
c.ErrorCount++
}
// MarkInvalid 标记 Cookie 无效
func (c *MorphCookie) MarkInvalid() {
c.IsValid = false
now := time.Now()
c.LastValidated = &now
}
// MarkValid 标记 Cookie 有效
func (c *MorphCookie) MarkValid() {
c.IsValid = true
c.ErrorCount = 0
now := time.Now()
c.LastValidated = &now
}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869package model
import (
"fmt"
"log"
"os"
"time"
"gorm.io/driver/postgres"
"gorm.io/gorm"
"gorm.io/gorm/logger"
)
var DB *gorm.DB
// InitDB 初始化数据库连接
func InitDB() error {
databaseURL := os.Getenv("DATABASE_URL")
if databaseURL == "" {
return fmt.Errorf("DATABASE_URL environment variable is not set")
}
var err error
DB, err = gorm.Open(postgres.Open(databaseURL), &gorm.Config{
Logger: logger.Default.LogMode(logger.Info),
NowFunc: func() time.Time {
return time.Now().UTC()
},
})
if err != nil {
return fmt.Errorf("failed to connect to database: %w", err)
}
// 配置连接池
sqlDB, err := DB.DB()
if err != nil {
return fmt.Errorf("failed to get database instance: %w", err)
}
sqlDB.SetMaxIdleConns(10)
sqlDB.SetMaxOpenConns(100)
sqlDB.SetConnMaxLifetime(time.Hour)
// 自动迁移
if err := autoMigrate(); err != nil {
return fmt.Errorf("failed to migrate database: %w", err)
}
log.Println("Database connected and migrated successfully")
return nil
}
// autoMigrate 自动迁移数据库表结构
func autoMigrate() error {
return DB.AutoMigrate(
&User{},
&MorphCookie{},
&UserSession{},
)
}
// CloseDB 关闭数据库连接
func CloseDB() error {
sqlDB, err := DB.DB()
if err != nil {
return err
}
return sqlDB.Close()
}1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192package model
import (
"log"
"os"
"time"
"golang.org/x/crypto/bcrypt"
"gorm.io/gorm"
)
// User 用户模型
type User struct {
ID uint `gorm:"primaryKey" json:"id"`
Username string `gorm:"uniqueIndex;size:50;not null" json:"username"`
PasswordHash string `gorm:"size:255;not null" json:"-"`
CreatedAt time.Time `json:"created_at"`
UpdatedAt time.Time `json:"updated_at"`
}
// UserSession 用户会话模型
type UserSession struct {
ID uint `gorm:"primaryKey" json:"id"`
UserID uint `gorm:"not null;index" json:"user_id"`
User User `gorm:"foreignKey:UserID;constraint:OnDelete:CASCADE" json:"-"`
TokenHash string `gorm:"uniqueIndex;size:255;not null" json:"-"`
ExpiresAt time.Time `gorm:"not null;index" json:"expires_at"`
CreatedAt time.Time `json:"created_at"`
}
// SetPassword 设置用户密码(加密)
func (u *User) SetPassword(password string) error {
hash, err := bcrypt.GenerateFromPassword([]byte(password), bcrypt.DefaultCost)
if err != nil {
return err
}
u.PasswordHash = string(hash)
return nil
}
// CheckPassword 验证密码
func (u *User) CheckPassword(password string) bool {
err := bcrypt.CompareHashAndPassword([]byte(u.PasswordHash), []byte(password))
return err == nil
}
// TableName 指定表名
func (User) TableName() string {
return "users"
}
// TableName 指定表名
func (UserSession) TableName() string {
return "user_sessions"
}
// CreateDefaultAdmin 创建默认管理员用户
func CreateDefaultAdmin(db *gorm.DB) error {
username := os.Getenv("DEFAULT_ADMIN_USERNAME")
if username == "" {
username = "admin"
}
password := os.Getenv("DEFAULT_ADMIN_PASSWORD")
if password == "" {
password = "changeme123"
}
// 检查用户是否已存在
var existingUser User
result := db.Where("username = ?", username).First(&existingUser)
if result.Error == nil {
// 用户已存在
log.Printf("Default admin user '%s' already exists", username)
return nil
}
// 创建新用户
user := &User{
Username: username,
}
if err := user.SetPassword(password); err != nil {
return err
}
if err := db.Create(user).Error; err != nil {
return err
}
log.Printf("Default admin user '%s' created successfully", username)
return nil
}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190package service
import (
"crypto/sha256"
"encoding/hex"
"errors"
"fmt"
"os"
"time"
"opus-api/internal/model"
"github.com/golang-jwt/jwt/v5"
"gorm.io/gorm"
)
var (
ErrInvalidCredentials = errors.New("invalid username or password")
ErrUserNotFound = errors.New("user not found")
ErrInvalidToken = errors.New("invalid token")
)
// AuthService 认证服务
type AuthService struct {
db *gorm.DB
jwtSecret []byte
}
// NewAuthService 创建认证服务
func NewAuthService(db *gorm.DB) *AuthService {
secret := os.Getenv("JWT_SECRET")
if secret == "" {
secret = "default-secret-change-me-in-production"
}
return &AuthService{
db: db,
jwtSecret: []byte(secret),
}
}
// Claims JWT 声明
type Claims struct {
UserID uint `json:"user_id"`
Username string `json:"username"`
jwt.RegisteredClaims
}
// Login 用户登录
func (s *AuthService) Login(username, password string) (*model.User, string, error) {
var user model.User
if err := s.db.Where("username = ?", username).First(&user).Error; err != nil {
if errors.Is(err, gorm.ErrRecordNotFound) {
return nil, "", ErrInvalidCredentials
}
return nil, "", err
}
if !user.CheckPassword(password) {
return nil, "", ErrInvalidCredentials
}
// 生成 JWT token
token, err := s.generateToken(&user)
if err != nil {
return nil, "", err
}
// 保存会话
if err := s.saveSession(&user, token); err != nil {
return nil, "", err
}
return &user, token, nil
}
// generateToken 生成 JWT token
func (s *AuthService) generateToken(user *model.User) (string, error) {
expirationTime := time.Now().Add(24 * time.Hour)
claims := &Claims{
UserID: user.ID,
Username: user.Username,
RegisteredClaims: jwt.RegisteredClaims{
ExpiresAt: jwt.NewNumericDate(expirationTime),
IssuedAt: jwt.NewNumericDate(time.Now()),
},
}
token := jwt.NewWithClaims(jwt.SigningMethodHS256, claims)
return token.SignedString(s.jwtSecret)
}
// saveSession 保存会话
func (s *AuthService) saveSession(user *model.User, token string) error {
tokenHash := hashToken(token)
session := &model.UserSession{
UserID: user.ID,
TokenHash: tokenHash,
ExpiresAt: time.Now().Add(24 * time.Hour),
}
return s.db.Create(session).Error
}
// ValidateToken 验证 token,返回用户 ID
func (s *AuthService) ValidateToken(tokenString string) (uint, error) {
claims := &Claims{}
token, err := jwt.ParseWithClaims(tokenString, claims, func(token *jwt.Token) (interface{}, error) {
if _, ok := token.Method.(*jwt.SigningMethodHMAC); !ok {
return 0, fmt.Errorf("unexpected signing method: %v", token.Header["alg"])
}
return s.jwtSecret, nil
})
if err != nil {
return 0, ErrInvalidToken
}
if !token.Valid {
return 0, ErrInvalidToken
}
// 检查会话是否存在且未过期
tokenHash := hashToken(tokenString)
var session model.UserSession
if err := s.db.Where("token_hash = ? AND expires_at > ?", tokenHash, time.Now()).First(&session).Error; err != nil {
if errors.Is(err, gorm.ErrRecordNotFound) {
return 0, ErrInvalidToken
}
return 0, err
}
return claims.UserID, nil
}
// Logout 用户登出(删除用户的所有会话)
func (s *AuthService) Logout(userID uint) error {
return s.db.Where("user_id = ?", userID).Delete(&model.UserSession{}).Error
}
// GetUserByID 根据 ID 获取用户
func (s *AuthService) GetUserByID(userID uint) (*model.User, error) {
var user model.User
if err := s.db.First(&user, userID).Error; err != nil {
if errors.Is(err, gorm.ErrRecordNotFound) {
return nil, ErrUserNotFound
}
return nil, err
}
return &user, nil
}
// hashToken 对 token 进行哈希
func hashToken(token string) string {
hash := sha256.Sum256([]byte(token))
return hex.EncodeToString(hash[:])
}
// CleanExpiredSessions 清理过期会话
func (s *AuthService) CleanExpiredSessions() error {
return s.db.Where("expires_at < ?", time.Now()).Delete(&model.UserSession{}).Error
}
// ChangePassword 修改用户密码
func (s *AuthService) ChangePassword(userID uint, oldPassword, newPassword string) error {
var user model.User
// 查找用户
if err := s.db.First(&user, userID).Error; err != nil {
if errors.Is(err, gorm.ErrRecordNotFound) {
return ErrUserNotFound
}
return err
}
// 验证旧密码
if !user.CheckPassword(oldPassword) {
return ErrInvalidCredentials
}
// 设置新密码
if err := user.SetPassword(newPassword); err != nil {
return fmt.Errorf("failed to hash password: %w", err)
}
// 保存到数据库
if err := s.db.Save(&user).Error; err != nil {
return fmt.Errorf("failed to update password: %w", err)
}
return nil
}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125package service
import (
"errors"
"opus-api/internal/model"
"gorm.io/gorm"
)
var (
ErrCookieNotFound = errors.New("cookie not found")
)
// CookieService Cookie 管理服务
type CookieService struct {
db *gorm.DB
}
// NewCookieService 创建 Cookie 服务
func NewCookieService(db *gorm.DB) *CookieService {
return &CookieService{db: db}
}
// GetDB 获取数据库连接
func (s *CookieService) GetDB() *gorm.DB {
return s.db
}
// ListCookies 获取用户的所有 Cookie
func (s *CookieService) ListCookies(userID uint) ([]model.MorphCookie, error) {
var cookies []model.MorphCookie
err := s.db.Where("user_id = ?", userID).
Order("priority DESC, created_at DESC").
Find(&cookies).Error
return cookies, err
}
// GetCookie 获取单个 Cookie
func (s *CookieService) GetCookie(id, userID uint) (*model.MorphCookie, error) {
var cookie model.MorphCookie
err := s.db.Where("id = ? AND user_id = ?", id, userID).First(&cookie).Error
if err != nil {
if errors.Is(err, gorm.ErrRecordNotFound) {
return nil, ErrCookieNotFound
}
return nil, err
}
return &cookie, nil
}
// CreateCookie 创建 Cookie
func (s *CookieService) CreateCookie(cookie *model.MorphCookie) error {
return s.db.Create(cookie).Error
}
// UpdateCookie 更新 Cookie
func (s *CookieService) UpdateCookie(cookie *model.MorphCookie) error {
return s.db.Save(cookie).Error
}
// DeleteCookie 删除 Cookie
func (s *CookieService) DeleteCookie(id, userID uint) error {
result := s.db.Where("id = ? AND user_id = ?", id, userID).Delete(&model.MorphCookie{})
if result.Error != nil {
return result.Error
}
if result.RowsAffected == 0 {
return ErrCookieNotFound
}
return nil
}
// GetStats 获取统计信息
func (s *CookieService) GetStats(userID uint) (*model.CookieStats, error) {
stats := &model.CookieStats{}
// 总数
if err := s.db.Model(&model.MorphCookie{}).
Where("user_id = ?", userID).
Count(&stats.TotalCount).Error; err != nil {
return nil, err
}
// 有效数量
if err := s.db.Model(&model.MorphCookie{}).
Where("user_id = ? AND is_valid = ?", userID, true).
Count(&stats.ValidCount).Error; err != nil {
return nil, err
}
// 无效数量
stats.InvalidCount = stats.TotalCount - stats.ValidCount
// 总使用次数
var totalUsage *int64
if err := s.db.Model(&model.MorphCookie{}).
Where("user_id = ?", userID).
Select("COALESCE(SUM(usage_count), 0)").
Scan(&totalUsage).Error; err != nil {
return nil, err
}
if totalUsage != nil {
stats.TotalUsage = *totalUsage
}
return stats, nil
}
// GetValidCookies 获取所有有效的 Cookie
func (s *CookieService) GetValidCookies(userID uint) ([]model.MorphCookie, error) {
var cookies []model.MorphCookie
err := s.db.Where("user_id = ? AND is_valid = ?", userID, true).
Order("priority DESC, usage_count ASC").
Find(&cookies).Error
return cookies, err
}
// GetAllValidCookies 获取系统中所有有效的 Cookie(用于轮询)
func (s *CookieService) GetAllValidCookies() ([]model.MorphCookie, error) {
var cookies []model.MorphCookie
err := s.db.Where("is_valid = ?", true).
Order("priority DESC, usage_count ASC").
Find(&cookies).Error
return cookies, err
}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167package service
import (
"errors"
"opus-api/internal/model"
"sync"
"time"
"gorm.io/gorm"
)
// RotationStrategy Cookie 轮询策略
type RotationStrategy string
const (
StrategyRoundRobin RotationStrategy = "round_robin" // 轮询
StrategyPriority RotationStrategy = "priority" // 优先级
StrategyLeastUsed RotationStrategy = "least_used" // 最少使用
)
var (
ErrNoCookiesAvailable = errors.New("no valid cookies available")
)
// CookieRotator Cookie 轮询器
type CookieRotator struct {
service *CookieService
strategy RotationStrategy
mu sync.RWMutex
index int // 用于 round_robin 策略
}
// NewCookieRotator 创建轮询器
func NewCookieRotator(service *CookieService, strategy RotationStrategy) *CookieRotator {
if strategy == "" {
strategy = StrategyRoundRobin
}
return &CookieRotator{
service: service,
strategy: strategy,
index: 0,
}
}
// NextCookie 获取下一个可用的 Cookie
func (r *CookieRotator) NextCookie() (interface{}, error) {
r.mu.Lock()
defer r.mu.Unlock()
cookies, err := r.service.GetAllValidCookies()
if err != nil {
return nil, err
}
if len(cookies) == 0 {
return nil, ErrNoCookiesAvailable
}
var selected *model.MorphCookie
switch r.strategy {
case StrategyRoundRobin:
selected = r.roundRobin(cookies)
case StrategyPriority:
selected = r.priority(cookies)
case StrategyLeastUsed:
selected = r.leastUsed(cookies)
default:
selected = r.roundRobin(cookies)
}
if selected == nil {
return nil, ErrNoCookiesAvailable
}
return selected, nil
}
// roundRobin 轮询策略
func (r *CookieRotator) roundRobin(cookies []model.MorphCookie) *model.MorphCookie {
if len(cookies) == 0 {
return nil
}
r.index = r.index % len(cookies)
selected := &cookies[r.index]
r.index++
return selected
}
// priority 优先级策略(优先级高的优先使用)
func (r *CookieRotator) priority(cookies []model.MorphCookie) *model.MorphCookie {
if len(cookies) == 0 {
return nil
}
// cookies 已经按照 priority DESC 排序
return &cookies[0]
}
// leastUsed 最少使用策略
func (r *CookieRotator) leastUsed(cookies []model.MorphCookie) *model.MorphCookie {
if len(cookies) == 0 {
return nil
}
// cookies 已经按照 usage_count ASC 排序
return &cookies[0]
}
// MarkUsed 标记 Cookie 已使用
func (r *CookieRotator) MarkUsed(cookieID uint) error {
db := r.service.GetDB()
return db.Model(&model.MorphCookie{}).
Where("id = ?", cookieID).
Updates(map[string]interface{}{
"usage_count": gorm.Expr("usage_count + ?", 1),
"last_used": time.Now(),
}).Error
}
// MarkInvalid 标记 Cookie 无效
func (r *CookieRotator) MarkInvalid(cookieID uint) error {
db := r.service.GetDB()
return db.Model(&model.MorphCookie{}).
Where("id = ?", cookieID).
Updates(map[string]interface{}{
"is_valid": false,
}).Error
}
// MarkError 标记 Cookie 错误
func (r *CookieRotator) MarkError(cookieID uint) error {
db := r.service.GetDB()
var cookie model.MorphCookie
if err := db.First(&cookie, cookieID).Error; err != nil {
return err
}
updates := map[string]interface{}{
"error_count": gorm.Expr("error_count + ?", 1),
}
// 如果错误次数超过阈值,标记为无效
if cookie.ErrorCount >= 5 {
updates["is_valid"] = false
}
return db.Model(&model.MorphCookie{}).
Where("id = ?", cookieID).
Updates(updates).Error
}
// GetStrategy 获取当前策略
func (r *CookieRotator) GetStrategy() RotationStrategy {
return r.strategy
}
// SetStrategy 设置轮询策略
func (r *CookieRotator) SetStrategy(strategy RotationStrategy) {
r.mu.Lock()
defer r.mu.Unlock()
r.strategy = strategy
r.index = 0 // 重置索引
}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141package service
import (
"bytes"
"encoding/json"
"io"
"net/http"
"opus-api/internal/converter"
"opus-api/internal/model"
"opus-api/internal/types"
"time"
"gorm.io/gorm"
)
// CookieValidator Cookie 验证器
type CookieValidator struct {
service *CookieService
}
// NewCookieValidator 创建验证器
func NewCookieValidator(service *CookieService) *CookieValidator {
return &CookieValidator{service: service}
}
// ValidateCookie 验证单个 Cookie
func (v *CookieValidator) ValidateCookie(cookie *model.MorphCookie) bool {
result := v.testCookie(cookie)
db := v.service.GetDB()
if result {
db.Model(cookie).Updates(map[string]interface{}{
"is_valid": true,
"last_validated": time.Now(),
"error_count": 0,
})
} else {
db.Model(cookie).Updates(map[string]interface{}{
"is_valid": false,
"last_validated": time.Now(),
"error_count": gorm.Expr("error_count + ?", 1),
})
}
return result
}
// ValidateAllCookies 验证用户的所有 Cookie
func (v *CookieValidator) ValidateAllCookies(userID uint) map[uint]bool {
cookies, err := v.service.ListCookies(userID)
if err != nil {
return nil
}
results := make(map[uint]bool)
for _, cookie := range cookies {
results[cookie.ID] = v.ValidateCookie(&cookie)
}
return results
}
// testCookie 测试 Cookie 是否有效(与 /v1/messages 逻辑完全一致)
func (v *CookieValidator) testCookie(cookie *model.MorphCookie) bool {
client := &http.Client{
Timeout: 30 * time.Second,
}
// 创建 Claude 格式的测试请求
claudeReq := types.ClaudeRequest{
Model: types.DefaultModel,
MaxTokens: 1024,
Messages: []types.ClaudeMessage{
{
Role: "user",
Content: "Hello!",
},
},
}
// 使用与 /v1/messages 相同的转换逻辑,将 Claude 格式转换为 Morph 格式
morphReq := converter.ClaudeToMorph(claudeReq)
reqBody, _ := json.Marshal(morphReq)
req, err := http.NewRequest("POST", types.MorphAPIURL, bytes.NewReader(reqBody))
if err != nil {
return false
}
// 使用与 /v1/messages 相同的请求头
for key, value := range types.MorphHeaders {
req.Header.Set(key, value)
}
// 覆盖 Cookie
req.Header.Set("cookie", cookie.APIKey)
resp, err := client.Do(req)
if err != nil {
return false
}
defer resp.Body.Close()
// 检查响应状态码
// 200 OK 表示成功,401/403 表示认证失败
if resp.StatusCode == http.StatusUnauthorized || resp.StatusCode == http.StatusForbidden {
return false
}
// 尝试读取响应体
body, _ := io.ReadAll(resp.Body)
// 检查是否是有效的 API 响应(SSE 流格式)
bodyStr := string(body)
// Morph API 返回 SSE 流,有效的响应会包含 "data:" 前缀
if !containsPrefix(bodyStr, "data:") {
return false
}
return true
}
// containsPrefix 检查字符串是否包含指定前缀(忽略空白字符)
func containsPrefix(s, prefix string) bool {
// 去除前导空白字符
start := 0
for start < len(s) && (s[start] == ' ' || s[start] == '\t' || s[start] == '\n' || s[start] == '\r') {
start++
}
if start >= len(s) {
return false
}
return len(s[start:]) >= len(prefix) && s[start:start+len(prefix)] == prefix
}
// validateCookieQuiet 静默验证 Cookie(不更新数据库)
func (v *CookieValidator) validateCookieQuiet(cookie *model.MorphCookie) bool {
return v.testCookie(cookie)
}12345678912 unmodified lines222324252627282930313233package typesconst (MorphAPIURL = "https://www.morphllm.com/api/warpgrep-chat"MorphCookies = "_gcl_aw=GCL.1769242305.Cj0KCQiA-NHLBhDSARIsAIhe9X36gjH12LKRxYZ1bqy4c8wATix3qqxauv9-7H-rewEfnKOW0npi5ZMaAjfHEALw_wcB; _gcl_gs=2.1.k1$i1769242301$u142736937; _ga=GA1.1.1601700642.1769242305; __client_uat=1769312595; __client_uat_B3JMRlZP=1769312595; __refresh_B3JMRlZP=mCRNoZazsM9bFPAAxEwv; clerk_active_context=sess_38jUhuq7Hkg8fiqhHMduDWfmycM:; _rdt_uuid=1769242305266.9f8d183d-a987-4e5b-9dee-336b47494719; _rdt_em=:3a02869661fc8f1da6409edc313bf251ebc4586f202b2b84a31646b48d1beca7,3a02869661fc8f1da6409edc313bf251ebc4586f202b2b84a31646b48d1beca7,320e81b4145c1933c25a4ee8275675397a23cb7594b9ac52006f470805bbbe42,3eb2031bc3c935a9a6f57367e9d851317a41280a8ac0693930942a8ee631e447,a03bc4dd2a023bebb17e8f64b22f9803685055600064656f8f85675a4dd3622d; __session=eyJhbGciOiJSUzI1NiIsImNhdCI6ImNsX0I3ZDRQRDExMUFBQSIsImtpZCI6Imluc18yc2NFSEpuWHRhREZVVXhVQ1habldocTVYS0MiLCJ0eXAiOiJKV1QifQ.eyJhenAiOiJodHRwczovL3d3dy5tb3JwaGxsbS5jb20iLCJleHAiOjE3NjkzMjU5MzIsImZ2YSI6WzIyMSwtMV0sImlhdCI6MTc2OTMyNTg3MiwiaXNzIjoiaHR0cHM6Ly9jbGVyay5tb3JwaGxsbS5jb20iLCJuYmYiOjE3NjkzMjU4NjIsInNpZCI6InNlc3NfMzhqVWh1cTdIa2c4ZmlxaEhNZHVEV2ZteWNNIiwic3RzIjoiYWN0aXZlIiwic3ViIjoidXNlcl8zOGpVaHRFRTBTTzNaaTFZaVhFZmI5UjQ3RVoifQ.HhJ-kSkAOlU7xofFZOjHEjH_RbzkEtJwdjxTJ_C09_VgLCOv1dd7OOKtMt5sRXpIl80aF4FrWt8_XaBd4bx63JDzZUC1len0b1CIubu1n6t6vNRts_0hHsaxVo6NTxiElJzZkBZfoZIdnUC5zsEPDldct3wW9C0Jb77Em_uDWlDvs1D-5UF0Hol75v8wj-dnys01IVUqN0svt-QlJ0mKTwbCMeFh4mh1UbE8rMKassgblVJpGfNWWr3pzscuS3yxRbvq9URrr-HoweybWlq57SaJJMxpwopGdnRx2jrKrw_IcJQlQ_Ug_8HxF69i3Upu_rVFIdbIx2hsV0o7LfHzGg; __session_B3JMRlZP=eyJhbGciOiJSUzI1NiIsImNhdCI6ImNsX0I3ZDRQRDExMUFBQSIsImtpZCI6Imluc18yc2NFSEpuWHRhREZVVXhVQ1habldocTVYS0MiLCJ0eXAiOiJKV1QifQ.eyJhenAiOiJodHRwczovL3d3dy5tb3JwaGxsbS5jb20iLCJleHAiOjE3NjkzMjU5MzIsImZ2YSI6WzIyMSwtMV0sImlhdCI6MTc2OTMyNTg3MiwiaXNzIjoiaHR0cHM6Ly9jbGVyay5tb3JwaGxsbS5jb20iLCJuYmYiOjE3NjkzMjU4NjIsInNpZCI6InNlc3NfMzhqVWh1cTdIa2c4ZmlxaEhNZHVEV2ZteWNNIiwic3RzIjoiYWN0aXZlIiwic3ViIjoidXNlcl8zOGpVaHRFRTBTTzNaaTFZaVhFZmI5UjQ3RVoifQ.HhJ-kSkAOlU7xofFZOjHEjH_RbzkEtJwdjxTJ_C09_VgLCOv1dd7OOKtMt5sRXpIl80aF4FrWt8_XaBd4bx63JDzZUC1len0b1CIubu1n6t6vNRts_0hHsaxVo6NTxiElJzZkBZfoZIdnUC5zsEPDldct3wW9C0Jb77Em_uDWlDvs1D-5UF0Hol75v8wj-dnys01IVUqN0svt-QlJ0mKTwbCMeFh4mh1UbE8rMKassgblVJpGfNWWr3pzscuS3yxRbvq9URrr-HoweybWlq57SaJJMxpwopGdnRx2jrKrw_IcJQlQ_Ug_8HxF69i3Upu_rVFIdbIx2hsV0o7LfHzGg; _ga_5ET01XBKB1=GS2.1.s1769324224$o6$g1$t1769325875$j59$l0$h0; ph_phc_i9YGegL9gG85W32ArqnIiBECNTAzUYlFFK8B0Odbhk8_posthog=%7B%22%24device_id%22%3A%22019bef0f-25f6-7e51-b718-8db6665d4470%22%2C%22distinct_id%22%3A%22user_38jUhtEE0SO3Zi1YiXEfb9R47EZ%22%2C%22%24sesid%22%3A%5B1769325875736%2C%22019bf3f1-202a-7fd6-8dbb-6cbea73ffa8f%22%2C1769324224553%5D%2C%22%24epp%22%3Atrue%2C%22%24initial_person_info%22%3A%7B%22r%22%3A%22https%3A%2F%2Fwww.google.com%2F%22%2C%22u%22%3A%22https%3A%2F%2Fwww.morphllm.com%2Fpricing%3Fgad_source%3D1%26gad_campaignid%3D23473818447%26gbraid%3D0AAAAA_wYB2fufbMARVR2fJKKHNzc8Ovu-%26gclid%3DCj0KCQiA-NHLBhDSARIsAIhe9X36gjH12LKRxYZ1bqy4c8wATix3qqxauv9-7H-rewEfnKOW0npi5ZMaAjfHEALw_wcB%22%7D%7D"LogDir = "./logs")var MorphHeaders = map[string]string{12 unmodified lines"sec-fetch-mode": "cors","sec-fetch-site": "same-origin","user-agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/144.0.0.0 Safari/537.36","cookie": MorphCookies,}var DebugMode = truetype ParsedToolCall struct {Name string `json:"name"`Input map[string]interface{} `json:"input"`}1234567891011121312 unmodified lines2627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384package typesimport ("errors""strings")const (MorphAPIURL = "https://www.morphllm.com/api/warpgrep-chat"LogDir = "./logs")var MorphHeaders = map[string]string{12 unmodified lines"sec-fetch-mode": "cors","sec-fetch-site": "same-origin","user-agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/144.0.0.0 Safari/537.36",}var DebugMode = true// CookieRotatorInstance is a global reference to the cookie rotator service// It's set in main.go after initializationvar CookieRotatorInstance interface {NextCookie() (cookie interface{}, err error)MarkUsed(cookieID uint) errorMarkError(cookieID uint) error}// GetNextCookieFromRotator 从轮询器获取下一个 Cookie// 这是一个辅助函数,用于从全局轮询器实例获取 Cookiefunc GetNextCookieFromRotator() (interface{}, error) {if CookieRotatorInstance == nil {return nil, errors.New("cookie rotator not initialized")}return CookieRotatorInstance.NextCookie()}type ParsedToolCall struct {Name string `json:"name"`Input map[string]interface{} `json:"input"`}// ========== 模型配置 ==========// DefaultModel 默认使用的模型const DefaultModel = "claude-opus-4-5-20251101"// SupportedModels 支持的模型列表var SupportedModels = []string{"claude-opus-4-5-20251101",}// IsModelSupported 检查模型是否在支持列表中func IsModelSupported(model string) bool {if model == "" {return false}for _, supported := range SupportedModels {if strings.EqualFold(supported, model) {return true}}return false}// ========== 认证请求/响应类型 ==========// ChangePasswordRequest 修改密码请求type ChangePasswordRequest struct {OldPassword string `json:"old_password" binding:"required"`NewPassword string `json:"new_password" binding:"required,min=6"`}
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484// API 基础路径
const API_BASE = window.location.origin;
// 存储认证 token
let authToken = localStorage.getItem('auth_token');
// 页面加载时检查认证状态
document.addEventListener('DOMContentLoaded', function() {
const currentPage = window.location.pathname;
console.log('[DEBUG] Current page:', currentPage);
console.log('[DEBUG] Auth token:', authToken ? 'exists' : 'none');
if (currentPage.includes('dashboard')) {
console.log('[DEBUG] Loading dashboard...');
if (!authToken) {
window.location.href = '/static/index.html';
return;
}
loadDashboard();
} else {
// 登录页面(包括 /static/index.html, /, 或其他)
console.log('[DEBUG] Loading login page...');
if (authToken) {
console.log('[DEBUG] Already logged in, redirecting to dashboard...');
window.location.href = '/dashboard';
return;
}
setupLoginForm();
}
});
// ========== 认证功能 ==========
// 设置登录表单
function setupLoginForm() {
console.log('[DEBUG] setupLoginForm called');
const loginForm = document.getElementById('loginForm');
console.log('[DEBUG] loginForm element:', loginForm);
if (loginForm) {
console.log('[DEBUG] Adding submit event listener to loginForm');
loginForm.addEventListener('submit', async (e) => {
e.preventDefault();
console.log('[DEBUG] Form submitted!');
const username = document.getElementById('username').value;
const password = document.getElementById('password').value;
const errorDiv = document.getElementById('loginError');
console.log('[DEBUG] Attempting login with username:', username);
try {
console.log('[DEBUG] Sending request to:', `${API_BASE}/api/auth/login`);
const response = await fetch(`${API_BASE}/api/auth/login`, {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({ username, password })
});
const data = await response.json();
if (response.ok) {
authToken = data.token;
localStorage.setItem('auth_token', authToken);
window.location.href = '/dashboard';
} else {
errorDiv.textContent = data.error || '登录失败';
errorDiv.style.display = 'block';
}
} catch (error) {
errorDiv.textContent = '网络错误,请稍后重试';
errorDiv.style.display = 'block';
}
});
}
}
// 登出
function logout() {
if (confirm('确定要退出吗?')) {
localStorage.removeItem('auth_token');
authToken = null;
window.location.href = '/';
}
}
// 显示修改密码弹窗
function showChangePasswordModal() {
document.getElementById('changePasswordModal').style.display = 'flex';
document.getElementById('changePasswordForm').reset();
document.getElementById('changePasswordError').style.display = 'none';
}
// 关闭修改密码弹窗
function closeChangePasswordModal() {
document.getElementById('changePasswordModal').style.display = 'none';
}
// 修改密码
async function changePassword(oldPassword, newPassword) {
try {
const response = await apiRequest('/api/auth/password', {
method: 'PUT',
body: JSON.stringify({
old_password: oldPassword,
new_password: newPassword
})
});
if (response.ok) {
showToast('密码修改成功', 'success');
closeChangePasswordModal();
return true;
} else {
const data = await response.json();
return { error: data.error || '密码修改失败' };
}
} catch (error) {
console.error('修改密码错误:', error);
return { error: '网络错误,请重试' };
}
}
// 设置修改密码表单
function setupChangePasswordForm() {
const form = document.getElementById('changePasswordForm');
if (form) {
form.addEventListener('submit', async (e) => {
e.preventDefault();
const oldPassword = document.getElementById('oldPassword').value;
const newPassword = document.getElementById('newPassword').value;
const confirmPassword = document.getElementById('confirmPassword').value;
const errorDiv = document.getElementById('changePasswordError');
// 验证新密码长度
if (newPassword.length < 6) {
errorDiv.textContent = '新密码至少需要6位字符';
errorDiv.style.display = 'block';
return;
}
// 验证两次密码是否一致
if (newPassword !== confirmPassword) {
errorDiv.textContent = '两次输入的密码不一致';
errorDiv.style.display = 'block';
return;
}
const result = await changePassword(oldPassword, newPassword);
if (result === true) {
// 成功
} else if (result && result.error) {
errorDiv.textContent = result.error;
errorDiv.style.display = 'block';
}
});
}
}
// API 请求封装
async function apiRequest(url, options = {}) {
const headers = {
'Content-Type': 'application/json',
...options.headers
};
if (authToken) {
headers['Authorization'] = `Bearer ${authToken}`;
}
const response = await fetch(`${API_BASE}${url}`, {
...options,
headers
});
// 如果 401,跳转到登录页
if (response.status === 401) {
localStorage.removeItem('auth_token');
authToken = null;
window.location.href = '/';
return;
}
return response;
}
// ========== Dashboard 功能 ==========
// 加载 Dashboard
async function loadDashboard() {
setupChangePasswordForm();
await loadUserInfo();
await loadStats();
await loadCookies();
}
// 加载用户信息
async function loadUserInfo() {
try {
const response = await apiRequest('/api/auth/me');
if (response.ok) {
const user = await response.json();
document.getElementById('currentUser').textContent = user.username;
}
} catch (error) {
console.error('加载用户信息失败:', error);
}
}
// 加载统计信息
async function loadStats() {
try {
const response = await apiRequest('/api/cookies/stats');
if (response.ok) {
const stats = await response.json();
document.getElementById('totalCount').textContent = stats.total_count;
document.getElementById('validCount').textContent = stats.valid_count;
document.getElementById('invalidCount').textContent = stats.invalid_count;
document.getElementById('totalUsage').textContent = stats.total_usage.toLocaleString();
}
} catch (error) {
console.error('加载统计信息失败:', error);
}
}
// 加载 Cookie 列表
async function loadCookies() {
try {
const response = await apiRequest('/api/cookies');
if (response.ok) {
const data = await response.json();
// API 返回的是数组而不是对象
renderCookieTable(Array.isArray(data) ? data : (data.cookies || []));
}
} catch (error) {
console.error('加载 Cookie 列表失败:', error);
}
}
// 渲染 Cookie 表格
function renderCookieTable(cookies) {
const tbody = document.getElementById('cookieTableBody');
const emptyState = document.getElementById('emptyState');
if (cookies.length === 0) {
tbody.innerHTML = '';
emptyState.style.display = 'block';
return;
}
emptyState.style.display = 'none';
tbody.innerHTML = cookies.map((cookie, index) => `
<tr>
<td>${index + 1}</td>
<td>${escapeHtml(cookie.name)}</td>
<td>
<span class="status-badge ${cookie.is_valid ? 'status-valid' : 'status-invalid'}">
${cookie.is_valid ? '✅ 有效' : '❌ 无效'}
</span>
</td>
<td>${(cookie.usage_count || 0).toLocaleString()}</td>
<td>${cookie.priority || 0}</td>
<td>${formatTime(cookie.last_validated)}</td>
<td>
<div class="action-buttons">
<button class="btn btn-secondary btn-sm" onclick="validateCookie(${cookie.id})">🔄</button>
<button class="btn btn-secondary btn-sm" onclick="editCookie(${cookie.id})">⚙️</button>
<button class="btn btn-danger btn-sm" onclick="deleteCookie(${cookie.id})">🗑️</button>
</div>
</td>
</tr>
`).join('');
}
// 刷新 Cookie 列表
function refreshCookies() {
loadCookies();
loadStats();
}
// ========== Cookie 操作 ==========
// 显示添加弹窗
function showAddModal() {
document.getElementById('addModal').style.display = 'flex';
document.getElementById('addCookieForm').reset();
}
// 关闭添加弹窗
function closeAddModal() {
document.getElementById('addModal').style.display = 'none';
}
// 添加 Cookie
document.getElementById('addCookieForm')?.addEventListener('submit', async (e) => {
e.preventDefault();
const formData = new FormData(e.target);
const data = {
name: formData.get('name'),
api_key: formData.get('api_key'),
session_key: formData.get('session_key') || '',
priority: parseInt(formData.get('priority') || '0')
};
try {
const response = await apiRequest('/api/cookies', {
method: 'POST',
body: JSON.stringify(data)
});
if (response.ok) {
showToast('Cookie 添加成功', 'success');
closeAddModal();
refreshCookies();
} else {
const error = await response.json();
showToast(error.error || '添加失败', 'error');
}
} catch (error) {
showToast('网络错误', 'error');
}
});
// 显示编辑弹窗
async function editCookie(id) {
try {
const response = await apiRequest(`/api/cookies/${id}`);
if (response.ok) {
const cookie = await response.json();
document.getElementById('editCookieId').value = cookie.id;
document.getElementById('editCookieName').value = cookie.name;
document.getElementById('editApiKey').value = cookie.api_key || '';
document.getElementById('editSessionKey').value = cookie.session_key || '';
document.getElementById('editCookiePriority').value = cookie.priority || 0;
document.getElementById('editModal').style.display = 'flex';
}
} catch (error) {
showToast('加载失败', 'error');
}
}
// 关闭编辑弹窗
function closeEditModal() {
document.getElementById('editModal').style.display = 'none';
}
// 更新 Cookie
document.getElementById('editCookieForm')?.addEventListener('submit', async (e) => {
e.preventDefault();
const id = document.getElementById('editCookieId').value;
const formData = new FormData(e.target);
const data = {
name: formData.get('name'),
api_key: formData.get('api_key'),
session_key: formData.get('session_key') || '',
priority: parseInt(formData.get('priority') || '0')
};
try {
const response = await apiRequest(`/api/cookies/${id}`, {
method: 'PUT',
body: JSON.stringify(data)
});
if (response.ok) {
showToast('Cookie 更新成功', 'success');
closeEditModal();
refreshCookies();
} else {
const error = await response.json();
showToast(error.error || '更新失败', 'error');
}
} catch (error) {
showToast('网络错误', 'error');
}
});
// 删除 Cookie
async function deleteCookie(id) {
if (!confirm('确定要删除这个 Cookie 吗?')) {
return;
}
try {
const response = await apiRequest(`/api/cookies/${id}`, {
method: 'DELETE'
});
if (response.ok) {
showToast('Cookie 删除成功', 'success');
refreshCookies();
} else {
const error = await response.json();
showToast(error.error || '删除失败', 'error');
}
} catch (error) {
showToast('网络错误', 'error');
}
}
// 验证单个 Cookie
async function validateCookie(id) {
try {
showToast('正在验证...', 'success');
const response = await apiRequest(`/api/cookies/${id}/validate`, {
method: 'POST'
});
if (response.ok) {
const result = await response.json();
showToast(result.is_valid ? '✅ Cookie 有效' : '❌ Cookie 无效', result.is_valid ? 'success' : 'error');
refreshCookies();
} else {
const error = await response.json();
showToast(error.error || '验证失败', 'error');
}
} catch (error) {
showToast('网络错误', 'error');
}
}
// 批量验证所有 Cookie
async function validateAll() {
if (!confirm('确定要验证所有 Cookie 吗?这可能需要一些时间。')) {
return;
}
try {
showToast('正在批量验证...', 'success');
const response = await apiRequest('/api/cookies/validate/all', {
method: 'POST'
});
if (response.ok) {
const result = await response.json();
showToast(`验证完成:${result.valid_count} 个有效,${result.invalid_count} 个无效`, 'success');
refreshCookies();
} else {
const error = await response.json();
showToast(error.error || '验证失败', 'error');
}
} catch (error) {
showToast('网络错误', 'error');
}
}
// ========== 工具函数 ==========
// 显示 Toast 通知
function showToast(message, type = 'success') {
const toast = document.getElementById('toast');
toast.textContent = message;
toast.className = `toast ${type}`;
toast.style.display = 'block';
setTimeout(() => {
toast.style.display = 'none';
}, 3000);
}
// 格式化时间
function formatTime(timeStr) {
if (!timeStr) return '-';
const date = new Date(timeStr);
const now = new Date();
const diff = Math.floor((now - date) / 1000);
if (diff < 60) return '刚刚';
if (diff < 3600) return `${Math.floor(diff / 60)} 分钟前`;
if (diff < 86400) return `${Math.floor(diff / 3600)} 小时前`;
return `${Math.floor(diff / 86400)} 天前`;
}
// HTML 转义
function escapeHtml(text) {
const div = document.createElement('div');
div.textContent = text;
return div.innerHTML;
}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Opus API 管理系统 - Cookie 管理</title>
<link rel="stylesheet" href="/static/styles.css">
</head>
<body>
<div class="dashboard-container">
<!-- 顶部导航 -->
<header class="header">
<h1>🚀 Opus API 管理系统</h1>
<div class="user-menu">
<span id="currentUser">admin</span>
<button class="btn btn-secondary" onclick="showChangePasswordModal()">修改密码</button>
<button class="btn btn-secondary" onclick="logout()">退出</button>
</div>
</header>
<!-- 主内容区 -->
<main class="main-content">
<!-- 统计卡片 -->
<section class="stats-section">
<div class="stats-grid">
<div class="stat-card">
<div class="stat-icon">📊</div>
<div class="stat-info">
<h3 id="totalCount">0</h3>
<p>总账号数</p>
</div>
</div>
<div class="stat-card valid">
<div class="stat-icon">✅</div>
<div class="stat-info">
<h3 id="validCount">0</h3>
<p>有效账号</p>
</div>
</div>
<div class="stat-card invalid">
<div class="stat-icon">❌</div>
<div class="stat-info">
<h3 id="invalidCount">0</h3>
<p>无效账号</p>
</div>
</div>
<div class="stat-card">
<div class="stat-icon">📈</div>
<div class="stat-info">
<h3 id="totalUsage">0</h3>
<p>总请求数</p>
</div>
</div>
</div>
</section>
<!-- 操作按钮 -->
<section class="actions-section">
<button class="btn btn-primary" onclick="showAddModal()">
➕ 添加 Cookie
</button>
<button class="btn btn-secondary" onclick="validateAll()">
🔄 批量验证
</button>
<button class="btn btn-secondary" onclick="refreshCookies()">
🔃 刷新列表
</button>
</section>
<!-- Cookie 列表 -->
<section class="table-section">
<h2>Cookie 列表</h2>
<div class="table-container">
<table id="cookieTable">
<thead>
<tr>
<th>#</th>
<th>名称</th>
<th>状态</th>
<th>使用次数</th>
<th>优先级</th>
<th>最后验证</th>
<th>操作</th>
</tr>
</thead>
<tbody id="cookieTableBody">
<!-- 动态填充 -->
</tbody>
</table>
<div id="emptyState" class="empty-state" style="display: none;">
<p>暂无 Cookie,点击上方按钮添加</p>
</div>
</div>
</section>
</main>
<!-- 添加 Cookie 弹窗 -->
<div id="addModal" class="modal" style="display: none;">
<div class="modal-content">
<div class="modal-header">
<h2>添加 Morph Cookie</h2>
<button class="modal-close" onclick="closeAddModal()">×</button>
</div>
<form id="addCookieForm">
<div class="form-group">
<label for="cookieName">账号名称</label>
<input type="text" id="cookieName" name="name" placeholder="例如:主账号" required>
</div>
<div class="form-group">
<label for="apiKey">API Key</label>
<input type="text" id="apiKey" name="api_key" placeholder="输入 API Key..." required>
</div>
<div class="form-group">
<label for="sessionKey">Session Key (可选)</label>
<input type="text" id="sessionKey" name="session_key" placeholder="输入 Session Key...">
</div>
<div class="form-group">
<label for="cookiePriority">优先级 (0-100)</label>
<input type="number" id="cookiePriority" name="priority" value="0" min="0" max="100">
</div>
<div class="modal-footer">
<button type="button" class="btn btn-secondary" onclick="closeAddModal()">取消</button>
<button type="submit" class="btn btn-primary">确定</button>
</div>
</form>
</div>
</div>
<!-- 编辑 Cookie 弹窗 -->
<div id="editModal" class="modal" style="display: none;">
<div class="modal-content">
<div class="modal-header">
<h2>编辑 Cookie</h2>
<button class="modal-close" onclick="closeEditModal()">×</button>
</div>
<form id="editCookieForm">
<input type="hidden" id="editCookieId">
<div class="form-group">
<label for="editCookieName">账号名称</label>
<input type="text" id="editCookieName" name="name" placeholder="例如:主账号">
</div>
<div class="form-group">
<label for="editApiKey">API Key</label>
<input type="text" id="editApiKey" name="api_key" placeholder="输入 API Key...">
</div>
<div class="form-group">
<label for="editSessionKey">Session Key (可选)</label>
<input type="text" id="editSessionKey" name="session_key" placeholder="输入 Session Key...">
</div>
<div class="form-group">
<label for="editCookiePriority">优先级 (0-100)</label>
<input type="number" id="editCookiePriority" name="priority" min="0" max="100">
</div>
<div class="modal-footer">
<button type="button" class="btn btn-secondary" onclick="closeEditModal()">取消</button>
<button type="submit" class="btn btn-primary">保存</button>
</div>
</form>
</div>
</div>
<!-- 修改密码弹窗 -->
<div id="changePasswordModal" class="modal" style="display: none;">
<div class="modal-content">
<div class="modal-header">
<h2>修改密码</h2>
<button class="modal-close" onclick="closeChangePasswordModal()">×</button>
</div>
<form id="changePasswordForm">
<div class="form-group">
<label for="oldPassword">原密码</label>
<input type="password" id="oldPassword" name="old_password" placeholder="请输入原密码" required>
</div>
<div class="form-group">
<label for="newPassword">新密码</label>
<input type="password" id="newPassword" name="new_password" placeholder="请输入新密码 (至少6位)" required minlength="6">
</div>
<div class="form-group">
<label for="confirmPassword">确认新密码</label>
<input type="password" id="confirmPassword" name="confirm_password" placeholder="请再次输入新密码" required>
</div>
<div class="error" id="changePasswordError" style="display: none;"></div>
<div class="modal-footer">
<button type="button" class="btn btn-secondary" onclick="closeChangePasswordModal()">取消</button>
<button type="submit" class="btn btn-primary">确定</button>
</div>
</form>
</div>
</div>
<!-- Toast 通知 -->
<div id="toast" class="toast" style="display: none;"></div>
</div>
<script src="/static/app.js"></script>
</body>
</html>123456789101112131415161718192021222324252627<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Opus API 管理系统 - 登录</title>
<link rel="stylesheet" href="/static/styles.css">
</head>
<body>
<div class="login-container">
<div class="login-box">
<h1>🚀 Opus API 管理系统</h1>
<form id="loginForm">
<div class="form-group">
<input type="text" id="username" name="username" placeholder="用户名" required autocomplete="username">
</div>
<div class="form-group">
<input type="password" id="password" name="password" placeholder="密码" required autocomplete="current-password">
</div>
<button type="submit" class="btn btn-primary btn-block">登录</button>
</form>
<div class="error" id="loginError"></div>
</div>
</div>
<script src="/static/app.js"></script>
</body>
</html>123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447/* 全局样式 */
* {
margin: 0;
padding: 0;
box-sizing: border-box;
}
body {
font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, 'Helvetica Neue', Arial, sans-serif;
background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
min-height: 100vh;
color: #333;
}
/* 登录页面 */
.login-container {
display: flex;
justify-content: center;
align-items: center;
min-height: 100vh;
padding: 20px;
}
.login-box {
background: white;
border-radius: 12px;
box-shadow: 0 10px 40px rgba(0, 0, 0, 0.2);
padding: 40px;
width: 100%;
max-width: 400px;
}
.login-box h1 {
text-align: center;
margin-bottom: 30px;
color: #667eea;
font-size: 28px;
}
/* 表单样式 */
.form-group {
margin-bottom: 20px;
}
.form-group label {
display: block;
margin-bottom: 8px;
font-weight: 500;
color: #555;
}
.form-group input,
.form-group textarea,
.form-group select {
width: 100%;
padding: 12px 16px;
border: 2px solid #e0e0e0;
border-radius: 8px;
font-size: 14px;
transition: border-color 0.3s;
}
.form-group input:focus,
.form-group textarea:focus,
.form-group select:focus {
outline: none;
border-color: #667eea;
}
.form-group.checkbox {
display: flex;
align-items: center;
}
.form-group.checkbox label {
margin: 0;
margin-left: 8px;
font-weight: normal;
}
.form-group.checkbox input {
width: auto;
}
/* 按钮样式 */
.btn {
padding: 12px 24px;
border: none;
border-radius: 8px;
font-size: 14px;
font-weight: 600;
cursor: pointer;
transition: all 0.3s;
text-decoration: none;
display: inline-block;
}
.btn-primary {
background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
color: white;
}
.btn-primary:hover {
transform: translateY(-2px);
box-shadow: 0 4px 12px rgba(102, 126, 234, 0.4);
}
.btn-secondary {
background: #f5f5f5;
color: #333;
}
.btn-secondary:hover {
background: #e0e0e0;
}
.btn-danger {
background: #ff4757;
color: white;
}
.btn-danger:hover {
background: #ee5a6f;
}
.btn-block {
width: 100%;
}
.btn:disabled {
opacity: 0.6;
cursor: not-allowed;
}
/* 错误提示 */
.error {
color: #ff4757;
font-size: 14px;
margin-top: 10px;
text-align: center;
}
/* Dashboard 样式 */
.dashboard-container {
min-height: 100vh;
background: #f5f7fa;
}
.header {
background: white;
padding: 20px 40px;
box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
display: flex;
justify-content: space-between;
align-items: center;
}
.header h1 {
color: #667eea;
font-size: 24px;
}
.user-menu {
display: flex;
align-items: center;
gap: 15px;
}
.user-menu span {
font-weight: 500;
color: #555;
}
.main-content {
max-width: 1200px;
margin: 0 auto;
padding: 40px 20px;
}
/* 统计卡片 */
.stats-section {
margin-bottom: 30px;
}
.stats-grid {
display: grid;
grid-template-columns: repeat(auto-fit, minmax(250px, 1fr));
gap: 20px;
}
.stat-card {
background: white;
border-radius: 12px;
padding: 24px;
box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
display: flex;
align-items: center;
gap: 20px;
transition: transform 0.3s;
}
.stat-card:hover {
transform: translateY(-4px);
box-shadow: 0 4px 16px rgba(0, 0, 0, 0.15);
}
.stat-card.valid {
border-left: 4px solid #2ecc71;
}
.stat-card.invalid {
border-left: 4px solid #ff4757;
}
.stat-icon {
font-size: 40px;
}
.stat-info h3 {
font-size: 32px;
color: #333;
margin-bottom: 4px;
}
.stat-info p {
color: #888;
font-size: 14px;
}
/* 操作按钮区 */
.actions-section {
margin-bottom: 30px;
display: flex;
gap: 15px;
flex-wrap: wrap;
}
/* 表格样式 */
.table-section {
background: white;
border-radius: 12px;
padding: 24px;
box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}
.table-section h2 {
margin-bottom: 20px;
color: #333;
}
.table-container {
overflow-x: auto;
}
table {
width: 100%;
border-collapse: collapse;
}
thead {
background: #f8f9fa;
}
th {
padding: 12px;
text-align: left;
font-weight: 600;
color: #555;
border-bottom: 2px solid #e0e0e0;
}
td {
padding: 12px;
border-bottom: 1px solid #f0f0f0;
}
tr:hover {
background: #f8f9fa;
}
.status-badge {
display: inline-block;
padding: 4px 12px;
border-radius: 12px;
font-size: 12px;
font-weight: 600;
}
.status-valid {
background: #d4edda;
color: #155724;
}
.status-invalid {
background: #f8d7da;
color: #721c24;
}
.action-buttons {
display: flex;
gap: 8px;
}
.btn-sm {
padding: 6px 12px;
font-size: 12px;
}
.empty-state {
text-align: center;
padding: 60px 20px;
color: #999;
}
/* 模态框 */
.modal {
position: fixed;
top: 0;
left: 0;
width: 100%;
height: 100%;
background: rgba(0, 0, 0, 0.5);
display: flex;
justify-content: center;
align-items: center;
z-index: 1000;
}
.modal-content {
background: white;
border-radius: 12px;
width: 90%;
max-width: 600px;
max-height: 90vh;
overflow-y: auto;
box-shadow: 0 10px 40px rgba(0, 0, 0, 0.3);
}
.modal-header {
padding: 24px;
border-bottom: 1px solid #e0e0e0;
display: flex;
justify-content: space-between;
align-items: center;
}
.modal-header h2 {
color: #333;
font-size: 20px;
}
.modal-close {
background: none;
border: none;
font-size: 28px;
color: #999;
cursor: pointer;
padding: 0;
width: 32px;
height: 32px;
display: flex;
align-items: center;
justify-content: center;
}
.modal-close:hover {
color: #333;
}
.modal-content form {
padding: 24px;
}
.modal-footer {
display: flex;
justify-content: flex-end;
gap: 12px;
margin-top: 24px;
}
/* Toast 通知 */
.toast {
position: fixed;
bottom: 30px;
right: 30px;
background: #333;
color: white;
padding: 16px 24px;
border-radius: 8px;
box-shadow: 0 4px 12px rgba(0, 0, 0, 0.3);
z-index: 2000;
animation: slideIn 0.3s ease-out;
}
.toast.success {
background: #2ecc71;
}
.toast.error {
background: #ff4757;
}
@keyframes slideIn {
from {
transform: translateX(400px);
opacity: 0;
}
to {
transform: translateX(0);
opacity: 1;
}
}
/* 响应式设计 */
@media (max-width: 768px) {
.header {
padding: 15px 20px;
}
.header h1 {
font-size: 20px;
}
.main-content {
padding: 20px 15px;
}
.stats-grid {
grid-template-columns: 1fr;
}
.actions-section {
flex-direction: column;
}
.actions-section .btn {
width: 100%;
}
table {
font-size: 14px;
}
th, td {
padding: 8px;
}
}.env.exampleAdded+15
.gitignore+3-1
Dockerfile+3
README.md+231-49
cmd/server/main.go+80-1
go.mod+50-37
go.sum+118-92
internal/handler/auth.goAdded+125
internal/handler/cookies.goAdded+320
internal/handler/messages.go+34
internal/middleware/auth.goAdded+53
internal/model/cookie.goAdded+64
internal/model/db.goAdded+69
internal/model/user.goAdded+92
internal/service/auth_service.goAdded+190
internal/service/cookie_service.goAdded+125
internal/service/rotator.goAdded+167
internal/service/validator.goAdded+141
internal/types/common.go+55-4
web/static/app.jsAdded+484
web/static/dashboard.htmlAdded+196
web/static/index.htmlAdded+27
web/static/styles.cssAdded+447