Files
Cyrene_v2/internal/auth/apikey.go
T
Aska 1ebc82fffd
CI / Backend (build / vet / test / cross-compile) (push) Has been cancelled
CI / Frontend (tsc + vite build) (push) Has been cancelled
feat: JWT过期自动重置 + 用户端登录页 + 系统设置前三个真实实现
agent-111 JWT过期重置+系统设置去占位:
- ws.ts 识别401/过期 markAuthExpired(清token+停重连+expired态),isTokenExpired;wsParse.ts拆出压行371;scheduleReconnect有token未过期才重连
- api.ts REST 401→auth_expired+清token+引导重登;login走skipAuthExpired密码错不误清
- types.ts WsStatus加expired;TopBar/Nav expired显示登录过期;System.tsx去alert占位改4张事实卡+合并Notice

agent-113 用户端登录页:
- components/Login.tsx Miuix登录卡(用户名/密码→login()→setAuthToken);App !getAuthToken()→<Login>;AdminApp LoginGate指向

agent-112 系统设置前三个(owner+审计):
- auth.APIKey.RevokeAll(吊销全部key);auth.JWTService.RotateSecret(≥32校验+并发安全+新密钥不回显)
- gateway admin_system.go: POST revoke-keys/rotate-jwt/backup(VACUUM INTO)/restore(防路径穿越+恢复前自动备份+原子替换+需重启)
- wire.go 传DatabasePath;全仓 build/vet/test绿+交叉编译;api-client v0.17系统设置契约

实机验证: 登录(role=owner)+revoke-keys 200+渠道列表含kook; 全仓绿+前端build绿; .env密码仅登录验证不打印
2026-09-07 13:57:36 +08:00

134 lines
4.0 KiB
Go

package auth
import (
"crypto/rand"
"encoding/base64"
"fmt"
"log/slog"
"sync"
"git.yeij.top/AskaEth/Cyrene_v2/internal/config"
"git.yeij.top/AskaEth/Cyrene_v2/internal/logger"
)
// APIKey manages a bounded, in-memory constant table of API keys, each bound to
// a Role so keys can be minted for admin/owner to reach administrative
// endpoints. Keys are generated with crypto/rand and stored by their string
// form. This suits the current single-binary milestone; production should
// persist keys (e.g. hashed) and support revocation.
type APIKey struct {
mu sync.RWMutex
cfg config.AuthConfig
keys map[string]Role
log *slog.Logger
}
// NewAPIKey returns an empty key manager. cfg is accepted for constructor
// parity and future persistence settings; keys are runtime-generated.
func NewAPIKey(cfg config.AuthConfig) *APIKey {
return &APIKey{
cfg: cfg,
keys: make(map[string]Role),
log: logger.WithSource(slog.Default(), source),
}
}
// Generate mints a new random key bound to role and stores it. Returns the
// plaintext key exactly once; it must not be logged.
func (k *APIKey) Generate(role Role) (string, error) {
if !role.Valid() {
return "", fmt.Errorf("%w: %q", ErrInvalidRole, role)
}
raw := make([]byte, keyLength)
if _, err := rand.Read(raw); err != nil {
return "", fmt.Errorf("auth: generate api key: %w", err)
}
key := base64.RawURLEncoding.EncodeToString(raw)
k.mu.Lock()
k.keys[key] = role
k.mu.Unlock()
return key, nil
}
// Verify reports whether key is a known, unrevoked API key.
func (k *APIKey) Verify(key string) bool {
_, ok := k.Lookup(key)
return ok
}
// Lookup returns the role bound to key.
func (k *APIKey) Lookup(key string) (Role, bool) {
k.mu.RLock()
defer k.mu.RUnlock()
role, ok := k.keys[key]
return role, ok
}
// Revoke removes key from the constant table.
func (k *APIKey) Revoke(key string) {
k.mu.Lock()
defer k.mu.Unlock()
delete(k.keys, key)
}
// RevokeAll removes every currently registered API key and returns how many were
// removed. It is the administrative "revoke all" operation: after a call the
// table is empty, so no previously issued key can authenticate.
func (k *APIKey) RevokeAll() int {
k.mu.Lock()
defer k.mu.Unlock()
n := len(k.keys)
k.keys = make(map[string]Role)
return n
}
// RevokeByMask removes every key whose masked identifier (the same derived id
// List returns) matches mask. It returns true when at least one key was revoked.
// The mask is lossy, so it is matched by recomputing it for each key; the table
// is small so a linear scan is fine. An empty or nil-returning call is a no-op.
func (k *APIKey) RevokeByMask(mask string) bool {
if mask == "" {
return false
}
k.mu.Lock()
defer k.mu.Unlock()
revoked := false
for key := range k.keys {
if maskKey(key) == mask {
delete(k.keys, key)
revoked = true
}
}
return revoked
}
// List returns a summary of every currently registered API key for the admin
// panel. Key material is never returned; each identifier is masked so the panel
// can tell keys apart without exposing the secret. The in-memory store keeps no
// creation time, so CreatedAt is nil for every entry.
func (k *APIKey) List() []UserSummary {
k.mu.RLock()
defer k.mu.RUnlock()
out := make([]UserSummary, 0, len(k.keys))
for key, role := range k.keys {
out = append(out, UserSummary{ID: maskKey(key), Username: "apikey", Role: role})
}
return out
}
// MaskKey renders a key's leading and trailing groups so the panel can identify
// an entry without revealing the secret. Short keys are fully hidden. It is the
// exported form of maskKey so callers (e.g. the admin issue handler) can return
// the same masked id the List page shows.
func MaskKey(key string) string { return maskKey(key) }
// maskKey renders a key's leading and trailing groups so the panel can identify
// an entry without revealing the secret. Short keys are fully hidden.
func maskKey(key string) string {
if len(key) <= 8 {
return "••••"
}
return key[:4] + "••••" + key[len(key)-4:]
}