Files
wangjia 1d154bd627
ci-pangolin / Redline Scan — 脱敏 (UI 文案) (push) Successful in 25s
ci-pangolin / Cleartext Scan — Android 禁明文 (push) Successful in 20s
ci-pangolin / Lint — shellcheck (push) Successful in 51s
ci-pangolin / Portable SQL — 可移植性 (mysql/sqlite) (push) Successful in 23s
ci-pangolin / OpenAPI Sync Check (push) Successful in 1m10s
ci-pangolin / Flutter — analyze + test (push) Successful in 3m44s
ci-pangolin / Codegen Drift — token 生成物未漂移 (push) Successful in 1m7s
ci-pangolin / DS-flow — 原型/跨端同源/代码色单源闸 (push) Successful in 24s
ci-pangolin / Go — build + test (push) Failing after 1m0s
ci-pangolin / E2E Smoke — L4 进程级端到端 (push) Failing after 40s
ci-pangolin / Go — integration (mysql/redis testcontainers) (push) Failing after 6m9s
ci-pangolin / Golden — 视觉回归 (全量:components/auth/desktop/tablet) (push) Successful in 42s
feat(admin): 后台登录支持「记住此设备」(免二次验证 + 保持登录)
常用设备(已在 mTLS 白名单内)每次都要输 TOTP + 30 分钟就掉线,体验差。
新增登录页「记住此设备」勾选:

- 勾选并成功登录(需完整 密码+TOTP)后,签发 30 天设备信任令牌(HttpOnly/
  Secure/SameSite=Strict cookie,Redis 存储绑定 admin ID),并把会话延到 30 天
  (持久 cookie + 服务端 TTL,滑动续期按会话自身 TTL)。
- 之后该设备重登只需 用户名+密码,**跳过 TOTP**;会话在有效期内保持登录。

安全不变量(均有测试覆盖):
- 密码永远必验——即便持有效信任令牌,密码错一律拒(只跳过第二因子,不跳过密码);
- 信任令牌绑定 admin,alice 的令牌不能给 bob 免 TOTP;
- 无令牌 + 空 TOTP 一律拒(未记住设备仍强制二次验证);
- 令牌过期/Redis 清空/未知令牌全部 fail-closed 回退到「要 TOTP」;
- TrustedDeviceTTL=0 关闭整功能(勾选无效)。

实现:新增 TrustedStore(Redis, trusted.go);Authenticator.LoginDevice
(旧 Login 保持签名,委托新方法,零行为变化);SessionStore.CreateWithTTL +
Session.TTLSeconds 支持持久会话按自身 TTL 滑动;handler 读 cookie/勾选、
按 Persistent 设长短会话 cookie、下发信任 cookie;登录页加勾选、TOTP 去
required。配置项 ADMIN_TRUSTED_DEVICE_TTL(默认 720h)。

测试:trusted_test(签发/校验/绑定/吊销/过期/禁用)、login_device_test
(跳过TOTP/仍需密码/绑定admin/无令牌需TOTP)、login_device_handler_test
(端到端 勾选→双cookie→凭信任cookie免TOTP、无信任空TOTP 401);
go test ./internal/admin 全绿,go vet 净。

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01P9G7E3wmAYL9KeYCVZVsqu
2026-07-24 09:52:56 +08:00

148 lines
4.4 KiB
Go

