Skip to content

armgit / lyftr

Public Imported from GitHub
0

Self-hosted fitness tracker. Log workouts, track nutrition, and monitor progress. Docker deployment, mobile-friendly.

Change your password in-app, and reset it from the CLI when it's lost (#114)

Carterae73be3dfeac
diff --git a/backend/controllers/auth.go b/backend/controllers/auth.go
index a628206..22e02f3 100644
--- a/backend/controllers/auth.go
+++ b/backend/controllers/auth.go
@@ -5,6 +5,7 @@ import (
"errors"
"github.com/Cawlumm/lyftr-backend/config"
+ "github.com/Cawlumm/lyftr-backend/middleware"
"github.com/Cawlumm/lyftr-backend/models"
"github.com/Cawlumm/lyftr-backend/stores"
"github.com/Cawlumm/lyftr-backend/utils"
@@ -61,6 +62,14 @@ func (h *Handler) Register(c *gin.Context) {
return
}
+ // Before hashing: bcrypt refuses anything over 72 bytes outright, and mapping that
+ // to a 500 told the user the server had broken on input their password manager
+ // generates by default.
+ if utils.PasswordTooLong(req.Password) {
+ utils.BadRequest(c, utils.PasswordTooLongMessage)
+ return
+ }
+
hash, err := utils.HashPassword(req.Password)
if err != nil {
utils.InternalError(c)
@@ -85,13 +94,23 @@ func (h *Handler) Register(c *gin.Context) {
return
}
- access, refresh, err := utils.GenerateTokenPair(userID, req.Email)
+ // A brand new row is at token_version 1 by schema default.
+ access, refresh, err := utils.GenerateTokenPair(userID, req.Email, 1)
if err != nil {
utils.InternalError(c)
return
}
- user := models.User{ID: userID, Email: req.Email}
+ // Read the row back rather than assembling the response by hand. Building it from
+ // the request left created_at/updated_at at Go's zero time, which serialises as
+ // "0001-01-01T00:00:00Z" — and the clients render that, so a new account's Settings
+ // page showed "Member since December 1" until something refetched /me.
+ user, err := h.s.User.GetMe(userID)
+ if err != nil {
+ // The account exists and the tokens are valid; only the echoed profile is
+ // missing. Fall back rather than fail the registration.
+ user = models.User{ID: userID, Email: req.Email}
+ }
utils.Created(c, models.AuthResponse{Token: access, RefreshToken: refresh, User: user})
}
@@ -108,6 +127,11 @@ func (h *Handler) Login(c *gin.Context) {
user, err := h.s.User.GetByEmail(req.Email)
if err == sql.ErrNoRows {
+ // Pay the bcrypt round a real account would have cost. Returning straight away
+ // made a missing address answer ~12x faster than a wrong password, which tells
+ // anyone asking exactly which addresses are registered — undoing the point of
+ // giving both cases the same message.
+ utils.BurnPasswordComparison(req.Password)
utils.Unauthorized(c, "invalid email or password")
return
}
@@ -119,7 +143,7 @@ func (h *Handler) Login(c *gin.Context) {
return
}
- access, refresh, err := utils.GenerateTokenPair(user.ID, user.Email)
+ access, refresh, err := utils.GenerateTokenPair(user.ID, user.Email, user.TokenVersion)
if err != nil {
utils.InternalError(c)
return
@@ -129,6 +153,76 @@ func (h *Handler) Login(c *gin.Context) {
utils.OK(c, models.AuthResponse{Token: access, RefreshToken: refresh, User: user})
}
+// ChangePassword sets a new password for the signed-in caller and ends every other
+// session. The device that made the change gets a fresh token pair in the response, so
+// it stays signed in while the rest fall off as their access tokens lapse.
+func (h *Handler) ChangePassword(c *gin.Context) {
+ uid := middleware.UserID(c)
+
+ var req models.ChangePasswordRequest
+ if err := c.ShouldBindJSON(&req); err != nil {
+ utils.BadRequest(c, err.Error())
+ return
+ }
+ if err := validate.Struct(req); err != nil {
+ utils.ValidationError(c, err)
+ return
+ }
+
+ // Looked up by ID, not by the email in the token: an address that changed since the
+ // token was minted would otherwise resolve to the wrong row or to none at all.
+ user, err := h.s.User.GetByID(uid)
+ if err == sql.ErrNoRows {
+ utils.Unauthorized(c, "account no longer exists")
+ return
+ }
+ if utils.DBError(c, err) {
+ return
+ }
+
+ if !utils.CheckPassword(req.CurrentPassword, user.Password) {
+ utils.Unauthorized(c, "current password is incorrect")
+ return
+ }
+ // Rejected before hashing. Allowing it would burn a bcrypt round to no effect and,
+ // worse, still bump token_version — signing every other device out for a change
+ // that never happened.
+ if req.CurrentPassword == req.NewPassword {
+ utils.BadRequest(c, "new password must be different from the current one")
+ return
+ }
+
+ if utils.PasswordTooLong(req.NewPassword) {
+ utils.BadRequest(c, utils.PasswordTooLongMessage)
+ return
+ }
+
+ newHash, err := utils.HashPassword(req.NewPassword)
+ if err != nil {
+ utils.InternalError(c)
+ return
+ }
+
+ version, err := h.s.User.ChangePassword(uid, user.Password, newHash)
+ if errors.Is(err, stores.ErrPasswordChanged) {
+ utils.Conflict(c, "password was changed elsewhere, please try again")
+ return
+ }
+ if utils.DBError(c, err) {
+ return
+ }
+
+ access, refresh, err := utils.GenerateTokenPair(uid, user.Email, version)
+ if err != nil {
+ // The password did change — reporting a failure here would send the user off to
+ // retry with a password that no longer works. Say what happened instead.
+ utils.Unauthorized(c, "password changed, please sign in again")
+ return
+ }
+
+ utils.OK(c, gin.H{"token": access, "refresh_token": refresh})
+}
+
func (h *Handler) RefreshToken(c *gin.Context) {
var req models.RefreshRequest
if err := c.ShouldBindJSON(&req); err != nil {
@@ -142,7 +236,25 @@ func (h *Handler) RefreshToken(c *gin.Context) {
return
}
- access, refresh, err := utils.GenerateTokenPair(claims.UserID, claims.Email)
+ // The one place a stateless token meets server state. Signature validity says the
+ // token was minted by us; it cannot say the credentials behind it still stand. A
+ // refresh lives 30 days, so without this check a password change would leave every
+ // other device — including whoever the change was meant to evict — able to mint
+ // fresh access tokens for a month.
+ current, err := h.s.User.TokenVersion(claims.UserID)
+ if err == sql.ErrNoRows {
+ utils.Unauthorized(c, "invalid refresh token")
+ return
+ }
+ if utils.DBError(c, err) {
+ return
+ }
+ if utils.NormalizeTokenVersion(claims.TokenVersion) != current {
+ utils.Unauthorized(c, "session expired, please sign in again")
+ return
+ }
+
+ access, refresh, err := utils.GenerateTokenPair(claims.UserID, claims.Email, current)
if err != nil {
utils.InternalError(c)
return
diff --git a/backend/controllers/auth_test.go b/backend/controllers/auth_test.go
index 8678e49..84dfd3a 100644
--- a/backend/controllers/auth_test.go
+++ b/backend/controllers/auth_test.go
@@ -3,7 +3,9 @@ package controllers
import (
"errors"
"net/http"
+ "sort"
"testing"
+ "time"
"github.com/Cawlumm/lyftr-backend/config"
"github.com/Cawlumm/lyftr-backend/db"
@@ -166,3 +168,85 @@ func TestUserCount(t *testing.T) {
t.Errorf("Count = %d (err %v), want 1", n, err)
}
}
+
+// Register used to assemble its response from the request, leaving created_at at Go's
+// zero time. That serialises as "0001-01-01T00:00:00Z", which is truthy and parses fine,
+// so the clients formatted it rather than rejecting it — a brand new account's Settings
+// page read "Member since December 1".
+func TestRegisterReturnsRealTimestamps(t *testing.T) {
+ setupTestDB(t)
+ setRegistration(t, config.RegistrationOpen)
+
+ c, w := newContext(0, "POST", "/api/v1/auth/register",
+ map[string]string{"email": "[email protected]", "password": "password123"})
+ th.Register(c)
+ if w.Code != http.StatusCreated {
+ t.Fatalf("status = %d, want 201", w.Code)
+ }
+
+ body := decodeResponse(t, w)
+ data, _ := body["data"].(map[string]any)
+ user, _ := data["user"].(map[string]any)
+ created, _ := user["created_at"].(string)
+ if created == "" {
+ t.Fatal("no created_at in the register response")
+ }
+ ts, err := time.Parse(time.RFC3339, created)
+ if err != nil {
+ t.Fatalf("created_at %q does not parse: %v", created, err)
+ }
+ if ts.IsZero() || ts.Year() < 2000 {
+ t.Errorf("created_at = %q, want a real timestamp", created)
+ }
+}
+
+// A sign-in for an address with no account used to return before hashing, while a real
+// address paid a full bcrypt round. That is a 12x difference in practice — an oracle for
+// which addresses are registered, which is exactly what giving both cases the same
+// message is meant to prevent.
+//
+// Asserted as a ratio rather than an absolute, since bcrypt cost and machine speed both
+// move. The bound is loose on purpose: this catches "one path skips bcrypt entirely",
+// not micro-variation.
+func TestLoginDoesNotLeakAccountExistenceByTiming(t *testing.T) {
+ setupTestDB(t)
+
+ const password = "password123"
+ c, w := newContext(0, "POST", "/api/v1/auth/register",
+ map[string]string{"email": "[email protected]", "password": password})
+ th.Register(c)
+ if w.Code != http.StatusCreated {
+ t.Fatalf("register status = %d", w.Code)
+ }
+
+ attempt := func(email string) time.Duration {
+ start := time.Now()
+ c, w := newContext(0, "POST", "/api/v1/auth/login",
+ map[string]string{"email": email, "password": "definitely-the-wrong-password"})
+ th.Login(c)
+ if w.Code != http.StatusUnauthorized {
+ t.Fatalf("login status = %d, want 401", w.Code)
+ }
+ return time.Since(start)
+ }
+
+ // Median of a handful, so one scheduling hiccup cannot decide the result.
+ median := func(email string) time.Duration {
+ const n = 5
+ var xs []time.Duration
+ for i := 0; i < n; i++ {
+ xs = append(xs, attempt(email))
+ }
+ sort.Slice(xs, func(i, j int) bool { return xs[i] < xs[j] })
+ return xs[n/2]
+ }
+
+ existing := median("[email protected]")
+ missing := median("[email protected]")
+
+ ratio := float64(existing) / float64(missing)
+ if ratio > 3 || ratio < 1.0/3 {
+ t.Errorf("existing=%v missing=%v (%.1fx apart) — one path is skipping the password comparison",
+ existing, missing, ratio)
+ }
+}
diff --git a/backend/controllers/password_test.go b/backend/controllers/password_test.go
new file mode 100644
index 0000000..98b2e6c
--- /dev/null
+++ b/backend/controllers/password_test.go
@@ -0,0 +1,422 @@
+package controllers
+
+import (
+ "errors"
+ "net/http"
+ "strings"
+ "testing"
+
+ "github.com/Cawlumm/lyftr-backend/db"
+ "github.com/Cawlumm/lyftr-backend/stores"
+ "github.com/Cawlumm/lyftr-backend/utils"
+)
+
+// registerAndLogin creates a real account through the handler so the row carries a real
+// bcrypt hash and token_version, then returns its id and refresh token.
+func registerAndLogin(t *testing.T, email, password string) (int64, string) {
+ t.Helper()
+ c, w := newContext(0, "POST", "/api/v1/auth/register",
+ map[string]string{"email": email, "password": password})
+ th.Register(c)
+ if w.Code != http.StatusCreated {
+ t.Fatalf("register status = %d, want 201", w.Code)
+ }
+ body := decodeResponse(t, w)
+ data, ok := body["data"].(map[string]any)
+ if !ok {
+ t.Fatalf("register response has no data object: %v", body)
+ }
+ refresh, _ := data["refresh_token"].(string)
+ if refresh == "" {
+ t.Fatal("register returned no refresh token")
+ }
+ user, _ := data["user"].(map[string]any)
+ id, _ := user["id"].(float64)
+ if id == 0 {
+ t.Fatalf("register returned no user id: %v", data)
+ }
+ return int64(id), refresh
+}
+
+func changePassword(t *testing.T, uid int64, current, next string) (int, map[string]any) {
+ t.Helper()
+ c, w := newContext(uid, "PUT", "/api/v1/me/password",
+ map[string]string{"current_password": current, "new_password": next})
+ th.ChangePassword(c)
+ return w.Code, decodeResponse(t, w)
+}
+
+func storedHash(t *testing.T, uid int64) string {
+ t.Helper()
+ var h string
+ if err := db.DB.QueryRow(`SELECT password_hash FROM users WHERE id = ?`, uid).Scan(&h); err != nil {
+ t.Fatalf("read hash: %v", err)
+ }
+ return h
+}
+
+func tokenVersion(t *testing.T, uid int64) int {
+ t.Helper()
+ var v int
+ if err := db.DB.QueryRow(`SELECT token_version FROM users WHERE id = ?`, uid).Scan(&v); err != nil {
+ t.Fatalf("read token_version: %v", err)
+ }
+ return v
+}
+
+func refreshWith(t *testing.T, token string) int {
+ t.Helper()
+ c, w := newContext(0, "POST", "/api/v1/auth/refresh",
+ map[string]string{"refresh_token": token})
+ th.RefreshToken(c)
+ return w.Code
+}
+
+func TestChangePasswordReplacesHashAndIssuesNewTokens(t *testing.T) {
+ setupTestDB(t)
+ uid, _ := registerAndLogin(t, "[email protected]", "password123")
+ before := storedHash(t, uid)
+
+ code, body := changePassword(t, uid, "password123", "newpassword456")
+ if code != http.StatusOK {
+ t.Fatalf("status = %d, want 200 (%v)", code, body)
+ }
+
+ after := storedHash(t, uid)
+ if after == before {
+ t.Error("password hash unchanged")
+ }
+ if !utils.CheckPassword("newpassword456", after) {
+ t.Error("new password does not verify against the stored hash")
+ }
+ if utils.CheckPassword("password123", after) {
+ t.Error("old password still verifies")
+ }
+
+ // The device that made the change must stay signed in.
+ data, _ := body["data"].(map[string]any)
+ if tok, _ := data["token"].(string); tok == "" {
+ t.Error("no access token returned")
+ }
+ fresh, _ := data["refresh_token"].(string)
+ if fresh == "" {
+ t.Fatal("no refresh token returned")
+ }
+ if code := refreshWith(t, fresh); code != http.StatusOK {
+ t.Errorf("refresh with the newly issued token = %d, want 200", code)
+ }
+}
+
+// The reason the feature exists: a session opened before the change must not survive it.
+func TestChangePasswordRevokesOtherSessions(t *testing.T) {
+ setupTestDB(t)
+ uid, oldRefresh := registerAndLogin(t, "[email protected]", "password123")
+
+ // Sanity: that token works before the change, so a failure after it means something.
+ if code := refreshWith(t, oldRefresh); code != http.StatusOK {
+ t.Fatalf("pre-change refresh = %d, want 200", code)
+ }
+
+ if code, body := changePassword(t, uid, "password123", "newpassword456"); code != http.StatusOK {
+ t.Fatalf("change status = %d, want 200 (%v)", code, body)
+ }
+
+ if code := refreshWith(t, oldRefresh); code != http.StatusUnauthorized {
+ t.Errorf("post-change refresh with the old token = %d, want 401", code)
+ }
+ if v := tokenVersion(t, uid); v != 2 {
+ t.Errorf("token_version = %d, want 2", v)
+ }
+}
+
+func TestChangePasswordRejectsWrongCurrentPassword(t *testing.T) {
+ setupTestDB(t)
+ uid, refresh := registerAndLogin(t, "[email protected]", "password123")
+ before := storedHash(t, uid)
+
+ code, _ := changePassword(t, uid, "notmypassword", "newpassword456")
+ if code != http.StatusUnauthorized {
+ t.Fatalf("status = %d, want 401", code)
+ }
+ if storedHash(t, uid) != before {
+ t.Error("hash changed despite a rejected current password")
+ }
+ // A failed attempt must not evict the legitimate sessions.
+ if v := tokenVersion(t, uid); v != 1 {
+ t.Errorf("token_version = %d, want 1", v)
+ }
+ if code := refreshWith(t, refresh); code != http.StatusOK {
+ t.Errorf("refresh after a failed change = %d, want 200", code)
+ }
+}
+
+func TestChangePasswordRejectsShortPassword(t *testing.T) {
+ setupTestDB(t)
+ uid, _ := registerAndLogin(t, "[email protected]", "password123")
+ before := storedHash(t, uid)
+
+ // 422, matching what Register returns for the same min=8 tag — the two paths must
+ // not disagree about what a too-short password is.
+ code, _ := changePassword(t, uid, "password123", "short")
+ if code != http.StatusUnprocessableEntity {
+ t.Fatalf("status = %d, want 422", code)
+ }
+ if storedHash(t, uid) != before {
+ t.Error("hash changed despite a rejected new password")
+ }
+}
+
+// Reusing the current password would otherwise bump token_version and sign every other
+// device out for a change that did not happen.
+func TestChangePasswordRejectsUnchangedPassword(t *testing.T) {
+ setupTestDB(t)
+ uid, refresh := registerAndLogin(t, "[email protected]", "password123")
+
+ code, _ := changePassword(t, uid, "password123", "password123")
+ if code != http.StatusBadRequest {
+ t.Fatalf("status = %d, want 400", code)
+ }
+ if v := tokenVersion(t, uid); v != 1 {
+ t.Errorf("token_version = %d, want 1", v)
+ }
+ if code := refreshWith(t, refresh); code != http.StatusOK {
+ t.Errorf("refresh after a no-op change = %d, want 200", code)
+ }
+}
+
+// The compare-and-set guard in the store: two changes racing off the same verified hash
+// must not both succeed, or the loser's password wins while its user is told otherwise.
+func TestChangePasswordConcurrentLoserConflicts(t *testing.T) {
+ setupTestDB(t)
+ uid, _ := registerAndLogin(t, "[email protected]", "password123")
+ staleHash := storedHash(t, uid)
+
+ if code, _ := changePassword(t, uid, "password123", "newpassword456"); code != http.StatusOK {
+ t.Fatalf("first change failed")
+ }
+
+ // The second request verified against staleHash before the first landed.
+ newHash, err := utils.HashPassword("thirdpassword789")
+ if err != nil {
+ t.Fatalf("hash: %v", err)
+ }
+ if _, err := th.s.User.ChangePassword(uid, staleHash, newHash); err == nil {
+ t.Fatal("stale-hash change succeeded, want ErrPasswordChanged")
+ }
+ if !utils.CheckPassword("newpassword456", storedHash(t, uid)) {
+ t.Error("the winning change was overwritten by the loser")
+ }
+ if v := tokenVersion(t, uid); v != 2 {
+ t.Errorf("token_version = %d, want 2 (the loser must not bump it)", v)
+ }
+}
+
+// Tokens minted before the "ver" claim existed decode as 0. Folding that up to 1 is what
+// keeps existing installs signed in across the upgrade.
+func TestLegacyTokenWithoutVersionStillRefreshes(t *testing.T) {
+ setupTestDB(t)
+ uid, _ := registerAndLogin(t, "[email protected]", "password123")
+
+ _, legacyRefresh, err := utils.GenerateTokenPair(uid, "[email protected]", 0)
+ if err != nil {
+ t.Fatalf("generate: %v", err)
+ }
+ if code := refreshWith(t, legacyRefresh); code != http.StatusOK {
+ t.Errorf("legacy refresh = %d, want 200", code)
+ }
+
+ // ...but it dies as soon as the password moves.
+ if code, _ := changePassword(t, uid, "password123", "newpassword456"); code != http.StatusOK {
+ t.Fatal("change failed")
+ }
+ if code := refreshWith(t, legacyRefresh); code != http.StatusUnauthorized {
+ t.Errorf("legacy refresh after change = %d, want 401", code)
+ }
+}
+
+func TestNormalizeTokenVersion(t *testing.T) {
+ for _, tc := range []struct{ in, want int }{
+ {-1, 1}, {0, 1}, {1, 1}, {2, 2}, {7, 7},
+ } {
+ if got := utils.NormalizeTokenVersion(tc.in); got != tc.want {
+ t.Errorf("NormalizeTokenVersion(%d) = %d, want %d", tc.in, got, tc.want)
+ }
+ }
+}
+
+// A deleted account's refresh token must not be renewable.
+func TestRefreshRejectsDeletedAccount(t *testing.T) {
+ setupTestDB(t)
+ uid, refresh := registerAndLogin(t, "[email protected]", "password123")
+
+ if err := th.s.User.Delete(uid); err != nil {
+ t.Fatalf("delete: %v", err)
+ }
+ if code := refreshWith(t, refresh); code != http.StatusUnauthorized {
+ t.Errorf("refresh for a deleted account = %d, want 401", code)
+ }
+}
+
+// The operator's recovery path. Keyed on email, with no old hash to verify — the whole
+// premise is that nobody knows it.
+func TestResetPasswordReplacesHashAndRevokesSessions(t *testing.T) {
+ setupTestDB(t)
+ uid, refresh := registerAndLogin(t, "[email protected]", "password123")
+ before := storedHash(t, uid)
+
+ newHash, err := utils.HashPassword("operatorset789")
+ if err != nil {
+ t.Fatalf("hash: %v", err)
+ }
+ if err := th.s.User.ResetPassword("[email protected]", newHash); err != nil {
+ t.Fatalf("reset: %v", err)
+ }
+
+ after := storedHash(t, uid)
+ if after == before {
+ t.Error("hash unchanged")
+ }
+ if !utils.CheckPassword("operatorset789", after) {
+ t.Error("the new password does not verify")
+ }
+ if utils.CheckPassword("password123", after) {
+ t.Error("the old password still verifies")
+ }
+ // An operator resetting a password may be evicting an intruder; the intruder's
+ // refresh token must not outlive the reset.
+ if v := tokenVersion(t, uid); v != 2 {
+ t.Errorf("token_version = %d, want 2", v)
+ }
+ if code := refreshWith(t, refresh); code != http.StatusUnauthorized {
+ t.Errorf("refresh after reset = %d, want 401", code)
+ }
+}
+
+func TestResetPasswordUnknownEmail(t *testing.T) {
+ setupTestDB(t)
+ registerAndLogin(t, "[email protected]", "password123")
+
+ err := th.s.User.ResetPassword("[email protected]", "irrelevant-hash")
+ if !errors.Is(err, stores.ErrNoSuchUser) {
+ t.Fatalf("err = %v, want ErrNoSuchUser", err)
+ }
+}
+
+// Resetting one account must not disturb another's sessions.
+func TestResetPasswordLeavesOtherAccountsAlone(t *testing.T) {
+ setupTestDB(t)
+ registerAndLogin(t, "[email protected]", "password123")
+ bystanderID, bystanderRefresh := registerAndLogin(t, "[email protected]", "password123")
+
+ newHash, err := utils.HashPassword("operatorset789")
+ if err != nil {
+ t.Fatalf("hash: %v", err)
+ }
+ if err := th.s.User.ResetPassword("[email protected]", newHash); err != nil {
+ t.Fatalf("reset: %v", err)
+ }
+
+ if v := tokenVersion(t, bystanderID); v != 1 {
+ t.Errorf("bystander token_version = %d, want 1", v)
+ }
+ if code := refreshWith(t, bystanderRefresh); code != http.StatusOK {
+ t.Errorf("bystander refresh = %d, want 200", code)
+ }
+}
+
+// Review question: does ending sessions on a password change touch anyone else? The
+// UPDATE is keyed on the single row, but "keyed correctly" is exactly the kind of thing
+// that should be pinned rather than asserted.
+func TestChangePasswordLeavesOtherAccountsAlone(t *testing.T) {
+ setupTestDB(t)
+ uid, _ := registerAndLogin(t, "[email protected]", "password123")
+ bystanderID, bystanderRefresh := registerAndLogin(t, "[email protected]", "password123")
+ bystanderHash := storedHash(t, bystanderID)
+
+ if code, body := changePassword(t, uid, "password123", "newpassword456"); code != http.StatusOK {
+ t.Fatalf("change status = %d, want 200 (%v)", code, body)
+ }
+
+ if storedHash(t, bystanderID) != bystanderHash {
+ t.Error("the bystander's password hash changed")
+ }
+ if v := tokenVersion(t, bystanderID); v != 1 {
+ t.Errorf("bystander token_version = %d, want 1", v)
+ }
+ if code := refreshWith(t, bystanderRefresh); code != http.StatusOK {
+ t.Errorf("bystander refresh = %d, want 200 — their session was ended too", code)
+ }
+ // And the bystander's own password still works.
+ if !utils.CheckPassword("password123", storedHash(t, bystanderID)) {
+ t.Error("the bystander's password no longer verifies")
+ }
+}
+
+// An empty hash would be stored verbatim and then fail bcrypt against every password,
+// locking the account out silently while still bumping token_version.
+func TestPasswordWritesRefuseAnEmptyHash(t *testing.T) {
+ setupTestDB(t)
+ uid, _ := registerAndLogin(t, "[email protected]", "password123")
+ before := storedHash(t, uid)
+
+ if _, err := th.s.User.ChangePassword(uid, before, ""); !errors.Is(err, stores.ErrEmptyHash) {
+ t.Errorf("ChangePassword with an empty hash: err = %v, want ErrEmptyHash", err)
+ }
+ if err := th.s.User.ResetPassword("[email protected]", ""); !errors.Is(err, stores.ErrEmptyHash) {
+ t.Errorf("ResetPassword with an empty hash: err = %v, want ErrEmptyHash", err)
+ }
+ if storedHash(t, uid) != before {
+ t.Error("the stored hash was modified")
+ }
+ if v := tokenVersion(t, uid); v != 1 {
+ t.Errorf("token_version = %d, want 1 — a refused write must not evict sessions", v)
+ }
+}
+
+// bcrypt refuses over 72 bytes outright rather than truncating, and both handlers used to
+// hand that error to InternalError. The user was told the server had broken and to try
+// again, on input a password manager generates by default — advice that could never work.
+func TestPasswordLengthLimitIsAClientError(t *testing.T) {
+ setupTestDB(t)
+
+ tooLong := strings.Repeat("a", utils.MaxPasswordBytes+1)
+ atLimit := strings.Repeat("a", utils.MaxPasswordBytes)
+
+ register := func(email, password string) int {
+ c, w := newContext(0, "POST", "/api/v1/auth/register",
+ map[string]string{"email": email, "password": password})
+ th.Register(c)
+ return w.Code
+ }
+
+ t.Run("register rejects it as a client error", func(t *testing.T) {
+ if got := register("[email protected]", tooLong); got != http.StatusBadRequest {
+ t.Fatalf("status = %d, want %d — a 5xx tells the user to retry something that cannot work", got, http.StatusBadRequest)
+ }
+ })
+
+ t.Run("register still accepts exactly the limit", func(t *testing.T) {
+ if got := register("[email protected]", atLimit); got != http.StatusCreated {
+ t.Fatalf("status = %d, want %d", got, http.StatusCreated)
+ }
+ })
+
+ // The limit is bytes, so a 19-character passphrase is already too long. Worth pinning:
+ // the obvious `max=72` validator tag counts runes and would let this through to the
+ // same 500 the fix exists to remove.
+ t.Run("counts bytes, so multibyte fails well under 72 characters", func(t *testing.T) {
+ emoji := strings.Repeat("🏋", 19)
+ if got := register("[email protected]", emoji); got != http.StatusBadRequest {
+ t.Fatalf("status = %d, want %d for %d bytes in %d characters",
+ got, http.StatusBadRequest, len(emoji), len([]rune(emoji)))
+ }
+ })
+
+ t.Run("change password rejects it as a client error", func(t *testing.T) {
+ uid, _ := registerAndLogin(t, "[email protected]", "password123")
+ code, _ := changePassword(t, uid, "password123", tooLong)
+ if code != http.StatusBadRequest {
+ t.Fatalf("status = %d, want %d", code, http.StatusBadRequest)
+ }
+ })
+}
diff --git a/backend/db/migrations.go b/backend/db/migrations.go
index 8402cea..34c8236 100644
--- a/backend/db/migrations.go
+++ b/backend/db/migrations.go
@@ -76,6 +76,14 @@ func alterMigrations() {
ensureColumn("workouts", "program_id", `ALTER TABLE workouts ADD COLUMN program_id INTEGER`)
ensureIndex("idx_workouts_program", `CREATE INDEX IF NOT EXISTS idx_workouts_program ON workouts(program_id)`)
+ // Bumped whenever the account's credentials change, and carried in every token as
+ // the "ver" claim. Refresh compares the two and refuses a token minted before the
+ // bump, which is the only way a stateless JWT can be revoked: without it a stolen
+ // refresh token outlives a password change by its full 30-day life, defeating the
+ // entire point of changing the password. Existing rows start at 1, matching the
+ // tokens already in the wild, so nobody is signed out by the upgrade itself.
+ ensureColumn("users", "token_version", `ALTER TABLE users ADD COLUMN token_version INTEGER NOT NULL DEFAULT 1`)
+
// The zone the server buckets this user's day-scoped data in. Defaults to UTC,
// which is exactly the behaviour every existing row was written under, so this
// column changes nothing until a client reports a real zone.
@@ -662,6 +670,7 @@ CREATE TABLE IF NOT EXISTS users (
id INTEGER PRIMARY KEY AUTOINCREMENT,
email TEXT NOT NULL UNIQUE,
password_hash TEXT NOT NULL,
+ token_version INTEGER NOT NULL DEFAULT 1,
created_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
updated_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP
);
diff --git a/backend/go.mod b/backend/go.mod
index 5156105..babfb56 100644
--- a/backend/go.mod
+++ b/backend/go.mod
@@ -9,6 +9,7 @@ require (
github.com/golang-jwt/jwt/v5 v5.3.1
github.com/joho/godotenv v1.5.1
golang.org/x/crypto v0.50.0
+ golang.org/x/term v0.42.0
modernc.org/sqlite v1.49.1
)
diff --git a/backend/go.sum b/backend/go.sum
index 6bf7cdc..1921b26 100644
--- a/backend/go.sum
+++ b/backend/go.sum
@@ -101,6 +101,8 @@ golang.org/x/sync v0.20.0/go.mod h1:9xrNwdLfx4jkKbNva9FpL6vEN7evnE43NNNJQ2LF3+0=
golang.org/x/sys v0.6.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.43.0 h1:Rlag2XtaFTxp19wS8MXlJwTvoh8ArU6ezoyFsMyCTNI=
golang.org/x/sys v0.43.0/go.mod h1:4GL1E5IUh+htKOUEOaiffhrAeqysfVGipDYzABqnCmw=
+golang.org/x/term v0.42.0 h1:UiKe+zDFmJobeJ5ggPwOshJIVt6/Ft0rcfrXZDLWAWY=
+golang.org/x/term v0.42.0/go.mod h1:Dq/D+snpsbazcBG5+F9Q1n2rXV8Ma+71xEjTRufARgY=
golang.org/x/text v0.36.0 h1:JfKh3XmcRPqZPKevfXVpI1wXPTqbkE5f7JA92a55Yxg=
golang.org/x/text v0.36.0/go.mod h1:NIdBknypM8iqVmPiuco0Dh6P5Jcdk8lJL0CUebqK164=
golang.org/x/tools v0.43.0 h1:12BdW9CeB3Z+J/I/wj34VMl8X+fEXBxVR90JeMX5E7s=
diff --git a/backend/main.go b/backend/main.go
index ee5b6ef..25ba91d 100644
--- a/backend/main.go
+++ b/backend/main.go
@@ -5,6 +5,8 @@ import (
"fmt"
"log"
"os"
+ "sort"
+ "strings"
"github.com/Cawlumm/lyftr-backend/config"
"github.com/Cawlumm/lyftr-backend/controllers"
@@ -42,7 +44,42 @@ func warnIfUnclaimed() {
"data volume is not mounted: stop it before someone else claims it.")
}
+// subcommands are the non-server entry points on this binary. Dispatched before
+// flag.Parse, which would otherwise treat the name as a positional argument and start the
+// server as usual.
+var subcommands = map[string]func(args []string) int{
+ "reset-password": runResetPassword,
+}
+
+// dispatchSubcommand runs a subcommand and reports its exit code, or -1 to carry on and
+// start the server.
+//
+// A bare word that is not a known subcommand is an error rather than something to ignore:
+// `lyftr-api reset-passwrod [email protected]` would otherwise silently boot the API, look
+// like it worked, and leave the operator believing a password had been reset. Anything
+// starting with "-" is left alone for flag.Parse.
+func dispatchSubcommand(argv []string) int {
+ if len(argv) < 2 || strings.HasPrefix(argv[1], "-") {
+ return -1
+ }
+ if run, ok := subcommands[argv[1]]; ok {
+ return run(argv[2:])
+ }
+ names := make([]string, 0, len(subcommands))
+ for name := range subcommands {
+ names = append(names, name)
+ }
+ sort.Strings(names)
+ fmt.Fprintf(os.Stderr, "unknown command %q\n", argv[1])
+ fmt.Fprintf(os.Stderr, "available commands: %s\n", strings.Join(names, ", "))
+ return 2
+}
+
func main() {
+ if code := dispatchSubcommand(os.Args); code >= 0 {
+ os.Exit(code)
+ }
+
showVersion := flag.Bool("version", false, "print the build version and exit")
flag.Parse()
if *showVersion {
diff --git a/backend/main_test.go b/backend/main_test.go
new file mode 100644
index 0000000..245f304
--- /dev/null
+++ b/backend/main_test.go
@@ -0,0 +1,34 @@
+package main
+
+import "testing"
+
+// A bare word that is not a subcommand used to fall through to the server. `reset-passwrod
+// [email protected]` would boot the API, exit 0 on shutdown, and leave the operator
+// believing a password had been reset.
+func TestDispatchSubcommand(t *testing.T) {
+ cases := []struct {
+ name string
+ argv []string
+ want int
+ }{
+ {"no args starts the server", []string{"lyftr-api"}, -1},
+ {"a flag is left for flag.Parse", []string{"lyftr-api", "-version"}, -1},
+ {"a long flag is left for flag.Parse", []string{"lyftr-api", "--version"}, -1},
+ {"an unknown word is rejected", []string{"lyftr-api", "reset-passwrod", "[email protected]"}, 2},
+ {"an unknown word with no args is rejected", []string{"lyftr-api", "serve"}, 2},
+ }
+ for _, tc := range cases {
+ t.Run(tc.name, func(t *testing.T) {
+ if got := dispatchSubcommand(tc.argv); got != tc.want {
+ t.Errorf("dispatchSubcommand(%q) = %d, want %d", tc.argv, got, tc.want)
+ }
+ })
+ }
+}
+
+// The table is the registry; a name in it must be dispatchable.
+func TestResetPasswordIsRegistered(t *testing.T) {
+ if _, ok := subcommands["reset-password"]; !ok {
+ t.Fatal("reset-password is not in the subcommand table")
+ }
+}
diff --git a/backend/models/models.go b/backend/models/models.go
index 717aaa4..c5e2ce8 100644
--- a/backend/models/models.go
+++ b/backend/models/models.go
@@ -3,11 +3,13 @@ package models
import "time"
type User struct {
- ID int64 `json:"id" db:"id"`
- Email string `json:"email" db:"email"`
- Password string `json:"-" db:"password_hash"`
- CreatedAt time.Time `json:"created_at" db:"created_at"`
- UpdatedAt time.Time `json:"updated_at" db:"updated_at"`
+ ID int64 `json:"id" db:"id"`
+ Email string `json:"email" db:"email"`
+ Password string `json:"-" db:"password_hash"`
+ // TokenVersion is a server-side detail; like the hash it must never reach a client.
+ TokenVersion int `json:"-" db:"token_version"`
+ CreatedAt time.Time `json:"created_at" db:"created_at"`
+ UpdatedAt time.Time `json:"updated_at" db:"updated_at"`
}
type UserSettings struct {
@@ -208,6 +210,16 @@ type RefreshRequest struct {
RefreshToken string `json:"refresh_token" validate:"required"`
}
+// ChangePasswordRequest re-authenticates the caller before the change. A valid access
+// token is not enough on its own: it is exactly what an attacker holding a hijacked
+// session already has, and letting that alone rewrite the password would turn session
+// theft into permanent account takeover. min=8 mirrors RegisterRequest so the two
+// cannot drift into a weaker password being settable than is registerable.
+type ChangePasswordRequest struct {
+ CurrentPassword string `json:"current_password" validate:"required"`
+ NewPassword string `json:"new_password" validate:"required,min=8"`
+}
+
// MaxWorkoutSets bounds the TOTAL number of sets across every exercise in a
// CreateWorkoutRequest (sum of len(Exercises[i].Sets), not each list's own max=500
// below independently) — enforced by the struct-level validation registered in
diff --git a/backend/resetpassword.go b/backend/resetpassword.go
new file mode 100644
index 0000000..4583ba2
--- /dev/null
+++ b/backend/resetpassword.go
@@ -0,0 +1,134 @@
+package main
+
+import (
+ "bufio"
+ "errors"
+ "fmt"
+ "os"
+ "strings"
+ "unicode/utf8"
+
+ "github.com/Cawlumm/lyftr-backend/config"
+ "github.com/Cawlumm/lyftr-backend/db"
+ "github.com/Cawlumm/lyftr-backend/stores"
+ "github.com/Cawlumm/lyftr-backend/utils"
+ "golang.org/x/term"
+)
+
+// minPasswordLength mirrors the `min=8` on RegisterRequest. An operator reset must not be
+// a way to set a password the app itself would refuse.
+const minPasswordLength = 8
+
+const resetUsage = `usage: lyftr-api reset-password <email>
+
+Sets a new password for an account whose password is lost, and signs out every
+session that account currently has.
+
+Run it against the container holding your data volume:
+
+ docker compose exec backend ./lyftr-api reset-password [email protected]
+`
+
+// runResetPassword is the operator's recovery path. There is no self-service reset: a
+// self-hosted instance has no mail server to send a link through, so recovery belongs to
+// whoever has a shell on the box.
+//
+// The password is prompted for, never taken as a flag. A --password argument is visible in
+// `ps`, in shell history, and in any process-listing the container exports, which is why
+// Immich, Nextcloud, wger and Paperless all prompt. Gitea's --password flag is the odd one
+// out and carries exactly those problems.
+//
+// Returns the process exit code.
+func runResetPassword(args []string) int {
+ if len(args) != 1 || strings.HasPrefix(args[0], "-") {
+ fmt.Fprint(os.Stderr, resetUsage)
+ return 2
+ }
+ email := strings.TrimSpace(args[0])
+
+ // Load config and open the database exactly as the server does, so the command reads
+ // the same DB_PATH the running instance uses and cannot quietly touch a different file.
+ config.Load()
+ db.Connect()
+
+ password, err := readNewPassword()
+ if err != nil {
+ fmt.Fprintf(os.Stderr, "\n%v\n", err)
+ return 1
+ }
+
+ hash, err := utils.HashPassword(password)
+ if err != nil {
+ fmt.Fprintf(os.Stderr, "hashing failed: %v\n", err)
+ return 1
+ }
+
+ s := stores.New(db.DB)
+ if err := s.User.ResetPassword(email, hash); err != nil {
+ if errors.Is(err, stores.ErrNoSuchUser) {
+ fmt.Fprintf(os.Stderr, "no account found for %s\n", email)
+ // Addresses match exactly here and at login, so a case slip looks identical
+ // to a missing account. Someone recovering an account they cannot get into
+ // should not be left concluding it is gone.
+ if stored, ferr := s.User.FindEmailFold(email); ferr == nil && stored != email {
+ fmt.Fprintf(os.Stderr, "did you mean %s? addresses are case-sensitive.\n", stored)
+ }
+ return 1
+ }
+ fmt.Fprintf(os.Stderr, "reset failed: %v\n", err)
+ return 1
+ }
+
+ fmt.Printf("Password reset for %s.\n", email)
+ fmt.Println("Every existing session for that account has been signed out.")
+ return 0
+}
+
+// readNewPassword prompts twice with echo off. When stdin is not a terminal — a piped
+// heredoc, or `docker compose exec` without -it — it falls back to reading plain lines,
+// so the command still works unattended instead of failing on an ioctl.
+func readNewPassword() (string, error) {
+ fd := int(os.Stdin.Fd())
+ if !term.IsTerminal(fd) {
+ r := bufio.NewReader(os.Stdin)
+ line, err := r.ReadString('\n')
+ if err != nil && line == "" {
+ return "", errors.New("no password on stdin (run with -it for a prompt)")
+ }
+ return validatePassword(strings.TrimRight(line, "\r\n"))
+ }
+
+ fmt.Print("New password: ")
+ first, err := term.ReadPassword(fd)
+ fmt.Println()
+ if err != nil {
+ return "", fmt.Errorf("could not read password: %w", err)
+ }
+
+ fmt.Print("Confirm password: ")
+ second, err := term.ReadPassword(fd)
+ fmt.Println()
+ if err != nil {
+ return "", fmt.Errorf("could not read password: %w", err)
+ }
+
+ if string(first) != string(second) {
+ return "", errors.New("passwords do not match")
+ }
+ return validatePassword(string(first))
+}
+
+func validatePassword(p string) (string, error) {
+ // Runes, not bytes, because the API's `min=8` tag counts runes — counting bytes here
+ // let the CLI set a short passphrase of multibyte characters that the app itself
+ // would refuse, so the two disagreed about the same password.
+ if utf8.RuneCountInString(p) < minPasswordLength {
+ return "", fmt.Errorf("password must be at least %d characters", minPasswordLength)
+ }
+ // Bytes, because this limit is bcrypt's and bcrypt counts bytes. Checked here so the
+ // operator gets the same sentence the API gives, rather than a raw hashing error.
+ if utils.PasswordTooLong(p) {
+ return "", errors.New(utils.PasswordTooLongMessage)
+ }
+ return p, nil
+}
diff --git a/backend/resetpassword_test.go b/backend/resetpassword_test.go
new file mode 100644
index 0000000..61e4b48
--- /dev/null
+++ b/backend/resetpassword_test.go
@@ -0,0 +1,177 @@
+package main
+
+import (
+ "os"
+ "strings"
+ "testing"
+ "unicode/utf8"
+
+ "github.com/Cawlumm/lyftr-backend/utils"
+)
+
+// validatePassword is the only thing standing between an operator reset and a password
+// shorter than the one the API itself enforces (`min=8` on both auth requests). A reset
+// that quietly accepts "abc" would leave an account weaker than any the app would let a
+// user choose, on the one code path that exists precisely because someone is locked out.
+func TestValidatePassword(t *testing.T) {
+ cases := []struct {
+ name string
+ in string
+ wantErr bool
+ }{
+ {"empty", "", true},
+ {"one short", strings.Repeat("a", minPasswordLength-1), true},
+ {"exactly the minimum", strings.Repeat("a", minPasswordLength), false},
+ {"comfortably long", "a-perfectly-fine-password", false},
+ // 5 runes, so short whichever way you count — the rune-vs-byte distinction is
+ // pinned properly in TestValidatePasswordLength.
+ {"multibyte below the minimum", "héllo", true},
+ }
+
+ for _, tc := range cases {
+ t.Run(tc.name, func(t *testing.T) {
+ got, err := validatePassword(tc.in)
+ if tc.wantErr {
+ if err == nil {
+ t.Fatalf("validatePassword(%q) = %q, want an error", tc.in, got)
+ }
+ if got != "" {
+ t.Errorf("validatePassword(%q) returned %q alongside its error, want empty", tc.in, got)
+ }
+ return
+ }
+ if err != nil {
+ t.Fatalf("validatePassword(%q) errored: %v", tc.in, err)
+ }
+ if got != tc.in {
+ t.Errorf("validatePassword(%q) = %q, want the input back unchanged", tc.in, got)
+ }
+ })
+ }
+}
+
+// withStdin replaces os.Stdin with a pipe carrying `input`. A pipe is not a terminal, so
+// readNewPassword takes its non-TTY branch — which is the documented unattended path:
+//
+// echo 'new-password' | docker compose exec -T backend ./lyftr-api reset-password …
+func withStdin(t *testing.T, input string) {
+ t.Helper()
+
+ r, w, err := os.Pipe()
+ if err != nil {
+ t.Fatalf("os.Pipe: %v", err)
+ }
+ if _, err := w.WriteString(input); err != nil {
+ t.Fatalf("write to pipe: %v", err)
+ }
+ w.Close()
+
+ orig := os.Stdin
+ os.Stdin = r
+ t.Cleanup(func() {
+ os.Stdin = orig
+ r.Close()
+ })
+}
+
+func TestReadNewPasswordFromPipe(t *testing.T) {
+ t.Run("takes the line as the password", func(t *testing.T) {
+ withStdin(t, "piped-password\n")
+ got, err := readNewPassword()
+ if err != nil {
+ t.Fatalf("readNewPassword: %v", err)
+ }
+ if got != "piped-password" {
+ t.Errorf("got %q, want %q", got, "piped-password")
+ }
+ })
+
+ // A heredoc written on Windows, or any CRLF pipeline, would otherwise store a
+ // password with a trailing \r that the operator can never type back.
+ t.Run("strips a trailing CRLF", func(t *testing.T) {
+ withStdin(t, "piped-password\r\n")
+ got, err := readNewPassword()
+ if err != nil {
+ t.Fatalf("readNewPassword: %v", err)
+ }
+ if got != "piped-password" {
+ t.Errorf("got %q, want the \\r stripped", got)
+ }
+ })
+
+ // No trailing newline at all — `printf '%s' pw |` — is still a password.
+ t.Run("accepts a final line with no newline", func(t *testing.T) {
+ withStdin(t, "piped-password")
+ got, err := readNewPassword()
+ if err != nil {
+ t.Fatalf("readNewPassword: %v", err)
+ }
+ if got != "piped-password" {
+ t.Errorf("got %q, want %q", got, "piped-password")
+ }
+ })
+
+ // This branch skips the confirmation prompt entirely — nothing is typed twice — so
+ // the length check is the only guard left on it.
+ t.Run("still enforces the minimum length", func(t *testing.T) {
+ withStdin(t, "short\n")
+ if _, err := readNewPassword(); err == nil {
+ t.Fatal("readNewPassword accepted a password below the minimum")
+ }
+ })
+
+ t.Run("reports empty stdin rather than setting an empty password", func(t *testing.T) {
+ withStdin(t, "")
+ got, err := readNewPassword()
+ if err == nil {
+ t.Fatalf("readNewPassword returned %q for empty stdin, want an error", got)
+ }
+ if !strings.Contains(err.Error(), "no password on stdin") {
+ t.Errorf("error was %q, want it to name the empty stdin", err)
+ }
+ })
+}
+
+// bcrypt refuses anything over 72 bytes rather than truncating it, so this is a hard
+// storage limit, not a policy. The CLI must say so itself — surfacing a raw
+// "bcrypt: password length exceeds 72 bytes" is the operator's problem to decode.
+func TestValidatePasswordLength(t *testing.T) {
+ t.Run("accepts exactly the byte limit", func(t *testing.T) {
+ p := strings.Repeat("a", utils.MaxPasswordBytes)
+ if _, err := validatePassword(p); err != nil {
+ t.Fatalf("rejected a password at the limit: %v", err)
+ }
+ })
+
+ t.Run("rejects one byte over", func(t *testing.T) {
+ p := strings.Repeat("a", utils.MaxPasswordBytes+1)
+ _, err := validatePassword(p)
+ if err == nil {
+ t.Fatal("accepted a password bcrypt cannot hash")
+ }
+ if err.Error() != utils.PasswordTooLongMessage {
+ t.Errorf("error was %q, want the shared message", err)
+ }
+ })
+
+ // The limit is bytes, so multibyte input hits it far below 72 characters. 19 of these
+ // is 76 bytes — a passphrase that looks short and still cannot be stored.
+ t.Run("counts the maximum in bytes, not characters", func(t *testing.T) {
+ p := strings.Repeat("\U0001F3CB", 19)
+ if utf8.RuneCountInString(p) >= utils.MaxPasswordBytes {
+ t.Fatalf("test input is not the case being covered: %d runes", utf8.RuneCountInString(p))
+ }
+ if _, err := validatePassword(p); err == nil {
+ t.Error("accepted 76 bytes because it counted 19 characters")
+ }
+ })
+
+ // The minimum is the opposite: runes, matching the API's `min=8` tag. Counting bytes
+ // let the CLI set a 5-character passphrase the app would have refused.
+ t.Run("counts the minimum in runes, not bytes", func(t *testing.T) {
+ p := strings.Repeat("\U0001F3CB", 5) // 5 runes, 20 bytes
+ if _, err := validatePassword(p); err == nil {
+ t.Error("accepted 5 characters because it counted 20 bytes")
+ }
+ })
+}
diff --git a/backend/routes/routes.go b/backend/routes/routes.go
index 453d349..06e1e78 100644
--- a/backend/routes/routes.go
+++ b/backend/routes/routes.go
@@ -39,6 +39,7 @@ func Setup(r *gin.Engine, h *controllers.Handler) {
protected.GET("me", h.GetMe)
protected.GET("settings", h.GetSettings)
protected.PUT("settings", h.UpdateSettings)
+ protected.PUT("me/password", h.ChangePassword)
protected.DELETE("me", h.DeleteAccount)
// Workouts
diff --git a/backend/stores/user.go b/backend/stores/user.go
index 436ecda..3b9538c 100644
--- a/backend/stores/user.go
+++ b/backend/stores/user.go
@@ -23,11 +23,72 @@ func (s *UserStore) GetMe(uid int64) (models.User, error) {
func (s *UserStore) GetByEmail(email string) (models.User, error) {
var u models.User
err := s.db.QueryRow(
- `SELECT id, email, password_hash, created_at, updated_at FROM users WHERE email = ?`, email,
- ).Scan(&u.ID, &u.Email, &u.Password, &u.CreatedAt, &u.UpdatedAt)
+ `SELECT id, email, password_hash, token_version, created_at, updated_at FROM users WHERE email = ?`, email,
+ ).Scan(&u.ID, &u.Email, &u.Password, &u.TokenVersion, &u.CreatedAt, &u.UpdatedAt)
return u, err
}
+// GetByID is GetByEmail for an already-authenticated caller: it carries the hash, so
+// the password-change handler can verify the current password without trusting the
+// email in the token. sql.ErrNoRows if the account was deleted mid-session.
+func (s *UserStore) GetByID(uid int64) (models.User, error) {
+ var u models.User
+ err := s.db.QueryRow(
+ `SELECT id, email, password_hash, token_version, created_at, updated_at FROM users WHERE id = ?`, uid,
+ ).Scan(&u.ID, &u.Email, &u.Password, &u.TokenVersion, &u.CreatedAt, &u.UpdatedAt)
+ return u, err
+}
+
+// TokenVersion returns the account's current token generation, or sql.ErrNoRows if the
+// account is gone. Read on refresh only — never on the per-request auth path, which
+// stays free of database work.
+func (s *UserStore) TokenVersion(uid int64) (int, error) {
+ var v int
+ err := s.db.QueryRow(`SELECT token_version FROM users WHERE id = ?`, uid).Scan(&v)
+ return v, err
+}
+
+// ErrPasswordChanged means the stored hash moved between the handler reading it and
+// this update running — a second password change racing the first.
+var ErrPasswordChanged = errors.New("password changed concurrently")
+
+// ChangePassword swaps the hash and invalidates every token minted against the old one,
+// returning the new token version so the caller can re-issue a pair for the device that
+// made the change.
+//
+// The UPDATE is conditional on the hash the handler verified. Two concurrent changes
+// would otherwise both pass verification against the same old hash and both write, so
+// the loser's password would silently win while its user was told it had been set —
+// and both would land on token_version+1 rather than +2, leaving the first change's
+// tokens alive. Compare-and-set makes the loser fail loudly instead.
+func (s *UserStore) ChangePassword(uid int64, oldHash, newHash string) (int, error) {
+ if newHash == "" {
+ return 0, ErrEmptyHash
+ }
+ v, err := inTx(s.db, func(tx *sql.Tx) (int64, error) {
+ res, err := tx.Exec(
+ `UPDATE users SET password_hash = ?, token_version = token_version + 1,
+ updated_at = CURRENT_TIMESTAMP
+ WHERE id = ? AND password_hash = ?`, newHash, uid, oldHash)
+ if err != nil {
+ return 0, err
+ }
+ n, err := res.RowsAffected()
+ if err != nil {
+ return 0, err
+ }
+ if n == 0 {
+ return 0, ErrPasswordChanged
+ }
+ var v int
+ if err := tx.QueryRow(`SELECT token_version FROM users WHERE id = ?`, uid).Scan(&v); err != nil {
+ return 0, err
+ }
+ return int64(v), nil
+ })
+ return int(v), err
+}
+
const userSettingsSelect = `SELECT user_id, weight_unit, calorie_target, protein_target, carb_target, fat_target, timezone FROM user_settings`
// GetSettings returns the user's settings row, or sql.ErrNoRows if none (the
@@ -126,6 +187,58 @@ func createUserTx(tx *sql.Tx, email, hash string) (int64, error) {
return uid, nil
}
+// ErrEmptyHash guards the two statements that WRITE a password. Everywhere else an
+// empty argument simply matches no rows and surfaces as an error, so a guard would be
+// noise -- but these two would store the empty string, and bcrypt rejects it against
+// every password, silently locking the account out while still bumping token_version.
+// A caller that forgets to hash should fail loudly instead.
+var ErrEmptyHash = errors.New("refusing to store an empty password hash")
+
+// ErrNoSuchUser means no account carries that address.
+var ErrNoSuchUser = errors.New("no account with that email")
+
+// FindEmailFold returns the stored address matching email case-insensitively, or
+// sql.ErrNoRows. Addresses are stored and matched exactly everywhere else — including at
+// login — so this exists only to turn "no account found" into a useful message for an
+// operator who typed the wrong case while recovering an account. It must not become a way
+// to authenticate, which is why it returns the stored spelling rather than the row.
+func (s *UserStore) FindEmailFold(email string) (string, error) {
+ var stored string
+ err := s.db.QueryRow(
+ `SELECT email FROM users WHERE email = ? COLLATE NOCASE`, email,
+ ).Scan(&stored)
+ return stored, err
+}
+
+// ResetPassword is the operator's way in, for the account whose password is lost. Unlike
+// ChangePassword there is no old hash to verify against — the whole point is that nobody
+// knows it — so this is keyed on email and guarded only by having a shell on the server.
+//
+// It bumps token_version for the same reason the in-app change does, and here it matters
+// more: an operator resetting a password may be doing it because someone else got in, and
+// a new password is worthless while the intruder's refresh token still mints access
+// tokens for the rest of its 30 days.
+func (s *UserStore) ResetPassword(email, newHash string) error {
+ if newHash == "" {
+ return ErrEmptyHash
+ }
+ res, err := s.db.Exec(
+ `UPDATE users SET password_hash = ?, token_version = token_version + 1,
+ updated_at = CURRENT_TIMESTAMP
+ WHERE email = ?`, newHash, email)
+ if err != nil {
+ return err
+ }
+ n, err := res.RowsAffected()
+ if err != nil {
+ return err
+ }
+ if n == 0 {
+ return ErrNoSuchUser
+ }
+ return nil
+}
+
// Delete removes the user; child rows go via ON DELETE CASCADE (foreign_keys=on).
func (s *UserStore) Delete(uid int64) error {
_, err := s.db.Exec(`DELETE FROM users WHERE id = ?`, uid)
diff --git a/backend/utils/jwt.go b/backend/utils/jwt.go
index efe5bf6..ef44513 100644
--- a/backend/utils/jwt.go
+++ b/backend/utils/jwt.go
@@ -13,28 +13,46 @@ type Claims struct {
UserID int64 `json:"user_id"`
Email string `json:"email"`
Type string `json:"type"` // "access" or "refresh"
+ // TokenVersion is the users.token_version this token was minted against. Refresh
+ // rejects a mismatch, which is what makes a password change actually end other
+ // sessions. Absent in tokens issued before the claim existed, so it decodes as 0
+ // there — see NormalizeTokenVersion.
+ TokenVersion int `json:"ver,omitempty"`
jwt.RegisteredClaims
}
-func GenerateTokenPair(userID int64, email string) (access, refresh string, err error) {
+// NormalizeTokenVersion maps a token's version onto the same scale as the stored
+// column. Tokens minted before the "ver" claim existed decode as 0; accounts have
+// always started at 1. Folding 0 up to 1 keeps everyone signed in across the upgrade
+// while still invalidating those legacy tokens the moment a password change moves the
+// account to 2.
+func NormalizeTokenVersion(v int) int {
+ if v < 1 {
+ return 1
+ }
+ return v
+}
+
+func GenerateTokenPair(userID int64, email string, tokenVersion int) (access, refresh string, err error) {
expiry, _ := strconv.Atoi(config.C.JWTExpiry)
if expiry == 0 {
expiry = 3600
}
- access, err = generateToken(userID, email, "access", time.Duration(expiry)*time.Second)
+ access, err = generateToken(userID, email, "access", tokenVersion, time.Duration(expiry)*time.Second)
if err != nil {
return
}
- refresh, err = generateToken(userID, email, "refresh", 30*24*time.Hour)
+ refresh, err = generateToken(userID, email, "refresh", tokenVersion, 30*24*time.Hour)
return
}
-func generateToken(userID int64, email, tokenType string, dur time.Duration) (string, error) {
+func generateToken(userID int64, email, tokenType string, tokenVersion int, dur time.Duration) (string, error) {
claims := Claims{
- UserID: userID,
- Email: email,
- Type: tokenType,
+ UserID: userID,
+ Email: email,
+ Type: tokenType,
+ TokenVersion: NormalizeTokenVersion(tokenVersion),
RegisteredClaims: jwt.RegisteredClaims{
ExpiresAt: jwt.NewNumericDate(time.Now().Add(dur)),
IssuedAt: jwt.NewNumericDate(time.Now()),
diff --git a/backend/utils/password.go b/backend/utils/password.go
index ed7549a..3d75ad9 100644
--- a/backend/utils/password.go
+++ b/backend/utils/password.go
@@ -2,6 +2,28 @@ package utils
import "golang.org/x/crypto/bcrypt"
+// MaxPasswordBytes is bcrypt's own hard limit, not a policy choice.
+// GenerateFromPassword refuses anything longer rather than silently truncating, so a
+// password over this length cannot be stored at all.
+//
+// Counted in BYTES, which is why it is checked here rather than with the validator's
+// `max` tag: that tag counts runes, and a 19-character emoji passphrase is 76 bytes.
+// The `min=8` tag stays rune-counted, which is the right unit for a minimum.
+const MaxPasswordBytes = 72
+
+// PasswordTooLong reports whether bcrypt would reject this password outright.
+//
+// Callers must check before hashing. Without it the bcrypt error surfaces as a 500, which
+// tells the user the server broke and to try again — advice that can never work, on input
+// a password manager produces by default.
+func PasswordTooLong(plain string) bool {
+ return len(plain) > MaxPasswordBytes
+}
+
+// PasswordTooLongMessage is the one wording for the limit, so the two handlers and the
+// reset-password command cannot describe it differently.
+const PasswordTooLongMessage = "password must be 72 bytes or fewer (accented letters and emoji count for more than one)"
+
func HashPassword(plain string) (string, error) {
b, err := bcrypt.GenerateFromPassword([]byte(plain), bcrypt.DefaultCost)
return string(b), err
@@ -10,3 +32,26 @@ func HashPassword(plain string) (string, error) {
func CheckPassword(plain, hash string) bool {
return bcrypt.CompareHashAndPassword([]byte(hash), []byte(plain)) == nil
}
+
+// decoyHash is a real bcrypt hash at the same cost as a stored one. It exists to be
+// compared against when no account matched, so a sign-in attempt for an address that does
+// not exist costs the same as one for an address that does.
+//
+// Without it the two branches are trivially distinguishable: a miss returns before hashing
+// and a hit pays a full bcrypt round, which measured 8.7ms against 105.7ms — a 12x signal
+// that hands out a list of which addresses are registered. The handlers already answer
+// both cases with the same sentence for exactly that reason; the timing undid it.
+//
+// Generated at init from a fixed string, not a constant, so it always matches whatever
+// cost bcrypt.DefaultCost currently is.
+var decoyHash []byte
+
+func init() {
+ decoyHash, _ = bcrypt.GenerateFromPassword([]byte("decoy-for-constant-time-login"), bcrypt.DefaultCost)
+}
+
+// BurnPasswordComparison spends the work a real password check would, and discards it.
+// Call it on the no-such-account path before answering.
+func BurnPasswordComparison(plain string) {
+ _ = bcrypt.CompareHashAndPassword(decoyHash, []byte(plain))
+}
diff --git a/fly/nginx.fly.conf b/fly/nginx.fly.conf
index 0a9194a..5a4e518 100644
--- a/fly/nginx.fly.conf
+++ b/fly/nginx.fly.conf
@@ -29,6 +29,21 @@ server {
proxy_pass http://localhost:3000/health;
}
+ # W3C Change Password URL. Password managers (Safari Keychain, Chrome Password
+ # Checkup, 1Password) open this path to take a user straight to the change-password
+ # form. Exact-match so it wins over the SPA fallback, which would otherwise answer
+ # with index.html and leave React Router to bounce an unauthenticated visitor to
+ # /login. The dev/preview equivalent lives in web/vite.config.ts.
+ location = /.well-known/change-password {
+ # absolute_redirect off keeps the Location relative. With nginx's default (on) it
+ # would expand to an absolute URL built from $scheme — and this block listens on
+ # 80 behind a TLS terminator, so that scheme is http. A manager opening the https
+ # well-known URL would be bounced to cleartext and left to whatever the outer
+ # proxy does about it. Relative inherits the request's real scheme.
+ absolute_redirect off;
+ return 302 /settings/password;
+ }
+
# SPA fallback
location / {
try_files $uri $uri/ /index.html;
diff --git a/mobile/app/(auth)/register.tsx b/mobile/app/(auth)/register.tsx
index 4ed3472..c30cc5e 100644
--- a/mobile/app/(auth)/register.tsx
+++ b/mobile/app/(auth)/register.tsx
@@ -2,8 +2,9 @@ import { useState } from 'react'
import { Text, View } from 'react-native'
import { Link } from 'expo-router'
import { AuthScaffold } from '../../src/components/AuthScaffold'
+import { PasswordRule } from '../../src/components/ui'
import { IconInput, GradientButton, AuthError, ServerRow, Footer } from '../../src/components/authui'
-import { registrationOpen } from '@lyftr/shared'
+import { registrationOpen, lengthRuleLabel, matchRuleLabel, newPasswordRules } from '@lyftr/shared'
import { useAuthStore, useServerInfo } from '../../src/lib/lyftr'
import { useTheme } from '../../src/theme/useTheme'
@@ -15,7 +16,9 @@ export default function Register() {
const [email, setEmail] = useState('')
const [password, setPassword] = useState('')
const [passwordConfirm, setPasswordConfirm] = useState('')
- // Client-side validation errors (match / length), shown on submit like the web form.
+ // Only the email check lands here now — the password rules render under their own
+ // fields as the user types (see below), so this holds the one error that has nowhere
+ // else to go, plus whatever the server says.
const [localError, setLocalError] = useState<string | null>(null)
const register = useAuthStore((s) => s.register)
const loading = useAuthStore((s) => s.isLoading)
@@ -29,12 +32,15 @@ export default function Register() {
setter(t)
}
- // Validate only on submit (not while typing) — same checks, same order, same copy
- // as web/src/pages/Register.tsx, surfaced after the user presses Create account.
+ // Password rules come from @lyftr/shared, the same call web/src/pages/Register.tsx
+ // makes. They used to be two hand-written checks per app, which is how the wording
+ // drifted apart; now neither app can accept a password the other refuses.
+ const rules = newPasswordRules({ password, confirm: passwordConfirm })
+
const submit = async () => {
if (!EMAIL_RE.test(email.trim())) { setLocalError('Enter a valid email address'); return }
- if (password !== passwordConfirm) { setLocalError('Passwords do not match'); return }
- if (password.length < 8) { setLocalError('Password must be at least 8 characters'); return }
+ // Backstop — the button is disabled until the rules pass.
+ if (!rules.ready) return
setLocalError(null)
try { await register(email.trim(), password) } catch {}
}
@@ -86,8 +92,11 @@ export default function Register() {
password
value={password}
onChangeText={onChange(setPassword)}
- placeholder="At least 8 characters"
+ placeholder="••••••••"
/>
+ <View className="gap-1.5 mt-2">
+ <PasswordRule state={rules.length}>{lengthRuleLabel(password)}</PasswordRule>
+ </View>
<IconInput
label="Confirm password"
icon="lock"
@@ -96,8 +105,11 @@ export default function Register() {
onChangeText={onChange(setPasswordConfirm)}
placeholder="••••••••"
/>
+ <View className="gap-1.5 mt-2">
+ <PasswordRule state={rules.match}>{matchRuleLabel(rules.match)}</PasswordRule>
+ </View>
{shownError ? <AuthError message={shownError} /> : null}
- <GradientButton title="Create account" onPress={submit} loading={loading} />
+ <GradientButton title="Create account" onPress={submit} loading={loading} disabled={!rules.ready} />
<Footer>
<View style={{ flexDirection: 'row', gap: 5 }}>
<Text style={{ color: colors.txSecondary, fontFamily: 'PlusJakartaSans_600SemiBold', fontSize: 14 }}>Have an account?</Text>
diff --git a/mobile/app/(tabs)/settings/_layout.tsx b/mobile/app/(tabs)/settings/_layout.tsx
new file mode 100644
index 0000000..402f220
--- /dev/null
+++ b/mobile/app/(tabs)/settings/_layout.tsx
@@ -0,0 +1,17 @@
+import { Stack } from 'expo-router'
+import { useTheme } from '../../../src/theme/useTheme'
+
+// Nested stack under Settings: list → change password. Same shape and same reason as the
+// workouts and weight stacks — contentStyle pins the card background to the app surface so
+// the push transition doesn't flash the platform default.
+export default function SettingsLayout() {
+ const { colors } = useTheme()
+ return (
+ <Stack
+ screenOptions={{
+ headerShown: false,
+ contentStyle: { backgroundColor: colors.base },
+ }}
+ />
+ )
+}
diff --git a/mobile/app/(tabs)/settings.tsx b/mobile/app/(tabs)/settings/index.tsx
similarity index 96%
rename from mobile/app/(tabs)/settings.tsx
rename to mobile/app/(tabs)/settings/index.tsx
index 2263a3a..f1d8079 100644
--- a/mobile/app/(tabs)/settings.tsx
+++ b/mobile/app/(tabs)/settings/index.tsx
@@ -1,4 +1,4 @@
-import { useEffect, useMemo, useState } from 'react'
+import { useEffect, useState } from 'react'
import { Pressable, ScrollView, View } from 'react-native'
import { router } from 'expo-router'
import {
@@ -7,6 +7,7 @@ import {
Clock,
AlertTriangle,
Dumbbell,
+ KeyRound,
LogOut,
Mail,
Minus,
@@ -18,6 +19,7 @@ import {
Trash2,
} from 'lucide-react-native'
import {
+ memberSince,
normalizeServerUrl,
testServerConnection,
isInsecureServerUrl,
@@ -40,14 +42,9 @@ import {
Toast,
Toggle,
type ToastVariant,
-} from '../../src/components/ui'
-import { client, useAuthStore, useServerStore, useSettingsStore } from '../../src/lib/lyftr'
-import { useTheme } from '../../src/theme/useTheme'
-
-const MONTHS = [
- 'January', 'February', 'March', 'April', 'May', 'June',
- 'July', 'August', 'September', 'October', 'November', 'December',
-]
+} from '../../../src/components/ui'
+import { client, useAuthStore, useServerStore, useSettingsStore } from '../../../src/lib/lyftr'
+import { useTheme } from '../../../src/theme/useTheme'
const REST_PRESETS = [60, 90, 120, 180]
@@ -106,12 +103,6 @@ export default function SettingsScreen() {
})
}, [settings.calorie_target, settings.protein_target, settings.carb_target, settings.fat_target])
- const memberSince = useMemo(() => {
- if (!user?.created_at) return '—'
- const d = new Date(user.created_at)
- return `${MONTHS[d.getMonth()]} ${d.getFullYear()}`
- }, [user?.created_at])
-
const restEnabled = settings.rest_enabled ?? true
const restCur = settings.rest_seconds_default ?? 90
const restIsCustom = !REST_PRESETS.includes(restCur)
@@ -188,7 +179,15 @@ export default function SettingsScreen() {
{/* Account */}
<SettingsGroup title="Account">
<SettingsRow icon={Mail} label="Email" value={user?.email ?? '—'} />
- <SettingsRow icon={CalendarDays} label="Member since" value={memberSince} divider />
+ <SettingsRow icon={CalendarDays} label="Member since" value={memberSince(user?.created_at)} divider />
+ <SettingsRow
+ icon={KeyRound}
+ label="Password"
+ description="Changing it signs you out on your other devices"
+ divider
+ chevron
+ onPress={() => router.push('/settings/password')}
+ />
</SettingsGroup>
{/* Appearance */}
diff --git a/mobile/app/(tabs)/settings/password.tsx b/mobile/app/(tabs)/settings/password.tsx
new file mode 100644
index 0000000..1e0b4ad
--- /dev/null
+++ b/mobile/app/(tabs)/settings/password.tsx
@@ -0,0 +1,165 @@
+import { useState } from 'react'
+import { Pressable, ScrollView, View } from 'react-native'
+import { router } from 'expo-router'
+import { ArrowLeft, ShieldCheck } from 'lucide-react-native'
+import { apiErrorMessage, differentRuleLabel, lengthRuleLabel, matchRuleLabel, newPasswordRules } from '@lyftr/shared'
+import {
+ Alert,
+ AppText,
+ Button,
+ Card,
+ PageHeader,
+ PasswordField,
+ PasswordRule,
+ Screen,
+} from '../../../src/components/ui'
+import { client } from '../../../src/lib/lyftr'
+import { useTheme } from '../../../src/theme/useTheme'
+
+// Its own screen rather than a panel inside Settings, matching web's /settings/password.
+// Web needs the route so /.well-known/change-password has somewhere to redirect; mobile
+// follows so the two platforms stay one flow, and so this becomes deep-linkable if app
+// links are ever added.
+//
+// Laid out beat for beat with that page — back link, header, the form on a card, and a
+// centred confirmation card on success — so the two do not merely do the same thing, they
+// read as the same screen.
+export default function ChangePasswordScreen() {
+ const { colors, brand } = useTheme()
+
+ const [current, setCurrent] = useState('')
+ const [next, setNext] = useState('')
+ const [confirm, setConfirm] = useState('')
+ const [saving, setSaving] = useState(false)
+ const [error, setError] = useState<string | null>(null)
+ const [done, setDone] = useState(false)
+
+ const rules = newPasswordRules({ password: next, confirm, current })
+
+ const back = () => (router.canGoBack() ? router.back() : router.navigate('/settings'))
+
+ const submit = async () => {
+ setError(null)
+ // The rules render under the fields as the user types and the button stays disabled
+ // until they pass, so this is a backstop. The alert below is server failures only —
+ // a wrong current password, or a change that landed elsewhere first.
+ if (!rules.ready) return
+
+ setSaving(true)
+ try {
+ // The shared client persists the returned token pair, so this device stays signed
+ // in while every other one is evicted.
+ await client.userAPI.changePassword({ current_password: current, new_password: next })
+ setCurrent(''); setNext(''); setConfirm('')
+ setDone(true)
+ } catch (err: any) {
+ setError(apiErrorMessage(err, "Couldn't change your password. Please try again."))
+ } finally {
+ setSaving(false)
+ }
+ }
+
+ const backLink = (
+ <Pressable
+ onPress={back}
+ hitSlop={8}
+ className="flex-row items-center gap-1.5 self-start active:opacity-60"
+ >
+ <ArrowLeft size={16} color={colors.txMuted} />
+ <AppText variant="body" color="muted">Settings</AppText>
+ </Pressable>
+ )
+
+ // Success replaces the form rather than sitting above it. Three filled-looking boxes
+ // under a success banner invite a second submit that could only fail — the current
+ // password is no longer current. The card carries its own heading, so the page header
+ // is dropped here rather than saying the same words twice.
+ if (done) {
+ return (
+ <Screen>
+ <ScrollView showsVerticalScrollIndicator={false}>
+ <View className="gap-5 py-4">
+ {backLink}
+ <Card className="items-center gap-3 p-6">
+ <View className="h-12 w-12 items-center justify-center rounded-full border border-success-500/20 bg-success-500/10">
+ <ShieldCheck size={24} color={brand.successSoft} strokeWidth={2.2} />
+ </View>
+ <View className="gap-1">
+ <AppText variant="title" className="text-center">Password changed</AppText>
+ <AppText variant="body" color="muted" className="text-center">
+ You are still signed in here. Every other device has been signed out and
+ will need the new password.
+ </AppText>
+ </View>
+ <Button title="Back to settings" variant="secondary" onPress={back} className="mt-1" />
+ </Card>
+ </View>
+ </ScrollView>
+ </Screen>
+ )
+ }
+
+ return (
+ <Screen>
+ <ScrollView showsVerticalScrollIndicator={false} keyboardShouldPersistTaps="handled">
+ <View className="gap-5 py-4">
+ {backLink}
+ <PageHeader
+ title="Change password"
+ subtitle="You will stay signed in here. Every other device is signed out."
+ />
+
+ <Card className="gap-4">
+ <PasswordField
+ label="Current password"
+ value={current}
+ onChangeText={setCurrent}
+ textContentType="password"
+ />
+ {/* newPassword lets the OS keychain offer to generate and save one, and stops
+ it filing the new value under the old password's entry. */}
+ <PasswordField
+ label="New password"
+ value={next}
+ onChangeText={setNext}
+ textContentType="newPassword"
+ >
+ <PasswordRule state={rules.length}>{lengthRuleLabel(next)}</PasswordRule>
+ <PasswordRule state={rules.different}>{differentRuleLabel()}</PasswordRule>
+ </PasswordField>
+ <PasswordField
+ label="Confirm new password"
+ value={confirm}
+ onChangeText={setConfirm}
+ textContentType="newPassword"
+ >
+ <PasswordRule state={rules.match}>{matchRuleLabel(rules.match)}</PasswordRule>
+ </PasswordField>
+
+ {/* Form-level, so it belongs beside the action it blocked rather than hanging
+ off one field — pinning it to the confirm box pointed the user at the wrong
+ input for an error about the current password. */}
+ {error ? <Alert variant="error">{error}</Alert> : null}
+
+ <View className="flex-row gap-2">
+ <Button
+ title="Update password"
+ onPress={submit}
+ loading={saving}
+ disabled={!rules.ready}
+ className="flex-1"
+ />
+ <Button
+ title="Cancel"
+ variant="secondary"
+ onPress={back}
+ disabled={saving}
+ className="flex-1"
+ />
+ </View>
+ </Card>
+ </View>
+ </ScrollView>
+ </Screen>
+ )
+}
diff --git a/mobile/src/components/ui/Alert.tsx b/mobile/src/components/ui/Alert.tsx
new file mode 100644
index 0000000..18a5af8
--- /dev/null
+++ b/mobile/src/components/ui/Alert.tsx
@@ -0,0 +1,54 @@
+import type { ReactNode } from 'react'
+import { View } from 'react-native'
+import { AlertCircle, CheckCircle2, Info, TriangleAlert } from 'lucide-react-native'
+import { useTheme } from '../../theme/useTheme'
+import { AppText } from './Typography'
+
+type Variant = 'error' | 'success' | 'warning' | 'info'
+
+// Mirrors the web `.alert-*` primitives in web/src/index.css: tinted background at 10%,
+// border at 20%, matching foreground, leading icon, same radius and padding.
+//
+// Mobile had no equivalent, so form-level messages were hand-rolled per screen as a bare
+// icon-plus-text row — legible, but visibly lighter than the boxed alert the same message
+// gets on web. AuthError in components/authui.tsx is the sign-in screens' own copy of this
+// idea; screens built on the standard ui kit should use this one.
+// The `Soft` tokens are the 400s — web's alerts colour their text and icon at 400, not
+// the 500 used for the tint and border.
+const TONES: Record<Variant, { icon: typeof AlertCircle; tone: 'errorSoft' | 'successSoft' | 'warningSoft' | 'cyanLight' }> = {
+ error: { icon: AlertCircle, tone: 'errorSoft' },
+ success: { icon: CheckCircle2, tone: 'successSoft' },
+ warning: { icon: TriangleAlert, tone: 'warningSoft' },
+ info: { icon: Info, tone: 'cyanLight' },
+}
+
+const SURFACES: Record<Variant, string> = {
+ error: 'bg-error-500/10 border-error-500/20',
+ success: 'bg-success-500/10 border-success-500/20',
+ warning: 'bg-warning-500/10 border-warning-500/20',
+ info: 'bg-brand-500/10 border-brand-500/20',
+}
+
+interface Props {
+ variant: Variant
+ children: ReactNode
+ className?: string
+}
+
+export function Alert({ variant, children, className = '' }: Props) {
+ const { brand } = useTheme()
+ const { icon: Icon, tone } = TONES[variant]
+ const color = brand[tone]
+
+ return (
+ <View
+ accessibilityRole="alert"
+ className={`flex-row items-start gap-3 rounded-lg border p-3.5 ${SURFACES[variant]} ${className}`}
+ >
+ <Icon size={18} color={color} strokeWidth={2.2} style={{ marginTop: 1 }} />
+ <AppText variant="body" className="flex-1" style={{ color }}>
+ {children}
+ </AppText>
+ </View>
+ )
+}
diff --git a/mobile/src/components/ui/Button.tsx b/mobile/src/components/ui/Button.tsx
index baaf3a6..e44b0cd 100644
--- a/mobile/src/components/ui/Button.tsx
+++ b/mobile/src/components/ui/Button.tsx
@@ -36,7 +36,15 @@ export function Button({
disabled={isDisabled}
// active:scale-95 is the standard press feedback for every tappable (see
// CONVENTIONS.md "native feel") — it reads as native where hover states can't.
- className={`h-12 rounded-lg flex-row items-center justify-center gap-2 active:scale-95 ${v.bg} ${isDisabled ? 'opacity-40' : ''} ${className}`}
+ // px-4 matters only when the button sizes to its own label. Nearly every caller
+ // passes flex-1 or fills a column, so the padding is invisible there — but a
+ // centred button with none had its text touching both edges.
+ //
+ // Deliberately not px-5, which web's same-height btn-lg uses: the tightest caller
+ // is the two-button row on the change-password card, where at 390dp each half has
+ // only ~23dp of slack around "Update password". px-4 clears that; px-5 would sit
+ // on the edge of squeezing the label.
+ className={`h-12 px-4 rounded-lg flex-row items-center justify-center gap-2 active:scale-95 ${v.bg} ${isDisabled ? 'opacity-40' : ''} ${className}`}
>
{loading ? (
// White only sits on the brand-filled primary; other variants keep the surface
diff --git a/mobile/src/components/ui/PasswordField.tsx b/mobile/src/components/ui/PasswordField.tsx
new file mode 100644
index 0000000..2b46542
--- /dev/null
+++ b/mobile/src/components/ui/PasswordField.tsx
@@ -0,0 +1,82 @@
+import type { ReactNode } from 'react'
+import { useState } from 'react'
+import { Pressable, View } from 'react-native'
+import { Check, Eye, EyeOff, X } from 'lucide-react-native'
+import type { RuleState } from '@lyftr/shared'
+import { useTheme } from '../../theme/useTheme'
+import { Field } from './Field'
+import { AppText } from './Typography'
+
+// One rule, shown while typing. Mirrors web's `Rule` in web/src/components/ui/PasswordField —
+// same three states, same colours, and the state itself comes from the shared
+// newPasswordRules so the two apps cannot disagree about what passes.
+export function PasswordRule({ state, children }: { state: RuleState; children: ReactNode }) {
+ const { colors, brand } = useTheme()
+ const color = state === 'ok' ? brand.success : state === 'bad' ? brand.error : colors.txMuted
+
+ return (
+ <View className="flex-row items-center gap-1.5">
+ {state === 'ok' ? <Check size={12} color={color} strokeWidth={2.6} />
+ : state === 'bad' ? <X size={12} color={color} strokeWidth={2.6} />
+ : <View style={{ width: 10, height: 10, borderRadius: 5, borderWidth: 1, borderColor: color, opacity: 0.4 }} />}
+ <AppText variant="caption" className="flex-1" style={{ color }}>{children}</AppText>
+ </View>
+ )
+}
+
+interface Props {
+ label: string
+ value: string
+ onChangeText: (value: string) => void
+ /**
+ * `password` for the existing one, `newPassword` to let the keychain offer to save.
+ * Drives both platform hints — textContentType on iOS, autoComplete on Android.
+ */
+ textContentType: 'password' | 'newPassword'
+ /** Rule rows rendered under the field. */
+ children?: ReactNode
+}
+
+// The reveal toggle the auth screens already have (see IconInput's `password` prop in
+// src/components/authui.tsx), for the screens built on `Field` instead. Change password
+// asks for three in a row with no way to check what went in, which is the case that
+// needs it most — and without it a typo and a forgotten password are indistinguishable.
+//
+// No Caps Lock warning here, unlike web: a soft keyboard shows its own shift state, and
+// React Native surfaces no modifier state to read anyway.
+export function PasswordField({ label, value, onChangeText, textContentType, children }: Props) {
+ const { colors } = useTheme()
+ const [visible, setVisible] = useState(false)
+
+ return (
+ <View className="gap-1.5">
+ <Field
+ label={label}
+ value={value}
+ onChangeText={onChangeText}
+ secureTextEntry={!visible}
+ autoCapitalize="none"
+ autoCorrect={false}
+ textContentType={textContentType}
+ // textContentType is iOS-only, and Android is what this app actually ships to.
+ // autoComplete is React Native's unified hint — without it the Android password
+ // manager gets no signal and neither offers to save the new password nor fills
+ // the current one, which web has had all along via its own autoComplete.
+ autoComplete={textContentType === 'newPassword' ? 'password-new' : 'password'}
+ rightSlot={
+ <Pressable
+ onPress={() => setVisible((v) => !v)}
+ hitSlop={10}
+ accessibilityRole="button"
+ accessibilityLabel={`${visible ? 'Hide' : 'Show'} ${label.toLowerCase()}`}
+ >
+ {visible
+ ? <EyeOff size={18} color={colors.txMuted} strokeWidth={2} />
+ : <Eye size={18} color={colors.txMuted} strokeWidth={2} />}
+ </Pressable>
+ }
+ />
+ {children}
+ </View>
+ )
+}
diff --git a/mobile/src/components/ui/index.ts b/mobile/src/components/ui/index.ts
index 6767b98..8e5d9fc 100644
--- a/mobile/src/components/ui/index.ts
+++ b/mobile/src/components/ui/index.ts
@@ -9,6 +9,7 @@ export type { AppTextProps, TextVariant, TextColor } from './Typography'
// Layout / surfaces
export { Screen } from './Screen'
export { Card } from './Card'
+export { Alert } from './Alert'
// Headers (web-parity)
export { PageHeader } from './PageHeader'
@@ -23,6 +24,7 @@ export { SegmentedControl } from './SegmentedControl'
export { Field } from './Field'
export { SearchField } from './SearchField'
export { NumberField } from './NumberField'
+export { PasswordField, PasswordRule } from './PasswordField'
export { NumericKeyboardAccessory, NUMERIC_ACCESSORY_ID } from './NumericKeyboardAccessory'
export { StepperTile } from './StepperTile'
export { DateInput } from './DateInput'
diff --git a/packages/shared/src/client.test.ts b/packages/shared/src/client.test.ts
index d08cead..9c62d60 100644
--- a/packages/shared/src/client.test.ts
+++ b/packages/shared/src/client.test.ts
@@ -1,5 +1,5 @@
import { createClient } from './client'
-import { StorageAdapter } from './storage'
+import { StorageAdapter, STORAGE_KEYS } from './storage'
const memStorage = (): StorageAdapter => {
const m = new Map<string, string>()
@@ -192,3 +192,61 @@ describe('list timeouts scale with the requested limit', () => {
expect(seen[1].timeout).toBe(20000)
})
})
+
+// The change invalidates every token minted against the old password — including the
+// pair this device is holding. Persisting the replacements is what keeps the session
+// that made the change alive; drop them and the user is signed out minutes later, at
+// the next refresh, with nothing on screen to connect it to what they did.
+describe('userAPI.changePassword', () => {
+ const clientWithStorage = () => {
+ const store = memStorage()
+ const client = createClient(store)
+ client.api.defaults.adapter = async (config: any) => ({
+ data: { data: { token: 'new-access', refresh_token: 'new-refresh' } },
+ status: 200, statusText: 'OK', headers: {}, config,
+ })
+ return { client, store }
+ }
+
+ it('persists the token pair the server returns', async () => {
+ const { client, store } = clientWithStorage()
+ await store.set(STORAGE_KEYS.access, 'old-access')
+ await store.set(STORAGE_KEYS.refresh, 'old-refresh')
+
+ await client.userAPI.changePassword({
+ current_password: 'password123',
+ new_password: 'newpassword456',
+ })
+
+ expect(await store.get(STORAGE_KEYS.access)).toBe('new-access')
+ expect(await store.get(STORAGE_KEYS.refresh)).toBe('new-refresh')
+ })
+
+ // A 401 here means "that current password is wrong", not "your session lapsed". If the
+ // refresh interceptor treats it as the latter it retries, fails again, and signs the
+ // user out — losing the session over a typo.
+ it('does not trigger the refresh-and-sign-out path on a rejected password', async () => {
+ const store = memStorage()
+ let signedOut = false
+ const client = createClient(store, { onAuthFailure: () => { signedOut = true } })
+ client.api.defaults.adapter = async (config: any) => {
+ const err: any = new Error('Request failed with status code 401')
+ err.config = config
+ err.response = {
+ status: 401, data: { error: 'current password is incorrect' },
+ statusText: 'Unauthorized', headers: {}, config,
+ }
+ throw err
+ }
+ await store.set(STORAGE_KEYS.access, 'live-access')
+ await store.set(STORAGE_KEYS.refresh, 'live-refresh')
+
+ await expect(client.userAPI.changePassword({
+ current_password: 'wrong', new_password: 'newpassword456',
+ })).rejects.toBeDefined()
+
+ expect(signedOut).toBe(false)
+ expect(await store.get(STORAGE_KEYS.access)).toBe('live-access')
+ expect(await store.get(STORAGE_KEYS.refresh)).toBe('live-refresh')
+ })
+})
diff --git a/packages/shared/src/client.ts b/packages/shared/src/client.ts
index 8ffecdb..c258243 100644
--- a/packages/shared/src/client.ts
+++ b/packages/shared/src/client.ts
@@ -102,10 +102,14 @@ export function createClient(storage: StorageAdapter, opts: ClientOptions = {})
(response) => response,
async (error) => {
const original = error.config
- // A 401 from the auth endpoints themselves is a credential error, not an
- // expired session — let the page show it instead of refreshing/redirecting.
- const isAuthRequest = (original?.url || '').includes('/auth/')
- if (error.response?.status === 401 && !original._retry && !isAuthRequest) {
+ // A 401 from an endpoint that checks a password in its body is a credential
+ // error, not an expired session — let the page show it instead of
+ // refreshing/redirecting. /me/password belongs here for the same reason
+ // /auth/login does: it answers "that password is wrong", and refreshing would
+ // retry, fail again, and sign the user out over a typo.
+ const url = original?.url || ''
+ const isCredentialCheck = url.includes('/auth/') || url.includes('/me/password')
+ if (error.response?.status === 401 && !original._retry && !isCredentialCheck) {
original._retry = true
try {
const refreshToken = await storage.get(STORAGE_KEYS.refresh)
@@ -139,6 +143,16 @@ export function createClient(storage: StorageAdapter, opts: ClientOptions = {})
getSettings: () => api.get<{ data: types.UserSettings }>('/settings').then(unwrap),
updateSettings: (data: Partial<types.UserSettings>) => api.put<{ data: types.UserSettings }>('/settings', data).then(unwrap),
deleteAccount: () => api.delete('/me'),
+ // Persisting the returned pair is not optional. The change invalidates every token
+ // minted against the old password, this device's included, so skipping this would
+ // sign the user out of the very session that made the change — at the next refresh,
+ // minutes later, with nothing on screen to connect it to what they did.
+ changePassword: async (data: types.ChangePasswordRequest) => {
+ const res = await api.put<{ data: types.TokenPair }>('/me/password', data)
+ const pair = res.data.data
+ await storage.set(STORAGE_KEYS.access, pair.token)
+ await storage.set(STORAGE_KEYS.refresh, pair.refresh_token)
+ },
}
const workoutAPI = {
diff --git a/packages/shared/src/index.ts b/packages/shared/src/index.ts
index fd8c8ae..71f6b6f 100644
--- a/packages/shared/src/index.ts
+++ b/packages/shared/src/index.ts
@@ -21,6 +21,7 @@ export * from './utils/programDrafts'
export * from './utils/food'
export * from './utils/dashboard'
export * from './utils/version'
+export * from './utils/passwordRules'
export * from './theme/tokens'
export * from './hooks/useCountdown'
export * from './hooks/useNumericText'
diff --git a/packages/shared/src/types.ts b/packages/shared/src/types.ts
index c06f1a3..ae08a14 100644
--- a/packages/shared/src/types.ts
+++ b/packages/shared/src/types.ts
@@ -277,3 +277,14 @@ export interface RegisterRequest {
email: string
password: string
}
+
+/** What /auth/refresh and /me/password return: credentials without a user body. */
+export interface TokenPair {
+ token: string
+ refresh_token: string
+}
+
+export interface ChangePasswordRequest {
+ current_password: string
+ new_password: string
+}
diff --git a/packages/shared/src/utils/dateUtils.test.ts b/packages/shared/src/utils/dateUtils.test.ts
index fe47afb..095f9a2 100644
--- a/packages/shared/src/utils/dateUtils.test.ts
+++ b/packages/shared/src/utils/dateUtils.test.ts
@@ -1,4 +1,4 @@
-import { todayStr, dayToInstant, dayToLocalDate, instantToDay, entryDay, workoutDay } from './dateUtils'
+import { todayStr, dayToInstant, dayToLocalDate, instantToDay, entryDay, workoutDay, memberSince } from './dateUtils'
describe('dayToInstant', () => {
@@ -150,3 +150,28 @@ describe('dayToLocalDate', () => {
}
})
})
+
+describe('memberSince', () => {
+ it('renders the UTC month and year', () => {
+ expect(memberSince('2026-08-19T14:30:00Z')).toBe('August 2026')
+ })
+
+ // The bug it exists for: Go's zero time is truthy and parses fine, so it used to be
+ // formatted and shown as a real date on a brand new account.
+ it('rejects Go\'s zero time rather than formatting it', () => {
+ expect(memberSince('0001-01-01T00:00:00Z')).toBe('—')
+ })
+
+ it('reads as unknown for missing or unparseable input', () => {
+ expect(memberSince(undefined)).toBe('—')
+ expect(memberSince('')).toBe('—')
+ expect(memberSince('not-a-date')).toBe('—')
+ })
+
+ // UTC, not the reader's clock: created_at carries no offset, so a local reading would
+ // move a join date across a month boundary purely by travelling.
+ it('does not shift the month with the reader\'s timezone', () => {
+ expect(memberSince('2026-09-01T00:30:00Z')).toBe('September 2026')
+ expect(memberSince('2026-08-31T23:30:00Z')).toBe('August 2026')
+ })
+})
diff --git a/packages/shared/src/utils/dateUtils.ts b/packages/shared/src/utils/dateUtils.ts
index ea3be02..bb85ebb 100644
--- a/packages/shared/src/utils/dateUtils.ts
+++ b/packages/shared/src/utils/dateUtils.ts
@@ -154,3 +154,31 @@ export const workoutDay = (w: { started_at: string; tz_offset_minutes?: number }
const shifted = new Date(new Date(w.started_at).getTime() + w.tz_offset_minutes * 60_000)
return Number.isNaN(shifted.getTime()) ? instantToDay(w.started_at) : shifted.toISOString().slice(0, 10)
}
+
+const MONTH_NAMES = [
+ 'January', 'February', 'March', 'April', 'May', 'June',
+ 'July', 'August', 'September', 'October', 'November', 'December',
+]
+
+/**
+ * "August 2026" for the Settings → Member since row, or "—" when there is nothing real
+ * to show.
+ *
+ * A present-but-meaningless timestamp has to read as unknown rather than be formatted
+ * anyway. Go's zero time serialises as "0001-01-01T00:00:00Z", which is truthy and parses
+ * fine, so a plain `created_at ? format(...) : '—'` rendered it — web showed "December 1"
+ * and mobile "January 1" for a brand new account. The backend no longer sends it, but an
+ * older server still can, and no real account predates Lyftr.
+ *
+ * Read in UTC on purpose. Unlike the day-scoped rows above, `created_at` is a bare
+ * instant with no stored offset, so deriving the month from the reader's clock would move
+ * someone's join date across a month boundary purely by travelling. Month names are
+ * spelled out here rather than via toLocaleDateString so both apps render identically
+ * regardless of the Intl data the runtime happens to ship.
+ */
+export const memberSince = (iso?: string): string => {
+ if (!iso) return '—'
+ const d = new Date(iso)
+ if (Number.isNaN(d.getTime()) || d.getUTCFullYear() < 2000) return '—'
+ return `${MONTH_NAMES[d.getUTCMonth()]} ${d.getUTCFullYear()}`
+}
diff --git a/packages/shared/src/utils/passwordRules.test.ts b/packages/shared/src/utils/passwordRules.test.ts
new file mode 100644
index 0000000..022800a
--- /dev/null
+++ b/packages/shared/src/utils/passwordRules.test.ts
@@ -0,0 +1,139 @@
+import {
+ byteLength,
+ characterLength,
+ lengthRuleLabel,
+ matchRuleLabel,
+ MAX_PASSWORD_BYTES,
+ MIN_PASSWORD_LENGTH,
+ newPasswordRules,
+ ruleState,
+} from './passwordRules'
+
+describe('ruleState', () => {
+ it('is pending until the field is touched, whatever the answer would be', () => {
+ expect(ruleState(false, false)).toBe('pending')
+ expect(ruleState(false, true)).toBe('pending')
+ })
+
+ it('reports the answer once touched', () => {
+ expect(ruleState(true, true)).toBe('ok')
+ expect(ruleState(true, false)).toBe('bad')
+ })
+})
+
+describe('newPasswordRules on sign-up (no current password)', () => {
+ it('holds every rule pending on an empty form, and is not ready', () => {
+ const r = newPasswordRules({ password: '', confirm: '' })
+ expect(r).toMatchObject({ length: 'pending', different: 'pending', match: 'pending', ready: false })
+ })
+
+ it('never applies the "different" rule — there is no previous password to differ from', () => {
+ const r = newPasswordRules({ password: 'password123', confirm: 'password123' })
+ expect(r.different).toBe('pending')
+ expect(r.ready).toBe(true)
+ })
+
+ it('fails a short password and passes one exactly at the minimum', () => {
+ const short = 'a'.repeat(MIN_PASSWORD_LENGTH - 1)
+ expect(newPasswordRules({ password: short, confirm: short })).toMatchObject({ length: 'bad', ready: false })
+
+ const exact = 'a'.repeat(MIN_PASSWORD_LENGTH)
+ expect(newPasswordRules({ password: exact, confirm: exact })).toMatchObject({ length: 'ok', ready: true })
+ })
+
+ it('is not ready while the confirmation differs', () => {
+ const r = newPasswordRules({ password: 'password123', confirm: 'password12' })
+ expect(r).toMatchObject({ match: 'bad', ready: false })
+ })
+
+ it('leaves match pending while the confirmation is empty, rather than calling it wrong', () => {
+ const r = newPasswordRules({ password: 'password123', confirm: '' })
+ expect(r).toMatchObject({ match: 'pending', ready: false })
+ })
+})
+
+describe('newPasswordRules on change-password (current supplied)', () => {
+ const current = 'password123'
+
+ it('applies the "different" rule and blocks a no-op change', () => {
+ const r = newPasswordRules({ password: current, confirm: current, current })
+ expect(r).toMatchObject({ length: 'ok', match: 'ok', different: 'bad', ready: false })
+ })
+
+ it('is ready once the new password is long enough, matching, and different', () => {
+ const r = newPasswordRules({ password: 'newpassword456', confirm: 'newpassword456', current })
+ expect(r).toMatchObject({ length: 'ok', match: 'ok', different: 'ok', ready: true })
+ })
+
+ // The current-password box is the one field with no rule of its own, so nothing else
+ // would stop a submit that cannot possibly succeed.
+ it('is not ready while the current password is blank', () => {
+ const r = newPasswordRules({ password: 'newpassword456', confirm: 'newpassword456', current: '' })
+ expect(r.ready).toBe(false)
+ expect(r.different).toBe('pending')
+ })
+
+ // An empty current password would otherwise satisfy "different" for free and light up
+ // green before the user has said anything about it.
+ it('holds "different" pending until both the current and the new password have content', () => {
+ expect(newPasswordRules({ password: '', confirm: '', current }).different).toBe('pending')
+ expect(newPasswordRules({ password: 'newpassword456', confirm: '', current: '' }).different).toBe('pending')
+ })
+})
+
+describe('rule labels', () => {
+ it('states the length rule using the shared minimum', () => {
+ expect(lengthRuleLabel()).toBe(`At least ${MIN_PASSWORD_LENGTH} characters`)
+ })
+
+ // The pending wording is the point of routing this through the state: an untouched
+ // confirmation box must not claim the passwords already match.
+ it('does not claim a match before the confirmation is touched', () => {
+ expect(matchRuleLabel('pending')).not.toMatch(/match/i)
+ expect(matchRuleLabel('ok')).toBe('Passwords match')
+ expect(matchRuleLabel('bad')).toBe('Passwords do not match')
+ })
+})
+
+describe('length is measured the way the server measures it', () => {
+ // JavaScript's .length counts UTF-16 code units, so four emoji look like eight
+ // characters. The server counts runes and sees four — the client used to accept a
+ // password the server then rejected on submit.
+ it('counts characters, not UTF-16 code units, for the minimum', () => {
+ const fourEmoji = '\u{1F3CB}'.repeat(4)
+ expect(fourEmoji.length).toBe(8)
+ expect(characterLength(fourEmoji)).toBe(4)
+ expect(newPasswordRules({ password: fourEmoji, confirm: fourEmoji })).toMatchObject({
+ length: 'bad',
+ ready: false,
+ })
+ })
+
+ it('counts bytes for the maximum, matching bcrypt', () => {
+ expect(byteLength('a'.repeat(72))).toBe(72)
+ expect(byteLength('\u{1F3CB}'.repeat(19))).toBe(76)
+ })
+
+ it('accepts exactly the byte limit and rejects one over', () => {
+ const atLimit = 'a'.repeat(MAX_PASSWORD_BYTES)
+ expect(newPasswordRules({ password: atLimit, confirm: atLimit })).toMatchObject({ length: 'ok', ready: true })
+
+ const over = 'a'.repeat(MAX_PASSWORD_BYTES + 1)
+ expect(newPasswordRules({ password: over, confirm: over })).toMatchObject({ length: 'bad', ready: false })
+ })
+
+ // 19 characters, 76 bytes — long enough to be refused while looking far too short to be.
+ it('rejects a multibyte passphrase well under the character limit', () => {
+ const emoji = '\u{1F3CB}'.repeat(19)
+ expect(characterLength(emoji)).toBeLessThan(MAX_PASSWORD_BYTES)
+ expect(newPasswordRules({ password: emoji, confirm: emoji }).ready).toBe(false)
+ })
+
+ // Telling someone with a 100-character password that they need at least 8 sends them
+ // in the wrong direction.
+ it('flips the label when the password is too long', () => {
+ expect(lengthRuleLabel('a'.repeat(10))).toMatch(/at least/i)
+ expect(lengthRuleLabel('a'.repeat(MAX_PASSWORD_BYTES + 1))).toMatch(/at most/i)
+ expect(lengthRuleLabel()).toMatch(/at least/i)
+ })
+})
diff --git a/packages/shared/src/utils/passwordRules.ts b/packages/shared/src/utils/passwordRules.ts
new file mode 100644
index 0000000..325cf30
--- /dev/null
+++ b/packages/shared/src/utils/passwordRules.ts
@@ -0,0 +1,131 @@
+// What makes a new password acceptable, in one place for both apps.
+//
+// Three screens ask for one — web sign-up, web change-password, mobile change-password —
+// and each used to carry its own copy of the same three checks, written slightly
+// differently. The web pages compared lengths inline in their submit handlers; the mobile
+// screen had its own MIN_PASSWORD constant. Nothing kept them in step with each other or
+// with the backend's `min=8`, and a rule the two apps disagree about is worse than no
+// rule: the same password is accepted on one and refused on the other.
+//
+// The server is still the authority. This exists so the user learns the answer while
+// typing instead of after a round trip.
+
+/**
+ * Mirrors the backend's `min=8` on RegisterRequest and ChangePasswordRequest. That tag
+ * counts runes, so this minimum does too — see `characterLength`.
+ */
+export const MIN_PASSWORD_LENGTH = 8
+
+/**
+ * bcrypt's own hard limit, not a policy choice: GenerateFromPassword refuses anything
+ * longer rather than truncating, so a longer password cannot be stored at all.
+ *
+ * Counted in BYTES. A 19-character emoji passphrase is 76 of them, and password managers
+ * generate 100-character passwords by default — this is not an exotic input.
+ */
+export const MAX_PASSWORD_BYTES = 72
+
+/**
+ * Characters as a person counts them, and as Go's `min` tag counts them.
+ *
+ * `"a".length` agrees, but JavaScript measures UTF-16 code units, so an emoji counts as
+ * two — a four-emoji password looked like 8 characters here and like 4 to the server,
+ * which accepted it on the client and rejected it on submit.
+ */
+export const characterLength = (password: string): number => [...password].length
+
+/**
+ * UTF-8 byte length, computed rather than measured with TextEncoder — Hermes has not
+ * always shipped one, and this has to give the same answer as Go's `len()` on both apps.
+ */
+export const byteLength = (password: string): number => {
+ let bytes = 0
+ for (const ch of password) {
+ const code = ch.codePointAt(0) ?? 0
+ bytes += code < 0x80 ? 1 : code < 0x800 ? 2 : code < 0x10000 ? 3 : 4
+ }
+ return bytes
+}
+
+/**
+ * `pending` is the untouched state. An empty field is not yet wrong, and marking it red
+ * before the user has typed anything reads as an error they caused.
+ */
+export type RuleState = 'pending' | 'ok' | 'bad'
+
+export function ruleState(touched: boolean, satisfied: boolean): RuleState {
+ if (!touched) return 'pending'
+ return satisfied ? 'ok' : 'bad'
+}
+
+export interface NewPasswordInput {
+ password: string
+ confirm: string
+ /**
+ * The account's existing password, when the screen collects one. Supplying it adds the
+ * "must be different" rule and requires it to be non-empty before the form is ready —
+ * omit it on sign-up, where there is nothing to differ from.
+ */
+ current?: string
+}
+
+export interface NewPasswordRules {
+ length: RuleState
+ /** Always `pending` when no current password was supplied. */
+ different: RuleState
+ match: RuleState
+ /** Every applicable rule satisfied, so the form is worth submitting. */
+ ready: boolean
+}
+
+export function newPasswordRules({ password, confirm, current }: NewPasswordInput): NewPasswordRules {
+ const longEnough = characterLength(password) >= MIN_PASSWORD_LENGTH
+ const shortEnough = byteLength(password) <= MAX_PASSWORD_BYTES
+ const matches = password === confirm
+ // A change-password screen is the only caller that passes `current`; sign-up has no
+ // previous password, so the rule does not apply rather than silently passing.
+ const changing = current !== undefined
+ const isDifferent = changing && password !== current
+
+ return {
+ length: ruleState(password.length > 0, longEnough && shortEnough),
+ different: ruleState(changing && !!current && password.length > 0, isDifferent),
+ match: ruleState(confirm.length > 0, matches),
+ ready: longEnough && shortEnough && matches && (!changing || (!!current && isDifferent)),
+ }
+}
+
+// The wording, next to the rules themselves. Sharing the states but hand-copying the
+// labels across four screens leaves exactly the drift this module exists to stop — the
+// apps could no longer disagree about what passes, only about what to call it.
+/**
+ * Reads the password because the length rule has two failure directions, and "At least 8
+ * characters" under a 100-character password is nonsense — it is the message a manager's
+ * generated password would get, and it tells the user to do the opposite of what works.
+ */
+export function lengthRuleLabel(password = ''): string {
+ if (byteLength(password) > MAX_PASSWORD_BYTES) {
+ return `At most ${MAX_PASSWORD_BYTES} characters (accents and emoji count for more)`
+ }
+ return `At least ${MIN_PASSWORD_LENGTH} characters`
+}
+
+export function differentRuleLabel(): string {
+ return 'Different from your current password'
+}
+
+/**
+ * Reads the state rather than fixing one string, because the match rule is the only one
+ * whose phrasing flips. "Passwords match" in the `pending` state would assert something
+ * untrue about a confirmation box nobody has typed into yet.
+ */
+export function matchRuleLabel(state: RuleState): string {
+ switch (state) {
+ case 'ok':
+ return 'Passwords match'
+ case 'bad':
+ return 'Passwords do not match'
+ default:
+ return 'Repeat the new password'
+ }
+}
diff --git a/site/src/content/docs/configuration.md b/site/src/content/docs/configuration.md
index 86e793e..2bc6a93 100644
--- a/site/src/content/docs/configuration.md
+++ b/site/src/content/docs/configuration.md
@@ -70,6 +70,83 @@ quietly leaving you wide open. Check `docker compose logs backend` if the contai
This is enforced by the API, not the interface. The apps also hide the "Create account" link when
the server reports registration closed, but that is politeness — the 403 is the lock.
+## Changing your password
+
+**Settings → Account → Password**, on the web app and in the Android app. It asks for your current
+password, so a stolen session alone cannot lock you out of your own account.
+
+The web form has its own address, `/settings/password`, and `/.well-known/change-password`
+redirects to it. That is the [W3C Change Password URL](https://w3c.github.io/webappsec-change-password-url/),
+so Safari's Keychain, Chrome's Password Checkup and 1Password can send you straight to the form
+instead of dropping you on the front page. Nothing to configure — the bundled nginx serves the
+redirect. Behind your own reverse proxy, pass the path through to the frontend like any other
+route.
+
+### Password length
+
+Between 8 characters and 72 **bytes**. The minimum is Lyftr's; the maximum is bcrypt's, which
+refuses anything longer rather than silently truncating it.
+
+72 bytes is 72 ordinary characters, but accented letters cost two and most emoji cost four — so a
+19-character emoji passphrase is already over. Both apps say so while you type rather than on
+submit. Worth knowing if your password manager generates long passwords: cap it at 72.
+
+Changing it **signs you out everywhere else**. The device you changed it on stays signed in. That
+is deliberate — a password change is what you reach for when you think someone else has a session,
+so it has to actually end their session. Sign back in on your other devices with the new password.
+
+Other devices stop as soon as their current access token expires, which is `JWT_EXPIRY` seconds
+(one hour by default). Raising `JWT_EXPIRY` widens that window by exactly the same amount, so a
+long expiry trades a little convenience for a longer tail after a password change.
+
+## If you forget your password
+
+There is no self-service reset. Nothing here can email you a link, and an instance with no mail
+server could not send one. Recovery belongs to whoever has a shell on the server — which, since you
+self-host, is you:
+
+```bash
+docker compose exec backend ./lyftr-api reset-password [email protected]
+```
+
+It prompts for the new password twice, with no echo, and prints:
+
+```
+Password reset for [email protected].
+Every existing session for that account has been signed out.
+```
+
+The account and everything in it are untouched — only the password changes.
+
+The password is prompted for rather than passed as a flag, so it never reaches your shell history
+or the container's process list.
+
+If you need it unattended, pipe it in. Read it into a variable first rather than typing it into the
+command — `echo 'your-new-password' | ...` puts the password straight into your shell history, which
+is the thing the prompt exists to avoid:
+
+```bash
+read -rs NEWPW
+docker compose exec -T backend ./lyftr-api reset-password [email protected] <<< "$NEWPW"
+unset NEWPW
+```
+
+Piped input skips the confirmation prompt — there is nothing to type twice — so whatever arrives on
+stdin becomes the password, subject only to the same 8-character minimum and 72-byte maximum
+the apps enforce.
+
+Sessions are signed out because a reset is often prompted by someone else having got in, and a new
+password is worthless while their existing token still works.
+
+:::caution
+**Do not delete the account and sign up again.** `users` cascades — the row takes every workout,
+meal and weight entry with it. Under `REGISTRATION=closed` it also leaves you permanently locked
+out, since nothing would let you register the replacement.
+:::
+
+If the instance will not start at all, restoring `lyftr.db` from a backup predating the password
+change also works, at the cost of everything logged since — see [Backups](/backups/).
+
## The demo account
Every version before this one seeded `[email protected]` with a password published in this
@@ -78,7 +155,8 @@ you ask for it.
If you are upgrading, the account you already have is not deleted — deleting it might take real
workouts with it. The backend logs a warning at startup while it exists. To remove it: sign in as
-`[email protected]`, then **Settings → Delete account**.
+`[email protected]`, then **Settings → Delete account**. If that account has real data in it, change
+its password instead — that closes the published-credential hole without losing anything.
Turning registration off does nothing about this: a published password is a working login whatever
`REGISTRATION` says.
diff --git a/web/e2e/auth.spec.ts b/web/e2e/auth.spec.ts
index dbd7613..8489527 100644
--- a/web/e2e/auth.spec.ts
+++ b/web/e2e/auth.spec.ts
@@ -78,3 +78,125 @@ test('server settings Save stays enabled when the field equals the current serve
// exhaustively in web/src/stores/server.test.ts. The "rejects an invalid URL"
// test above is kept as the single E2E proof that the panel surfaces a
// validation error to the user.
+
+// Registers its own throwaway account rather than using the worker fixture: changing a
+// password bumps that account's token_version, and the worker account is shared by every
+// other spec in the run.
+test('changes the password, then signs in with the new one', { tag: '@mobile' }, async ({ page }) => {
+ const email = `e2e-pw+${Date.now()}@lyftr.local`
+ const oldPassword = 'password123'
+ const newPassword = 'newpassword456'
+
+ await page.goto('/register')
+ await page.getByPlaceholder('[email protected]').fill(email)
+ await page.locator('#password').fill(oldPassword)
+ await page.locator('#password-confirm').fill(oldPassword)
+ await page.getByRole('button', { name: /create account/i }).click()
+ await page.waitForURL(url => new URL(url).pathname === '/')
+
+ const token = await page.evaluate(() => localStorage.getItem('access_token'))
+ if (token) recordCreatedUser(token)
+
+ // Via the Settings link rather than a direct goto: the row is the only entry point in
+ // the UI, so this is what proves the page is reachable at all.
+ await page.goto('/settings')
+ await page.getByRole('link', { name: /^change$/i }).click()
+ await expect(page).toHaveURL(/\/settings\/password$/)
+ await page.locator('#current-password').fill(oldPassword)
+ await page.locator('#new-password').fill(newPassword)
+ await page.locator('#confirm-password').fill(newPassword)
+ await page.getByRole('button', { name: /update password/i }).click()
+
+ await expect(page.getByRole('heading', { name: /password changed/i })).toBeVisible()
+ await expect(page.getByText(/still signed in here/i)).toBeVisible()
+
+ // The device that made the change keeps working — the client swapped in the pair the
+ // server returned, so a normal authenticated read still succeeds.
+ await page.goto('/workouts')
+ await expect(page).toHaveURL(/\/workouts$/)
+
+ // And the credential really moved: the old password no longer signs in, the new one does.
+ await page.evaluate(() => localStorage.clear())
+ await page.goto('/login')
+ await page.getByPlaceholder('[email protected]').fill(email)
+ await page.locator('#password').fill(oldPassword)
+ await page.getByRole('button', { name: /sign in/i }).click()
+ await expect(page.locator('.alert-error')).toBeVisible()
+
+ await page.locator('#password').fill(newPassword)
+ await page.getByRole('button', { name: /sign in/i }).click()
+ await page.waitForURL(url => new URL(url).pathname === '/')
+})
+
+// The bug this guards: /me/password returns 401 for a wrong current password, and the
+// shared client's refresh interceptor used to treat any 401 outside /auth/ as an expired
+// session — refreshing, retrying, failing, and signing the user out over a typo.
+test('a wrong current password shows an error without signing the user out', async ({ page }) => {
+ const email = `e2e-pw-bad+${Date.now()}@lyftr.local`
+
+ await page.goto('/register')
+ await page.getByPlaceholder('[email protected]').fill(email)
+ await page.locator('#password').fill('password123')
+ await page.locator('#password-confirm').fill('password123')
+ await page.getByRole('button', { name: /create account/i }).click()
+ await page.waitForURL(url => new URL(url).pathname === '/')
+
+ const token = await page.evaluate(() => localStorage.getItem('access_token'))
+ if (token) recordCreatedUser(token)
+
+ // Straight to the route — the same landing the /.well-known/change-password redirect
+ // produces, so a deep link is covered as well as the in-app path used above.
+ await page.goto('/settings/password')
+ await page.locator('#current-password').fill('not-my-password')
+ await page.locator('#new-password').fill('newpassword456')
+ await page.locator('#confirm-password').fill('newpassword456')
+ await page.getByRole('button', { name: /update password/i }).click()
+
+ await expect(page.locator('.alert-error')).toContainText(/current password is incorrect/i)
+ // Still signed in, still on the form — not bounced to /login.
+ await expect(page).toHaveURL(/\/settings\/password$/)
+ expect(await page.evaluate(() => localStorage.getItem('access_token'))).toBeTruthy()
+})
+
+// The W3C Change Password URL. Password managers open it to send a user to the form, and
+// expect a redirect — served by nginx in production and by a vite middleware in dev, so
+// this runs against either stack. Asserted without following, because a 200 here would
+// mean the SPA fallback swallowed it and the manager would land on whatever React Router
+// decides, not on the form.
+//
+// The exact relative Location is the assertion, not just the path: nginx defaults to
+// absolute_redirect on, which would rebuild it from $scheme and — behind a TLS
+// terminator, which is how both bundled configs run — hand a password manager an http://
+// URL for a site it reached over https. Both configs turn it off. A regression there
+// fails here rather than silently downgrading the redirect.
+test('/.well-known/change-password redirects to the change-password form', async ({ page }) => {
+ const res = await page.request.get('/.well-known/change-password', { maxRedirects: 0 })
+ expect(res.status()).toBe(302)
+ expect(res.headers()['location']).toBe('/settings/password')
+})
+
+// bcrypt cannot store more than 72 bytes, and a password manager's default generated
+// password is longer than that. Before the limit was surfaced, the form let it through
+// and the server answered 500 — the user was told to try again, which could never work.
+test('a password too long for bcrypt is refused before it can be submitted', async ({ page }) => {
+ const email = `e2e-pw-long+${Date.now()}@lyftr.local`
+
+ await page.goto('/register')
+ await page.getByPlaceholder('[email protected]').fill(email)
+
+ const tooLong = 'a'.repeat(100)
+ await page.locator('#password').fill(tooLong)
+ await page.locator('#password-confirm').fill(tooLong)
+
+ // "At least 8 characters" under a 100-character password points the wrong way, so the
+ // rule states the bound it actually failed.
+ await expect(page.getByText(/at most 72 characters/i)).toBeVisible()
+ await expect(page.getByRole('button', { name: /create account/i })).toBeDisabled()
+
+ // And the limit is bytes, so a passphrase that reads as short is still refused.
+ const emoji = '\u{1F3CB}'.repeat(19)
+ await page.locator('#password').fill(emoji)
+ await page.locator('#password-confirm').fill(emoji)
+ await expect(page.getByText(/at most 72 characters/i)).toBeVisible()
+ await expect(page.getByRole('button', { name: /create account/i })).toBeDisabled()
+})
diff --git a/web/nginx.conf.template b/web/nginx.conf.template
index 67d3e63..d4a9882 100644
--- a/web/nginx.conf.template
+++ b/web/nginx.conf.template
@@ -32,6 +32,21 @@ server {
proxy_read_timeout 60s;
}
+ # W3C Change Password URL. Password managers (Safari Keychain, Chrome Password
+ # Checkup, 1Password) open this path to take a user straight to the change-password
+ # form. Exact-match so it wins over the SPA fallback, which would otherwise answer
+ # with index.html and leave React Router to bounce an unauthenticated visitor to
+ # /login. The dev/preview equivalent lives in web/vite.config.ts.
+ location = /.well-known/change-password {
+ # absolute_redirect off keeps the Location relative. With nginx's default (on) it
+ # would expand to an absolute URL built from $scheme — and this block listens on
+ # 80 behind a TLS terminator, so that scheme is http. A manager opening the https
+ # well-known URL would be bounced to cleartext and left to whatever the outer
+ # proxy does about it. Relative inherits the request's real scheme.
+ absolute_redirect off;
+ return 302 /settings/password;
+ }
+
# SPA fallback — serve index.html for all non-file routes
location / {
try_files $uri $uri/ /index.html;
diff --git a/web/src/App.tsx b/web/src/App.tsx
index 06af503..eaa0717 100644
--- a/web/src/App.tsx
+++ b/web/src/App.tsx
@@ -21,6 +21,7 @@ import LogFood from './pages/LogFood'
import Weight from './pages/Weight'
import WeightDetail from './pages/WeightDetail'
import Settings from './pages/Settings'
+import ChangePassword from './pages/ChangePassword'
import Login from './pages/Login'
import Register from './pages/Register'
@@ -65,6 +66,7 @@ function App() {
<Route path="/weight" element={<Weight />} />
<Route path="/weight/:id" element={<WeightDetail />} />
<Route path="/settings" element={<Settings />} />
+ <Route path="/settings/password" element={<ChangePassword />} />
</Route>
) : (
<Route path="*" element={<Navigate to="/login" />} />
diff --git a/web/src/components/ui/PasswordField.tsx b/web/src/components/ui/PasswordField.tsx
new file mode 100644
index 0000000..cfafa6f
--- /dev/null
+++ b/web/src/components/ui/PasswordField.tsx
@@ -0,0 +1,81 @@
+import { useState } from 'react'
+import { AlertCircle, Check, Eye, EyeOff, X } from 'lucide-react'
+import type { RuleState } from '@lyftr/shared'
+
+export function Rule({ state, children }: { state: RuleState; children: React.ReactNode }) {
+ const tone =
+ state === 'ok' ? 'text-success-400' : state === 'bad' ? 'text-error-400' : 'text-tx-muted'
+ return (
+ <p className={`flex items-center gap-1.5 text-xs mt-1.5 ${tone}`}>
+ {state === 'ok' ? <Check className="w-3 h-3 flex-shrink-0" />
+ : state === 'bad' ? <X className="w-3 h-3 flex-shrink-0" />
+ : <span className="w-3 h-3 flex-shrink-0 rounded-full border border-current opacity-40" aria-hidden="true" />}
+ {children}
+ </p>
+ )
+}
+
+interface Props {
+ id: string
+ label: string
+ value: string
+ onChange: (value: string) => void
+ autoComplete: 'current-password' | 'new-password'
+ placeholder?: string
+ /** Rule rows rendered under the input. */
+ children?: React.ReactNode
+}
+
+// Every password input in the app, so the three screens that ask for one behave the same:
+// sign in, register, and change password.
+//
+// A reveal toggle and a Caps Lock warning are worth more on a password field than
+// anywhere else, because the field hides the only evidence of what went wrong. Without
+// them a typo and a forgotten password are indistinguishable — the user sees the same
+// rejection either way and cannot tell which mistake they made.
+export default function PasswordField({
+ id, label, value, onChange, autoComplete, placeholder, children,
+}: Props) {
+ const [visible, setVisible] = useState(false)
+ const [caps, setCaps] = useState(false)
+
+ return (
+ <div>
+ <label htmlFor={id} className="label">{label}</label>
+ <div className="relative mt-2">
+ <input
+ id={id}
+ type={visible ? 'text' : 'password'}
+ className="input pr-11"
+ autoComplete={autoComplete}
+ placeholder={placeholder}
+ value={value}
+ onChange={e => onChange(e.target.value)}
+ // Caps Lock is only readable from a key event, so it is tracked per field —
+ // the one being typed in is the only one with a current answer. Cleared on
+ // blur so a stale warning cannot outlive the field it belonged to.
+ onKeyUp={e => setCaps(e.getModifierState('CapsLock'))}
+ onBlur={() => setCaps(false)}
+ required
+ />
+ <button
+ type="button"
+ onClick={() => setVisible(v => !v)}
+ // tabIndex -1 keeps Tab running straight down the fields to the submit button,
+ // which is the path someone filling this form actually wants.
+ tabIndex={-1}
+ aria-label={visible ? `Hide ${label.toLowerCase()}` : `Show ${label.toLowerCase()}`}
+ className="absolute inset-y-0 right-0 px-3 flex items-center text-tx-muted hover:text-tx-primary transition-colors"
+ >
+ {visible ? <EyeOff className="w-4 h-4" /> : <Eye className="w-4 h-4" />}
+ </button>
+ </div>
+ {caps && (
+ <p className="flex items-center gap-1.5 text-xs mt-1.5 text-warning-400">
+ <AlertCircle className="w-3 h-3 flex-shrink-0" /> Caps Lock is on
+ </p>
+ )}
+ {children}
+ </div>
+ )
+}
diff --git a/web/src/pages/ChangePassword.tsx b/web/src/pages/ChangePassword.tsx
new file mode 100644
index 0000000..17049b0
--- /dev/null
+++ b/web/src/pages/ChangePassword.tsx
@@ -0,0 +1,153 @@
+import { useState } from 'react'
+import { Link } from 'react-router-dom'
+import { ArrowLeft, AlertCircle, Loader, ShieldCheck } from 'lucide-react'
+import { userAPI } from '../services/api'
+import { useAuthStore } from '../stores/auth'
+import { apiErrorMessage, differentRuleLabel, lengthRuleLabel, matchRuleLabel, newPasswordRules } from '@lyftr/shared'
+import PageHeader from '../components/ui/PageHeader'
+import PasswordField, { Rule } from '../components/ui/PasswordField'
+
+// Its own route rather than a disclosure inside Settings, because /.well-known/change-password
+// (W3C Change Password URL — Safari Keychain, Chrome Password Checkup, 1Password) redirects
+// here. That contract needs a URL that lands on the form itself; a collapsed panel on
+// /settings would drop the user on a settings list with nothing open.
+export default function ChangePassword() {
+ const user = useAuthStore(s => s.user)
+ const [current, setCurrent] = useState('')
+ const [next, setNext] = useState('')
+ const [confirm, setConfirm] = useState('')
+ const [saving, setSaving] = useState(false)
+ const [error, setError] = useState<string | null>(null)
+ const [done, setDone] = useState(false)
+
+ const rules = newPasswordRules({ password: next, confirm, current })
+
+ const submit = async (e: React.FormEvent) => {
+ e.preventDefault()
+ setError(null)
+
+ // The rules above already show these states while typing and the button is disabled
+ // until they pass, so this is a backstop rather than the primary feedback — a form
+ // can still be submitted by other means, and the server is the real authority.
+ if (!rules.ready) return
+
+ setSaving(true)
+ try {
+ await userAPI.changePassword({ current_password: current, new_password: next })
+ setCurrent(''); setNext(''); setConfirm('')
+ setDone(true)
+ } catch (err) {
+ setError(apiErrorMessage(err, "Couldn't change your password. Please try again."))
+ } finally {
+ setSaving(false)
+ }
+ }
+
+ // Success replaces the form. Leaving three filled-looking boxes under a success banner
+ // invites a second submit that would fail — the current password is no longer current.
+ if (done) {
+ return (
+ <div className="space-y-5 animate-slide-up max-w-lg">
+ <Link to="/settings" className="flex items-center gap-1.5 text-sm text-tx-muted hover:text-tx-primary transition-colors">
+ <ArrowLeft className="w-4 h-4" /> Settings
+ </Link>
+
+ <div className="card p-6 flex flex-col items-center text-center gap-3">
+ <div className="w-12 h-12 rounded-full bg-success-500/10 border border-success-500/20 flex items-center justify-center">
+ <ShieldCheck className="w-6 h-6 text-success-400" />
+ </div>
+ <div>
+ <h1 className="font-display font-bold text-xl text-tx-primary">Password changed</h1>
+ <p className="text-sm text-tx-muted mt-1">
+ You are still signed in here. Every other device has been signed out and will
+ need the new password.
+ </p>
+ </div>
+ <Link to="/settings" className="btn-secondary btn-sm mt-1">Back to settings</Link>
+ </div>
+ </div>
+ )
+ }
+
+ return (
+ <div className="space-y-5 animate-slide-up max-w-lg">
+ <Link to="/settings" className="flex items-center gap-1.5 text-sm text-tx-muted hover:text-tx-primary transition-colors">
+ <ArrowLeft className="w-4 h-4" /> Settings
+ </Link>
+
+ <PageHeader
+ title="Change password"
+ subtitle="You will stay signed in here. Every other device is signed out."
+ />
+
+ <form onSubmit={submit} className="card p-4 space-y-4">
+ {/* Password managers key the saved entry on a username field in the same form.
+ Without one they file the new password under a blank or guessed account. It has
+ to carry the real address to do that — an empty value is the same as having no
+ field at all. Hidden rather than absent, since the user already knows who they
+ are signed in as. */}
+ <input
+ type="text"
+ autoComplete="username"
+ className="hidden"
+ tabIndex={-1}
+ aria-hidden="true"
+ readOnly
+ value={user?.email ?? ''}
+ />
+
+ <PasswordField
+ id="current-password"
+ label="Current password"
+ value={current}
+ onChange={setCurrent}
+ autoComplete="current-password"
+ />
+
+ <PasswordField
+ id="new-password"
+ label="New password"
+ value={next}
+ onChange={setNext}
+ autoComplete="new-password"
+ >
+ <Rule state={rules.length}>{lengthRuleLabel(next)}</Rule>
+ <Rule state={rules.different}>{differentRuleLabel()}</Rule>
+ </PasswordField>
+
+ <PasswordField
+ id="confirm-password"
+ label="Confirm new password"
+ value={confirm}
+ onChange={setConfirm}
+ autoComplete="new-password"
+ >
+ <Rule state={rules.match}>{matchRuleLabel(rules.match)}</Rule>
+ </PasswordField>
+
+ {/* Server-side failures only — a wrong current password, or a change that landed
+ elsewhere first. Everything checkable in the browser is a Rule above, so this
+ box appearing always means the request was actually made and refused. */}
+ {error && (
+ <div className="alert-error">
+ <AlertCircle className="w-5 h-5 flex-shrink-0" />
+ <span>{error}</span>
+ </div>
+ )}
+
+ <div className="flex gap-2 pt-1">
+ <button
+ type="submit"
+ disabled={saving || !rules.ready}
+ className="btn-primary btn-sm flex-1 flex items-center justify-center gap-2"
+ >
+ {saving ? <><Loader className="w-3.5 h-3.5 animate-spin" /> Saving</> : 'Update password'}
+ </button>
+ <Link to="/settings" className="btn-secondary btn-sm flex-1 flex items-center justify-center">
+ Cancel
+ </Link>
+ </div>
+ </form>
+ </div>
+ )
+}
diff --git a/web/src/pages/Login.tsx b/web/src/pages/Login.tsx
index fb9f003..029d34f 100644
--- a/web/src/pages/Login.tsx
+++ b/web/src/pages/Login.tsx
@@ -7,6 +7,7 @@ import { useServerInfo } from '../hooks/useServerInfo'
import { formatVersion, registrationOpen } from '@lyftr/shared'
import Logo from '../components/Logo'
import ServerSettings from '../components/ServerSettings'
+import PasswordField from '../components/ui/PasswordField'
export default function Login() {
const navigate = useNavigate()
@@ -139,21 +140,14 @@ export default function Login() {
</div>
{/* Password */}
- <div>
- <div className="mb-2">
- <label htmlFor="password" className="label">Password</label>
- </div>
- <input
- id="password"
- type="password"
- value={password}
- onChange={e => setPassword(e.target.value)}
- className="input mt-2"
- placeholder="••••••••"
- autoComplete="current-password"
- required
- />
- </div>
+ <PasswordField
+ id="password"
+ label="Password"
+ value={password}
+ onChange={setPassword}
+ autoComplete="current-password"
+ placeholder="••••••••"
+ />
{/* Error */}
{error && (
diff --git a/web/src/pages/Register.tsx b/web/src/pages/Register.tsx
index ab34880..59adce0 100644
--- a/web/src/pages/Register.tsx
+++ b/web/src/pages/Register.tsx
@@ -4,9 +4,10 @@ import { AlertCircle, Dumbbell, Apple, TrendingUp, UserPlus, Lock } from 'lucide
import { useAuthStore } from '../stores/auth'
import { apiErrorMessage } from '../services/api'
import { useServerInfo } from '../hooks/useServerInfo'
-import { formatVersion, registrationOpen } from '@lyftr/shared'
+import { formatVersion, registrationOpen, lengthRuleLabel, matchRuleLabel, newPasswordRules } from '@lyftr/shared'
import Logo from '../components/Logo'
import ServerSettings from '../components/ServerSettings'
+import PasswordField, { Rule } from '../components/ui/PasswordField'
export default function Register() {
const navigate = useNavigate()
@@ -20,11 +21,14 @@ export default function Register() {
const [error, setError] = useState('')
const [isLoading, setLoading] = useState(false)
+ const rules = newPasswordRules({ password, confirm: passwordConfirm })
+
const handleSubmit = async (e: React.FormEvent) => {
e.preventDefault()
setError('')
- if (password !== passwordConfirm) { setError('Passwords do not match'); return }
- if (password.length < 8) { setError('Password must be at least 8 characters'); return }
+ // The rules render under the fields as they type and the button is disabled until
+ // they pass, so this is a backstop. The banner below is now server failures only.
+ if (!rules.ready) return
setLoading(true)
try {
await register(email, password)
@@ -151,34 +155,28 @@ export default function Register() {
</div>
{/* Password */}
- <div>
- <label htmlFor="password" className="label">Password</label>
- <input
- id="password"
- type="password"
- value={password}
- onChange={e => setPassword(e.target.value)}
- className="input mt-2"
- placeholder="Min 8 characters"
- autoComplete="new-password"
- required
- />
- </div>
+ <PasswordField
+ id="password"
+ label="Password"
+ value={password}
+ onChange={setPassword}
+ autoComplete="new-password"
+ placeholder="••••••••"
+ >
+ <Rule state={rules.length}>{lengthRuleLabel(password)}</Rule>
+ </PasswordField>
{/* Confirm password */}
- <div>
- <label htmlFor="password-confirm" className="label">Confirm password</label>
- <input
- id="password-confirm"
- type="password"
- value={passwordConfirm}
- onChange={e => setPasswordConfirm(e.target.value)}
- className="input mt-2"
- placeholder="••••••••"
- autoComplete="new-password"
- required
- />
- </div>
+ <PasswordField
+ id="password-confirm"
+ label="Confirm password"
+ value={passwordConfirm}
+ onChange={setPasswordConfirm}
+ autoComplete="new-password"
+ placeholder="••••••••"
+ >
+ <Rule state={rules.match}>{matchRuleLabel(rules.match)}</Rule>
+ </PasswordField>
{/* Error */}
{error && (
@@ -191,7 +189,7 @@ export default function Register() {
{/* Create account button */}
<button
type="submit"
- disabled={isLoading}
+ disabled={isLoading || !rules.ready}
className="btn-primary btn-lg w-full mt-6 flex items-center justify-center gap-2"
>
<UserPlus className="w-4 h-4" />
diff --git a/web/src/pages/Settings.tsx b/web/src/pages/Settings.tsx
index 0e9e792..31fe714 100644
--- a/web/src/pages/Settings.tsx
+++ b/web/src/pages/Settings.tsx
@@ -1,4 +1,5 @@
import { useState, useEffect, useCallback } from 'react'
+import { memberSince } from '@lyftr/shared'
import { useAuthStore } from '../stores/auth'
import { useServerStore } from '../stores/server'
import { useServerInfo } from '../hooks/useServerInfo'
@@ -7,19 +8,38 @@ import { useTheme } from '../hooks/useTheme'
import { exerciseAPI } from '../services/api'
import PageHeader from '../components/ui/PageHeader'
import ServerSettings from '../components/ServerSettings'
+import { Link } from 'react-router-dom'
import {
Moon, Sun, LogOut, Trash2, Check, AlertCircle, Loader,
- RefreshCw, Pencil, Clock, Minus, Plus,
+ RefreshCw, Pencil, Clock, Minus, Plus, KeyRound,
} from 'lucide-react'
+// Wraps per row, on content rather than on viewport width.
+//
+// Originally this was side-by-side at every width with `flex-shrink-0` on the value.
+// Since the value could not shrink, a wide one — an email address, most obviously — took
+// the space it wanted and the label column absorbed all the squeeze, so "Your login email
+// address" wrapped down four near-empty lines at 390px while the address still clipped at
+// the card edge.
+//
+// Stacking everything below `sm` fixed that and overcorrected: a compact control like the
+// theme toggle got dropped onto its own line too, for no gain, and the page grew to a
+// ~2800px scroll on a phone. `flex-wrap` asks the right question instead — does this
+// particular value fit beside its label? A toggle does and stays inline; an email address
+// does not and takes the next line at full width. No breakpoint decides it, so the row is
+// right at any width and for any content.
+//
+// The label keeps a `min-w` floor so wrapping actually triggers: with `min-w-0` alone it
+// would shrink to nothing and the pair would stay jammed on one line forever.
function SettingRow({ label, description, children }: { label: string; description?: string; children: React.ReactNode }) {
return (
- <div className="flex items-center justify-between py-4">
- <div className="flex-1 mr-4">
+ <div className="flex flex-wrap items-center justify-between gap-x-4 gap-y-2 py-4">
+ <div className="min-w-[9rem] flex-1">
<p className="text-sm font-medium text-tx-primary">{label}</p>
{description && <p className="text-xs text-tx-muted mt-0.5">{description}</p>}
</div>
- <div className="flex-shrink-0">{children}</div>
+ {/* break-words so a long unbroken value wraps instead of overflowing the card. */}
+ <div className="min-w-0 max-w-full flex-shrink-0 break-words">{children}</div>
</div>
)
}
@@ -170,9 +190,12 @@ export default function Settings() {
<span className="text-sm text-tx-muted font-mono">{user?.email}</span>
</SettingRow>
<SettingRow label="Member since">
- <span className="text-sm text-tx-muted">
- {user?.created_at ? new Date(user.created_at).toLocaleDateString('en-US', { month: 'long', year: 'numeric' }) : '—'}
- </span>
+ <span className="text-sm text-tx-muted">{memberSince(user?.created_at)}</span>
+ </SettingRow>
+ <SettingRow label="Password" description="Changing it signs you out on your other devices">
+ <Link to="/settings/password" className="btn-secondary btn-sm">
+ <KeyRound className="w-3.5 h-3.5" /> Change
+ </Link>
</SettingRow>
</Section>
diff --git a/web/vite.config.ts b/web/vite.config.ts
index c854396..1242ff1 100644
--- a/web/vite.config.ts
+++ b/web/vite.config.ts
@@ -2,10 +2,35 @@ import { defineConfig } from 'vite'
import react from '@vitejs/plugin-react'
import basicSsl from '@vitejs/plugin-basic-ssl'
import { resolveConfig } from './vite.resolve'
+import type { Connect, Plugin } from 'vite'
+
+// The W3C Change Password URL. Password managers (Safari Keychain, Chrome Password
+// Checkup, 1Password) open /.well-known/change-password to send a user straight to a
+// site's change-password form, and expect a redirect rather than a page.
+//
+// Production serves this from nginx (web/nginx.conf.template, fly/nginx.fly.conf). This
+// plugin is the dev/preview equivalent, so the behaviour is identical in every mode the
+// e2e suite can run against — without it the SPA fallback would answer with index.html
+// and React Router would bounce the user to /login.
+const CHANGE_PASSWORD_URL = '/.well-known/change-password'
+
+function wellKnownChangePassword(): Plugin {
+ const middleware: Connect.NextHandleFunction = (req, res, next) => {
+ if (req.url?.split('?')[0] !== CHANGE_PASSWORD_URL) return next()
+ res.writeHead(302, { Location: '/settings/password' })
+ res.end()
+ }
+ return {
+ name: 'lyftr-well-known-change-password',
+ configureServer: server => { server.middlewares.use(middleware) },
+ configurePreviewServer: server => { server.middlewares.use(middleware) },
+ }
+}
export default defineConfig(({ command }) => ({
plugins: [
react(),
+ wellKnownChangePassword(),
// Self-signed HTTPS so getUserMedia works on mobile LAN during dev.
// Production HTTPS is handled by the reverse proxy (nginx/Caddy) — this never runs in builds.
...(command === 'serve' ? [basicSsl()] : []),