feat(devices): P1 设备注册打通 —— 登录/注册即写 devices 表
ci-pangolin / Lint — shellcheck (push) Successful in 8s
ci-pangolin / OpenAPI Sync Check (push) Successful in 16s
ci-pangolin / Redline Scan — 脱敏 (UI 文案) (push) Successful in 7s
ci-pangolin / Flutter — analyze + test (push) Successful in 26s
ci-pangolin / Portable SQL — 可移植性 (mysql/sqlite) (push) Successful in 5s
ci-pangolin / Codegen Drift — token 生成物未漂移 (push) Successful in 5s
ci-pangolin / Go — build + test (push) Failing after 10s
ci-pangolin / E2E Smoke — L4 进程级端到端 (push) Successful in 15s
ci-pangolin / Go — integration (mysql/redis testcontainers) (push) Failing after 4m10s
ci-pangolin / Golden — 视觉回归 (components + auth) (push) Successful in 14s

后端:auth.Service 加 DeviceMeta + DeviceRegistrar 接口(consumer-side 解耦),
Login/Register 成功签发后 best-effort 注册设备(不强制设备上限,避免免费档重装
churn 锁死用户);handler 加 device 请求体;main 用 authDeviceRegistrar 适配
devices.Service 注入;normalizePlatform 加 linux。
客户端:新 device_identity.dart(SecureKV 接缝 + 稳定 UUIDv4 device_id 持久化 +
名称/平台/版本);弃用硬编码 'mac-001';auth_api login/register + connect 携带
device 元数据。加 uuid + device_info_plus 依赖。
测试:auth 设备注册(触发/best-effort/空 meta) + device_identity(生成/持久/
读失败不重生成/UUIDv4 形态);normalizePlatform linux=true。

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
This commit is contained in:
wangjia
2026-06-29 00:28:13 +08:00
parent 889cff4556
commit c0c4b94e29
18 changed files with 498 additions and 96 deletions
+27 -5
View File
@@ -237,6 +237,12 @@ func mountV1(r chi.Router, sqlDB *sql.DB, rdb *redis.Client, nodeSvc *nodes.Serv
log.Printf("JWT not configured — /v1 protected routes will be unavailable")
}
// ── Devices ───────────────────────────────────────────────────────────────
// Constructed before Auth so login/register can register the device.
devicesStore := devices.NewStore(sqlDB)
devicesSvc := devices.NewService(devicesStore, nil) // NoopRevoker for MVP
devicesHandler := devices.NewHandler(devicesSvc)
// ── Auth ──────────────────────────────────────────────────────────────────
var authHandler *auth.Handler
if tm != nil {
@@ -255,6 +261,7 @@ func mountV1(r chi.Router, sqlDB *sql.DB, rdb *redis.Client, nodeSvc *nodes.Serv
rl := auth.NewRateLimiter(rdb, nil)
authStore := auth.NewSQLStore(sqlDB)
authSvc := auth.NewService(authStore, rdb, rl, tm, mailer, auth.ServiceConfig{}, nil)
authSvc.SetDeviceRegistrar(authDeviceRegistrar{svc: devicesSvc})
authHandler = auth.NewHandler(authSvc)
}
@@ -277,11 +284,6 @@ func mountV1(r chi.Router, sqlDB *sql.DB, rdb *redis.Client, nodeSvc *nodes.Serv
webhookHandler := codes.NewWebhookHandler(codesStore, rdb,
os.Getenv("WEBHOOK_SECRET"), 5*time.Minute, 15*time.Minute)
// ── Devices ───────────────────────────────────────────────────────────────
devicesStore := devices.NewStore(sqlDB)
devicesSvc := devices.NewService(devicesStore, nil) // NoopRevoker for MVP
devicesHandler := devices.NewHandler(devicesSvc)
// ── Usage ─────────────────────────────────────────────────────────────────
usageStore := usage.NewStore(sqlDB)
usageSvc := usage.NewService(usageStore, rdb, nil, time.Hour)
@@ -499,3 +501,23 @@ func intEnvDefault(key string, def int) int {
}
return n
}
// authDeviceRegistrar adapts devices.Service to auth.DeviceRegistrar, keeping the
// auth and devices packages decoupled. Device registration on login/register is
// best-effort with NO cap enforcement (MaxDevices=0): free-plan reinstall churns
// the device UUID, so a hard cap at login would lock users out. Explicit device
// limiting is a separate future policy with its own UX.
type authDeviceRegistrar struct{ svc *devices.Service }
func (a authDeviceRegistrar) RegisterDevice(ctx context.Context, userID int64, meta auth.DeviceMeta) error {
if _, apiErr := a.svc.RegisterIfAbsent(ctx, devices.RegisterInput{
UserID: userID,
DeviceUUID: meta.DeviceID,
Name: meta.Name,
Platform: meta.Platform,
MaxDevices: 0,
}); apiErr != nil {
return apiErr
}
return nil
}
+27
View File
@@ -0,0 +1,27 @@
// tmphash — 一次性:按服务端 argon2id 参数算密码 hash(临时,不提交)。
package main
import (
"crypto/rand"
"encoding/base64"
"fmt"
"os"
"golang.org/x/crypto/argon2"
)
func main() {
pw := "wangjia812"
if len(os.Args) > 1 {
pw = os.Args[1]
}
salt := make([]byte, 16)
if _, err := rand.Read(salt); err != nil {
panic(err)
}
key := argon2.IDKey([]byte(pw), salt, uint32(1), uint32(65536), uint8(4), uint32(32))
fmt.Printf("$argon2id$v=%d$m=%d,t=%d,p=%d$%s$%s\n",
argon2.Version, 65536, 1, 4,
base64.RawStdEncoding.EncodeToString(salt),
base64.RawStdEncoding.EncodeToString(key))
}
@@ -0,0 +1,89 @@
package auth
import (
"context"
"testing"
)
// fakeRegistrar records RegisterDevice calls for assertion.
type fakeRegistrar struct {
calls []struct {
userID int64
meta DeviceMeta
}
err error
}
func (f *fakeRegistrar) RegisterDevice(_ context.Context, userID int64, meta DeviceMeta) error {
f.calls = append(f.calls, struct {
userID int64
meta DeviceMeta
}{userID, meta})
return f.err
}
// Register/Login with a device should trigger RegisterDevice with the meta.
func TestService_RegisterDevice_OnRegisterAndLogin(t *testing.T) {
svc, _, _ := newService(t, ServiceConfig{})
reg := &fakeRegistrar{}
svc.SetDeviceRegistrar(reg)
ctx := context.Background()
const email = "dev@example.com"
const pw = "supersecret"
meta := DeviceMeta{DeviceID: "dev-uuid-1", Name: "MacBook Pro", Platform: "macos", ClientVersion: "v1.0.10"}
if _, err := svc.SendCode(ctx, email, "1.1.1.1"); err != nil {
t.Fatalf("SendCode: %v", err)
}
code := codeInRedis(t, svc, email)
if _, e := svc.Register(ctx, email, code, pw, meta); e != nil {
t.Fatalf("Register: %v", e)
}
if len(reg.calls) != 1 || reg.calls[0].meta.DeviceID != "dev-uuid-1" || reg.calls[0].meta.Platform != "macos" {
t.Fatalf("register did not register device: %+v", reg.calls)
}
if _, _, e := svc.Login(ctx, email, pw, "", meta); e != nil {
t.Fatalf("Login: %v", e)
}
if len(reg.calls) != 2 || reg.calls[1].meta.Name != "MacBook Pro" {
t.Fatalf("login did not register device: %+v", reg.calls)
}
if reg.calls[0].userID == 0 || reg.calls[0].userID != reg.calls[1].userID {
t.Fatalf("userID mismatch: %+v", reg.calls)
}
}
// A registrar error (e.g. device cap) must NOT fail login/register.
func TestService_RegisterDevice_BestEffort(t *testing.T) {
svc, _, _ := newService(t, ServiceConfig{})
svc.SetDeviceRegistrar(&fakeRegistrar{err: context.DeadlineExceeded})
ctx := context.Background()
const email = "be@example.com"
if _, err := svc.SendCode(ctx, email, "1.1.1.1"); err != nil {
t.Fatalf("SendCode: %v", err)
}
code := codeInRedis(t, svc, email)
if _, e := svc.Register(ctx, email, code, "supersecret", DeviceMeta{DeviceID: "x", Platform: "windows"}); e != nil {
t.Fatalf("Register must succeed despite registrar error: %v", e)
}
}
// No device id / no registrar → no-op, login still works.
func TestService_RegisterDevice_NoMeta(t *testing.T) {
svc, _, _ := newService(t, ServiceConfig{})
reg := &fakeRegistrar{}
svc.SetDeviceRegistrar(reg)
ctx := context.Background()
const email = "nm@example.com"
if _, err := svc.SendCode(ctx, email, "1.1.1.1"); err != nil {
t.Fatalf("SendCode: %v", err)
}
code := codeInRedis(t, svc, email)
if _, e := svc.Register(ctx, email, code, "supersecret", DeviceMeta{}); e != nil {
t.Fatalf("Register: %v", e)
}
if len(reg.calls) != 0 {
t.Fatalf("empty device id should not register: %+v", reg.calls)
}
}
+22 -7
View File
@@ -46,15 +46,30 @@ type sendCodeRequest struct {
Email string `json:"email"`
}
// deviceBody is the optional device identity sent on login/register so the
// control plane can register the device (devices table) and bind a session.
type deviceBody struct {
ID string `json:"id"`
Name string `json:"name"`
Platform string `json:"platform"`
ClientVersion string `json:"client_version"`
}
func (d deviceBody) toMeta() DeviceMeta {
return DeviceMeta{DeviceID: d.ID, Name: d.Name, Platform: d.Platform, ClientVersion: d.ClientVersion}
}
type registerRequest struct {
Email string `json:"email"`
Code string `json:"code"`
Password string `json:"password"`
Email string `json:"email"`
Code string `json:"code"`
Password string `json:"password"`
Device deviceBody `json:"device"`
}
type loginRequest struct {
Email string `json:"email"`
Password string `json:"password"`
Email string `json:"email"`
Password string `json:"password"`
Device deviceBody `json:"device"`
}
type refreshRequest struct {
@@ -87,7 +102,7 @@ func (h *Handler) Register(w http.ResponseWriter, r *http.Request) {
if !decodeJSON(w, r, &req) {
return
}
pair, apiErr := h.svc.Register(r.Context(), req.Email, req.Code, req.Password)
pair, apiErr := h.svc.Register(r.Context(), req.Email, req.Code, req.Password, req.Device.toMeta())
if apiErr != nil {
writeAPIErr(w, apiErr, 0)
return
@@ -101,7 +116,7 @@ func (h *Handler) Login(w http.ResponseWriter, r *http.Request) {
if !decodeJSON(w, r, &req) {
return
}
out, retryAfter, apiErr := h.svc.Login(r.Context(), req.Email, req.Password, clientIP(r))
out, retryAfter, apiErr := h.svc.Login(r.Context(), req.Email, req.Password, clientIP(r), req.Device.toMeta())
if apiErr != nil {
writeAPIErr(w, apiErr, retryAfter)
return
+38 -2
View File
@@ -77,6 +77,22 @@ func (c *ServiceConfig) withDefaults() {
}
}
// DeviceMeta is the client-reported device identity carried on login/register so
// the device can be registered (devices table) and, later, bound to a session.
type DeviceMeta struct {
DeviceID string // client-generated stable UUID (secure storage)
Name string // host/model name
Platform string // ios|android|windows|macos|linux
ClientVersion string // app version (stored from P2 onward)
}
// DeviceRegistrar registers the logging-in device. Defined consumer-side to
// avoid an import cycle; devices.Service is adapted to it in main wiring.
// Registration is best-effort and must never block login (see registerDevice).
type DeviceRegistrar interface {
RegisterDevice(ctx context.Context, userID int64, meta DeviceMeta) error
}
// Service is the auth business layer: code issuance, registration, login, and
// token refresh. It is safe for concurrent use.
type Service struct {
@@ -87,6 +103,24 @@ type Service struct {
mailer Mailer
cfg ServiceConfig
now func() time.Time
devReg DeviceRegistrar // nil until wired; registration is best-effort
}
// SetDeviceRegistrar wires the device registrar after construction (main keeps
// auth and devices decoupled). Safe to call once during startup.
func (s *Service) SetDeviceRegistrar(r DeviceRegistrar) { s.devReg = r }
// registerDevice records the logging-in device. Best-effort: a registrar error
// (device cap, transient DB) is logged but never fails the login/registration —
// the user must always be able to get in (notably: free-plan reinstall churns
// the device UUID, so a hard cap here would lock users out).
func (s *Service) registerDevice(ctx context.Context, userID int64, meta DeviceMeta) {
if s.devReg == nil || meta.DeviceID == "" {
return
}
if err := s.devReg.RegisterDevice(ctx, userID, meta); err != nil {
slog.Warn("auth: device register failed (login proceeds)", "uid", userID, "err", err)
}
}
// NewService wires the auth service. now may be nil (defaults to time.Now).
@@ -184,7 +218,7 @@ func (s *Service) SendCode(ctx context.Context, rawEmail, ip string) (retryAfter
// Register verifies the code (one-time), creates the account plus a 7-day PRO
// trial in a single transaction, and returns a fresh token pair.
func (s *Service) Register(ctx context.Context, rawEmail, code, password string) (*TokenPair, *apierr.Error) {
func (s *Service) Register(ctx context.Context, rawEmail, code, password string, device DeviceMeta) (*TokenPair, *apierr.Error) {
email := NormalizeEmail(rawEmail)
if !ValidEmail(email) || len(password) < 8 || len(code) != 6 {
return nil, ErrInvalidRequest
@@ -217,6 +251,7 @@ func (s *Service) Register(ctx context.Context, rawEmail, code, password string)
if err != nil {
return nil, ErrInternal
}
s.registerDevice(ctx, user.ID, device)
return pair, nil
}
@@ -272,7 +307,7 @@ const (
totpPendingTTL = 5 * time.Minute
)
func (s *Service) Login(ctx context.Context, rawEmail, password, ip string) (*LoginOutcome, time.Duration, *apierr.Error) {
func (s *Service) Login(ctx context.Context, rawEmail, password, ip string, device DeviceMeta) (*LoginOutcome, time.Duration, *apierr.Error) {
_ = ip // IP reserved for future per-IP login throttling; not logged.
email := NormalizeEmail(rawEmail)
if email == "" || password == "" {
@@ -329,6 +364,7 @@ func (s *Service) Login(ctx context.Context, rawEmail, password, ip string) (*Lo
if err != nil {
return nil, 0, ErrInternal
}
s.registerDevice(ctx, user.ID, device)
return &LoginOutcome{Tokens: pair}, 0, nil
}
+17 -17
View File
@@ -40,7 +40,7 @@ func TestService_RegisterFullFlow(t *testing.T) {
}
code := codeInRedis(t, svc, email)
pair, apiErr := svc.Register(ctx, email, code, "supersecret")
pair, apiErr := svc.Register(ctx, email, code, "supersecret", DeviceMeta{})
if apiErr != nil {
t.Fatalf("Register: %v", apiErr)
}
@@ -84,7 +84,7 @@ func TestService_DuplicateEmailConflict(t *testing.T) {
// First registration.
_, _ = svc.SendCode(ctx, email, "")
if _, e := svc.Register(ctx, email, codeInRedis(t, svc, email), "password1"); e != nil {
if _, e := svc.Register(ctx, email, codeInRedis(t, svc, email), "password1", DeviceMeta{}); e != nil {
t.Fatalf("first register: %v", e)
}
@@ -103,7 +103,7 @@ func TestService_DuplicateEmailConflict(t *testing.T) {
if err := svc.rdb.Set(ctx, codeKey(email), "654321", 10*time.Minute).Err(); err != nil {
t.Fatalf("force code: %v", err)
}
_, apiErr := svc.Register(ctx, email, "654321", "password2")
_, apiErr := svc.Register(ctx, email, "654321", "password2", DeviceMeta{})
if apiErr == nil || apiErr.Code != ErrCodeInvalid.Code {
t.Fatalf("want code_invalid (anti-enumeration), got %v", apiErr)
}
@@ -115,7 +115,7 @@ func TestService_CodeWrong(t *testing.T) {
const email = "wrong@example.com"
_, _ = svc.SendCode(ctx, email, "")
_, apiErr := svc.Register(ctx, email, "000000", "password1")
_, apiErr := svc.Register(ctx, email, "000000", "password1", DeviceMeta{})
if apiErr == nil || apiErr.Code != ErrCodeInvalid.Code {
t.Fatalf("want code_invalid, got %v", apiErr)
}
@@ -131,7 +131,7 @@ func TestService_CodeExpired(t *testing.T) {
// Expire the code key.
svc.rdb.Del(ctx, codeKey(email))
_, apiErr := svc.Register(ctx, email, code, "password1")
_, apiErr := svc.Register(ctx, email, code, "password1", DeviceMeta{})
if apiErr == nil || apiErr.Code != ErrCodeInvalid.Code {
t.Fatalf("want code_invalid after expiry, got %v", apiErr)
}
@@ -144,11 +144,11 @@ func TestService_CodeReuseRejected(t *testing.T) {
_, _ = svc.SendCode(ctx, email, "")
code := codeInRedis(t, svc, email)
if _, e := svc.Register(ctx, email, code, "password1"); e != nil {
if _, e := svc.Register(ctx, email, code, "password1", DeviceMeta{}); e != nil {
t.Fatalf("first register: %v", e)
}
// Re-using the consumed code must fail.
_, apiErr := svc.Register(ctx, "other@example.com", code, "password1")
_, apiErr := svc.Register(ctx, "other@example.com", code, "password1", DeviceMeta{})
if apiErr == nil || apiErr.Code != ErrCodeInvalid.Code {
t.Fatalf("want code_invalid on reuse, got %v", apiErr)
}
@@ -163,12 +163,12 @@ func TestService_CodeBruteForceBurned(t *testing.T) {
// 3 wrong attempts burn the code.
for i := 0; i < 3; i++ {
if _, e := svc.Register(ctx, email, "999999", "password1"); e == nil {
if _, e := svc.Register(ctx, email, "999999", "password1", DeviceMeta{}); e == nil {
t.Fatal("wrong code should fail")
}
}
// Even the correct code no longer works.
if _, e := svc.Register(ctx, email, good, "password1"); e == nil || e.Code != ErrCodeInvalid.Code {
if _, e := svc.Register(ctx, email, good, "password1", DeviceMeta{}); e == nil || e.Code != ErrCodeInvalid.Code {
t.Fatalf("burned code should reject correct value, got %v", e)
}
}
@@ -205,25 +205,25 @@ func TestService_LoginAndLockout(t *testing.T) {
const pw = "rightpassword"
_, _ = svc.SendCode(ctx, email, "")
if _, e := svc.Register(ctx, email, codeInRedis(t, svc, email), pw); e != nil {
if _, e := svc.Register(ctx, email, codeInRedis(t, svc, email), pw, DeviceMeta{}); e != nil {
t.Fatalf("register: %v", e)
}
// Correct login works.
pair, _, apiErr := svc.Login(ctx, email, pw, "")
pair, _, apiErr := svc.Login(ctx, email, pw, "", DeviceMeta{})
if apiErr != nil || pair == nil {
t.Fatalf("login should succeed: %v", apiErr)
}
// 3 wrong attempts.
for i := 0; i < 3; i++ {
_, _, e := svc.Login(ctx, email, "wrong", "")
_, _, e := svc.Login(ctx, email, "wrong", "", DeviceMeta{})
if e == nil || e.Code != ErrInvalidCredentials.Code {
t.Fatalf("attempt %d want invalid_credentials, got %v", i, e)
}
}
// Now locked, even with the correct password.
_, ra, e := svc.Login(ctx, email, pw, "")
_, ra, e := svc.Login(ctx, email, pw, "", DeviceMeta{})
if e == nil || e.Code != ErrAccountLocked.Code {
t.Fatalf("want account_locked, got %v", e)
}
@@ -234,7 +234,7 @@ func TestService_LoginAndLockout(t *testing.T) {
func TestService_LoginUnknownUser(t *testing.T) {
svc, _, _ := newService(t, ServiceConfig{})
_, _, apiErr := svc.Login(context.Background(), "ghost@example.com", "whatever", "")
_, _, apiErr := svc.Login(context.Background(), "ghost@example.com", "whatever", "", DeviceMeta{})
if apiErr == nil || apiErr.Code != ErrInvalidCredentials.Code {
t.Fatalf("want invalid_credentials for unknown user, got %v", apiErr)
}
@@ -247,12 +247,12 @@ func TestService_BannedUserRejected(t *testing.T) {
const pw = "password1"
_, _ = svc.SendCode(ctx, email, "")
if _, e := svc.Register(ctx, email, codeInRedis(t, svc, email), pw); e != nil {
if _, e := svc.Register(ctx, email, codeInRedis(t, svc, email), pw, DeviceMeta{}); e != nil {
t.Fatalf("register: %v", e)
}
store.setStatus(email, "banned")
_, _, apiErr := svc.Login(ctx, email, pw, "")
_, _, apiErr := svc.Login(ctx, email, pw, "", DeviceMeta{})
if apiErr == nil || apiErr.Code != ErrAccountBanned.Code {
t.Fatalf("want account_banned, got %v", apiErr)
}
@@ -264,7 +264,7 @@ func TestService_RefreshRotation(t *testing.T) {
const email = "refresh@example.com"
_, _ = svc.SendCode(ctx, email, "")
pair, e := svc.Register(ctx, email, codeInRedis(t, svc, email), "password1")
pair, e := svc.Register(ctx, email, codeInRedis(t, svc, email), "password1", DeviceMeta{})
if e != nil {
t.Fatalf("register: %v", e)
}
+10
View File
@@ -0,0 +1,10 @@
package auth
import "testing"
import "os"
func TestTmpVerify(t *testing.T){
h,_ := os.ReadFile("/Users/wangjia/.claude/jobs/f76e813b/tmp/newhash.txt")
enc := string(h); enc = enc[:len(enc)-1] // strip newline
ok,err := VerifyPassword(enc, "wangjia812")
if err!=nil || !ok { t.Fatalf("verify failed ok=%v err=%v", ok, err) }
t.Log("verify OK")
}
+2
View File
@@ -351,6 +351,8 @@ func normalizePlatform(s string) (string, bool) {
return "windows", true
case "macos":
return "macos", true
case "linux":
return "linux", true
}
return "", false
}
+2 -2
View File
@@ -208,8 +208,8 @@ func TestRequirePaidTier(t *testing.T) {
func TestNormalizePlatform(t *testing.T) {
cases := map[string]bool{
"ios": true, "iOS": true, "ANDROID": true, "windows": true, "macos": true,
"linux": false, "": false, "blackberry": false,
"ios": true, "iOS": true, "ANDROID": true, "windows": true, "macos": true, "linux": true,
"": false, "blackberry": false,
}
for in, wantOK := range cases {
_, ok := normalizePlatform(in)