Files
openteam/server/internal/pkg/apikey/apikey.go
T
Sakurasan 360c6b33a6 M0+M1: 基建 + 用户/密钥/核心代理
后端 (Go/Gin/GORM):
- 配置(viper+env)、SQLite/Postgres 迁移、argon2id、AES-GCM 渠道密钥、JWT+refresh cookie
- 用户注册/登录/刷新/登出、API Key CRUD(仅存哈希、明文一次展示)
- 代理网关: /v1/chat/completions、/v1/responses、/v1/models 直通 OpenAI 渠道
  非流式+流式(SSE 零缓冲转发), 用量捕获(chat 末块/responses completed 嵌套),
  OpenAI 错误格式(401/402/404/502), 余额检查
- 异步批量记账 + 余额流水 + 日聚合, admin 用户/余额/配置 API
- 单测: crypto/jwt/apikey/流式 usage 提取

前端 (Vue3+TS+Vite+Tailwind v4):
- taste-skill 设计 tokens: 深色仪表盘, 石墨+信号铜色, Outfit+JetBrains Mono
- Landing/登录/注册, 控制台(仪表盘图表/密钥管理/用量明细)
- 基础组件 Button/Input/Badge/Modal, ECharts 用量图

部署: docker-compose(nginx+api+postgres), 双 Dockerfile, nginx SSE 反代
联调: scripts/mockupstream 本地 mock 上游, 端到端验证通过
2026-08-15 13:10:47 +08:00

53 lines
1.2 KiB
Go
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
// Package apikey 生成与管理 API Key:sk- + 48 位 base62 随机串。
// 库中仅存 SHA-256 哈希与展示前缀(PLANNING §4.3.3)。
package apikey
import (
"crypto/rand"
"crypto/sha256"
"encoding/base64"
"encoding/hex"
"strings"
)
const (
alphabet = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"
keyLen = 48
prefix = "sk-"
)
// Generate 生成明文 key(仅创建时展示一次)与哈希、前缀。
func Generate() (plain, hash, keyPrefix string, err error) {
buf := make([]byte, keyLen)
if _, err = rand.Read(buf); err != nil {
return "", "", "", err
}
for i := range buf {
buf[i] = alphabet[int(buf[i])%len(alphabet)]
}
plain = prefix + string(buf)
return plain, Hash(plain), Prefix(plain), nil
}
// Hash 返回 key 的 SHA-256 十六进制。
func Hash(key string) string {
sum := sha256.Sum256([]byte(key))
return hex.EncodeToString(sum[:])
}
// Prefix 展示前缀:sk-aB3cD5…(前 12 字符)
func Prefix(key string) string {
if len(key) <= 12 {
return key
}
return key[:12]
}
// Valid 校验明文格式。
func Valid(key string) bool {
return strings.HasPrefix(key, prefix) && len(key) == len(prefix)+keyLen
}
// base64 占位,避免未使用导入告警
var _ = base64.StdEncoding