feat(auth): add device session tracking with configurable limits

Track authenticated sessions per device (parsing user-agent for desktop
vs mobile via mileusna/useragent), enforce configurable concurrent device
limits (Auth.DeviceLimits), and surface device status and "remove other
devices" management in the account dialog. Adds device/session context to
the auth module stores and exposes limits through the API.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
This commit is contained in:
2026-07-11 01:01:54 +08:00
parent 875fff825c
commit 58f11302fe
32 changed files with 1783 additions and 253 deletions
@@ -15,6 +15,10 @@ type bearerAuthenticator interface {
UserIDFromBearer(ctx context.Context, authorization string) (string, bool)
}
type bearerIdentityAuthenticator interface {
IdentityFromBearer(ctx context.Context, authorization string) (authmodule.Identity, bool)
}
type profileAuthenticator interface {
GetProfile(ctx context.Context, userID string) (authmodule.User, error)
}
@@ -30,10 +34,22 @@ func UserContextMiddleware(authenticator bearerAuthenticator, shareAuthorizers .
}
return func(next http.HandlerFunc) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
ctx := authmodule.ContextWithRequestMetadata(r.Context(), authmodule.RequestMetadata{
UserAgent: r.Header.Get("User-Agent"),
Platform: r.Header.Get("Sec-CH-UA-Platform"),
Mobile: r.Header.Get("Sec-CH-UA-Mobile"),
})
userID := ""
sessionID := ""
authenticated := false
if authenticator != nil {
if tokenUserID, ok := userIDFromRequestAuth(r.Context(), r, authenticator); ok {
if identityAuthenticator, ok := authenticator.(bearerIdentityAuthenticator); ok {
if identity, valid := identityAuthenticator.IdentityFromBearer(ctx, r.Header.Get("Authorization")); valid {
userID = identity.UserID
sessionID = identity.SessionID
authenticated = true
}
} else if tokenUserID, ok := userIDFromRequestAuth(ctx, r, authenticator); ok {
userID = tokenUserID
authenticated = true
}
@@ -41,7 +57,7 @@ func UserContextMiddleware(authenticator bearerAuthenticator, shareAuthorizers .
actor := sharingmodule.Actor{Authenticated: authenticated, UserID: userID}
if authenticated && requestUsesShareAccess(r) {
if profiles, ok := authenticator.(profileAuthenticator); ok {
profile, err := profiles.GetProfile(r.Context(), userID)
profile, err := profiles.GetProfile(ctx, userID)
if err != nil {
writeAuthRequired(w)
return
@@ -54,7 +70,8 @@ func UserContextMiddleware(authenticator bearerAuthenticator, shareAuthorizers .
}
}
ctx := sharingmodule.ContextWithActor(r.Context(), actor)
ctx = sharingmodule.ContextWithActor(ctx, actor)
ctx = authmodule.ContextWithSessionID(ctx, sessionID)
ctx = design.ContextWithUserID(ctx, userID)
shareAuthorized := false
shareID := strings.TrimSpace(r.Header.Get("X-Share-Id"))
@@ -7,6 +7,7 @@ import (
"testing"
"img_infinite_canvas/internal/domain/design"
authmodule "img_infinite_canvas/internal/modules/auth"
sharingmodule "img_infinite_canvas/internal/modules/sharing"
)
@@ -19,6 +20,25 @@ func (fakeBearerAuthenticator) UserIDFromBearer(_ context.Context, authorization
return "", false
}
type fakeIdentityAuthenticator struct {
metadata authmodule.RequestMetadata
}
func (f *fakeIdentityAuthenticator) UserIDFromBearer(context.Context, string) (string, bool) {
return "", false
}
func (f *fakeIdentityAuthenticator) IdentityFromBearer(ctx context.Context, authorization string) (authmodule.Identity, bool) {
if authorization != "Bearer session-token" {
return authmodule.Identity{}, false
}
f.metadata = authmodule.RequestMetadataFromContext(ctx)
return authmodule.Identity{
UserID: "91cd197b-8255-4172-9981-77391fd38f33",
SessionID: "session-1",
}, true
}
type fakeShareAuthorizer struct {
access sharingmodule.Access
err error
@@ -50,6 +70,33 @@ func TestUserContextMiddlewareUsesAuthorizationHeader(t *testing.T) {
}
}
func TestUserContextMiddlewarePropagatesSessionAndDeviceMetadata(t *testing.T) {
authenticator := &fakeIdentityAuthenticator{}
req := httptest.NewRequest(http.MethodGet, "/api/account/devices", nil)
req.Header.Set("Authorization", "Bearer session-token")
req.Header.Set("User-Agent", "test-browser")
req.Header.Set("Sec-CH-UA-Platform", `"macOS"`)
req.Header.Set("Sec-CH-UA-Mobile", "?0")
rec := httptest.NewRecorder()
UserContextMiddleware(authenticator)(func(w http.ResponseWriter, r *http.Request) {
if got := design.UserIDFromContext(r.Context()); got != "91cd197b-8255-4172-9981-77391fd38f33" {
t.Fatalf("expected authenticated user in context, got %s", got)
}
if got := authmodule.SessionIDFromContext(r.Context()); got != "session-1" {
t.Fatalf("expected session id in context, got %s", got)
}
w.WriteHeader(http.StatusNoContent)
})(rec, req)
if rec.Code != http.StatusNoContent {
t.Fatalf("expected status %d, got %d", http.StatusNoContent, rec.Code)
}
if authenticator.metadata.UserAgent != "test-browser" || authenticator.metadata.Platform != `"macOS"` || authenticator.metadata.Mobile != "?0" {
t.Fatalf("unexpected request metadata %#v", authenticator.metadata)
}
}
func TestUserContextMiddlewareIgnoresLegacyTokenHeaderAndCookie(t *testing.T) {
req := httptest.NewRequest(http.MethodGet, "/api/projects", nil)
req.Header.Set("token", "valid")