package admin
import (
"context"
"crypto/rand"
"crypto/subtle"
"encoding/base64"
"encoding/json"
"errors"
"fmt"
"time"
"github.com/redis/go-redis/v9"
)
// SessionCookieName is the name of the admin session cookie.
const SessionCookieName = "admin_session"
// sessionKeyPrefix namespaces session keys in Redis.
const sessionKeyPrefix = "admin:sess:"
// Session is the server-side state for one logged-in admin.
type Session struct {
AdminID int64 `json:"admin_id"`
Username string `json:"username"`
CSRFToken string `json:"csrf"`
CreatedAt time.Time `json:"created_at"`
// TTLSeconds, when > 0, overrides the store's default sliding idle TTL for
// this session (used by "记住此设备" persistent sessions). 0 = use default.
TTLSeconds int64 `json:"ttl_seconds,omitempty"`
}
// SessionStore persists admin sessions in Redis with a sliding idle TTL.
type SessionStore struct {
rdb *redis.Client
ttl time.Duration
}
// NewSessionStore creates a SessionStore. ttl is the sliding idle timeout.
func NewSessionStore(rdb *redis.Client, ttl time.Duration) *SessionStore {
if ttl <= 0 {
ttl = 30 * time.Minute
}
return &SessionStore{rdb: rdb, ttl: ttl}
}
// Create starts a new session with the store's default sliding idle TTL.
func (s *SessionStore) Create(ctx context.Context, adminID int64, username string) (string, *Session, error) {
return s.CreateWithTTL(ctx, adminID, username, 0)
}
// CreateWithTTL starts a new session. When ttl > 0 the session uses that TTL
// (both the initial expiry and the per-request slide) instead of the store
// default — this is how "记住此设备" keeps a device logged in for e.g. 30 days.
func (s *SessionStore) CreateWithTTL(ctx context.Context, adminID int64, username string, ttl time.Duration) (string, *Session, error) {
sid, err := randToken(32)
if err != nil {
return "", nil, err
}
csrf, err := randToken(32)
if err != nil {
return "", nil, err
}
sess := &Session{
AdminID: adminID,
Username: username,
CSRFToken: csrf,
CreatedAt: time.Now().UTC(),
}
if ttl > 0 {
sess.TTLSeconds = int64(ttl / time.Second)
}
if err := s.save(ctx, sid, sess); err != nil {
return "", nil, err
}
return sid, sess, nil
}
// slideTTL is the TTL to (re)apply to a session: its own override if set,
// otherwise the store default.
func (s *SessionStore) slideTTL(sess *Session) time.Duration {
if sess != nil && sess.TTLSeconds > 0 {
return time.Duration(sess.TTLSeconds) * time.Second
}
return s.ttl
}
// Get loads a session and slides its TTL forward. Returns (nil, nil) when the
// session is absent or expired.
func (s *SessionStore) Get(ctx context.Context, sid string) (*Session, error) {
if sid == "" {
return nil, nil
}
val, err := s.rdb.Get(ctx, sessionKeyPrefix+sid).Bytes()
if errors.Is(err, redis.Nil) {
return nil, nil
}
if err != nil {
return nil, fmt.Errorf("admin.SessionStore.Get: %w", err)
}
var sess Session
if err := json.Unmarshal(val, &sess); err != nil {
return nil, fmt.Errorf("admin.SessionStore.Get unmarshal: %w", err)
}
// Slide the idle timeout (persistent sessions slide by their own TTL).
if err := s.rdb.Expire(ctx, sessionKeyPrefix+sid, s.slideTTL(&sess)).Err(); err != nil {
return nil, fmt.Errorf("admin.SessionStore.Get expire: %w", err)
}
return &sess, nil
}
// Delete removes a session (logout).
func (s *SessionStore) Delete(ctx context.Context, sid string) error {
if sid == "" {
return nil
}
return s.rdb.Del(ctx, sessionKeyPrefix+sid).Err()
}
func (s *SessionStore) save(ctx context.Context, sid string, sess *Session) error {
b, err := json.Marshal(sess)
if err != nil {
return fmt.Errorf("admin.SessionStore.save: %w", err)
}
if err := s.rdb.Set(ctx, sessionKeyPrefix+sid, b, s.slideTTL(sess)).Err(); err != nil {
return fmt.Errorf("admin.SessionStore.save set: %w", err)
}
return nil
}
// ValidCSRF reports, in constant time, whether token matches the session's
// CSRF token.
func (sess *Session) ValidCSRF(token string) bool {
if sess == nil || sess.CSRFToken == "" || token == "" {
return false
}
return subtle.ConstantTimeCompare([]byte(sess.CSRFToken), []byte(token)) == 1
}
// randToken returns a URL-safe random token of n bytes of entropy.
func randToken(n int) (string, error) {
buf := make([]byte, n)
if _, err := rand.Read(buf); err != nil {
return "", fmt.Errorf("admin.randToken: %w", err)
}
return base64.RawURLEncoding.EncodeToString(buf), nil
}