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 上游, 端到端验证通过
This commit is contained in:
@@ -0,0 +1,52 @@
|
||||
// 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
|
||||
@@ -0,0 +1,33 @@
|
||||
package apikey
|
||||
|
||||
import "testing"
|
||||
|
||||
func TestGenerate(t *testing.T) {
|
||||
plain, hash, prefix, err := Generate()
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if !Valid(plain) {
|
||||
t.Fatalf("generated key invalid: %q", plain)
|
||||
}
|
||||
if len(plain) != 3+48 {
|
||||
t.Fatalf("key length = %d, want 51", len(plain))
|
||||
}
|
||||
if Hash(plain) != hash {
|
||||
t.Fatal("hash mismatch")
|
||||
}
|
||||
if len(prefix) > len(plain) || prefix != plain[:len(prefix)] {
|
||||
t.Fatal("prefix must be prefix of plain key")
|
||||
}
|
||||
// 两次生成不重复
|
||||
plain2, _, _, _ := Generate()
|
||||
if plain == plain2 {
|
||||
t.Fatal("keys should be unique")
|
||||
}
|
||||
}
|
||||
|
||||
func TestValid(t *testing.T) {
|
||||
if Valid("") || Valid("sk-short") || Valid("xxx") {
|
||||
t.Fatal("invalid keys should be rejected")
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,125 @@
|
||||
// Package crypto 密码哈希(argon2id)与对称加密(AES-GCM)。
|
||||
package crypto
|
||||
|
||||
import (
|
||||
"crypto/aes"
|
||||
"crypto/cipher"
|
||||
"crypto/rand"
|
||||
"crypto/subtle"
|
||||
"encoding/base64"
|
||||
"errors"
|
||||
"fmt"
|
||||
"strings"
|
||||
|
||||
"golang.org/x/crypto/argon2"
|
||||
)
|
||||
|
||||
type PasswordHasher struct {
|
||||
Time uint32
|
||||
Memory uint32
|
||||
Threads uint8
|
||||
KeyLen uint32
|
||||
SaltLen int
|
||||
}
|
||||
|
||||
func NewPasswordHasher(time, memory uint32, threads uint8, keyLen uint32, saltLen int) *PasswordHasher {
|
||||
return &PasswordHasher{Time: time, Memory: memory, Threads: threads, KeyLen: keyLen, SaltLen: saltLen}
|
||||
}
|
||||
|
||||
// HashPassword argon2id 编码为 $argon2id$v=19$m=...,t=...,p=...$salt$hash
|
||||
func (h *PasswordHasher) HashPassword(password string) (string, error) {
|
||||
salt := make([]byte, h.SaltLen)
|
||||
if _, err := rand.Read(salt); err != nil {
|
||||
return "", err
|
||||
}
|
||||
key := argon2.IDKey([]byte(password), salt, h.Time, h.Memory, h.Threads, h.KeyLen)
|
||||
enc := base64.RawStdEncoding
|
||||
return fmt.Sprintf("$argon2id$v=19$m=%d,t=%d,p=%d$%s$%s",
|
||||
h.Memory, h.Time, h.Threads, enc.EncodeToString(salt), enc.EncodeToString(key)), nil
|
||||
}
|
||||
|
||||
// VerifyPassword 校验密码,返回是否匹配(常数时间比较)。
|
||||
func (h *PasswordHasher) VerifyPassword(encoded, password string) (bool, error) {
|
||||
parts := strings.Split(encoded, "$")
|
||||
if len(parts) != 6 || parts[1] != "argon2id" {
|
||||
return false, errors.New("invalid hash format")
|
||||
}
|
||||
var memory uint32
|
||||
var time uint32
|
||||
var threads uint8
|
||||
if _, err := fmt.Sscanf(parts[3], "m=%d,t=%d,p=%d", &memory, &time, &threads); err != nil {
|
||||
return false, err
|
||||
}
|
||||
enc := base64.RawStdEncoding
|
||||
salt, err := enc.DecodeString(parts[4])
|
||||
if err != nil {
|
||||
return false, err
|
||||
}
|
||||
want, err := enc.DecodeString(parts[5])
|
||||
if err != nil {
|
||||
return false, err
|
||||
}
|
||||
got := argon2.IDKey([]byte(password), salt, time, memory, threads, uint32(len(want)))
|
||||
return subtle.ConstantTimeCompare(got, want) == 1, nil
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// AES-GCM 渠道密钥加密
|
||||
|
||||
type Encryptor struct {
|
||||
key []byte
|
||||
}
|
||||
|
||||
// NewEncryptor 主密钥必须为 16/24/32 字节;不足时用 SHA-256 派生固定 32 字节。
|
||||
func NewEncryptor(master string) *Encryptor {
|
||||
key := []byte(master)
|
||||
switch len(key) {
|
||||
case 16, 24, 32:
|
||||
default:
|
||||
sum := sha256Sum(master)
|
||||
key = sum
|
||||
}
|
||||
return &Encryptor{key: key}
|
||||
}
|
||||
|
||||
// Encrypt 输出 base64(nonce || ciphertext)
|
||||
func (e *Encryptor) Encrypt(plain string) (string, error) {
|
||||
block, err := aes.NewCipher(e.key)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
gcm, err := cipher.NewGCM(block)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
nonce := make([]byte, gcm.NonceSize())
|
||||
if _, err := rand.Read(nonce); err != nil {
|
||||
return "", err
|
||||
}
|
||||
ct := gcm.Seal(nil, nonce, []byte(plain), nil)
|
||||
return base64.StdEncoding.EncodeToString(append(nonce, ct...)), nil
|
||||
}
|
||||
|
||||
func (e *Encryptor) Decrypt(enc string) (string, error) {
|
||||
raw, err := base64.StdEncoding.DecodeString(enc)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
block, err := aes.NewCipher(e.key)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
gcm, err := cipher.NewGCM(block)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
if len(raw) < gcm.NonceSize() {
|
||||
return "", errors.New("ciphertext too short")
|
||||
}
|
||||
nonce, ct := raw[:gcm.NonceSize()], raw[gcm.NonceSize():]
|
||||
plain, err := gcm.Open(nil, nonce, ct, nil)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
return string(plain), nil
|
||||
}
|
||||
@@ -0,0 +1,44 @@
|
||||
package crypto
|
||||
|
||||
import "testing"
|
||||
|
||||
func TestPasswordHashRoundTrip(t *testing.T) {
|
||||
h := NewPasswordHasher(3, 64*1024, 2, 32, 16)
|
||||
hash, err := h.HashPassword("s3cret-password")
|
||||
if err != nil {
|
||||
t.Fatalf("hash: %v", err)
|
||||
}
|
||||
ok, err := h.VerifyPassword(hash, "s3cret-password")
|
||||
if err != nil || !ok {
|
||||
t.Fatalf("verify correct password: ok=%v err=%v", ok, err)
|
||||
}
|
||||
ok, _ = h.VerifyPassword(hash, "wrong-password")
|
||||
if ok {
|
||||
t.Fatal("wrong password should not verify")
|
||||
}
|
||||
}
|
||||
|
||||
func TestEncryptDecrypt(t *testing.T) {
|
||||
e := NewEncryptor("master-key-0123456789abcdef")
|
||||
enc, err := e.Encrypt("sk-upstream-secret")
|
||||
if err != nil {
|
||||
t.Fatalf("encrypt: %v", err)
|
||||
}
|
||||
dec, err := e.Decrypt(enc)
|
||||
if err != nil || dec != "sk-upstream-secret" {
|
||||
t.Fatalf("decrypt: got %q err %v", dec, err)
|
||||
}
|
||||
// 密文不可读
|
||||
if dec == enc {
|
||||
t.Fatal("ciphertext should differ from plaintext")
|
||||
}
|
||||
}
|
||||
|
||||
func TestShortMasterKeyDerived(t *testing.T) {
|
||||
e := NewEncryptor("short")
|
||||
enc, _ := e.Encrypt("x")
|
||||
dec, err := e.Decrypt(enc)
|
||||
if err != nil || dec != "x" {
|
||||
t.Fatalf("short key derive failed: %v", err)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,8 @@
|
||||
package crypto
|
||||
|
||||
import "crypto/sha256"
|
||||
|
||||
func sha256Sum(s string) []byte {
|
||||
sum := sha256.Sum256([]byte(s))
|
||||
return sum[:]
|
||||
}
|
||||
@@ -0,0 +1,71 @@
|
||||
// Package jwt 访问令牌(短时,存内存)与刷新令牌(HttpOnly Cookie)签发/校验。
|
||||
package jwt
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"time"
|
||||
|
||||
"github.com/golang-jwt/jwt/v5"
|
||||
)
|
||||
|
||||
type Claims struct {
|
||||
UserID uint64 `json:"uid"`
|
||||
Username string `json:"uname"`
|
||||
Role string `json:"role"`
|
||||
jwt.RegisteredClaims
|
||||
}
|
||||
|
||||
type Manager struct {
|
||||
secret []byte
|
||||
issuer string
|
||||
accessTTL time.Duration
|
||||
refreshTTL time.Duration
|
||||
}
|
||||
|
||||
func NewManager(secret, issuer string, accessTTL, refreshTTL time.Duration) *Manager {
|
||||
return &Manager{secret: []byte(secret), issuer: issuer, accessTTL: accessTTL, refreshTTL: refreshTTL}
|
||||
}
|
||||
|
||||
func (m *Manager) AccessTTL() time.Duration { return m.accessTTL }
|
||||
func (m *Manager) RefreshTTL() time.Duration { return m.refreshTTL }
|
||||
|
||||
// Sign 签发 token;typ 取 "access" / "refresh"。
|
||||
func (m *Manager) Sign(userID uint64, username, role, typ string) (string, time.Time, error) {
|
||||
ttl := m.accessTTL
|
||||
if typ == "refresh" {
|
||||
ttl = m.refreshTTL
|
||||
}
|
||||
now := time.Now()
|
||||
exp := now.Add(ttl)
|
||||
claims := Claims{
|
||||
UserID: userID,
|
||||
Username: username,
|
||||
Role: role,
|
||||
RegisteredClaims: jwt.RegisteredClaims{
|
||||
Issuer: m.issuer,
|
||||
Subject: typ,
|
||||
IssuedAt: jwt.NewNumericDate(now),
|
||||
ExpiresAt: jwt.NewNumericDate(exp),
|
||||
},
|
||||
}
|
||||
tok := jwt.NewWithClaims(jwt.SigningMethodHS256, claims)
|
||||
s, err := tok.SignedString(m.secret)
|
||||
return s, exp, err
|
||||
}
|
||||
|
||||
var ErrInvalidToken = errors.New("invalid token")
|
||||
|
||||
// Parse 校验签名与有效期。
|
||||
func (m *Manager) Parse(token string) (*Claims, error) {
|
||||
claims := &Claims{}
|
||||
tok, err := jwt.ParseWithClaims(token, claims, func(t *jwt.Token) (any, error) {
|
||||
if _, ok := t.Method.(*jwt.SigningMethodHMAC); !ok {
|
||||
return nil, ErrInvalidToken
|
||||
}
|
||||
return m.secret, nil
|
||||
})
|
||||
if err != nil || !tok.Valid {
|
||||
return nil, ErrInvalidToken
|
||||
}
|
||||
return claims, nil
|
||||
}
|
||||
@@ -0,0 +1,41 @@
|
||||
package jwt
|
||||
|
||||
import (
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
func TestSignParse(t *testing.T) {
|
||||
m := NewManager("test-secret", "openteam", time.Hour, 24*time.Hour)
|
||||
tok, exp, err := m.Sign(42, "alice", "admin", "access")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if time.Until(exp) < 50*time.Minute {
|
||||
t.Fatal("expiry too short")
|
||||
}
|
||||
claims, err := m.Parse(tok)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if claims.UserID != 42 || claims.Username != "alice" || claims.Role != "admin" || claims.Subject != "access" {
|
||||
t.Fatalf("claims mismatch: %+v", claims)
|
||||
}
|
||||
}
|
||||
|
||||
func TestExpiredToken(t *testing.T) {
|
||||
m := NewManager("test-secret", "openteam", -time.Minute, time.Hour)
|
||||
tok, _, _ := m.Sign(1, "a", "user", "access")
|
||||
if _, err := m.Parse(tok); err == nil {
|
||||
t.Fatal("expired token should fail")
|
||||
}
|
||||
}
|
||||
|
||||
func TestWrongSecret(t *testing.T) {
|
||||
m1 := NewManager("secret-a", "openteam", time.Hour, time.Hour)
|
||||
m2 := NewManager("secret-b", "openteam", time.Hour, time.Hour)
|
||||
tok, _, _ := m1.Sign(1, "a", "user", "access")
|
||||
if _, err := m2.Parse(tok); err == nil {
|
||||
t.Fatal("token signed with different secret should fail")
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,39 @@
|
||||
// Package resp 统一 JSON 响应与错误格式。
|
||||
package resp
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
)
|
||||
|
||||
type Body struct {
|
||||
Data any `json:"data,omitempty"`
|
||||
Error *Error `json:"error,omitempty"`
|
||||
}
|
||||
|
||||
type Error struct {
|
||||
Message string `json:"message"`
|
||||
Type string `json:"type,omitempty"`
|
||||
Code string `json:"code,omitempty"`
|
||||
}
|
||||
|
||||
// OK 200
|
||||
func OK(c *gin.Context, data any) {
|
||||
c.JSON(http.StatusOK, Body{Data: data})
|
||||
}
|
||||
|
||||
// Created 201
|
||||
func Created(c *gin.Context, data any) {
|
||||
c.JSON(http.StatusCreated, Body{Data: data})
|
||||
}
|
||||
|
||||
// Fail 业务错误(message 会展示给用户)
|
||||
func Fail(c *gin.Context, status int, message string) {
|
||||
c.JSON(status, Body{Error: &Error{Message: message}})
|
||||
}
|
||||
|
||||
// FailCode 带错误码的业务错误
|
||||
func FailCode(c *gin.Context, status int, code, message string) {
|
||||
c.JSON(status, Body{Error: &Error{Message: message, Type: code}})
|
||||
}
|
||||
Reference in New Issue
Block a user