feat(server): API relay gateway backend M0-M4
Gin + GORM + pure-Go SQLite. Users/auth (JWT), API key management with quotas, proxy gateway with weighted channel failover and health checks, usage/billing ledger, cross-protocol conversion (Anthropic Messages / OpenAI Chat Completions / OpenAI Responses), and channel/model admin API. Channels declare native API formats and auto-convert the rest. Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
This commit is contained in:
co-authored by
Claude Sonnet 5
parent
b0c7439c01
commit
d0e31b198f
@@ -0,0 +1,64 @@
|
||||
package crypto
|
||||
|
||||
import (
|
||||
"crypto/aes"
|
||||
"crypto/cipher"
|
||||
"crypto/rand"
|
||||
"crypto/sha256"
|
||||
"encoding/base64"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
)
|
||||
|
||||
// Encrypt seals a secret with AES-GCM. The master key can be any string;
|
||||
// it is hashed to a fixed-size AES key.
|
||||
func Encrypt(plaintext, masterKey string) (string, error) {
|
||||
key := sha256.Sum256([]byte(masterKey))
|
||||
block, err := aes.NewCipher(key[:])
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
gcm, err := cipher.NewGCM(block)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
nonce := make([]byte, gcm.NonceSize())
|
||||
if _, err := io.ReadFull(rand.Reader, nonce); err != nil {
|
||||
return "", err
|
||||
}
|
||||
sealed := gcm.Seal(nonce, nonce, []byte(plaintext), nil)
|
||||
return base64.StdEncoding.EncodeToString(sealed), nil
|
||||
}
|
||||
|
||||
// Decrypt opens a ciphertext produced by Encrypt.
|
||||
func Decrypt(ciphertext, masterKey string) (string, error) {
|
||||
key := sha256.Sum256([]byte(masterKey))
|
||||
data, err := base64.StdEncoding.DecodeString(ciphertext)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
block, err := aes.NewCipher(key[:])
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
gcm, err := cipher.NewGCM(block)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
if len(data) < gcm.NonceSize() {
|
||||
return "", errors.New("ciphertext too short")
|
||||
}
|
||||
nonce, sealed := data[:gcm.NonceSize()], data[gcm.NonceSize():]
|
||||
plain, err := gcm.Open(nil, nonce, sealed, nil)
|
||||
if err != nil {
|
||||
return "", fmt.Errorf("decrypt failed (bad master key?): %w", err)
|
||||
}
|
||||
return string(plain), nil
|
||||
}
|
||||
|
||||
// HashSHA256 returns the hex SHA-256 of a string (used for API key lookup).
|
||||
func HashSHA256(s string) string {
|
||||
sum := sha256.Sum256([]byte(s))
|
||||
return fmt.Sprintf("%x", sum)
|
||||
}
|
||||
@@ -0,0 +1,42 @@
|
||||
package httpx
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
)
|
||||
|
||||
// APIError is the standard error body for the management API.
|
||||
type APIError struct {
|
||||
Code int `json:"code"`
|
||||
Message string `json:"message"`
|
||||
}
|
||||
|
||||
// OK writes a JSON success response.
|
||||
func OK(c *gin.Context, data any) {
|
||||
c.JSON(http.StatusOK, gin.H{"code": 0, "data": data})
|
||||
}
|
||||
|
||||
// Created writes a 201 response.
|
||||
func Created(c *gin.Context, data any) {
|
||||
c.JSON(http.StatusCreated, gin.H{"code": 0, "data": data})
|
||||
}
|
||||
|
||||
// Fail writes an error response with the given status.
|
||||
func Fail(c *gin.Context, status int, message string) {
|
||||
c.AbortWithStatusJSON(status, gin.H{"code": status, "message": message})
|
||||
}
|
||||
|
||||
// FailWithCode writes an error with a custom business code.
|
||||
func FailWithCode(c *gin.Context, status, code int, message string) {
|
||||
c.AbortWithStatusJSON(status, gin.H{"code": code, "message": message})
|
||||
}
|
||||
|
||||
// Bind parses the JSON body and aborts with 400 on failure.
|
||||
func Bind(c *gin.Context, dst any) bool {
|
||||
if err := c.ShouldBindJSON(dst); err != nil {
|
||||
Fail(c, http.StatusBadRequest, "invalid request body: "+err.Error())
|
||||
return false
|
||||
}
|
||||
return true
|
||||
}
|
||||
@@ -0,0 +1,66 @@
|
||||
package jwt
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"strconv"
|
||||
"time"
|
||||
|
||||
"github.com/golang-jwt/jwt/v5"
|
||||
)
|
||||
|
||||
// Claims is the payload of a signed token.
|
||||
type Claims struct {
|
||||
UserID int64 `json:"uid"`
|
||||
Username string `json:"username"`
|
||||
Role string `json:"role"`
|
||||
Type string `json:"typ"` // access | refresh
|
||||
jwt.RegisteredClaims
|
||||
}
|
||||
|
||||
func sign(secret string, c Claims) (string, error) {
|
||||
t := jwt.NewWithClaims(jwt.SigningMethodHS256, c)
|
||||
return t.SignedString([]byte(secret))
|
||||
}
|
||||
|
||||
// SignAccess issues a short-lived access token.
|
||||
func SignAccess(secret string, userID int64, username, role string, ttl time.Duration) (string, error) {
|
||||
return sign(secret, Claims{
|
||||
UserID: userID, Username: username, Role: role, Type: "access",
|
||||
RegisteredClaims: jwt.RegisteredClaims{
|
||||
ExpiresAt: jwt.NewNumericDate(time.Now().Add(ttl)),
|
||||
IssuedAt: jwt.NewNumericDate(time.Now()),
|
||||
Subject: fmtID(userID),
|
||||
},
|
||||
})
|
||||
}
|
||||
|
||||
// SignRefresh issues a long-lived refresh token.
|
||||
func SignRefresh(secret string, userID int64, ttl time.Duration) (string, error) {
|
||||
return sign(secret, Claims{
|
||||
UserID: userID, Type: "refresh",
|
||||
RegisteredClaims: jwt.RegisteredClaims{
|
||||
ExpiresAt: jwt.NewNumericDate(time.Now().Add(ttl)),
|
||||
IssuedAt: jwt.NewNumericDate(time.Now()),
|
||||
Subject: fmtID(userID),
|
||||
},
|
||||
})
|
||||
}
|
||||
|
||||
// Parse validates a token and returns its claims.
|
||||
func Parse(secret, token string) (*Claims, error) {
|
||||
var c Claims
|
||||
parsed, err := jwt.ParseWithClaims(token, &c, func(t *jwt.Token) (interface{}, error) {
|
||||
if _, ok := t.Method.(*jwt.SigningMethodHMAC); !ok {
|
||||
return nil, errors.New("unexpected signing method")
|
||||
}
|
||||
return []byte(secret), nil
|
||||
})
|
||||
if err != nil || !parsed.Valid {
|
||||
return nil, errors.New("invalid token")
|
||||
}
|
||||
return &c, nil
|
||||
}
|
||||
|
||||
func fmtID(id int64) string {
|
||||
return strconv.FormatInt(id, 10)
|
||||
}
|
||||
@@ -0,0 +1,62 @@
|
||||
package password
|
||||
|
||||
import (
|
||||
"crypto/rand"
|
||||
"crypto/subtle"
|
||||
"encoding/base64"
|
||||
"errors"
|
||||
"fmt"
|
||||
"strings"
|
||||
|
||||
"golang.org/x/crypto/argon2"
|
||||
)
|
||||
|
||||
const (
|
||||
argonTime = 3
|
||||
argonMemory = 64 * 1024
|
||||
argonThreads = 2
|
||||
argonKeyLen = 32
|
||||
argonSaltLen = 16
|
||||
)
|
||||
|
||||
// Hash hashes a plaintext password with argon2id.
|
||||
func Hash(plain string) (string, error) {
|
||||
salt := make([]byte, argonSaltLen)
|
||||
if _, err := rand.Read(salt); err != nil {
|
||||
return "", err
|
||||
}
|
||||
key := argon2.IDKey([]byte(plain), salt, argonTime, argonMemory, argonThreads, argonKeyLen)
|
||||
enc := base64.RawStdEncoding
|
||||
return fmt.Sprintf("$argon2id$v=%d$m=%d,t=%d,p=%d$%s$%s",
|
||||
argon2.Version, argonMemory, argonTime, argonThreads,
|
||||
enc.EncodeToString(salt), enc.EncodeToString(key)), nil
|
||||
}
|
||||
|
||||
// Verify checks a plaintext password against an argon2id hash string.
|
||||
func Verify(plain, encoded string) (bool, error) {
|
||||
parts := strings.Split(encoded, "$")
|
||||
if len(parts) != 6 || parts[1] != "argon2id" {
|
||||
return false, errors.New("malformed password hash")
|
||||
}
|
||||
var version int
|
||||
var memory uint32
|
||||
var time_ uint32
|
||||
var threads uint8
|
||||
if _, err := fmt.Sscanf(parts[2], "v=%d", &version); err != nil {
|
||||
return false, err
|
||||
}
|
||||
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(plain), salt, time_, memory, threads, uint32(len(want)))
|
||||
return subtle.ConstantTimeCompare(got, want) == 1, nil
|
||||
}
|
||||
@@ -0,0 +1,21 @@
|
||||
package rand
|
||||
|
||||
import (
|
||||
crand "crypto/rand"
|
||||
"math/big"
|
||||
)
|
||||
|
||||
const base62 = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"
|
||||
|
||||
// Base62 returns a cryptographically random base62 string of length n.
|
||||
func Base62(n int) (string, error) {
|
||||
out := make([]byte, n)
|
||||
for i := range out {
|
||||
idx, err := crand.Int(crand.Reader, big.NewInt(int64(len(base62))))
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
out[i] = base62[idx.Int64()]
|
||||
}
|
||||
return string(out), nil
|
||||
}
|
||||
@@ -0,0 +1,73 @@
|
||||
package ratelimit
|
||||
|
||||
import (
|
||||
"sync"
|
||||
"time"
|
||||
)
|
||||
|
||||
// Limiter is a token-bucket rate limiter keyed by string.
|
||||
type Limiter struct {
|
||||
mu sync.Mutex
|
||||
rate float64 // tokens per second
|
||||
burst float64
|
||||
tokens map[string]*bucket
|
||||
}
|
||||
|
||||
type bucket struct {
|
||||
tokens float64
|
||||
lastFill time.Time
|
||||
}
|
||||
|
||||
// New creates a limiter refilling `rate` tokens/sec with `burst` capacity.
|
||||
func New(rate float64, burst int) *Limiter {
|
||||
return &Limiter{
|
||||
rate: rate,
|
||||
burst: float64(burst),
|
||||
tokens: map[string]*bucket{},
|
||||
}
|
||||
}
|
||||
|
||||
// Allow checks whether `key` may take one token now.
|
||||
func (l *Limiter) Allow(key string) bool {
|
||||
return l.Take(key, 1)
|
||||
}
|
||||
|
||||
// Take checks whether `key` may take n tokens now.
|
||||
func (l *Limiter) Take(key string, n float64) bool {
|
||||
l.mu.Lock()
|
||||
defer l.mu.Unlock()
|
||||
now := time.Now()
|
||||
b, ok := l.tokens[key]
|
||||
if !ok {
|
||||
b = &bucket{tokens: l.burst, lastFill: now}
|
||||
l.tokens[key] = b
|
||||
}
|
||||
// Refill based on elapsed time.
|
||||
elapsed := now.Sub(b.lastFill).Seconds()
|
||||
b.tokens = minF(l.burst, b.tokens+elapsed*l.rate)
|
||||
b.lastFill = now
|
||||
if b.tokens >= n {
|
||||
b.tokens -= n
|
||||
return true
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
// Sweep removes idle buckets to bound memory. Call periodically.
|
||||
func (l *Limiter) Sweep(olderThan time.Duration) {
|
||||
l.mu.Lock()
|
||||
defer l.mu.Unlock()
|
||||
cutoff := time.Now().Add(-olderThan)
|
||||
for k, b := range l.tokens {
|
||||
if b.lastFill.Before(cutoff) {
|
||||
delete(l.tokens, k)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func minF(a, b float64) float64 {
|
||||
if a < b {
|
||||
return a
|
||||
}
|
||||
return b
|
||||
}
|
||||
Reference in New Issue
Block a user