Self-hosted fitness tracker. Log workouts, track nutrition, and monitor progress. Docker deployment, mobile-friendly.
Give every API error a stable code the apps can translate (#202)
Carter7d8a0ba798c5
diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.ymlindex 5f577df..5ecd4b2 100644--- a/.github/workflows/ci.yml+++ b/.github/workflows/ci.yml@@ -57,6 +57,8 @@ jobs:filters: |backend:- 'backend/**'+ # utils/codes_test.go pins the registry to the client catalog.+ - 'packages/shared/src/i18n/locales/en.json'- 'fly.toml'- 'fly/**'- 'docker-compose.yml'diff --git a/backend/controllers/active_session.go b/backend/controllers/active_session.goindex f31cfa0..0dcb297 100644--- a/backend/controllers/active_session.go+++ b/backend/controllers/active_session.go@@ -4,6 +4,7 @@ import ("database/sql""github.com/Cawlumm/lyftr-backend/middleware"+ "github.com/Cawlumm/lyftr-backend/models""github.com/Cawlumm/lyftr-backend/utils""github.com/gin-gonic/gin")@@ -23,11 +24,9 @@ func (h *Handler) GetActiveSession(c *gin.Context) {func (h *Handler) UpsertActiveSession(c *gin.Context) {uid := middleware.UserID(c)- var body struct {- Data string `json:"data" binding:"required"`- }+ var body models.ActiveSessionRequestif err := c.ShouldBindJSON(&body); err != nil {- utils.BadRequest(c, utils.BindMessage(err))+ utils.BindError(c, err)return}if utils.DBError(c, h.s.ActiveSession.Upsert(uid, body.Data)) {diff --git a/backend/controllers/auth.go b/backend/controllers/auth.goindex 9e839e3..6692356 100644--- a/backend/controllers/auth.go+++ b/backend/controllers/auth.go@@ -14,19 +14,6 @@ import (var validate = utils.NewValidator()-// EmailTakenMessage is the 409 for an address another account holds, shared by-// registration and email change.-const EmailTakenMessage = "That email is already registered."--// passwordChangedMessage is the 409 when the stored hash moved under a request that had-// already verified the old one.-const passwordChangedMessage = "Your password was changed elsewhere. Please try again."--// RegistrationClosedMessage is what a rejected signup sees. One constant so the two-// ways of being closed (REGISTRATION=closed, and first-user with the slot taken) are-// indistinguishable to a caller — and so the handler and its tests cannot drift.-const RegistrationClosedMessage = "Registration is closed on this server."-// registrationOpen reports whether a new account may be created right now. Errors are// reported as closed: advertising an open instance because a COUNT failed is the wrong// direction to fail.@@ -55,13 +42,13 @@ func (h *Handler) Register(c *gin.Context) {return}if !open {- utils.Forbidden(c, RegistrationClosedMessage)+ utils.Fail(c, utils.CodeRegistrationClosed, nil)return}var req models.RegisterRequestif err := c.ShouldBindJSON(&req); err != nil {- utils.BadRequest(c, utils.BindMessage(err))+ utils.BindError(c, err)return}if err := validate.Struct(req); err != nil {@@ -73,7 +60,7 @@ func (h *Handler) Register(c *gin.Context) {// 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)+ utils.Fail(c, utils.CodePasswordTooLong, nil)return}@@ -90,11 +77,11 @@ func (h *Handler) Register(c *gin.Context) {userID, err := create(req.Email, hash)if errors.Is(err, stores.ErrRegistrationClosed) {- utils.Forbidden(c, RegistrationClosedMessage)+ utils.Fail(c, utils.CodeRegistrationClosed, nil)return}if errors.Is(err, stores.ErrEmailTaken) || utils.IsUniqueViolation(err) {- utils.Conflict(c, EmailTakenMessage)+ utils.Fail(c, utils.CodeEmailTaken, nil)return}if utils.DBError(c, err) {@@ -124,7 +111,7 @@ func (h *Handler) Register(c *gin.Context) {func (h *Handler) Login(c *gin.Context) {var req models.LoginRequestif err := c.ShouldBindJSON(&req); err != nil {- utils.BadRequest(c, utils.BindMessage(err))+ utils.BindError(c, err)return}if err := validate.Struct(req); err != nil {@@ -139,14 +126,14 @@ func (h *Handler) Login(c *gin.Context) {// 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.")+ utils.Fail(c, utils.CodeInvalidCredentials, nil)return}if utils.DBError(c, err) {return}if !utils.CheckPassword(req.Password, user.Password) {- utils.Unauthorized(c, "Invalid email or password.")+ utils.Fail(c, utils.CodeInvalidCredentials, nil)return}@@ -167,7 +154,7 @@ func (h *Handler) reauthenticate(c *gin.Context, password string) (models.User,// token was minted would otherwise resolve to the wrong row or to none at all.user, err := h.s.User.GetByID(middleware.UserID(c))if err == sql.ErrNoRows {- utils.Unauthorized(c, "That account no longer exists.")+ utils.Fail(c, utils.CodeAccountNotFound, nil)return models.User{}, false}if utils.DBError(c, err) {@@ -175,7 +162,7 @@ func (h *Handler) reauthenticate(c *gin.Context, password string) (models.User,}if !utils.CheckPassword(password, user.Password) {- utils.Unauthorized(c, "Your current password is incorrect.")+ utils.Fail(c, utils.CodeWrongCurrentPassword, nil)return models.User{}, false}return user, true@@ -189,7 +176,7 @@ func (h *Handler) ChangePassword(c *gin.Context) {var req models.ChangePasswordRequestif err := c.ShouldBindJSON(&req); err != nil {- utils.BadRequest(c, utils.BindMessage(err))+ utils.BindError(c, err)return}if err := validate.Struct(req); err != nil {@@ -205,12 +192,12 @@ func (h *Handler) ChangePassword(c *gin.Context) {// worse, still bump token_version — signing every other device out for a change// that never happened.if req.CurrentPassword == req.NewPassword {- utils.BadRequest(c, "Your new password must be different from your current one.")+ utils.Fail(c, utils.CodePasswordUnchanged, nil)return}if utils.PasswordTooLong(req.NewPassword) {- utils.BadRequest(c, utils.PasswordTooLongMessage)+ utils.Fail(c, utils.CodePasswordTooLong, nil)return}@@ -222,7 +209,7 @@ func (h *Handler) ChangePassword(c *gin.Context) {version, err := h.s.User.ChangePassword(uid, user.Password, newHash)if errors.Is(err, stores.ErrPasswordChanged) {- utils.Conflict(c, passwordChangedMessage)+ utils.Fail(c, utils.CodePasswordChangedElsewhere, nil)return}if utils.DBError(c, err) {@@ -233,7 +220,7 @@ func (h *Handler) ChangePassword(c *gin.Context) {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, "Your password changed. Please sign in again.")+ utils.Fail(c, utils.CodePasswordChangedSignIn, nil)return}@@ -251,7 +238,7 @@ func (h *Handler) ChangePassword(c *gin.Context) {func (h *Handler) ChangeEmail(c *gin.Context) {var req models.ChangeEmailRequestif err := c.ShouldBindJSON(&req); err != nil {- utils.BadRequest(c, utils.BindMessage(err))+ utils.BindError(c, err)return}if err := validate.Struct(req); err != nil {@@ -270,11 +257,11 @@ func (h *Handler) ChangeEmail(c *gin.Context) {updated, err := h.s.User.ChangeEmail(user.ID, user.Password, req.Email)if errors.Is(err, stores.ErrEmailTaken) || utils.IsUniqueViolation(err) {- utils.Conflict(c, EmailTakenMessage)+ utils.Fail(c, utils.CodeEmailTaken, nil)return}if errors.Is(err, stores.ErrPasswordChanged) {- utils.Conflict(c, passwordChangedMessage)+ utils.Fail(c, utils.CodePasswordChangedElsewhere, nil)return}if utils.DBError(c, err) {@@ -290,7 +277,7 @@ func (h *Handler) ChangeEmail(c *gin.Context) {func (h *Handler) respondWithSession(c *gin.Context, user models.User) {access, refresh, err := utils.GenerateTokenPair(user.ID, user.Email, user.TokenVersion)if err != nil {- utils.Unauthorized(c, "Your email changed. Please sign in again.")+ utils.Fail(c, utils.CodeEmailChangedSignIn, nil)return}utils.OK(c, models.AuthResponse{Token: access, RefreshToken: refresh, User: user})@@ -299,13 +286,13 @@ func (h *Handler) respondWithSession(c *gin.Context, user models.User) {func (h *Handler) RefreshToken(c *gin.Context) {var req models.RefreshRequestif err := c.ShouldBindJSON(&req); err != nil {- utils.BadRequest(c, utils.BindMessage(err))+ utils.BindError(c, err)return}claims, err := utils.ValidateToken(req.RefreshToken)if err != nil || claims.Type != "refresh" {- utils.Unauthorized(c, "Your session isn't valid. Please sign in again.")+ utils.Fail(c, utils.CodeSessionInvalid, nil)return}@@ -316,14 +303,14 @@ func (h *Handler) RefreshToken(c *gin.Context) {// for access tokens on every request, so a revoked device stops at its next request.current, err := h.s.User.TokenVersion(claims.UserID)if err == sql.ErrNoRows {- utils.Unauthorized(c, "Your session isn't valid. Please sign in again.")+ utils.Fail(c, utils.CodeSessionInvalid, nil)return}if utils.DBError(c, err) {return}if utils.NormalizeTokenVersion(claims.TokenVersion) != current {- utils.Unauthorized(c, "Your session expired. Please sign in again.")+ utils.Fail(c, utils.CodeSessionExpired, nil)return}diff --git a/backend/controllers/auth_test.go b/backend/controllers/auth_test.goindex 4e3ff68..16fa051 100644--- a/backend/controllers/auth_test.go+++ b/backend/controllers/auth_test.go@@ -2,6 +2,7 @@ package controllersimport ("errors"+ "fmt""net/http""sort""testing"@@ -58,8 +59,8 @@ func TestRegisterClosedRejectsAndWritesNothing(t *testing.T) {t.Fatalf("status = %d, want 403", w.Code)}body := decodeResponse(t, w)- if body["error"] != RegistrationClosedMessage {- t.Errorf("error = %v, want %q", body["error"], RegistrationClosedMessage)+ if body["error"] != utils.CodeRegistrationClosed.Message(nil) || body["code"] != "REGISTRATION_CLOSED" {+ t.Errorf("body = %v, want REGISTRATION_CLOSED", body)}// The rejection must happen before the insert, not merely be reported after one.if n := userCount(t); n != 0 {@@ -98,8 +99,8 @@ func TestRegisterFirstUserOpensOnceThenCloses(t *testing.T) {t.Fatalf("second register status = %d, want 403", w.Code)}// Identical to the closed message: a caller cannot tell first-user from closed.- if body := decodeResponse(t, w); body["error"] != RegistrationClosedMessage {- t.Errorf("error = %v, want %q", body["error"], RegistrationClosedMessage)+ if body := decodeResponse(t, w); body["error"] != utils.CodeRegistrationClosed.Message(nil) || body["code"] != "REGISTRATION_CLOSED" {+ t.Errorf("body = %v, want REGISTRATION_CLOSED", body)}if n := userCount(t); n != 1 {t.Errorf("user count = %d, want 1", n)@@ -296,8 +297,8 @@ func TestRegisterRejectsAnAddressDifferingOnlyInCase(t *testing.T) {if w.Code != http.StatusConflict {t.Fatalf("status = %d, want 409", w.Code)}- if msg := decodeResponse(t, w)["error"]; msg != "That email is already registered." {- t.Errorf("error = %v", msg)+ if body := decodeResponse(t, w); body["error"] != "That email is already registered." || body["code"] != "EMAIL_TAKEN" {+ t.Errorf("body = %v", body)}if n := userCount(t); n != 1 {t.Errorf("users = %d, want 1", n)@@ -319,8 +320,15 @@ func TestLoginIgnoresCase(t *testing.T) {}code, body = loginRequest(t, "[email protected]", "wrongpassword1")- if code != http.StatusUnauthorized || body["error"] != "Invalid email or password." {- t.Errorf("wrong password = %d %v, want 401 generic", code, body["error"])+ if code != http.StatusUnauthorized || body["error"] != "Invalid email or password." || body["code"] != "INVALID_CREDENTIALS" {+ t.Errorf("wrong password = %d %v, want 401 generic", code, body)+ }+ if _, has := body["params"]; has {+ t.Errorf("params present: %v", body)+ }+ _, unknown := loginRequest(t, "[email protected]", "wrongpassword1")+ if fmt.Sprint(unknown) != fmt.Sprint(body) {+ t.Errorf("unknown address %v differs from wrong password %v", unknown, body)}}diff --git a/backend/controllers/email_test.go b/backend/controllers/email_test.goindex 0527599..b8e3efb 100644--- a/backend/controllers/email_test.go+++ b/backend/controllers/email_test.go@@ -85,7 +85,7 @@ func TestChangeEmailRejectsWrongCurrentPassword(t *testing.T) {uid, _ := registerAndLogin(t, "[email protected]", "password123")code, body := changeEmail(t, uid, "[email protected]", "wrongpassword")- if code != http.StatusUnauthorized || errorOf(body) != "Your current password is incorrect." {+ if code != http.StatusUnauthorized || errorOf(body) != "Your current password is incorrect." || body["code"] != "WRONG_CURRENT_PASSWORD" {t.Fatalf("got %d %v", code, body)}if got := storedEmail(t, uid); got != "[email protected]" {@@ -110,7 +110,7 @@ func TestChangeEmailRejectsAddressHeldInAnotherCase(t *testing.T) {uid, _ := registerAndLogin(t, "[email protected]", "password123")code, body := changeEmail(t, uid, "[email protected]", "password123")- if code != http.StatusConflict || errorOf(body) != "That email is already registered." {+ if code != http.StatusConflict || errorOf(body) != "That email is already registered." || body["code"] != "EMAIL_TAKEN" {t.Fatalf("got %d %v", code, body)}if got := storedEmail(t, uid); got != "[email protected]" {diff --git a/backend/controllers/exercises.go b/backend/controllers/exercises.goindex 167bba8..9037c7d 100644--- a/backend/controllers/exercises.go+++ b/backend/controllers/exercises.go@@ -35,12 +35,12 @@ func (h *Handler) ListExercises(c *gin.Context) {func (h *Handler) GetExercise(c *gin.Context) {id, err := strconv.ParseInt(c.Param("id"), 10, 64)if err != nil {- utils.BadRequest(c, "That exercise id isn't valid.")+ utils.Fail(c, utils.CodeInvalidExerciseID, nil)return}e, err := h.s.Exercise.Get(id)if err == sql.ErrNoRows {- utils.NotFound(c, "That exercise no longer exists.")+ utils.Fail(c, utils.CodeExerciseNotFound, nil)return}if utils.DBError(c, err) {@@ -53,7 +53,7 @@ func (h *Handler) GetExercisePRs(c *gin.Context) {uid := middleware.UserID(c)exerciseID, err := strconv.ParseInt(c.Param("id"), 10, 64)if err != nil {- utils.BadRequest(c, "That exercise id isn't valid.")+ utils.Fail(c, utils.CodeInvalidExerciseID, nil)return}pr, err := h.s.Workout.PRForExercise(uid, exerciseID)@@ -77,7 +77,7 @@ func (h *Handler) GetExerciseHistory(c *gin.Context) {uid := middleware.UserID(c)exerciseID, err := strconv.ParseInt(c.Param("id"), 10, 64)if err != nil {- utils.BadRequest(c, "That exercise id isn't valid.")+ utils.Fail(c, utils.CodeInvalidExerciseID, nil)return}limit := 20@@ -100,11 +100,11 @@ func (h *Handler) GetExerciseHistory(c *gin.Context) {func (h *Handler) RefreshExerciseCache(c *gin.Context) {n, err := h.s.Exercise.RefreshCached(c.Request.Context())if errors.Is(err, stores.ErrNoCatalog) {- utils.BadRequest(c, "This server has no exercise catalog configured.")+ utils.Fail(c, utils.CodeNoExerciseCatalog, nil)return}if err != nil {- utils.BadRequest(c, utils.BindMessage(err))+ utils.BindError(c, err)return}utils.OK(c, gin.H{"refreshed": n})diff --git a/backend/controllers/food.go b/backend/controllers/food.goindex 78693c5..0ba8099 100644--- a/backend/controllers/food.go+++ b/backend/controllers/food.go@@ -33,7 +33,7 @@ func (h *Handler) ListFoodLogs(c *gin.Context) {// only to answer "what is today" when the parameter is omitted.date, ok := h.resolveQueryDay(uid, c.Query("date"))if !ok {- utils.BadRequest(c, "Date must be in YYYY-MM-DD format.")+ utils.Fail(c, utils.CodeInvalidDate, nil)return}logs, err := h.s.Food.ListByDay(uid, date)@@ -47,13 +47,13 @@ func (h *Handler) GetFoodLog(c *gin.Context) {uid := middleware.UserID(c)lid, err := strconv.ParseInt(c.Param("id"), 10, 64)if err != nil {- utils.BadRequest(c, "That id isn't valid.")+ utils.Fail(c, utils.CodeInvalidID, nil)return}f, err := h.s.Food.Get(uid, lid)if err == sql.ErrNoRows {- utils.NotFound(c, "That entry no longer exists.")+ utils.Fail(c, utils.CodeEntryNotFound, nil)return}if utils.DBError(c, err) {@@ -66,7 +66,7 @@ func (h *Handler) LogFood(c *gin.Context) {uid := middleware.UserID(c)var req models.LogFoodRequestif err := c.ShouldBindJSON(&req); err != nil {- utils.BadRequest(c, utils.BindMessage(err))+ utils.BindError(c, err)return}// Same normalisation the favourites path applies, and for a reason that only exists@@ -80,24 +80,8 @@ func (h *Handler) LogFood(c *gin.Context) {utils.ValidationError(c, err)return}- if len(req.Name) > 200 {- utils.BadRequest(c, "Name must be 200 characters or fewer.")- return- }- if len(req.Brand) > 200 {- utils.BadRequest(c, "Brand must be 200 characters or fewer.")- return- }- if len(req.ServingSize) > 100 {- utils.BadRequest(c, "Serving size must be 100 characters or fewer.")- return- }- if len(req.Barcode) > 50 {- utils.BadRequest(c, "Barcode must be 50 characters or fewer.")- return- }- if len(req.ImageURL) > 500 {- utils.BadRequest(c, "Image URL must be 500 characters or fewer.")+ if code, limit, bad := foodTextTooLong(req.Name, req.Brand, req.ServingSize, req.Barcode, req.ImageURL); bad {+ utils.Fail(c, code, map[string]any{"max": limit})return}@@ -108,7 +92,7 @@ func (h *Handler) LogFood(c *gin.Context) {day, ok := h.resolveDay(uid, req.LoggedOn, req.LoggedAt)if !ok {- utils.BadRequest(c, "Logged on must be in YYYY-MM-DD format.")+ utils.Fail(c, utils.CodeInvalidLoggedOn, nil)return}@@ -123,13 +107,13 @@ func (h *Handler) UpdateFoodLog(c *gin.Context) {uid := middleware.UserID(c)lid, err := strconv.ParseInt(c.Param("id"), 10, 64)if err != nil {- utils.BadRequest(c, "That id isn't valid.")+ utils.Fail(c, utils.CodeInvalidID, nil)return}var req models.LogFoodRequestif err := c.ShouldBindJSON(&req); err != nil {- utils.BadRequest(c, utils.BindMessage(err))+ utils.BindError(c, err)return}// Same normalisation the favourites path applies, and for a reason that only exists@@ -143,24 +127,8 @@ func (h *Handler) UpdateFoodLog(c *gin.Context) {utils.ValidationError(c, err)return}- if len(req.Name) > 200 {- utils.BadRequest(c, "Name must be 200 characters or fewer.")- return- }- if len(req.Brand) > 200 {- utils.BadRequest(c, "Brand must be 200 characters or fewer.")- return- }- if len(req.ServingSize) > 100 {- utils.BadRequest(c, "Serving size must be 100 characters or fewer.")- return- }- if len(req.Barcode) > 50 {- utils.BadRequest(c, "Barcode must be 50 characters or fewer.")- return- }- if len(req.ImageURL) > 500 {- utils.BadRequest(c, "Image URL must be 500 characters or fewer.")+ if code, limit, bad := foodTextTooLong(req.Name, req.Brand, req.ServingSize, req.Barcode, req.ImageURL); bad {+ utils.Fail(c, code, map[string]any{"max": limit})return}req.LoggedAt = normalizeLoggedAt(req.LoggedAt)@@ -170,13 +138,13 @@ func (h *Handler) UpdateFoodLog(c *gin.Context) {day, ok := h.resolveDay(uid, req.LoggedOn, req.LoggedAt)if !ok {- utils.BadRequest(c, "Logged on must be in YYYY-MM-DD format.")+ utils.Fail(c, utils.CodeInvalidLoggedOn, nil)return}f, err := h.s.Food.Update(uid, lid, req, day)if err == sql.ErrNoRows {- utils.NotFound(c, "That entry no longer exists.")+ utils.Fail(c, utils.CodeEntryNotFound, nil)return}if utils.DBError(c, err) {@@ -189,7 +157,7 @@ func (h *Handler) DeleteFoodLog(c *gin.Context) {uid := middleware.UserID(c)lid, err := strconv.ParseInt(c.Param("id"), 10, 64)if err != nil {- utils.BadRequest(c, "That id isn't valid.")+ utils.Fail(c, utils.CodeInvalidID, nil)return}@@ -198,7 +166,7 @@ func (h *Handler) DeleteFoodLog(c *gin.Context) {return}if n == 0 {- utils.NotFound(c, "That entry no longer exists.")+ utils.Fail(c, utils.CodeEntryNotFound, nil)return}utils.OK(c, gin.H{"deleted": true})@@ -208,7 +176,7 @@ func (h *Handler) GetDailyStats(c *gin.Context) {uid := middleware.UserID(c)date, ok := h.resolveQueryDay(uid, c.Query("date"))if !ok {- utils.BadRequest(c, "Date must be in YYYY-MM-DD format.")+ utils.Fail(c, utils.CodeInvalidDate, nil)return}stats, err := h.s.Food.DailyMacros(uid, date)@@ -433,7 +401,7 @@ func doOFFRequest(ctx context.Context, rawURL string) ([]byte, int, error) {func (h *Handler) SearchFood(c *gin.Context) {q := c.Query("q")if q == "" {- utils.BadRequest(c, "A search term is required.")+ utils.Fail(c, utils.CodeSearchTermRequired, nil)return}@@ -459,11 +427,11 @@ func (h *Handler) SearchFood(c *gin.Context) {if err != nil {if ctx.Err() == context.DeadlineExceeded {log.Printf("[food/search] OFF timeout after %dms", elapsed.Milliseconds())- utils.ServiceUnavailable(c, "The food database didn't respond in time. Try again.")+ utils.Fail(c, utils.CodeFoodDatabaseTimeout, nil)return}log.Printf("[food/search] OFF network error: %v", err)- utils.ServiceUnavailable(c, "Couldn't reach the food database.")+ utils.Fail(c, utils.CodeFoodDatabaseUnreachable, nil)return}@@ -471,15 +439,15 @@ func (h *Handler) SearchFood(c *gin.Context) {case status == 429:log.Printf("[food/search] OFF rate limit hit")c.Header("Retry-After", "60")- c.JSON(http.StatusTooManyRequests, gin.H{"error": "Too many requests. Wait a moment and try again."})+ utils.Fail(c, utils.CodeRateLimited, nil)returncase status >= 500:log.Printf("[food/search] OFF upstream error: %d", status)- utils.ServiceUnavailable(c, "Food search is temporarily unavailable.")+ utils.Fail(c, utils.CodeFoodSearchUnavailable, nil)returncase status != 200:log.Printf("[food/search] OFF unexpected status: %d", status)- utils.ServiceUnavailable(c, "Food search is temporarily unavailable.")+ utils.Fail(c, utils.CodeFoodSearchUnavailable, nil)return}@@ -512,14 +480,10 @@ type offBarcodeResponse struct {func (h *Handler) LookupBarcode(c *gin.Context) {code := c.Param("code")- if code == "" {- utils.BadRequest(c, "A barcode is required.")- return- }matched, err := regexp.MatchString(`^\d{6,14}$`, code)if err != nil || !matched {- utils.BadRequest(c, "That barcode isn't valid.")+ utils.Fail(c, utils.CodeInvalidBarcode, nil)return}@@ -537,11 +501,11 @@ func (h *Handler) LookupBarcode(c *gin.Context) {if err != nil {if ctx.Err() == context.DeadlineExceeded {log.Printf("[food/barcode] OFF timeout after %dms", elapsed.Milliseconds())- utils.ServiceUnavailable(c, "The food database didn't respond in time. Try again.")+ utils.Fail(c, utils.CodeFoodDatabaseTimeout, nil)return}log.Printf("[food/barcode] OFF network error: %v", err)- utils.ServiceUnavailable(c, "Couldn't reach the food database.")+ utils.Fail(c, utils.CodeFoodDatabaseUnreachable, nil)return}@@ -549,11 +513,11 @@ func (h *Handler) LookupBarcode(c *gin.Context) {case status == 429:log.Printf("[food/barcode] OFF rate limit hit")c.Header("Retry-After", "60")- c.JSON(http.StatusTooManyRequests, gin.H{"error": "Too many requests. Wait a moment and try again."})+ utils.Fail(c, utils.CodeRateLimited, nil)returncase status >= 500:log.Printf("[food/barcode] OFF upstream error: %d", status)- utils.ServiceUnavailable(c, "Barcode lookup is temporarily unavailable.")+ utils.Fail(c, utils.CodeBarcodeLookupUnavailable, nil)return}@@ -565,7 +529,7 @@ func (h *Handler) LookupBarcode(c *gin.Context) {}if !strings.HasPrefix(parsed.Status, "success") || parsed.Product.ProductName == "" {- utils.NotFound(c, "No product matched that barcode.")+ utils.Fail(c, utils.CodeProductNotFound, nil)return}@@ -588,7 +552,7 @@ func (h *Handler) CreateSavedFood(c *gin.Context) {uid := middleware.UserID(c)var req models.SaveFoodRequestif err := c.ShouldBindJSON(&req); err != nil {- utils.BadRequest(c, utils.BindMessage(err))+ utils.BindError(c, err)return}// Surrounding whitespace is not a distinguishing feature of a food:@@ -603,20 +567,8 @@ func (h *Handler) CreateSavedFood(c *gin.Context) {utils.ValidationError(c, err)return}- if len(req.Name) > 200 {- utils.BadRequest(c, "Name must be 200 characters or fewer.")- return- }- if len(req.Brand) > 200 {- utils.BadRequest(c, "Brand must be 200 characters or fewer.")- return- }- if len(req.ServingSize) > 100 {- utils.BadRequest(c, "Serving size must be 100 characters or fewer.")- return- }- if len(req.Barcode) > 50 {- utils.BadRequest(c, "Barcode must be 50 characters or fewer.")+ if code, limit, bad := foodTextTooLong(req.Name, req.Brand, req.ServingSize, req.Barcode, ""); bad {+ utils.Fail(c, code, map[string]any{"max": limit})return}@@ -644,7 +596,7 @@ func (h *Handler) DeleteSavedFood(c *gin.Context) {uid := middleware.UserID(c)fid, err := strconv.ParseInt(c.Param("id"), 10, 64)if err != nil {- utils.BadRequest(c, "That id isn't valid.")+ utils.Fail(c, utils.CodeInvalidID, nil)return}@@ -653,8 +605,29 @@ func (h *Handler) DeleteSavedFood(c *gin.Context) {return}if n == 0 {- utils.NotFound(c, "That saved food no longer exists.")+ utils.Fail(c, utils.CodeSavedFoodNotFound, nil)return}utils.OK(c, gin.H{"deleted": true})}++// foodTextTooLong checks the free-text columns against their limits, in the order the+// form lists them, and reports the first one that is over. Lengths are bytes, as before.+func foodTextTooLong(name, brand, servingSize, barcode, imageURL string) (code utils.Code, limit int, bad bool) {+ for _, f := range []struct {+ value string+ limit int+ code utils.Code+ }{+ {name, 200, utils.CodeFoodNameTooLong},+ {brand, 200, utils.CodeFoodBrandTooLong},+ {servingSize, 100, utils.CodeServingSizeTooLong},+ {barcode, 50, utils.CodeBarcodeTooLong},+ {imageURL, 500, utils.CodeImageURLTooLong},+ } {+ if len(f.value) > f.limit {+ return f.code, f.limit, true+ }+ }+ return code, 0, false+}diff --git a/backend/controllers/food_codes_test.go b/backend/controllers/food_codes_test.gonew file mode 100644index 0000000..0438f90--- /dev/null+++ b/backend/controllers/food_codes_test.go@@ -0,0 +1,159 @@+package controllers++import (+ "context"+ "errors"+ "net/http"+ "net/http/httptest"+ "strings"+ "testing"+ "time"+)++// These pin the code, the status and the sentence of every error the food-database and+// exercise-catalog paths can answer with, so a client can word each one itself.++func wantCode(t *testing.T, w *httptest.ResponseRecorder, status int, code, sentence string) map[string]any {+ t.Helper()+ body := decodeResponse(t, w)+ if w.Code != status || body["code"] != code || body["error"] != sentence {+ t.Fatalf("got %d %v, want %d %s %q", w.Code, body, status, code, sentence)+ }+ return body+}++type failingTransport struct{}++func (failingTransport) RoundTrip(*http.Request) (*http.Response, error) {+ return nil, errors.New("dial tcp: connection refused")+}++func TestLookupBarcode_productNotFoundCode(t *testing.T) {+ setupTestDB(t)+ uid := createTestUser(t)+ withOFFMock(t, func(w http.ResponseWriter, r *http.Request) {+ w.Write([]byte(`{"status":"failure","product":{}}`))+ })++ c, w := newContext(uid, http.MethodGet, "/api/v1/food/barcode/012345678901", nil)+ setParam(c, "code", "012345678901")+ th.LookupBarcode(c)++ wantCode(t, w, http.StatusNotFound, "PRODUCT_NOT_FOUND", "No product matched that barcode.")+}++func TestLookupBarcode_invalidBarcodeCode(t *testing.T) {+ setupTestDB(t)+ uid := createTestUser(t)++ for _, code := range []string{"abc", " ", "12345"} {+ c, w := newContext(uid, http.MethodGet, "/api/v1/food/barcode/"+code, nil)+ setParam(c, "code", code)+ th.LookupBarcode(c)+ wantCode(t, w, http.StatusBadRequest, "INVALID_BARCODE", "That barcode isn't valid.")+ }+}++func TestSearchFood_failureCodes(t *testing.T) {+ setupTestDB(t)+ uid := createTestUser(t)++ t.Run("missing term", func(t *testing.T) {+ c, w := newContext(uid, http.MethodGet, "/api/v1/food/search", nil)+ th.SearchFood(c)+ wantCode(t, w, http.StatusBadRequest, "SEARCH_TERM_REQUIRED", "A search term is required.")+ })++ t.Run("upstream 5xx", func(t *testing.T) {+ withOFFMock(t, func(w http.ResponseWriter, r *http.Request) { w.WriteHeader(http.StatusInternalServerError) })+ c, w := newContext(uid, http.MethodGet, "/api/v1/food/search?q=pizza", nil)+ th.SearchFood(c)+ wantCode(t, w, http.StatusServiceUnavailable, "FOOD_SEARCH_UNAVAILABLE", "Food search is temporarily unavailable.")+ if w.Header().Get("Retry-After") != "2" {+ t.Errorf("Retry-After = %q, want 2", w.Header().Get("Retry-After"))+ }+ })++ t.Run("unreachable", func(t *testing.T) {+ prev := offClient+ offClient = &http.Client{Transport: failingTransport{}, Timeout: 5 * time.Second}+ t.Cleanup(func() { offClient = prev })+ c, w := newContext(uid, http.MethodGet, "/api/v1/food/search?q=pizza", nil)+ th.SearchFood(c)+ wantCode(t, w, http.StatusServiceUnavailable, "FOOD_DATABASE_UNREACHABLE", "Couldn't reach the food database.")+ })++ t.Run("timeout", func(t *testing.T) {+ withOFFMock(t, func(w http.ResponseWriter, r *http.Request) {})+ c, w := newContext(uid, http.MethodGet, "/api/v1/food/search?q=pizza", nil)+ expired, cancel := context.WithDeadline(context.Background(), time.Now().Add(-time.Second))+ defer cancel()+ c.Request = c.Request.WithContext(expired)+ th.SearchFood(c)+ wantCode(t, w, http.StatusServiceUnavailable, "FOOD_DATABASE_TIMEOUT", "The food database didn't respond in time. Try again.")+ if w.Header().Get("Retry-After") != "2" {+ t.Errorf("Retry-After = %q, want 2", w.Header().Get("Retry-After"))+ }+ })+}++func TestLookupBarcode_failureCodes(t *testing.T) {+ setupTestDB(t)+ uid := createTestUser(t)+ lookup := func() *httptest.ResponseRecorder {+ c, w := newContext(uid, http.MethodGet, "/api/v1/food/barcode/012345678901", nil)+ setParam(c, "code", "012345678901")+ th.LookupBarcode(c)+ return w+ }++ t.Run("upstream 5xx", func(t *testing.T) {+ withOFFMock(t, func(w http.ResponseWriter, r *http.Request) { w.WriteHeader(http.StatusBadGateway) })+ wantCode(t, lookup(), http.StatusServiceUnavailable, "BARCODE_LOOKUP_UNAVAILABLE", "Barcode lookup is temporarily unavailable.")+ })++ t.Run("unreachable", func(t *testing.T) {+ prev := offClient+ offClient = &http.Client{Transport: failingTransport{}, Timeout: 5 * time.Second}+ t.Cleanup(func() { offClient = prev })+ wantCode(t, lookup(), http.StatusServiceUnavailable, "FOOD_DATABASE_UNREACHABLE", "Couldn't reach the food database.")+ })+}++func TestLogFood_lengthLimitCodes(t *testing.T) {+ setupTestDB(t)+ uid := createTestUser(t)++ cases := []struct {+ field, code, sentence string+ max int+ }{+ {"name", "FOOD_NAME_TOO_LONG", "Name must be 200 characters or fewer.", 200},+ {"brand", "FOOD_BRAND_TOO_LONG", "Brand must be 200 characters or fewer.", 200},+ {"serving_size", "SERVING_SIZE_TOO_LONG", "Serving size must be 100 characters or fewer.", 100},+ {"barcode", "BARCODE_TOO_LONG", "Barcode must be 50 characters or fewer.", 50},+ {"image_url", "IMAGE_URL_TOO_LONG", "Image URL must be 500 characters or fewer.", 500},+ }+ for _, tc := range cases {+ t.Run(tc.field, func(t *testing.T) {+ body := map[string]any{"name": "Test", "meal": "dinner"}+ body[tc.field] = strings.Repeat("1", tc.max+1)+ c, w := newContext(uid, http.MethodPost, "/api/v1/food", body)+ th.LogFood(c)+ got := wantCode(t, w, http.StatusBadRequest, tc.code, tc.sentence)+ if p, _ := got["params"].(map[string]any); p["max"] != float64(tc.max) {+ t.Errorf("params = %v, want max %d", got["params"], tc.max)+ }+ })+ }+}++func TestRefreshExerciseCache_withoutCatalogCode(t *testing.T) {+ setupTestDB(t)+ uid := createTestUser(t)++ c, w := newContext(uid, http.MethodPost, "/api/v1/admin/sync-exercises", nil)+ th.RefreshExerciseCache(c)++ wantCode(t, w, http.StatusBadRequest, "NO_EXERCISE_CATALOG", "This server has no exercise catalog configured.")+}diff --git a/backend/controllers/food_test.go b/backend/controllers/food_test.goindex 763314b..417efce 100644--- a/backend/controllers/food_test.go+++ b/backend/controllers/food_test.go@@ -1012,6 +1012,9 @@ func TestLookupBarcode_rateLimited(t *testing.T) {if w.Code != http.StatusTooManyRequests {t.Fatalf("expected 429 forwarded, got %d", w.Code)}+ if got := decodeResponse(t, w)["code"]; got != "RATE_LIMITED" || w.Header().Get("Retry-After") != "60" {+ t.Fatalf("code = %v, Retry-After = %q", got, w.Header().Get("Retry-After"))+ }}// ─── SearchFood ───────────────────────────────────────────────────────────────@@ -1070,6 +1073,9 @@ func TestSearchFood_rateLimited(t *testing.T) {if w.Code != http.StatusTooManyRequests {t.Fatalf("expected 429 forwarded, got %d", w.Code)}+ if got := decodeResponse(t, w)["code"]; got != "RATE_LIMITED" || w.Header().Get("Retry-After") != "60" {+ t.Fatalf("code = %v, Retry-After = %q", got, w.Header().Get("Retry-After"))+ }}func TestSearchFood_upstreamError(t *testing.T) {diff --git a/backend/controllers/message_voice_test.go b/backend/controllers/message_voice_test.godeleted file mode 100644index c1da8fd..0000000--- a/backend/controllers/message_voice_test.go+++ /dev/null@@ -1,149 +0,0 @@-package controllers--import (- "go/ast"- "go/parser"- "go/token"- "os"- "path/filepath"- "strconv"- "strings"- "testing"- "unicode"-)--// Everything the API says lands in the same `error` field, and the client renders it-// verbatim — apiErrorMessage prefers a server message over anything it would write-// itself, because a server message is the most specific thing available. That makes-// this copy the product's copy, not internal logging.-//-// validation.go has answered in sentences since it was written ("Calories must be a-// number."). Every other handler answered in log lines ("workout not found"), so a-// login form could show one of each, stacked. This pins the agreement rather than the-// individual strings: a new handler is free to say anything, in this voice.-//-// Lives in controllers, not utils, because CI runs `go test ./controllers/ ./db/-// ./routes/` — a guard in a package CI never runs is a guard that does not exist.--var messageHelpers = map[string]bool{- "BadRequest": true,- "Unauthorized": true,- "Forbidden": true,- "NotFound": true,- "Conflict": true,- "ServiceUnavailable": true,-}--// backendRoot walks up from this package to the module root, so the scan covers-// middleware and stores as well as controllers.-func backendRoot(t *testing.T) string {- t.Helper()- wd, err := os.Getwd()- if err != nil {- t.Fatalf("getwd: %v", err)- }- return filepath.Dir(wd)-}--func checkSentence(t *testing.T, where, msg string, terminal bool) {- t.Helper()- if msg == "" {- return- }- if strings.TrimSpace(msg) != strings.TrimRight(msg, " ") {- t.Errorf("%s: %q has leading whitespace", where, msg)- }- if first := []rune(msg)[0]; !unicode.IsUpper(first) {- t.Errorf("%s: %q should start with a capital — it is shown to a person, not logged", where, msg)- }- if !terminal {- return- }- switch msg[len(msg)-1] {- case '.', '!', '?':- default:- t.Errorf("%s: %q should end in punctuation, like the validator's own messages", where, msg)- }-}--func TestEveryAPIMessageIsASentence(t *testing.T) {- root := backendRoot(t)- fset := token.NewFileSet()-- err := filepath.Walk(root, func(path string, info os.FileInfo, err error) error {- if err != nil {- return err- }- if info.IsDir() {- if name := info.Name(); name == "data" || strings.HasPrefix(name, ".") {- return filepath.SkipDir- }- return nil- }- if !strings.HasSuffix(path, ".go") || strings.HasSuffix(path, "_test.go") {- return nil- }-- file, perr := parser.ParseFile(fset, path, nil, 0)- if perr != nil {- return perr- }-- ast.Inspect(file, func(n ast.Node) bool {- // const RegistrationClosedMessage = "..." — a message by another route.- if vs, ok := n.(*ast.ValueSpec); ok {- for i, name := range vs.Names {- if !strings.HasSuffix(name.Name, "Message") || i >= len(vs.Values) {- continue- }- if lit, ok := vs.Values[i].(*ast.BasicLit); ok && lit.Kind == token.STRING {- if s, e := strconv.Unquote(lit.Value); e == nil {- checkSentence(t, fset.Position(lit.Pos()).String(), s, true)- }- }- }- return true- }-- call, ok := n.(*ast.CallExpr)- if !ok || len(call.Args) < 2 {- return true- }- switch fn := call.Fun.(type) {- case *ast.SelectorExpr: // utils.NotFound(c, "…")- if !messageHelpers[fn.Sel.Name] {- return true- }- case *ast.Ident: // inside package utils itself- if !messageHelpers[fn.Name] {- return true- }- default:- return true- }-- pos := fset.Position(call.Pos()).String()- switch arg := call.Args[1].(type) {- case *ast.BasicLit:- if arg.Kind == token.STRING {- if s, e := strconv.Unquote(arg.Value); e == nil {- checkSentence(t, pos, s, true)- }- }- case *ast.BinaryExpr:- // "Unknown timezone: " + zone + "." — only the opening literal is fixed,- // so the capital is checkable and the full stop is not.- if lit, ok := arg.X.(*ast.BasicLit); ok && lit.Kind == token.STRING {- if s, e := strconv.Unquote(lit.Value); e == nil {- checkSentence(t, pos, s, false)- }- }- }- return true- })- return nil- })- if err != nil {- t.Fatalf("walking backend: %v", err)- }-}diff --git a/backend/controllers/programs.go b/backend/controllers/programs.goindex af85625..af68505 100644--- a/backend/controllers/programs.go+++ b/backend/controllers/programs.go@@ -56,12 +56,12 @@ func (h *Handler) GetProgram(c *gin.Context) {uid := middleware.UserID(c)pid, err := strconv.ParseInt(c.Param("id"), 10, 64)if err != nil {- utils.BadRequest(c, "That program id isn't valid.")+ utils.Fail(c, utils.CodeInvalidProgramID, nil)return}p, err := h.s.Program.Get(uid, pid)if err == sql.ErrNoRows {- utils.NotFound(c, "That program no longer exists.")+ utils.Fail(c, utils.CodeProgramNotFound, nil)return}if utils.DBError(c, err) {@@ -74,7 +74,7 @@ func (h *Handler) CreateProgram(c *gin.Context) {uid := middleware.UserID(c)var req models.CreateProgramRequestif err := c.ShouldBindJSON(&req); err != nil {- utils.BadRequest(c, utils.BindMessage(err))+ utils.BindError(c, err)return}if err := validate.Struct(req); err != nil {@@ -83,7 +83,7 @@ func (h *Handler) CreateProgram(c *gin.Context) {}p, err := h.s.Program.Create(uid, req)if utils.IsForeignKeyViolation(err) {- utils.BadRequest(c, "One or more of those exercises no longer exist.")+ utils.Fail(c, utils.CodeUnknownExercises, nil)return}if utils.DBError(c, err) {@@ -96,12 +96,12 @@ func (h *Handler) UpdateProgram(c *gin.Context) {uid := middleware.UserID(c)pid, err := strconv.ParseInt(c.Param("id"), 10, 64)if err != nil {- utils.BadRequest(c, "That program id isn't valid.")+ utils.Fail(c, utils.CodeInvalidProgramID, nil)return}var req models.CreateProgramRequestif err := c.ShouldBindJSON(&req); err != nil {- utils.BadRequest(c, utils.BindMessage(err))+ utils.BindError(c, err)return}if err := validate.Struct(req); err != nil {@@ -110,11 +110,11 @@ func (h *Handler) UpdateProgram(c *gin.Context) {}p, err := h.s.Program.Update(uid, pid, req)if err == sql.ErrNoRows {- utils.NotFound(c, "That program no longer exists.")+ utils.Fail(c, utils.CodeProgramNotFound, nil)return}if utils.IsForeignKeyViolation(err) {- utils.BadRequest(c, "One or more of those exercises no longer exist.")+ utils.Fail(c, utils.CodeUnknownExercises, nil)return}if utils.DBError(c, err) {@@ -127,7 +127,7 @@ func (h *Handler) DeleteProgram(c *gin.Context) {uid := middleware.UserID(c)pid, err := strconv.ParseInt(c.Param("id"), 10, 64)if err != nil {- utils.BadRequest(c, "That program id isn't valid.")+ utils.Fail(c, utils.CodeInvalidProgramID, nil)return}n, err := h.s.Program.Delete(uid, pid)@@ -135,7 +135,7 @@ func (h *Handler) DeleteProgram(c *gin.Context) {return}if n == 0 {- utils.NotFound(c, "That program no longer exists.")+ utils.Fail(c, utils.CodeProgramNotFound, nil)return}utils.OK(c, gin.H{"deleted": true})@@ -147,12 +147,12 @@ func (h *Handler) ResolveSuggestions(c *gin.Context) {uid := middleware.UserID(c)pid, err := strconv.ParseInt(c.Param("id"), 10, 64)if err != nil {- utils.BadRequest(c, "That program id isn't valid.")+ utils.Fail(c, utils.CodeInvalidProgramID, nil)return}var req models.ResolveSuggestionsReqif err := c.ShouldBindJSON(&req); err != nil {- utils.BadRequest(c, utils.BindMessage(err))+ utils.BindError(c, err)return}if err := validate.Struct(req); err != nil {@@ -161,7 +161,7 @@ func (h *Handler) ResolveSuggestions(c *gin.Context) {}p, err := h.s.Program.ResolveSuggestions(uid, pid, req.Accept, req.Dismiss)if err == sql.ErrNoRows {- utils.NotFound(c, "That program no longer exists.")+ utils.Fail(c, utils.CodeProgramNotFound, nil)return}if utils.DBError(c, err) {diff --git a/backend/controllers/user.go b/backend/controllers/user.goindex 4a50746..3a7dcb6 100644--- a/backend/controllers/user.go+++ b/backend/controllers/user.go@@ -15,7 +15,7 @@ func (h *Handler) GetMe(c *gin.Context) {uid := middleware.UserID(c)u, err := h.s.User.GetMe(uid)if err == sql.ErrNoRows {- utils.Unauthorized(c, "That account no longer exists.")+ utils.Fail(c, utils.CodeAccountNotFound, nil)return}if utils.DBError(c, err) {@@ -42,7 +42,7 @@ func (h *Handler) UpdateSettings(c *gin.Context) {uid := middleware.UserID(c)var req models.UpdateSettingsRequestif err := c.ShouldBindJSON(&req); err != nil {- utils.BadRequest(c, utils.BindMessage(err))+ utils.BindError(c, err)return}// Trimmed before it is measured, so " Carter " is a 6-character name rather than@@ -63,7 +63,7 @@ func (h *Handler) UpdateSettings(c *gin.Context) {// inside a greeting is a layout bug, and a NUL in a text field is never// intentional (Django rejects it on every CharField for that reason).if strings.ContainsFunc(trimmed, unicode.IsControl) {- utils.BadRequest(c, "A name can't contain line breaks or other control characters.")+ utils.Fail(c, utils.CodeDisplayNameControlChars, nil)return}req.DisplayName = &trimmed@@ -72,7 +72,7 @@ func (h *Handler) UpdateSettings(c *gin.Context) {// controller — binding alone doesn't run them, so without this an invalid unit// or a negative target would be persisted unchecked.if err := validate.Struct(req); err != nil {- utils.BadRequest(c, utils.BindMessage(err))+ utils.BindError(c, err)return}// A zone name is only valid if the runtime can load it, so check it here rather@@ -85,11 +85,11 @@ func (h *Handler) UpdateSettings(c *gin.Context) {// that silently reverts every day boundary to UTC — a 200 OK, a stored value// that is neither null nor rejected, and nothing to point at afterwards.if *req.Timezone == "" {- utils.BadRequest(c, "Timezone can't be empty.")+ utils.Fail(c, utils.CodeTimezoneEmpty, nil)return}if _, err := ParseLocation(*req.Timezone); err != nil {- utils.BadRequest(c, "Unknown timezone: "+*req.Timezone+".")+ utils.Fail(c, utils.CodeUnknownTimezone, map[string]any{"timezone": *req.Timezone})return}}diff --git a/backend/controllers/weight.go b/backend/controllers/weight.goindex 89060b1..662c16c 100644--- a/backend/controllers/weight.go+++ b/backend/controllers/weight.go@@ -34,7 +34,7 @@ func (h *Handler) ListWeightLogs(c *gin.Context) {if from := c.Query("from"); from != "" {day, ok := h.resolveQueryDay(uid, from)if !ok {- utils.BadRequest(c, "From must be in YYYY-MM-DD format.")+ utils.Fail(c, utils.CodeInvalidFromDate, nil)return}f.FromDay = &day@@ -42,7 +42,7 @@ func (h *Handler) ListWeightLogs(c *gin.Context) {if to := c.Query("to"); to != "" {day, ok := h.resolveQueryDay(uid, to)if !ok {- utils.BadRequest(c, "To must be in YYYY-MM-DD format.")+ utils.Fail(c, utils.CodeInvalidToDate, nil)return}f.ToDay = &day@@ -59,7 +59,7 @@ func (h *Handler) LogWeight(c *gin.Context) {uid := middleware.UserID(c)var req models.LogWeightRequestif err := c.ShouldBindJSON(&req); err != nil {- utils.BadRequest(c, utils.BindMessage(err))+ utils.BindError(c, err)return}if err := validate.Struct(req); err != nil {@@ -70,7 +70,7 @@ func (h *Handler) LogWeight(c *gin.Context) {day, ok := h.resolveDay(uid, req.LoggedOn, req.LoggedAt)if !ok {- utils.BadRequest(c, "Logged on must be in YYYY-MM-DD format.")+ utils.Fail(c, utils.CodeInvalidLoggedOn, nil)return}log, err := h.s.Weight.UpsertForDay(uid, req, day)@@ -84,12 +84,12 @@ func (h *Handler) GetWeightLog(c *gin.Context) {uid := middleware.UserID(c)lid, err := strconv.ParseInt(c.Param("id"), 10, 64)if err != nil {- utils.BadRequest(c, "That id isn't valid.")+ utils.Fail(c, utils.CodeInvalidID, nil)return}log, err := h.s.Weight.Get(uid, lid)if err == sql.ErrNoRows {- utils.NotFound(c, "That entry no longer exists.")+ utils.Fail(c, utils.CodeEntryNotFound, nil)return}if utils.DBError(c, err) {@@ -102,12 +102,12 @@ func (h *Handler) UpdateWeightLog(c *gin.Context) {uid := middleware.UserID(c)lid, err := strconv.ParseInt(c.Param("id"), 10, 64)if err != nil {- utils.BadRequest(c, "That id isn't valid.")+ utils.Fail(c, utils.CodeInvalidID, nil)return}var req models.LogWeightRequestif err := c.ShouldBindJSON(&req); err != nil {- utils.BadRequest(c, utils.BindMessage(err))+ utils.BindError(c, err)return}if err := validate.Struct(req); err != nil {@@ -118,12 +118,12 @@ func (h *Handler) UpdateWeightLog(c *gin.Context) {day, ok := h.resolveDay(uid, req.LoggedOn, req.LoggedAt)if !ok {- utils.BadRequest(c, "Logged on must be in YYYY-MM-DD format.")+ utils.Fail(c, utils.CodeInvalidLoggedOn, nil)return}log, err := h.s.Weight.Update(uid, lid, req, day)if err == sql.ErrNoRows {- utils.NotFound(c, "That entry no longer exists.")+ utils.Fail(c, utils.CodeEntryNotFound, nil)return}if utils.DBError(c, err) {@@ -136,7 +136,7 @@ func (h *Handler) DeleteWeightLog(c *gin.Context) {uid := middleware.UserID(c)lid, err := strconv.ParseInt(c.Param("id"), 10, 64)if err != nil {- utils.BadRequest(c, "That id isn't valid.")+ utils.Fail(c, utils.CodeInvalidID, nil)return}n, err := h.s.Weight.Delete(uid, lid)@@ -144,7 +144,7 @@ func (h *Handler) DeleteWeightLog(c *gin.Context) {return}if n == 0 {- utils.NotFound(c, "That entry no longer exists.")+ utils.Fail(c, utils.CodeEntryNotFound, nil)return}utils.OK(c, gin.H{"deleted": true})diff --git a/backend/controllers/workouts.go b/backend/controllers/workouts.goindex 132c5da..186dd0b 100644--- a/backend/controllers/workouts.go+++ b/backend/controllers/workouts.go@@ -51,12 +51,12 @@ func (h *Handler) GetWorkout(c *gin.Context) {uid := middleware.UserID(c)wid, err := strconv.ParseInt(c.Param("id"), 10, 64)if err != nil {- utils.BadRequest(c, "That workout id isn't valid.")+ utils.Fail(c, utils.CodeInvalidWorkoutID, nil)return}w, err := h.s.Workout.Get(uid, wid)if err == sql.ErrNoRows {- utils.NotFound(c, "That workout no longer exists.")+ utils.Fail(c, utils.CodeWorkoutNotFound, nil)return}if utils.DBError(c, err) {@@ -69,7 +69,7 @@ func (h *Handler) CreateWorkout(c *gin.Context) {uid := middleware.UserID(c)var req models.CreateWorkoutRequestif err := c.ShouldBindJSON(&req); err != nil {- utils.BadRequest(c, utils.BindMessage(err))+ utils.BindError(c, err)return}if err := validate.Struct(req); err != nil {@@ -96,7 +96,7 @@ func (h *Handler) CreateWorkout(c *gin.Context) {// never fails the already-saved workout.w, progression, err := h.s.CreateWorkoutWithProgression(uid, req)if utils.IsForeignKeyViolation(err) {- utils.BadRequest(c, "One or more of those exercises no longer exist.")+ utils.Fail(c, utils.CodeUnknownExercises, nil)return}if utils.DBError(c, err) {@@ -110,12 +110,12 @@ func (h *Handler) UpdateWorkout(c *gin.Context) {uid := middleware.UserID(c)wid, err := strconv.ParseInt(c.Param("id"), 10, 64)if err != nil {- utils.BadRequest(c, "That workout id isn't valid.")+ utils.Fail(c, utils.CodeInvalidWorkoutID, nil)return}var req models.CreateWorkoutRequestif err := c.ShouldBindJSON(&req); err != nil {- utils.BadRequest(c, utils.BindMessage(err))+ utils.BindError(c, err)return}if err := validate.Struct(req); err != nil {@@ -138,11 +138,11 @@ func (h *Handler) UpdateWorkout(c *gin.Context) {}w, err := h.s.Workout.Update(uid, wid, req)if err == sql.ErrNoRows {- utils.NotFound(c, "That workout no longer exists.")+ utils.Fail(c, utils.CodeWorkoutNotFound, nil)return}if utils.IsForeignKeyViolation(err) {- utils.BadRequest(c, "One or more of those exercises no longer exist.")+ utils.Fail(c, utils.CodeUnknownExercises, nil)return}if utils.DBError(c, err) {@@ -155,7 +155,7 @@ func (h *Handler) DeleteWorkout(c *gin.Context) {uid := middleware.UserID(c)wid, err := strconv.ParseInt(c.Param("id"), 10, 64)if err != nil {- utils.BadRequest(c, "That workout id isn't valid.")+ utils.Fail(c, utils.CodeInvalidWorkoutID, nil)return}n, err := h.s.Workout.Delete(uid, wid)@@ -163,7 +163,7 @@ func (h *Handler) DeleteWorkout(c *gin.Context) {return}if n == 0 {- utils.NotFound(c, "That workout no longer exists.")+ utils.Fail(c, utils.CodeWorkoutNotFound, nil)return}utils.OK(c, gin.H{"deleted": true})diff --git a/backend/middleware/auth.go b/backend/middleware/auth.goindex 89ac53a..acf3c54 100644--- a/backend/middleware/auth.go+++ b/backend/middleware/auth.go@@ -31,27 +31,27 @@ func Auth(versions TokenVersions) gin.HandlerFunc {return func(c *gin.Context) {header := c.GetHeader("Authorization")if !strings.HasPrefix(header, "Bearer ") {- utils.Unauthorized(c, "You need to sign in to do that.")+ utils.Fail(c, utils.CodeSignInRequired, nil)c.Abort()return}claims, err := utils.ValidateToken(strings.TrimPrefix(header, "Bearer "))if err != nil {- utils.Unauthorized(c, "Your session isn't valid. Please sign in again.")+ utils.Fail(c, utils.CodeSessionInvalid, nil)c.Abort()return}if claims.Type != "access" {- utils.Unauthorized(c, "That token can't be used here.")+ utils.Fail(c, utils.CodeWrongTokenType, nil)c.Abort()return}current, err := versions.TokenVersion(claims.UserID)if errors.Is(err, sql.ErrNoRows) {- utils.Unauthorized(c, "Your session isn't valid. Please sign in again.")+ utils.Fail(c, utils.CodeSessionInvalid, nil)c.Abort()return}@@ -60,7 +60,7 @@ func Auth(versions TokenVersions) gin.HandlerFunc {return}if utils.NormalizeTokenVersion(claims.TokenVersion) != current {- utils.Unauthorized(c, "Your session expired. Please sign in again.")+ utils.Fail(c, utils.CodeSessionExpired, nil)c.Abort()return}diff --git a/backend/middleware/auth_test.go b/backend/middleware/auth_test.goindex d545297..fe6985c 100644--- a/backend/middleware/auth_test.go+++ b/backend/middleware/auth_test.go@@ -2,6 +2,7 @@ package middlewareimport ("database/sql"+ "encoding/json""errors""net/http""net/http/httptest"@@ -54,6 +55,16 @@ func pair(t *testing.T, version int) (access, refresh string) {return a, r}+func codeOf(t *testing.T, w *httptest.ResponseRecorder) string {+ t.Helper()+ var body map[string]any+ if err := json.Unmarshal(w.Body.Bytes(), &body); err != nil {+ t.Fatal(err)+ }+ s, _ := body["code"].(string)+ return s+}+func TestAuthAcceptsATokenAtTheCurrentVersion(t *testing.T) {useConfig(t)access, _ := pair(t, 3)@@ -67,8 +78,8 @@ func TestAuthRejectsATokenFromAnEarlierVersion(t *testing.T) {useConfig(t)access, _ := pair(t, 2)w, reached := serve(t, fakeVersions{version: 3}, "Bearer "+access)- if w.Code != http.StatusUnauthorized || *reached {- t.Fatalf("status = %d reached = %v, want 401 and not reached", w.Code, *reached)+ if w.Code != http.StatusUnauthorized || *reached || codeOf(t, w) != "SESSION_EXPIRED" {+ t.Fatalf("status = %d reached = %v code = %s, want 401 SESSION_EXPIRED and not reached", w.Code, *reached, codeOf(t, w))}}@@ -76,8 +87,8 @@ func TestAuthRejectsADeletedAccount(t *testing.T) {useConfig(t)access, _ := pair(t, 1)w, reached := serve(t, fakeVersions{err: sql.ErrNoRows}, "Bearer "+access)- if w.Code != http.StatusUnauthorized || *reached {- t.Fatalf("status = %d reached = %v, want 401 and not reached", w.Code, *reached)+ if w.Code != http.StatusUnauthorized || *reached || codeOf(t, w) != "SESSION_INVALID" {+ t.Fatalf("status = %d reached = %v code = %s, want 401 SESSION_INVALID and not reached", w.Code, *reached, codeOf(t, w))}}@@ -132,6 +143,9 @@ func TestAuthAnswers503WhenTheDatabaseIsLocked(t *testing.T) {if w.Code != http.StatusServiceUnavailable || *reached {t.Fatalf("status = %d reached = %v, want 503 and not reached", w.Code, *reached)}+ if got := codeOf(t, w); got != "DATABASE_BUSY" {+ t.Errorf("code = %s", got)+ }}// Tokens minted before the version claim existed decode as 0. They stay valid while the@@ -150,14 +164,14 @@ func TestAuthTreatsAPreVersionTokenAsVersionOne(t *testing.T) {func TestAuthRejectsMissingMalformedAndRefreshTokens(t *testing.T) {useConfig(t)_, refresh := pair(t, 1)- for name, header := range map[string]string{- "no header": "",- "not a bearer": "Basic abc",- "garbage": "Bearer not-a-token",- "a refresh one": "Bearer " + refresh,+ for name, c := range map[string]struct{ header, code string }{+ "no header": {"", "SIGN_IN_REQUIRED"},+ "not a bearer": {"Basic abc", "SIGN_IN_REQUIRED"},+ "garbage": {"Bearer not-a-token", "SESSION_INVALID"},+ "a refresh one": {"Bearer " + refresh, "WRONG_TOKEN_TYPE"},} {- if w, reached := serve(t, fakeVersions{version: 1}, header); w.Code != http.StatusUnauthorized || *reached {- t.Errorf("%s: status = %d reached = %v, want 401", name, w.Code, *reached)+ if w, reached := serve(t, fakeVersions{version: 1}, c.header); w.Code != http.StatusUnauthorized || *reached || codeOf(t, w) != c.code {+ t.Errorf("%s: status = %d reached = %v code = %s, want 401 %s", name, w.Code, *reached, codeOf(t, w), c.code)}}}diff --git a/backend/models/models.go b/backend/models/models.goindex c5986fc..eaf9b36 100644--- a/backend/models/models.go+++ b/backend/models/models.go@@ -526,3 +526,8 @@ type DailyStats struct {TotalFiber float64 `json:"total_fiber"`WorkoutCount int `json:"workout_count"`}++// ActiveSessionRequest is the body of PUT /active-session.+type ActiveSessionRequest struct {+ Data string `json:"data" binding:"required"`+}diff --git a/backend/resetpassword.go b/backend/resetpassword.goindex f9ec4e7..b1fb211 100644--- a/backend/resetpassword.go+++ b/backend/resetpassword.go@@ -127,7 +127,7 @@ func validatePassword(p string) (string, error) {// 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 "", errors.New(utils.CodePasswordTooLong.Message(nil))}return p, nil}diff --git a/backend/resetpassword_test.go b/backend/resetpassword_test.goindex 61e4b48..e1319f2 100644--- a/backend/resetpassword_test.go+++ b/backend/resetpassword_test.go@@ -149,7 +149,7 @@ func TestValidatePasswordLength(t *testing.T) {if err == nil {t.Fatal("accepted a password bcrypt cannot hash")}- if err.Error() != utils.PasswordTooLongMessage {+ if err.Error() != utils.CodePasswordTooLong.Message(nil) {t.Errorf("error was %q, want the shared message", err)}})diff --git a/backend/routes/error_codes_test.go b/backend/routes/error_codes_test.gonew file mode 100644index 0000000..e8723c3--- /dev/null+++ b/backend/routes/error_codes_test.go@@ -0,0 +1,277 @@+package routes++import (+ "encoding/json"+ "net/http"+ "net/http/httptest"+ "strings"+ "testing"++ "github.com/Cawlumm/lyftr-backend/db"+ "github.com/Cawlumm/lyftr-backend/utils"+)++// These pin the wire contract of the error codes through the real router: the unchanged+// English sentence, the stable code, and the status, together.++func wantError(t *testing.T, name string, gotStatus int, body map[string]any, status int, code, sentence string) {+ t.Helper()+ if gotStatus != status || body["code"] != code || body["error"] != sentence {+ t.Errorf("%s = %d %v, want %d %s %q", name, gotStatus, body, status, code, sentence)+ }+}++func TestPasswordChangeErrorsCarryCodes(t *testing.T) {+ a := newAPI(t)+ access, _ := a.register("[email protected]")+ change := func(current, next string) (int, map[string]any) {+ return a.do("PUT", "/api/v1/me/password", access, map[string]string{"current_password": current, "new_password": next})+ }++ code, body := change("not-my-password", "a-new-password-9")+ wantError(t, "wrong current", code, body, 401, "WRONG_CURRENT_PASSWORD", "Your current password is incorrect.")++ code, body = change("password123", strings.Repeat("a", utils.MaxPasswordBytes+1))+ wantError(t, "change too long", code, body, 400, "PASSWORD_TOO_LONG", utils.CodePasswordTooLong.Message(nil))++ code, body = change("password123", "password123")+ wantError(t, "unchanged", code, body, 400, "PASSWORD_UNCHANGED", "Your new password must be different from your current one.")++ code, body = a.do("POST", "/api/v1/auth/register", "", map[string]string{+ "email": "[email protected]", "password": strings.Repeat("a", utils.MaxPasswordBytes+1)})+ wantError(t, "register too long", code, body, 400, "PASSWORD_TOO_LONG", utils.CodePasswordTooLong.Message(nil))+}++func TestStaleTokensAnswerSessionCodes(t *testing.T) {+ a := newAPI(t)+ a.register("[email protected]")+ oldAccess, oldRefresh := a.login("[email protected]")++ probe := func(name, access, refresh string, wantCode, sentence string) {+ code, body := a.do("GET", "/api/v1/me", access, nil)+ wantError(t, name+" access", code, body, 401, wantCode, sentence)+ code, body = a.do("POST", "/api/v1/auth/refresh", "", map[string]string{"refresh_token": refresh})+ wantError(t, name+" refresh", code, body, 401, wantCode, sentence)+ }++ if code, body := a.do("PUT", "/api/v1/me/password", oldAccess, map[string]string{+ "current_password": "password123", "new_password": "a-new-password-9"}); code != 200 {+ t.Fatalf("change password = %d %v", code, body)+ }+ probe("after password change", oldAccess, oldRefresh, "SESSION_EXPIRED", "Your session expired. Please sign in again.")++ // Same for an email change, on a fresh session.+ a.register("[email protected]")+ access2, refresh2 := a.login("[email protected]")+ if code, body := a.do("PUT", "/api/v1/me/email", access2, map[string]string{+ "email": "[email protected]", "current_password": "password123"}); code != 200 {+ t.Fatalf("change email = %d %v", code, body)+ }+ probe("after email change", access2, refresh2, "SESSION_EXPIRED", "Your session expired. Please sign in again.")+}++func TestDeletedAccountAnswersSessionInvalid(t *testing.T) {+ a := newAPI(t)+ access, refresh := a.register("[email protected]")+ if code, body := a.do("DELETE", "/api/v1/me", access, nil); code != 200 {+ t.Fatalf("delete = %d %v", code, body)+ }+ sentence := "Your session isn't valid. Please sign in again."+ code, body := a.do("POST", "/api/v1/auth/refresh", "", map[string]string{"refresh_token": refresh})+ wantError(t, "refresh", code, body, 401, "SESSION_INVALID", sentence)+ code, body = a.do("GET", "/api/v1/me", access, nil)+ wantError(t, "access", code, body, 401, "SESSION_INVALID", sentence)+}++func TestAuthMiddlewareCodes(t *testing.T) {+ a := newAPI(t)+ _, refresh := a.register("[email protected]")+ for _, tc := range []struct {+ name, token, code, sentence string+ }{+ {"no token", "", "SIGN_IN_REQUIRED", "You need to sign in to do that."},+ {"garbage", "garbage", "SESSION_INVALID", "Your session isn't valid. Please sign in again."},+ {"refresh as access", refresh, "WRONG_TOKEN_TYPE", "That token can't be used here."},+ } {+ code, body := a.do("GET", "/api/v1/me", tc.token, nil)+ wantError(t, tc.name, code, body, 401, tc.code, tc.sentence)+ }+}++func TestRegisterAndLoginErrorsCarryCodes(t *testing.T) {+ a := newAPI(t)+ a.register("[email protected]")++ for _, email := range []string{"[email protected]", "[email protected]"} {+ code, body := a.do("POST", "/api/v1/auth/register", "", map[string]string{"email": email, "password": "password123"})+ wantError(t, "register "+email, code, body, 409, "EMAIL_TAKEN", "That email is already registered.")+ }++ _, wrong := a.do("POST", "/api/v1/auth/login", "", map[string]string{"email": "[email protected]", "password": "nope-nope-1"})+ _, unknown := a.do("POST", "/api/v1/auth/login", "", map[string]string{"email": "[email protected]", "password": "nope-nope-1"})+ for name, body := range map[string]map[string]any{"wrong password": wrong, "unknown email": unknown} {+ wantError(t, name, 401, body, 401, "INVALID_CREDENTIALS", "Invalid email or password.")+ if _, has := body["params"]; has {+ t.Errorf("%s: params present: %v", name, body)+ }+ }+ if len(wrong) != len(unknown) {+ t.Errorf("bodies differ: %v vs %v", wrong, unknown)+ }+}++func TestRegisterValidationFailureCarriesViolations(t *testing.T) {+ a := newAPI(t)+ code, body := a.do("POST", "/api/v1/auth/register", "", map[string]string{"email": "not-an-email", "password": "short"})+ wantError(t, "register", code, body, 422, "VALIDATION_FAILED",+ "Email must be a valid email address. Password must be at least 8 characters in length.")++ params, _ := body["params"].(map[string]any)+ vs, _ := params["violations"].([]any)+ if len(vs) != 2 {+ t.Fatalf("violations = %v, want 2", params)+ }+ want := []struct {+ code, field string+ min any+ }{{"INVALID_EMAIL", "email", nil}, {"TOO_SHORT", "password", float64(8)}}+ for i, w := range want {+ v, _ := vs[i].(map[string]any)+ p, _ := v["params"].(map[string]any)+ if v["code"] != w.code || p["field"] != w.field || p["min"] != w.min {+ t.Errorf("violation %d = %v, want %+v", i, v, w)+ }+ }+}++func TestUnexpectedDBErrorAnswersInternalError(t *testing.T) {+ a := newAPI(t)+ access, _ := a.register("[email protected]")+ db.DB.Close()+ code, body := a.do("GET", "/api/v1/me", access, nil)+ wantError(t, "closed db", code, body, http.StatusInternalServerError, "INTERNAL_ERROR", "Something went wrong on the server.")+}++func TestRequestBodyErrorsCarryBindCodes(t *testing.T) {+ a := newAPI(t)+ access, _ := a.register("[email protected]")++ req := httptest.NewRequest("POST", "/api/v1/auth/login", strings.NewReader("{"))+ req.Header.Set("Content-Type", "application/json")+ w := httptest.NewRecorder()+ a.r.ServeHTTP(w, req)+ var body map[string]any+ _ = json.Unmarshal(w.Body.Bytes(), &body)+ wantError(t, "login with a truncated body", w.Code, body, 400, "BODY_NOT_JSON", "The request body wasn't valid JSON.")++ code, body := a.do("POST", "/api/v1/workouts", access, map[string]any{+ "name": "w",+ "exercises": []any{map[string]any{"exercise_id": 1, "sets": []any{map[string]any{"weight": "x"}}}},+ })+ wantError(t, "nested weight", code, body, 400, "NOT_A_NUMBER", "Exercises.sets.weight must be a number.")+ if p, _ := body["params"].(map[string]any); p["field"] != "exercises.sets.weight" {+ t.Errorf("params = %v, want the dotted path", body["params"])+ }++ code, body = a.do("PUT", "/api/v1/active-session", access, map[string]any{})+ wantError(t, "active session without data", code, body, 400, "INVALID_FIELDS", "Data is a required field.")+ params, _ := body["params"].(map[string]any)+ vs, _ := params["violations"].([]any)+ if len(vs) != 1 {+ t.Fatalf("violations = %v", params)+ }+ if v, _ := vs[0].(map[string]any); v["code"] != "REQUIRED" {+ t.Errorf("violation = %v", vs[0])+ }+}++func TestSettingsErrorsCarryCodes(t *testing.T) {+ a := newAPI(t)+ access, _ := a.register("[email protected]")+ put := func(body map[string]any) (int, map[string]any) { return a.do("PUT", "/api/v1/settings", access, body) }++ code, body := put(map[string]any{"weight_unit": "stone"})+ wantError(t, "weight unit", code, body, 400, "INVALID_FIELDS", "Weight unit must be one of: lbs, kg.")+ params, _ := body["params"].(map[string]any)+ vs, _ := params["violations"].([]any)+ if len(vs) != 1 {+ t.Fatalf("violations = %v", params)+ }+ v, _ := vs[0].(map[string]any)+ vp, _ := v["params"].(map[string]any)+ if v["code"] != "NOT_AN_OPTION" || vp["field"] != "weight_unit" || vp["options"] != "lbs, kg" {+ t.Errorf("violation = %v", v)+ }++ code, body = put(map[string]any{"timezone": "Mars/Base"})+ wantError(t, "unknown zone", code, body, 400, "UNKNOWN_TIMEZONE", "Unknown timezone: Mars/Base.")+ if p, _ := body["params"].(map[string]any); p["timezone"] != "Mars/Base" {+ t.Errorf("params = %v", body["params"])+ }++ code, body = put(map[string]any{"timezone": ""})+ wantError(t, "empty zone", code, body, 400, "TIMEZONE_EMPTY", "Timezone can't be empty.")++ code, body = put(map[string]any{"display_name": "a\nb"})+ wantError(t, "control chars", code, body, 400, "DISPLAY_NAME_CONTROL_CHARS", "A name can't contain line breaks or other control characters.")+}++func TestResourceErrorsCarryCodes(t *testing.T) {+ a := newAPI(t)+ access, _ := a.register("[email protected]")++ cases := []struct {+ name, method, path string+ body any+ status int+ code, sentence string+ }{+ {"workout id", "GET", "/workouts/abc", nil, 400, "INVALID_WORKOUT_ID", "That workout id isn't valid."},+ {"workout gone", "GET", "/workouts/999999", nil, 404, "WORKOUT_NOT_FOUND", "That workout no longer exists."},+ {"program id", "GET", "/programs/abc", nil, 400, "INVALID_PROGRAM_ID", "That program id isn't valid."},+ {"program gone", "GET", "/programs/999999", nil, 404, "PROGRAM_NOT_FOUND", "That program no longer exists."},+ {"program unknown exercise", "POST", "/programs", map[string]any{+ "name": "p",+ "days": []any{map[string]any{"name": "d", "exercises": []any{map[string]any{"exercise_id": 999999}}}},+ }, 400, "UNKNOWN_EXERCISES", "One or more of those exercises no longer exist."},+ {"weight from", "GET", "/weight?from=x", nil, 400, "INVALID_FROM_DATE", "From must be in YYYY-MM-DD format."},+ {"weight to", "GET", "/weight?to=x", nil, 400, "INVALID_TO_DATE", "To must be in YYYY-MM-DD format."},+ {"weight gone", "GET", "/weight/999999", nil, 404, "ENTRY_NOT_FOUND", "That entry no longer exists."},+ {"weight id", "GET", "/weight/abc", nil, 400, "INVALID_ID", "That id isn't valid."},+ {"exercise id", "GET", "/exercises/abc", nil, 400, "INVALID_EXERCISE_ID", "That exercise id isn't valid."},+ {"exercise gone", "GET", "/exercises/999999", nil, 404, "EXERCISE_NOT_FOUND", "That exercise no longer exists."},+ {"food date", "GET", "/food?date=x", nil, 400, "INVALID_DATE", "Date must be in YYYY-MM-DD format."},+ {"food id", "GET", "/food/abc", nil, 400, "INVALID_ID", "That id isn't valid."},+ {"food gone", "DELETE", "/food/999999", nil, 404, "ENTRY_NOT_FOUND", "That entry no longer exists."},+ {"saved food gone", "DELETE", "/food/saved/999999", nil, 404, "SAVED_FOOD_NOT_FOUND", "That saved food no longer exists."},+ {"search without a term", "GET", "/food/search", nil, 400, "SEARCH_TERM_REQUIRED", "A search term is required."},+ {"barcode shape", "GET", "/food/barcode/abc", nil, 400, "INVALID_BARCODE", "That barcode isn't valid."},+ {"logged on", "POST", "/food", map[string]any{"name": "Oats", "meal": "lunch", "logged_on": "tomorrow"},+ 400, "INVALID_LOGGED_ON", "Logged on must be in YYYY-MM-DD format."},+ }+ for _, tc := range cases {+ code, body := a.do(tc.method, "/api/v1"+tc.path, access, tc.body)+ wantError(t, tc.name, code, body, tc.status, tc.code, tc.sentence)+ }+}++func TestFoodLengthLimitsCarryTheLimit(t *testing.T) {+ a := newAPI(t)+ access, _ := a.register("[email protected]")++ cases := []struct {+ field, code, sentence string+ max, over int+ }{+ {"brand", "FOOD_BRAND_TOO_LONG", "Brand must be 200 characters or fewer.", 200, 201},+ {"image_url", "IMAGE_URL_TOO_LONG", "Image URL must be 500 characters or fewer.", 500, 501},+ }+ for _, tc := range cases {+ code, body := a.do("POST", "/api/v1/food", access, map[string]any{+ "name": "Oats", "meal": "lunch", tc.field: strings.Repeat("x", tc.over)})+ wantError(t, tc.field, code, body, 400, tc.code, tc.sentence)+ if p, _ := body["params"].(map[string]any); p["max"] != float64(tc.max) {+ t.Errorf("%s params = %v, want max %d as a JSON number", tc.field, body["params"], tc.max)+ }+ }+}diff --git a/backend/routes/routes_test.go b/backend/routes/routes_test.goindex 1370fc9..80d99fc 100644--- a/backend/routes/routes_test.go+++ b/backend/routes/routes_test.go@@ -25,7 +25,7 @@ func TestChangeEmailRequiresAuth(t *testing.T) {if err := json.Unmarshal(w.Body.Bytes(), &body); err != nil {t.Fatal(err)}- if body["error"] != "You need to sign in to do that." {- t.Errorf("error = %v", body["error"])+ if body["error"] != "You need to sign in to do that." || body["code"] != "SIGN_IN_REQUIRED" {+ t.Errorf("body = %v", body)}}diff --git a/backend/utils/codes.go b/backend/utils/codes.gonew file mode 100644index 0000000..bc7cfdd--- /dev/null+++ b/backend/utils/codes.go@@ -0,0 +1,130 @@+package utils++import (+ "encoding/json"+ "fmt"+ "regexp"+ "strconv"+ "strings"+)++// Clients key their own wording on Code.ID; the sentence stays for older clients and curl.+// The id, status and English template live here and nowhere else.+type Code struct {+ ID string+ Status int+ text string+}++var registry = map[string]Code{}++func define(id string, status int, text string) Code {+ if _, dup := registry[id]; dup {+ panic("utils: duplicate error code " + id)+ }+ c := Code{ID: id, Status: status, text: text}+ registry[id] = c+ return c+}++var placeholder = regexp.MustCompile(`\{\{(\w+)\}\}`)++// Message renders the code's English sentence.+func (c Code) Message(params map[string]any) string {+ return placeholder.ReplaceAllStringFunc(c.text, func(m string) string {+ name := placeholder.FindStringSubmatch(m)[1]+ v, ok := params[name]+ if !ok {+ return m+ }+ switch x := v.(type) {+ case string:+ if name == "field" {+ return label(x)+ }+ return x+ case json.Number:+ digits := uint64(0)+ if i := strings.Index(string(x), "."); i != -1 {+ digits = uint64(len(x) - i - 1)+ }+ f, _ := strconv.ParseFloat(string(x), 64)+ return translator.FmtNumber(f, digits)+ default:+ return fmt.Sprint(x)+ }+ })+}++var (+ CodeValidationFailed = define("VALIDATION_FAILED", 422, "Some of the details you entered aren't valid.")+ CodeInvalidCredentials = define("INVALID_CREDENTIALS", 401, "Invalid email or password.")+ CodeEmailTaken = define("EMAIL_TAKEN", 409, "That email is already registered.")+ CodeRegistrationClosed = define("REGISTRATION_CLOSED", 403, "Registration is closed on this server.")+ CodePasswordTooLong = define("PASSWORD_TOO_LONG", 400, "Password must be 72 bytes or fewer — accented letters and emoji count for more than one.")+ CodePasswordUnchanged = define("PASSWORD_UNCHANGED", 400, "Your new password must be different from your current one.")+ CodeWrongCurrentPassword = define("WRONG_CURRENT_PASSWORD", 401, "Your current password is incorrect.")+ CodeAccountNotFound = define("ACCOUNT_NOT_FOUND", 401, "That account no longer exists.")+ CodePasswordChangedElsewhere = define("PASSWORD_CHANGED_ELSEWHERE", 409, "Your password was changed elsewhere. Please try again.")+ CodePasswordChangedSignIn = define("PASSWORD_CHANGED_SIGN_IN_AGAIN", 401, "Your password changed. Please sign in again.")+ CodeEmailChangedSignIn = define("EMAIL_CHANGED_SIGN_IN_AGAIN", 401, "Your email changed. Please sign in again.")+ CodeSignInRequired = define("SIGN_IN_REQUIRED", 401, "You need to sign in to do that.")+ CodeSessionInvalid = define("SESSION_INVALID", 401, "Your session isn't valid. Please sign in again.")+ CodeSessionExpired = define("SESSION_EXPIRED", 401, "Your session expired. Please sign in again.")+ CodeWrongTokenType = define("WRONG_TOKEN_TYPE", 401, "That token can't be used here.")+ CodeInternalError = define("INTERNAL_ERROR", 500, "Something went wrong on the server.")+ CodeDatabaseBusy = define("DATABASE_BUSY", 503, "The database is busy. Try again in a moment.")+ CodeRateLimited = define("RATE_LIMITED", 429, "Too many requests. Wait a moment and try again.")+ codeRequired = define("REQUIRED", 422, "{{field}} is a required field.")+ codeInvalidEmail = define("INVALID_EMAIL", 422, "{{field}} must be a valid email address.")+ codeTooShort = define("TOO_SHORT", 422, "{{field}} must be at least {{min}} characters in length.")+ codeTooLong = define("TOO_LONG", 422, "{{field}} must be a maximum of {{max}} characters in length.")+ codeTooManyItems = define("TOO_MANY_ITEMS", 422, "{{field}} must contain at maximum {{max}} items.")+ codeBelowMinimum = define("BELOW_MINIMUM", 422, "{{field}} must be {{min}} or greater.")+ codeNotAboveMinimum = define("NOT_ABOVE_MINIMUM", 422, "{{field}} must be greater than {{min}}.")+ codeAboveMaximum = define("ABOVE_MAXIMUM", 422, "{{field}} must be {{max}} or less.")+ codeNotAnOption = define("NOT_AN_OPTION", 422, "{{field}} must be one of: {{options}}.")+ codeTooManyWorkoutSets = define("TOO_MANY_WORKOUT_SETS", 422, "A workout can't have more than {{max}} sets.")+ codeTooManyProgramRows = define("TOO_MANY_PROGRAM_ROWS", 422, "A program can't have more than {{max}} days, exercises and sets combined.")+ codeInvalidField = define("INVALID_FIELD", 422, "{{field}} isn't valid.")+ CodeInvalidID = define("INVALID_ID", 400, "That id isn't valid.")+ CodeInvalidExerciseID = define("INVALID_EXERCISE_ID", 400, "That exercise id isn't valid.")+ CodeInvalidProgramID = define("INVALID_PROGRAM_ID", 400, "That program id isn't valid.")+ CodeInvalidWorkoutID = define("INVALID_WORKOUT_ID", 400, "That workout id isn't valid.")+ CodeEntryNotFound = define("ENTRY_NOT_FOUND", 404, "That entry no longer exists.")+ CodeSavedFoodNotFound = define("SAVED_FOOD_NOT_FOUND", 404, "That saved food no longer exists.")+ CodeExerciseNotFound = define("EXERCISE_NOT_FOUND", 404, "That exercise no longer exists.")+ CodeProgramNotFound = define("PROGRAM_NOT_FOUND", 404, "That program no longer exists.")+ CodeWorkoutNotFound = define("WORKOUT_NOT_FOUND", 404, "That workout no longer exists.")+ CodeUnknownExercises = define("UNKNOWN_EXERCISES", 400, "One or more of those exercises no longer exist.")+ CodeInvalidDate = define("INVALID_DATE", 400, "Date must be in YYYY-MM-DD format.")+ CodeInvalidLoggedOn = define("INVALID_LOGGED_ON", 400, "Logged on must be in YYYY-MM-DD format.")+ CodeInvalidFromDate = define("INVALID_FROM_DATE", 400, "From must be in YYYY-MM-DD format.")+ CodeInvalidToDate = define("INVALID_TO_DATE", 400, "To must be in YYYY-MM-DD format.")+ CodeFoodNameTooLong = define("FOOD_NAME_TOO_LONG", 400, "Name must be {{max}} characters or fewer.")+ CodeFoodBrandTooLong = define("FOOD_BRAND_TOO_LONG", 400, "Brand must be {{max}} characters or fewer.")+ CodeServingSizeTooLong = define("SERVING_SIZE_TOO_LONG", 400, "Serving size must be {{max}} characters or fewer.")+ CodeBarcodeTooLong = define("BARCODE_TOO_LONG", 400, "Barcode must be {{max}} characters or fewer.")+ CodeImageURLTooLong = define("IMAGE_URL_TOO_LONG", 400, "Image URL must be {{max}} characters or fewer.")+ CodeSearchTermRequired = define("SEARCH_TERM_REQUIRED", 400, "A search term is required.")+ CodeInvalidBarcode = define("INVALID_BARCODE", 400, "That barcode isn't valid.")+ CodeProductNotFound = define("PRODUCT_NOT_FOUND", 404, "No product matched that barcode.")+ CodeFoodDatabaseTimeout = define("FOOD_DATABASE_TIMEOUT", 503, "The food database didn't respond in time. Try again.")+ CodeFoodDatabaseUnreachable = define("FOOD_DATABASE_UNREACHABLE", 503, "Couldn't reach the food database.")+ CodeFoodSearchUnavailable = define("FOOD_SEARCH_UNAVAILABLE", 503, "Food search is temporarily unavailable.")+ CodeBarcodeLookupUnavailable = define("BARCODE_LOOKUP_UNAVAILABLE", 503, "Barcode lookup is temporarily unavailable.")+ CodeNoExerciseCatalog = define("NO_EXERCISE_CATALOG", 400, "This server has no exercise catalog configured.")+ CodeDisplayNameControlChars = define("DISPLAY_NAME_CONTROL_CHARS", 400, "A name can't contain line breaks or other control characters.")+ CodeTimezoneEmpty = define("TIMEZONE_EMPTY", 400, "Timezone can't be empty.")+ CodeUnknownTimezone = define("UNKNOWN_TIMEZONE", 400, "Unknown timezone: {{timezone}}.")+ codeNotANumber = define("NOT_A_NUMBER", 400, "{{field}} must be a number.")+ codeNotText = define("NOT_TEXT", 400, "{{field}} must be text.")+ codeNotTrueOrFalse = define("NOT_TRUE_OR_FALSE", 400, "{{field}} must be true or false.")+ codeNotAList = define("NOT_A_LIST", 400, "{{field}} must be a list.")+ codeNotAnObject = define("NOT_AN_OBJECT", 400, "{{field}} must be an object.")+ codeBodyWrongType = define("BODY_WRONG_TYPE", 400, "The request body had a field of the wrong type.")+ codeBodyNotJSON = define("BODY_NOT_JSON", 400, "The request body wasn't valid JSON.")+ codeBodyEmpty = define("BODY_EMPTY", 400, "The request body was empty.")+ codeBodyUnreadable = define("BODY_UNREADABLE", 400, "The request couldn't be read.")+ codeInvalidFields = define("INVALID_FIELDS", 400, "Some of the details you entered aren't valid.")+)diff --git a/backend/utils/codes_test.go b/backend/utils/codes_test.gonew file mode 100644index 0000000..90a1b0f--- /dev/null+++ b/backend/utils/codes_test.go@@ -0,0 +1,230 @@+package utils++import (+ "encoding/json"+ "go/ast"+ "go/parser"+ "go/token"+ "os"+ "path/filepath"+ "reflect"+ "regexp"+ "sort"+ "strings"+ "testing"+ "unicode"+)++func TestCodeIDs(t *testing.T) {+ re := regexp.MustCompile(`^[A-Z][A-Z0-9_]*[A-Z0-9]$`)+ for id, c := range registry {+ if !re.MatchString(id) || len(id) > 63 {+ t.Errorf("%q is not an UPPER_SNAKE id of at most 63 characters", id)+ }+ if c.ID != id || c.Status < 400 {+ t.Errorf("%s: id %q status %d", id, c.ID, c.Status)+ }+ }+}++func TestCodeTemplatesAreSentences(t *testing.T) {+ params := map[string]any{"field": "exercises.sets.weight", "min": json.Number("8"), "max": 500, "options": "a, b", "timezone": "Mars/Base"}+ for id, c := range registry {+ if c.text == "" {+ t.Errorf("%s has no text", id)+ continue+ }+ if strings.TrimSpace(c.text) != c.text {+ t.Errorf("%s: %q has leading or trailing whitespace", id, c.text)+ }+ msg := c.Message(params)+ if !unicode.IsUpper([]rune(msg)[0]) {+ t.Errorf("%s: %q should start with a capital", id, msg)+ }+ switch msg[len(msg)-1] {+ case '.', '!', '?':+ default:+ t.Errorf("%s: %q should end in punctuation", id, msg)+ }+ if strings.Contains(msg, "{{") {+ t.Errorf("%s: unrendered placeholder in %q", id, msg)+ }+ }+}++// modelRules returns json name -> validate tags for every validated model field.+func modelRules(t *testing.T) map[string]string {+ t.Helper()+ files, err := filepath.Glob("../models/*.go")+ if err != nil || len(files) == 0 {+ t.Fatalf("no model files: %v", err)+ }+ out := map[string]string{}+ fset := token.NewFileSet()+ for _, f := range files {+ file, err := parser.ParseFile(fset, f, nil, 0)+ if err != nil {+ t.Fatal(err)+ }+ ast.Inspect(file, func(n ast.Node) bool {+ field, ok := n.(*ast.Field)+ if !ok || field.Tag == nil {+ return true+ }+ tag := reflect.StructTag(strings.Trim(field.Tag.Value, "`"))+ validate := tag.Get("validate")+ name := strings.SplitN(tag.Get("json"), ",", 2)[0]+ if validate != "" && name != "" && name != "-" {+ out[name] += validate + ","+ }+ return true+ })+ }+ return out+}++func clientCatalog(t *testing.T) map[string]map[string]string {+ t.Helper()+ raw, err := os.ReadFile("../../packages/shared/src/i18n/locales/en.json")+ if err != nil {+ t.Fatal(err)+ }+ var doc struct {+ Errors struct {+ API struct {+ Codes map[string]string `json:"codes"`+ Fields map[string]string `json:"fields"`+ } `json:"api"`+ } `json:"errors"`+ }+ if err := json.Unmarshal(raw, &doc); err != nil {+ t.Fatal(err)+ }+ return map[string]map[string]string{"codes": doc.Errors.API.Codes, "fields": doc.Errors.API.Fields}+}++func keys[V any](m map[string]V) []string {+ out := make([]string, 0, len(m))+ for k := range m {+ out = append(out, k)+ }+ sort.Strings(out)+ return out+}++func TestClientCatalogMatchesRegistry(t *testing.T) {+ cat := clientCatalog(t)++ registered := map[string]string{}+ for id, c := range registry {+ registered[id] = c.text+ }+ if !reflect.DeepEqual(keys(cat["codes"]), keys(registered)) {+ t.Fatalf("en.json errors.api.codes keys differ from the registry:\n catalog %v\n registry %v", keys(cat["codes"]), keys(registered))+ }+ for id, text := range registered {+ if cat["codes"][id] != text {+ t.Errorf("%s: en.json says %q, registry says %q", id, cat["codes"][id], text)+ }+ }++ fields := requestFields(t)+ if !reflect.DeepEqual(keys(cat["fields"]), keys(fields)) {+ t.Fatalf("en.json errors.api.fields keys differ from the request models' JSON names:\n catalog %v\n models %v", keys(cat["fields"]), keys(fields))+ }+ for name, text := range cat["fields"] {+ if text != label(name) {+ t.Errorf("field %s: en.json says %q, label() says %q", name, text, label(name))+ }+ }+}++// isRequestType is the one definition of "a body a client sends": the field catalog is+// every JSON name of these, and every bind target must be one.+func isRequestType(name string) bool {+ return strings.HasSuffix(name, "Request") || strings.HasSuffix(name, "Req")+}++// requestFields returns the JSON name of every field of every models Request/Req struct.+func requestFields(t *testing.T) map[string]bool {+ t.Helper()+ files, err := filepath.Glob("../models/*.go")+ if err != nil || len(files) == 0 {+ t.Fatalf("no model files: %v", err)+ }+ out := map[string]bool{}+ fset := token.NewFileSet()+ for _, f := range files {+ file, err := parser.ParseFile(fset, f, nil, 0)+ if err != nil {+ t.Fatal(err)+ }+ ast.Inspect(file, func(n ast.Node) bool {+ spec, ok := n.(*ast.TypeSpec)+ if !ok || !isRequestType(spec.Name.Name) {+ return true+ }+ st, ok := spec.Type.(*ast.StructType)+ if !ok {+ return true+ }+ for _, field := range st.Fields.List {+ if field.Tag == nil {+ continue+ }+ tag := reflect.StructTag(strings.Trim(field.Tag.Value, "`"))+ name := strings.SplitN(tag.Get("json"), ",", 2)[0]+ if name != "" && name != "-" {+ out[name] = true+ }+ }+ return true+ })+ }+ return out+}++func TestEveryModelTagHasARule(t *testing.T) {+ known := map[string]bool{"omitempty": true, "dive": true}+ for name, tags := range modelRules(t) {+ for _, part := range strings.Split(strings.Trim(tags, ","), ",") {+ tag, param, _ := strings.Cut(part, "=")+ if known[tag] {+ continue+ }+ if param == "1" && (tag == "min" || tag == "max") {+ t.Errorf("%s: %s=1 breaks the plural templates", name, part)+ }+ found := false+ for k := range rules {+ if k == tag || strings.HasPrefix(k, tag+":") {+ found = true+ }+ }+ if !found {+ t.Errorf("%s: tag %q has no rule, so it would answer INVALID_FIELD", name, tag)+ }+ }+ }+}++func TestUnlabelInvertsLabel(t *testing.T) {+ for name := range modelRules(t) {+ if got := unlabel(label(name)); got != name {+ t.Errorf("unlabel(label(%q)) = %q", name, got)+ }+ }+}++func TestMessageRendersNumbers(t *testing.T) {+ cases := []struct {+ in any+ want string+ }{{json.Number("2000"), "2,000"}, {2000, "2000"}, {json.Number("0"), "0"}}+ for _, tc := range cases {+ got := codeAboveMaximum.Message(map[string]any{"field": "weight", "max": tc.in})+ if want := "Weight must be " + tc.want + " or less."; got != want {+ t.Errorf("got %q, want %q", got, want)+ }+ }+}diff --git a/backend/utils/dberr.go b/backend/utils/dberr.goindex 916d6fe..c2ffd8f 100644--- a/backend/utils/dberr.go+++ b/backend/utils/dberr.go@@ -57,7 +57,7 @@ func IsForeignKeyViolation(err error) bool {// itself before delegating the rest here://// err := db.DB.QueryRow(...).Scan(...)-// if err == sql.ErrNoRows { utils.NotFound(c, "..."); return }+// if err == sql.ErrNoRows { utils.Fail(c, utils.CodeEntryNotFound, nil); return }// if utils.DBError(c, err) { return }//// A locked database becomes a 503 the client can retry; anything else is a@@ -70,7 +70,7 @@ func DBError(c *gin.Context, err error) bool {}if IsLocked(err) {log.Printf("db locked on %s %s: %v", c.Request.Method, c.Request.URL.Path, err)- ServiceUnavailable(c, "The database is busy. Try again in a moment.")+ Fail(c, CodeDatabaseBusy, nil)return true}log.Printf("db error on %s %s: %v", c.Request.Method, c.Request.URL.Path, err)diff --git a/backend/utils/dberr_test.go b/backend/utils/dberr_test.goindex dd74f09..b5c2f74 100644--- a/backend/utils/dberr_test.go+++ b/backend/utils/dberr_test.go@@ -2,6 +2,7 @@ package utilsimport ("database/sql"+ "encoding/json""errors""net/http""net/http/httptest"@@ -116,6 +117,55 @@ func TestDBError(t *testing.T) {if w.Code != tc.wantCode {t.Fatalf("status = %d, want %d", w.Code, tc.wantCode)}+ if tc.handled && tc.wantCode == http.StatusServiceUnavailable {+ if got := bodyOf(t, w)["code"]; got != "DATABASE_BUSY" || w.Header().Get("Retry-After") != "2" {+ t.Fatalf("code = %v, Retry-After = %q", got, w.Header().Get("Retry-After"))+ }+ }+ if tc.handled && tc.wantCode == http.StatusInternalServerError {+ if b := bodyOf(t, w); b["code"] != "INTERNAL_ERROR" || b["error"] != "Something went wrong on the server." {+ t.Fatalf("body = %v", b)+ }+ }})}}++func bodyOf(t *testing.T, w *httptest.ResponseRecorder) map[string]any {+ t.Helper()+ var b map[string]any+ if err := json.Unmarshal(w.Body.Bytes(), &b); err != nil {+ t.Fatal(err)+ }+ return b+}++func TestFailWritesACode(t *testing.T) {+ c, w := testCtx()+ Fail(c, CodeFoodDatabaseTimeout, nil)+ if b := bodyOf(t, w); w.Code != 503 || b["code"] != "FOOD_DATABASE_TIMEOUT" ||+ b["error"] != "The food database didn't respond in time. Try again." || w.Header().Get("Retry-After") != "2" {+ t.Fatalf("503 code = %d %v retry %q", w.Code, b, w.Header().Get("Retry-After"))+ }++ c, w = testCtx()+ Fail(c, CodeEntryNotFound, nil)+ if b := bodyOf(t, w); w.Code != 404 || b["code"] != "ENTRY_NOT_FOUND" || b["params"] != nil || w.Header().Get("Retry-After") != "" {+ t.Fatalf("404 code = %d %v", w.Code, b)+ }++ c, w = testCtx()+ Fail(c, CodeEmailTaken, nil)+ if b := bodyOf(t, w); w.Code != 409 || b["code"] != "EMAIL_TAKEN" || b["error"] != "That email is already registered." {+ t.Fatalf("Fail = %d %v", w.Code, b)+ }+ if _, has := bodyOf2(w)["params"]; has {+ t.Fatal("Fail wrote an empty params key")+ }+}++func bodyOf2(w *httptest.ResponseRecorder) map[string]any {+ var b map[string]any+ _ = json.Unmarshal(w.Body.Bytes(), &b)+ return b+}diff --git a/backend/utils/enforce_test.go b/backend/utils/enforce_test.gonew file mode 100644index 0000000..8535cfe--- /dev/null+++ b/backend/utils/enforce_test.go@@ -0,0 +1,180 @@+package utils++import (+ "go/ast"+ "go/parser"+ "go/token"+ "io/fs"+ "path/filepath"+ "strconv"+ "strings"+ "testing"+)++// responseWriters are the gin methods that put a status line on the wire.+var responseWriters = map[string]bool{+ "JSON": true, "AbortWithStatusJSON": true, "IndentedJSON": true, "PureJSON": true,+ "SecureJSON": true, "AsciiJSON": true, "JSONP": true, "String": true,+ "AbortWithStatus": true, "AbortWithError": true,+}++var bindMethods = map[string]bool{"ShouldBindJSON": true, "ShouldBind": true, "BindJSON": true}++// successStatus reports whether expr is a status below 400 spelled the way handlers spell it.+func successStatus(expr ast.Expr) bool {+ switch x := expr.(type) {+ case *ast.BasicLit:+ n, err := strconv.Atoi(x.Value)+ return x.Kind == token.INT && err == nil && n < 400+ case *ast.SelectorExpr:+ pkg, ok := x.X.(*ast.Ident)+ return ok && pkg.Name == "http" && (x.Sel.Name == "StatusOK" || x.Sel.Name == "StatusCreated" || x.Sel.Name == "StatusNoContent")+ }+ return false+}++func typeName(expr ast.Expr) string {+ switch x := expr.(type) {+ case *ast.Ident:+ return x.Name+ case *ast.SelectorExpr:+ return typeName(x.X) + "." + x.Sel.Name+ case *ast.StarExpr:+ return "*" + typeName(x.X)+ }+ return ""+}++// declaredAs returns the type of `var name T` declared anywhere inside fn.+func declaredAs(fn *ast.FuncDecl, name string) string {+ found := ""+ ast.Inspect(fn, func(n ast.Node) bool {+ spec, ok := n.(*ast.ValueSpec)+ if !ok || spec.Type == nil {+ return true+ }+ for _, id := range spec.Names {+ if id.Name == name {+ found = typeName(spec.Type)+ }+ }+ return true+ })+ return found+}++// TestErrorBodiesComeOnlyFromTheRegistry is the proof that no handler can answer with an+// English sentence of its own: every error body is built by write in response.go from a+// Code defined in codes.go. It reads the production sources, so a new handler that writes+// c.JSON(400, gin.H{"error": "..."}) fails here rather than reaching a Spanish user.+func TestErrorBodiesComeOnlyFromTheRegistry(t *testing.T) {+ root, err := filepath.Abs("..")+ if err != nil {+ t.Fatal(err)+ }+ fset := token.NewFileSet()+ checked := 0++ err = filepath.WalkDir(root, func(path string, d fs.DirEntry, err error) error {+ if err != nil {+ return err+ }+ name := d.Name()+ if d.IsDir() {+ if path != root && (strings.HasPrefix(name, ".") || name == "data" || name == "vendor" || name == "node_modules") {+ return filepath.SkipDir+ }+ return nil+ }+ if !strings.HasSuffix(name, ".go") || strings.HasSuffix(name, "_test.go") {+ return nil+ }+ file, err := parser.ParseFile(fset, path, nil, 0)+ if err != nil {+ return err+ }+ checked+++ rel, _ := filepath.Rel(root, path)+ rel = filepath.ToSlash(rel)+ inResponse := rel == "utils/response.go"+ inCodes := rel == "utils/codes.go"+ at := func(n ast.Node) string { return fset.Position(n.Pos()).String() }++ ast.Inspect(file, func(n ast.Node) bool {+ switch x := n.(type) {+ case *ast.CallExpr:+ if sel, ok := x.Fun.(*ast.SelectorExpr); ok && responseWriters[sel.Sel.Name] && len(x.Args) > 0 && !inResponse {+ if !successStatus(x.Args[0]) {+ t.Errorf("%s: %s with a non-success status; answer errors with utils.Fail", at(x), sel.Sel.Name)+ }+ }+ if id, ok := x.Fun.(*ast.Ident); ok && id.Name == "define" && file.Name.Name == "utils" && !inCodes {+ t.Errorf("%s: define is for codes.go only", at(x))+ }+ case *ast.CompositeLit:+ if tn := typeName(x.Type); tn == "Code" || tn == "utils.Code" {+ if !inCodes {+ t.Errorf("%s: a Code is built only by define in codes.go", at(x))+ }+ }+ for _, elt := range x.Elts {+ kv, ok := elt.(*ast.KeyValueExpr)+ if !ok || inResponse {+ continue+ }+ if key, ok := kv.Key.(*ast.BasicLit); ok && key.Value == `"error"` {+ t.Errorf("%s: an \"error\" key outside utils/response.go; answer with utils.Fail", at(x))+ }+ }+ case *ast.FuncDecl:+ if file.Name.Name == "utils" && x.Name.IsExported() && x.Recv == nil && x.Type.Params != nil {+ params := x.Type.Params.List+ if len(params) > 0 && typeName(params[0].Type) == "*gin.Context" {+ for _, p := range params[1:] {+ if typeName(p.Type) == "string" {+ t.Errorf("%s: %s takes a string next to the context; that is BadRequest(c, msg) again", at(x), x.Name.Name)+ }+ }+ }+ }+ if x.Body == nil {+ return true+ }+ ast.Inspect(x.Body, func(m ast.Node) bool {+ call, ok := m.(*ast.CallExpr)+ if !ok {+ return true+ }+ sel, ok := call.Fun.(*ast.SelectorExpr)+ if !ok || !bindMethods[sel.Sel.Name] || len(call.Args) != 1 {+ return true+ }+ unary, ok := call.Args[0].(*ast.UnaryExpr)+ if !ok || unary.Op != token.AND {+ t.Errorf("%s: bind into &variable", at(call))+ return true+ }+ id, ok := unary.X.(*ast.Ident)+ if !ok {+ t.Errorf("%s: bind into &variable", at(call))+ return true+ }+ typ := declaredAs(x, id.Name)+ pkg, tn, _ := strings.Cut(typ, ".")+ if pkg != "models" || !isRequestType(tn) {+ t.Errorf("%s: %s binds into %q; use `var %s models.<Name>Request` so its fields have client wording", at(call), sel.Sel.Name, typ, id.Name)+ }+ return true+ })+ }+ return true+ })+ return nil+ })+ if err != nil {+ t.Fatal(err)+ }+ if checked < 20 {+ t.Fatalf("only %d source files checked; the walk is not reaching the backend", checked)+ }+}diff --git a/backend/utils/password.go b/backend/utils/password.goindex 2aadd25..83cdcff 100644--- a/backend/utils/password.go+++ b/backend/utils/password.go@@ -20,10 +20,6 @@ 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), errdiff --git a/backend/utils/response.go b/backend/utils/response.goindex c5ef582..ba6195e 100644--- a/backend/utils/response.go+++ b/backend/utils/response.go@@ -1,9 +1,11 @@package utilsimport (+ "errors""net/http""github.com/gin-gonic/gin"+ "github.com/go-playground/validator/v10")func OK(c *gin.Context, data any) {@@ -14,39 +16,53 @@ func Created(c *gin.Context, data any) {c.JSON(http.StatusCreated, gin.H{"data": data})}-func BadRequest(c *gin.Context, msg string) {- c.JSON(http.StatusBadRequest, gin.H{"error": msg})+// write is the one place an error body is built: the sentence in `error`, the stable id in+// `code`, and `params` only when the sentence has variables.+func write(c *gin.Context, code Code, msg string, params map[string]any) {+ if code.Status == http.StatusServiceUnavailable {+ c.Header("Retry-After", "2")+ }+ body := gin.H{"error": msg, "code": code.ID}+ if len(params) > 0 {+ body["params"] = params+ }+ c.JSON(code.Status, body)}-func Unauthorized(c *gin.Context, msg string) {- c.JSON(http.StatusUnauthorized, gin.H{"error": msg})-}--func Forbidden(c *gin.Context, msg string) {- c.JSON(http.StatusForbidden, gin.H{"error": msg})-}--func NotFound(c *gin.Context, msg string) {- c.JSON(http.StatusNotFound, gin.H{"error": msg})+// Fail answers with a registered code and its English sentence.+func Fail(c *gin.Context, code Code, params map[string]any) {+ write(c, code, code.Message(params), params)}func InternalError(c *gin.Context) {- c.JSON(http.StatusInternalServerError, gin.H{"error": "Something went wrong on the server."})+ Fail(c, CodeInternalError, nil)}-// ValidationError reports a request whose fields broke a rule. The message is built-// by validationMessage rather than taken from err.Error(), which is a Go struct dump.-func ValidationError(c *gin.Context, err error) {- c.JSON(http.StatusUnprocessableEntity, gin.H{"error": validationMessage(err)})+// fieldFailure answers a request whose fields broke a rule. The message is built by+// describe rather than taken from err.Error(), which is a Go struct dump.+func fieldFailure(c *gin.Context, code Code, err error) {+ var fieldErrs validator.ValidationErrors+ if !errors.As(err, &fieldErrs) || len(fieldErrs) == 0 {+ Fail(c, code, nil)+ return+ }+ msg, violations := describe(err)+ write(c, code, msg, map[string]any{"violations": violations})}-func Conflict(c *gin.Context, msg string) {- c.JSON(http.StatusConflict, gin.H{"error": msg})+// ValidationError reports a request whose fields broke a rule (422).+func ValidationError(c *gin.Context, err error) {+ fieldFailure(c, CodeValidationFailed, err)}-// ServiceUnavailable signals a transient failure the client may retry, such as-// a busy/locked database.-func ServiceUnavailable(c *gin.Context, msg string) {- c.Header("Retry-After", "2")- c.JSON(http.StatusServiceUnavailable, gin.H{"error": msg})+// BindError reports a request body that could not be bound: undecodable JSON (400 with a+// code per kind of failure) or, for `binding` tags, broken field rules (400 INVALID_FIELDS).+func BindError(c *gin.Context, err error) {+ var fe validator.ValidationErrors+ if errors.As(err, &fe) {+ fieldFailure(c, codeInvalidFields, err)+ return+ }+ code, params := bindFailure(err)+ Fail(c, code, params)}diff --git a/backend/utils/validation.go b/backend/utils/validation.goindex dcf442a..3dd2bcb 100644--- a/backend/utils/validation.go+++ b/backend/utils/validation.go@@ -3,12 +3,10 @@ package utilsimport ("encoding/json""errors"- "fmt""io""reflect""strings""sync"- "time""github.com/Cawlumm/lyftr-backend/models""github.com/go-playground/locales/en"@@ -71,38 +69,9 @@ var shared = sync.OnceValue(func() *validator.Validate {panic("validator: registering English translations: " + err.Error())}- // The default renders the options as a Go slice — "must be one of [breakfast lunch- // dinner snack]", brackets and all.- translate(v, "oneof", "{0} must be one of: {1}", func(fe validator.FieldError) []string {- return []string{fe.Field(), strings.ReplaceAll(fe.Param(), " ", ", ")}- })-- // Struct-level tags are ours, so their sentences have to be too. Without these,- // Translate falls through to fe.Error() — see sentenceFor.- translate(v, "maxtotalrows", fmt.Sprintf("A program can't have more than %d days, exercises and sets combined.", models.MaxProgramRows), nil)- translate(v, "maxtotalsets", fmt.Sprintf("A workout can't have more than %d sets.", models.MaxWorkoutSets), nil)-return v})-// translate registers one override. args picks what fills {0}, {1}…; nil means the text-// stands alone.-func translate(v *validator.Validate, tag, text string, args func(validator.FieldError) []string) {- _ = v.RegisterTranslation(tag, translator,- func(t ut.Translator) error { return t.Add(tag, text, true) },- func(t ut.Translator, fe validator.FieldError) string {- var params []string- if args != nil {- params = args(fe)- }- out, err := t.T(tag, params...)- if err != nil {- return fe.Field() + " isn't valid."- }- return out- })-}-// label turns a JSON field name into something readable at the start of a sentence:// "calorie_target" -> "Calorie target".func label(field string) string {@@ -110,6 +79,11 @@ func label(field string) string {return strings.ToUpper(spaced[:1]) + spaced[1:]}+// unlabel is label's inverse for lowercase snake_case names: the raw JSON field name.+func unlabel(l string) string {+ return strings.ReplaceAll(strings.ToLower(l[:1])+l[1:], " ", "_")+}+// sentenceFor renders one failed rule, and guards the one way translations can regress on// the switch they replaced: Translate returns fe.Error() verbatim for a tag with no// translation registered, and fe.Error() is the struct dump. A future custom tag would leak@@ -130,78 +104,154 @@ func sentenceFor(fe validator.FieldError) string {return msg + "."}-// validationMessage renders a validator failure. Every failed rule is reported, not just-// the first: a sign-up form with a bad email AND a short password should say both, or the-// user fixes one and gets turned away again.-func validationMessage(err error) string {+type violation struct {+ Code string `json:"code"`+ Params map[string]any `json:"params,omitempty"`+}++type rule struct {+ code Code+ limit string // "min" or "max": the param that carries the tag's limit+ noName bool // struct-level: the sentence names no field+}++// kindClass says which meaning a tag has: min=8 on text is a length, gte=0 on a number a floor.+func kindClass(k reflect.Kind) string {+ switch k {+ case reflect.String:+ return "text"+ case reflect.Slice, reflect.Array, reflect.Map:+ return "list"+ case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64,+ reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64,+ reflect.Float32, reflect.Float64:+ return "number"+ }+ return ""+}++// The one map from validator failure to code, keyed by tag and kind class. A tag not+// here becomes INVALID_FIELD and keeps the library's sentence.+var rules = map[string]rule{+ "required": {code: codeRequired},+ "email:text": {code: codeInvalidEmail},+ "min:text": {code: codeTooShort, limit: "min"},+ "max:text": {code: codeTooLong, limit: "max"},+ "max:list": {code: codeTooManyItems, limit: "max"},+ "gte:number": {code: codeBelowMinimum, limit: "min"},+ "gt:number": {code: codeNotAboveMinimum, limit: "min"},+ "lte:number": {code: codeAboveMaximum, limit: "max"},+ "oneof": {code: codeNotAnOption},+ "maxtotalsets": {code: codeTooManyWorkoutSets, noName: true},+ "maxtotalrows": {code: codeTooManyProgramRows, noName: true},+}++func ruleFor(fe validator.FieldError) (rule, bool) {+ if r, ok := rules[fe.Tag()+":"+kindClass(fe.Kind())]; ok {+ return r, true+ }+ r, ok := rules[fe.Tag()]+ return r, ok+}++func violationOf(fe validator.FieldError) (violation, string) {+ r, ok := ruleFor(fe)+ if !ok {+ p := map[string]any{"field": unlabel(fe.Field())}+ return violation{Code: codeInvalidField.ID, Params: p}, sentenceFor(fe)+ }+ params := map[string]any{}+ if !r.noName {+ params["field"] = unlabel(fe.Field())+ }+ switch {+ case r.limit != "":+ params[r.limit] = json.Number(fe.Param())+ case fe.Tag() == "oneof":+ params["options"] = strings.ReplaceAll(fe.Param(), " ", ", ")+ case fe.Tag() == "maxtotalsets":+ params["max"] = models.MaxWorkoutSets+ case fe.Tag() == "maxtotalrows":+ params["max"] = models.MaxProgramRows+ }+ if len(params) == 0 {+ params = nil+ }+ return violation{Code: r.code.ID, Params: params}, r.code.Message(params)+}++// describe renders a validator failure as the joined English sentence plus its violations.+// Every failed rule is reported, not just the first: a sign-up form with a bad email AND a+// short password should say both, or the user fixes one and gets turned away again.+func describe(err error) (string, []violation) {var fieldErrs validator.ValidationErrorsif !errors.As(err, &fieldErrs) || len(fieldErrs) == 0 {- return "Some of the details you entered aren't valid."+ return CodeValidationFailed.Message(nil), nil}parts := make([]string, 0, len(fieldErrs))+ violations := make([]violation, 0, len(fieldErrs))for _, e := range fieldErrs {- parts = append(parts, sentenceFor(e))+ v, msg := violationOf(e)+ violations = append(violations, v)+ parts = append(parts, msg)}- return strings.Join(parts, " ")+ return strings.Join(parts, " "), violations}-// shapeName says what a field wanted in words a person can act on. typeErr.Type is a Go-// type, and printing it put "expected float64" in front of someone logging a meal — the-// same leak this file exists to stop, one size smaller and past a test that only checked-// for the name of the *error* type. Empty means we have no better word than "wrong type".-func shapeName(t reflect.Type) string {+func validationMessage(err error) string {+ msg, _ := describe(err)+ return msg+}++// bindClass says which code a field of this type failing to decode gets. typeErr.Type is a+// Go type, and printing it put "expected float64" in front of someone logging a meal, so the+// code names what the field wanted in words a person can act on.+func bindClass(t reflect.Type) Code {for t.Kind() == reflect.Ptr {t = t.Elem()}- if t == reflect.TypeOf(time.Time{}) {- return "a date"- }switch t.Kind() {case reflect.Bool:- return "true or false"+ return codeNotTrueOrFalsecase reflect.String:- return "text"+ return codeNotTextcase reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64,reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64,reflect.Float32, reflect.Float64:- return "a number"+ return codeNotANumbercase reflect.Slice, reflect.Array:- return "a list"+ return codeNotAListcase reflect.Map, reflect.Struct:- return "an object"+ return codeNotAnObject}- return ""+ return codeBodyWrongType}-// BindMessage renders a request body we could not read at all. These are not user+// bindFailure classifies a request body we could not read at all. These are not user// mistakes so much as client bugs or truncated uploads, but the person holding the phone-// still has to be told something — and "unexpected EOF" is not it.-func BindMessage(err error) string {+// still has to be told something — and "unexpected EOF" is not it. params.field is the+// raw dotted JSON path, which Message renders through label.+func bindFailure(err error) (Code, map[string]any) {var typeErr *json.UnmarshalTypeErrorif errors.As(err, &typeErr) {- if typeErr.Field != "" {- if want := shapeName(typeErr.Type); want != "" {- return fmt.Sprintf("%s must be %s.", label(typeErr.Field), want)- }- return fmt.Sprintf("%s has the wrong type.", label(typeErr.Field))+ if typeErr.Field == "" {+ return codeBodyWrongType, nil+ }+ code := bindClass(typeErr.Type)+ if code.ID == codeBodyWrongType.ID {+ return code, nil}- return "The request body had a field of the wrong type."+ return code, map[string]any{"field": typeErr.Field}}var syntaxErr *json.SyntaxErrorif errors.As(err, &syntaxErr) || errors.Is(err, io.ErrUnexpectedEOF) {- return "The request body wasn't valid JSON."+ return codeBodyNotJSON, nil}if errors.Is(err, io.EOF) {- return "The request body was empty."- }-- // gin also surfaces validator failures through Bind when binding tags are used.- var fieldErrs validator.ValidationErrors- if errors.As(err, &fieldErrs) {- return validationMessage(err)+ return codeBodyEmpty, nil}- return "The request couldn't be read."+ return codeBodyUnreadable, nil}diff --git a/backend/utils/validation_test.go b/backend/utils/validation_test.goindex 9656a55..9ee6a86 100644--- a/backend/utils/validation_test.go+++ b/backend/utils/validation_test.go@@ -2,9 +2,15 @@ package utilsimport ("encoding/json"+ "errors"+ "io"+ "net/http"+ "net/http/httptest"+ "reflect""strings""testing"+ "github.com/gin-gonic/gin""github.com/go-playground/validator/v10")@@ -24,6 +30,14 @@ type entry struct {Note string `json:"note" validate:"max=500"`}+type workoutSet struct {+ Weight float64 `json:"weight" validate:"required"`+}++type listed struct {+ Items []int `json:"items" validate:"max=500"`+}+func messageFor(t *testing.T, v any) string {t.Helper()err := NewValidator().Struct(v)@@ -84,6 +98,8 @@ func TestValidationMessagePerTag(t *testing.T) {{"gte=0 reads as a floor", entry{Meal: "lunch", Calories: -5, Servings: 1}, "Calories must be 0 or greater."},{"gt=0 excludes the floor", entry{Meal: "lunch", Servings: 0}, "Servings must be greater than 0."},{"lte gives the ceiling", entry{Meal: "lunch", Servings: 5000}, "Servings must be 2,000 or less."},+ {"required on a number", workoutSet{}, "Weight is a required field."},+ {"max on a list counts items", listed{Items: make([]int, 501)}, "Items must contain at maximum 500 items."},{"max on a string counts characters", entry{Meal: "lunch", Servings: 1, Note: strings.Repeat("x", 501)}, "Note must be a maximum of 500 characters in length."},}for _, tc := range cases {@@ -97,17 +113,19 @@ func TestValidationMessagePerTag(t *testing.T) {// Not a validator failure at all — a body we could not decode. "unexpected EOF" is the Go// runtime talking to itself.-func TestBindMessage(t *testing.T) {+func TestBindFailureForUndecodableBodies(t *testing.T) {var target signupcases := []struct {name stringbody string- want string+ want Code+ text string}{- {"truncated", `{"email":`, "The request body wasn't valid JSON."},- {"garbage", `not json at all`, "The request body wasn't valid JSON."},- {"empty", ``, "The request body was empty."},+ {"truncated", `{"email":`, codeBodyNotJSON, "The request body wasn't valid JSON."},+ {"garbage", `not json at all`, codeBodyNotJSON, "The request body wasn't valid JSON."},+ {"empty", ``, codeBodyEmpty, "The request body was empty."},+ {"top-level wrong type", `[1]`, codeBodyWrongType, "The request body had a field of the wrong type."},}for _, tc := range cases {t.Run(tc.name, func(t *testing.T) {@@ -118,38 +136,57 @@ func TestBindMessage(t *testing.T) {if err == nil {t.Fatal("expected a decode error")}- if got := BindMessage(err); got != tc.want {- t.Fatalf("got %q, want %q", got, tc.want)+ code, params := bindFailure(err)+ if code.ID != tc.want.ID || code.Message(params) != tc.text {+ t.Fatalf("got %s %q, want %s %q", code.ID, code.Message(params), tc.want.ID, tc.text)}})}++ if code, _ := bindFailure(errors.New("x")); code.ID != codeBodyUnreadable.ID {+ t.Fatalf("an unknown error should be %s, got %s", codeBodyUnreadable.ID, code.ID)+ }}// The field is named, and the SHAPE it wanted is said in English. The previous version of// this test only rejected "UnmarshalTypeError" — the name of the error type — which is why// "expected float64" reached users unnoticed. Go type names are checked for explicitly now.-func TestBindMessageNamesTheFieldWithTheWrongType(t *testing.T) {+func TestBindFailureNamesTheFieldWithTheWrongType(t *testing.T) {+ type set struct {+ Weight float64 `json:"weight"`+ }+ type exercise struct {+ Sets []set `json:"sets"`+ }cases := []struct {- name string- into any- body string- want string+ name string+ into any+ body string+ want Code+ field string+ text string}{{"number", &struct {Calories float64 `json:"calories"`- }{}, `{"calories":"lots"}`, "Calories must be a number."},+ }{}, `{"calories":"lots"}`, codeNotANumber, "calories", "Calories must be a number."},{"text", &struct {Name string `json:"name"`- }{}, `{"name":12}`, "Name must be text."},+ }{}, `{"name":12}`, codeNotText, "name", "Name must be text."},{"boolean", &struct {IsWarmup bool `json:"is_warmup"`- }{}, `{"is_warmup":"yes"}`, "Is warmup must be true or false."},+ }{}, `{"is_warmup":"yes"}`, codeNotTrueOrFalse, "is_warmup", "Is warmup must be true or false."},{"list", &struct {Sets []int `json:"sets"`- }{}, `{"sets":3}`, "Sets must be a list."},+ }{}, `{"sets":3}`, codeNotAList, "sets", "Sets must be a list."},+ {"object", &struct {+ Set set `json:"set"`+ }{}, `{"set":3}`, codeNotAnObject, "set", "Set must be an object."},{"pointer is followed", &struct {ProgramID *int64 `json:"program_id"`- }{}, `{"program_id":"seven"}`, "Program id must be a number."},+ }{}, `{"program_id":"seven"}`, codeNotANumber, "program_id", "Program id must be a number."},+ {"nested path", &struct {+ Exercises []exercise `json:"exercises"`+ }{}, `{"exercises":[{"sets":[{"weight":"x"}]}]}`, codeNotANumber, "exercises.sets.weight", "Exercises.sets.weight must be a number."},}for _, tc := range cases {t.Run(tc.name, func(t *testing.T) {@@ -157,9 +194,13 @@ func TestBindMessageNamesTheFieldWithTheWrongType(t *testing.T) {if err == nil {t.Fatal("expected a type error")}- got := BindMessage(err)- if got != tc.want {- t.Fatalf("got %q, want %q", got, tc.want)+ code, params := bindFailure(err)+ if code.ID != tc.want.ID || params["field"] != tc.field {+ t.Fatalf("got %s %v, want %s field %q", code.ID, params, tc.want.ID, tc.field)+ }+ got := code.Message(params)+ if got != tc.text {+ t.Fatalf("got %q, want %q", got, tc.text)}for _, goName := range []string{"float64", "int64", "int", "string", "bool", "[]", "*", "UnmarshalTypeError"} {if strings.Contains(got, goName) {@@ -170,6 +211,30 @@ func TestBindMessageNamesTheFieldWithTheWrongType(t *testing.T) {}}+// `binding` tags surface validator failures through the bind; they answer 400 INVALID_FIELDS+// with the same violations a 422 carries.+func TestBindErrorWithAValidatorFailure(t *testing.T) {+ type body struct {+ Data string `json:"data" validate:"required"`+ }+ err := NewValidator().Struct(body{})++ c, w := testCtx()+ BindError(c, err)++ b := bodyOf(t, w)+ params, _ := b["params"].(map[string]any)+ if w.Code != 400 || b["code"] != "INVALID_FIELDS" || b["error"] != "Data is a required field." || params["violations"] == nil {+ t.Fatalf("BindError = %d %v", w.Code, b)+ }++ c, w = testCtx()+ BindError(c, io.EOF)+ if b := bodyOf(t, w); w.Code != 400 || b["code"] != "BODY_EMPTY" || b["params"] != nil {+ t.Fatalf("BindError(EOF) = %d %v", w.Code, b)+ }+}+// A tag nobody here has written a sentence for still reads as one — this is what moving to// the library's translations bought. Before, `alphanum` fell through to "Code isn't valid."func TestValidationMessageCoversTagsWeNeverWrote(t *testing.T) {@@ -221,3 +286,63 @@ func TestValidationMessageTranslatesOurStructTags(t *testing.T) {t.Fatalf("got %q", got)}}++func validationBody(t *testing.T, err error) (int, map[string]any) {+ t.Helper()+ gin.SetMode(gin.TestMode)+ w := httptest.NewRecorder()+ c, _ := gin.CreateTestContext(w)+ c.Request = httptest.NewRequest(http.MethodPost, "/x", nil)+ ValidationError(c, err)+ var body map[string]any+ if e := json.Unmarshal(w.Body.Bytes(), &body); e != nil {+ t.Fatal(e)+ }+ return w.Code, body+}++func TestValidationErrorBody(t *testing.T) {+ code, body := validationBody(t, NewValidator().Struct(signup{Email: "nope", Password: "abc"}))+ if code != 422 || body["code"] != "VALIDATION_FAILED" ||+ body["error"] != "Email must be a valid email address. Password must be at least 8 characters in length." {+ t.Fatalf("got %d %v", code, body)+ }+ want := []any{+ map[string]any{"code": "INVALID_EMAIL", "params": map[string]any{"field": "email"}},+ map[string]any{"code": "TOO_SHORT", "params": map[string]any{"field": "password", "min": float64(8)}},+ }+ if got := body["params"].(map[string]any)["violations"]; !reflect.DeepEqual(got, want) {+ t.Fatalf("violations = %#v", got)+ }++ type capped struct {+ Sets int `json:"sets" validate:"required"`+ }+ vl := NewValidator()+ vl.RegisterStructValidation(func(sl validator.StructLevel) {+ sl.ReportError(1, "Sets", "Sets", "maxtotalsets", "")+ }, capped{})+ _, body = validationBody(t, vl.Struct(capped{Sets: 1}))+ got := body["params"].(map[string]any)["violations"].([]any)[0]+ if !reflect.DeepEqual(got, map[string]any{"code": "TOO_MANY_WORKOUT_SETS", "params": map[string]any{"max": float64(500)}}) {+ t.Fatalf("struct-level violation = %#v", got)+ }++ type odd struct {+ Code string `json:"code" validate:"alphanum"`+ }+ _, body = validationBody(t, NewValidator().Struct(odd{Code: "!!!"}))+ got = body["params"].(map[string]any)["violations"].([]any)[0]+ if body["error"] != "Code can only contain alphanumeric characters." ||+ !reflect.DeepEqual(got, map[string]any{"code": "INVALID_FIELD", "params": map[string]any{"field": "code"}}) {+ t.Fatalf("unmapped tag = %v", body)+ }++ code, body = validationBody(t, errors.New("boom"))+ if code != 422 || body["code"] != "VALIDATION_FAILED" {+ t.Fatalf("got %d %v", code, body)+ }+ if _, has := body["params"]; has {+ t.Fatalf("params present: %v", body)+ }+}diff --git a/docs/API_CHANGES.md b/docs/API_CHANGES.mdindex 46f9c87..46c35b6 100644--- a/docs/API_CHANGES.md+++ b/docs/API_CHANGES.md@@ -14,6 +14,68 @@ catches what the author knew and forgot; it cannot catch what the author never nIf your PR changes a status code, narrows an accepted value, or renames a response field,add the entry in that PR.+## Every error response — gains a stable `code` beside `error`++Additive: `error` is byte-identical to before and still authoritative for any caller that+ignores `code`. Every error body is now `{"error": "...", "code": "UPPER_SNAKE"}`, with an+optional `params` object when the sentence has variables. The first-party clients key their+own (localized) wording on `code` and fall back to `error`.++Codes (70). Every error has its own code with a fixed status; there is no generic+`BAD_REQUEST`, `NOT_FOUND` or `SERVICE_UNAVAILABLE`.++- Sign-in and session: `INVALID_CREDENTIALS`, `EMAIL_TAKEN`, `REGISTRATION_CLOSED`,+ `PASSWORD_TOO_LONG`, `PASSWORD_UNCHANGED`, `WRONG_CURRENT_PASSWORD`, `ACCOUNT_NOT_FOUND`,+ `PASSWORD_CHANGED_ELSEWHERE`, `PASSWORD_CHANGED_SIGN_IN_AGAIN`,+ `EMAIL_CHANGED_SIGN_IN_AGAIN`, `SIGN_IN_REQUIRED`, `SESSION_INVALID`, `SESSION_EXPIRED`,+ `WRONG_TOKEN_TYPE`.+- Server: `INTERNAL_ERROR`, `DATABASE_BUSY`, `RATE_LIMITED`.+- Validation (`422`, and the violation codes inside it): `VALIDATION_FAILED`, `REQUIRED`,+ `INVALID_EMAIL`, `TOO_SHORT`, `TOO_LONG`, `TOO_MANY_ITEMS`, `BELOW_MINIMUM`,+ `NOT_ABOVE_MINIMUM`, `ABOVE_MAXIMUM`, `NOT_AN_OPTION`, `TOO_MANY_WORKOUT_SETS`,+ `TOO_MANY_PROGRAM_ROWS`, `INVALID_FIELD`.+- Request body (`400`): `INVALID_FIELDS`, `NOT_A_NUMBER`, `NOT_TEXT`, `NOT_TRUE_OR_FALSE`,+ `NOT_A_LIST`, `NOT_AN_OBJECT`, `BODY_WRONG_TYPE`, `BODY_NOT_JSON`, `BODY_EMPTY`,+ `BODY_UNREADABLE`.+- Resources: `INVALID_ID`, `INVALID_EXERCISE_ID`, `INVALID_PROGRAM_ID`, `INVALID_WORKOUT_ID`+ (`400`); `ENTRY_NOT_FOUND`, `SAVED_FOOD_NOT_FOUND`, `EXERCISE_NOT_FOUND`,+ `PROGRAM_NOT_FOUND`, `WORKOUT_NOT_FOUND` (`404`); `UNKNOWN_EXERCISES`, `NO_EXERCISE_CATALOG`+ (`400`).+- Dates: `INVALID_DATE`, `INVALID_LOGGED_ON`, `INVALID_FROM_DATE`, `INVALID_TO_DATE` (`400`).+- Food: `FOOD_NAME_TOO_LONG`, `FOOD_BRAND_TOO_LONG`, `SERVING_SIZE_TOO_LONG`,+ `BARCODE_TOO_LONG`, `IMAGE_URL_TOO_LONG`, `SEARCH_TERM_REQUIRED`, `INVALID_BARCODE` (`400`);+ `PRODUCT_NOT_FOUND` (`404`); `FOOD_DATABASE_TIMEOUT`, `FOOD_DATABASE_UNREACHABLE`,+ `FOOD_SEARCH_UNAVAILABLE`, `BARCODE_LOOKUP_UNAVAILABLE` (`503`, with `Retry-After: 2`).+- Settings: `DISPLAY_NAME_CONTROL_CHARS`, `TIMEZONE_EMPTY`, `UNKNOWN_TIMEZONE` (`400`).++Parameters are JSON values: the length-limit codes carry `params.max` as a number,+`UNKNOWN_TIMEZONE` carries `params.timezone`, and the request-body codes (`NOT_A_NUMBER`,+`NOT_TEXT`, `NOT_TRUE_OR_FALSE`, `NOT_A_LIST`, `NOT_AN_OBJECT`) carry `params.field`, the+dotted JSON path of the field (`exercises.sets.weight`).++A `422` carries `params.violations`, one `{code, params}` per failed rule, with raw JSON+field names and limits as JSON numbers:++```json+{+ "error": "Email must be a valid email address. Password must be at least 8 characters in length.",+ "code": "VALIDATION_FAILED",+ "params": {+ "violations": [+ { "code": "INVALID_EMAIL", "params": { "field": "email" } },+ { "code": "TOO_SHORT", "params": { "field": "password", "min": 8 } }+ ]+ }+}+```++`PUT /api/v1/settings` and `PUT /api/v1/active-session` reject a field that breaks a rule+with `400` `INVALID_FIELDS`, the `400` twin of `VALIDATION_FAILED`: the same sentence and the+same `params.violations`, with the status those endpoints always had. Their body was+previously `BAD_REQUEST`, which no release shipped.++New codes may appear in later releases: treat an unknown `code` as "show `error`".+## `POST /api/v1/auth/register` — an address differing only in letter case is a duplicateAn address that differs from an existing account only in letter case (`[email protected]`diff --git a/packages/shared/src/client.test.ts b/packages/shared/src/client.test.tsindex cc7b1e1..b4d5448 100644--- a/packages/shared/src/client.test.ts+++ b/packages/shared/src/client.test.ts@@ -624,3 +624,187 @@ describe('apiErrorMessage and uiMessage translate when they run', () => {expect(uiMessage({ ...m, cause: bad502 })).toBe(es.errors.api.restarting)})})++describe('apiErrorMessage — server codes', () => {+ afterEach(async () => { await i18n.changeLanguage('en') })+ const body = (status: number, data: any) => ({ response: { status, data } })++ it('en: a known code renders the catalog text, not the server words', () => {+ expect(apiErrorMessage(body(409, { code: 'EMAIL_TAKEN', error: 'server words' }), 'x')).toBe(en.errors.api.codes.EMAIL_TAKEN)+ })++ it('es: a known code renders Spanish (a bare 500 is the observed bug)', async () => {+ await i18n.changeLanguage('es')+ expect(apiErrorMessage(body(500, { code: 'INTERNAL_ERROR', error: 'Something went wrong on the server.' }), 'x'))+ .toBe(es.errors.api.codes.INTERNAL_ERROR)+ })++ it('en: no code or an unregistered code returns the server sentence', () => {+ expect(apiErrorMessage(body(400, { error: 'Old server.' }), 'x')).toBe('Old server.')+ expect(apiErrorMessage(body(400, { code: 'BRAND_NEW', error: 'Newer server.' }), 'x')).toBe('Newer server.')+ expect(apiErrorMessage(body(400, { code: 'NOT_FOUND', error: 'Name is taken.' }), 'x')).toBe('Name is taken.')+ })++ it('en: no code and no sentence keeps the status handling', () => {+ expect(apiErrorMessage(body(404, {}), 'x')).toBe(en.errors.api.misconfigured)+ expect(apiErrorMessage(body(502, {}), 'x')).toBe(en.errors.api.restarting)+ expect(apiErrorMessage(body(500, {}), 'x')).toBe(en.errors.api.serverError)+ expect(apiErrorMessage(body(400, {}), 'fallback')).toBe('fallback')+ })++ it('es: VALIDATION_FAILED localizes each violation with Spanish field labels and joins them', async () => {+ await i18n.changeLanguage('es')+ const data = {+ error: 'English.',+ code: 'VALIDATION_FAILED',+ params: {+ violations: [+ { code: 'INVALID_EMAIL', params: { field: 'email' } },+ { code: 'TOO_SHORT', params: { field: 'password', min: 8 } },+ { code: 'BELOW_MINIMUM', params: { field: 'calories', min: 0 } },+ ],+ },+ }+ expect(apiErrorMessage(body(422, data), 'x')).toBe(+ [+ es.errors.api.codes.INVALID_EMAIL.replace('{{field}}', es.errors.api.fields.email),+ es.errors.api.codes.TOO_SHORT.replace('{{field}}', es.errors.api.fields.password).replace('{{min}}', '8'),+ es.errors.api.codes.BELOW_MINIMUM.replace('{{field}}', es.errors.api.fields.calories).replace('{{min}}', '0'),+ ].join(' '),+ )+ })++ it('es: one unresolvable violation falls back to the whole English sentence', async () => {+ await i18n.changeLanguage('es')+ const data = {+ error: 'English whole.',+ code: 'VALIDATION_FAILED',+ params: { violations: [{ code: 'REQUIRED', params: { field: 'email' } }, { code: 'NEW_RULE', params: { field: 'email' } }] },+ }+ expect(apiErrorMessage(body(422, data), 'x')).toBe('English whole.')+ data.params.violations = [{ code: 'REQUIRED', params: { field: 'email' } }, { code: 'REQUIRED', params: { field: 'not_a_field' } }]+ expect(apiErrorMessage(body(422, data), 'x')).toBe('English whole.')+ })++ it.each([+ ['FOOD_DATABASE_TIMEOUT', 503, undefined, undefined],+ ['PRODUCT_NOT_FOUND', 404, undefined, undefined],+ ['SEARCH_TERM_REQUIRED', 400, undefined, undefined],+ ['INVALID_WORKOUT_ID', 400, undefined, undefined],+ ['UNKNOWN_TIMEZONE', 400, { timezone: 'Mars/Base' }, 'Mars/Base'],+ ['FOOD_BRAND_TOO_LONG', 400, { max: 200 }, '200'],+ ])('es: %s renders Spanish', async (code, status, params, fill) => {+ await i18n.changeLanguage('es')+ const text = apiErrorMessage(body(status as number, { code, error: 'English.', params }), 'x')+ let want = (es.errors.api.codes as Record<string, string>)[code as string]+ if (params) want = want.replace('{{timezone}}', String((params as any).timezone ?? '')).replace('{{max}}', String((params as any).max ?? ''))+ expect(text).toBe(want)+ expect(text).not.toBe('English.')+ if (fill) expect(text).toContain(fill)+ })++ it('es: a bind failure on a nested field is labelled by its leaf', async () => {+ await i18n.changeLanguage('es')+ const data = { code: 'NOT_A_NUMBER', error: 'Exercises.sets.weight must be a number.', params: { field: 'exercises.sets.weight' } }+ expect(apiErrorMessage(body(400, data), 'x')).toBe('El campo Peso debe ser un número.')+ })++ it('en: a bind failure on a nested field names the leaf label', () => {+ const data = { code: 'NOT_A_NUMBER', error: 'Exercises.sets.weight must be a number.', params: { field: 'exercises.sets.weight' } }+ expect(apiErrorMessage(body(400, data), 'x')).toBe('Weight must be a number.')+ })++ it('es: INVALID_FIELDS (400) localizes its violations like VALIDATION_FAILED', async () => {+ await i18n.changeLanguage('es')+ const data = {+ code: 'INVALID_FIELDS',+ error: 'Weight unit must be one of: lbs, kg.',+ params: { violations: [{ code: 'NOT_AN_OPTION', params: { field: 'weight_unit', options: 'lbs, kg' } }] },+ }+ expect(apiErrorMessage(body(400, data), 'x')).toBe(+ es.errors.api.codes.NOT_AN_OPTION.replace('{{field}}', es.errors.api.fields.weight_unit).replace('{{options}}', 'lbs, kg'),+ )+ })++ it('en: VALIDATION_FAILED without violations shows the code text', () => {+ expect(apiErrorMessage(body(422, { code: 'VALIDATION_FAILED', error: 'e' }), 'x')).toBe(en.errors.api.codes.VALIDATION_FAILED)+ })++ it('en: a missing param falls back to the server sentence rather than showing {{max}}', () => {+ expect(apiErrorMessage(body(422, { code: 'TOO_LONG', error: 'Server sentence.', params: { field: 'name' } }), 'x')).toBe('Server sentence.')+ })++ it.each([+ ['non-string code', { code: 5, error: 'S.' }],+ ['lower-case code', { code: 'email_taken', error: 'S.' }],+ ['camelCase sibling key', { code: 'serverError', error: 'S.' }],+ ['dotted code', { code: 'EMAIL.TAKEN', error: 'S.' }],+ ['array params', { code: 'TOO_LONG', error: 'S.', params: [] }],+ ['object violations', { code: 'VALIDATION_FAILED', error: 'S.', params: { violations: {} } }],+ ['null violation', { code: 'VALIDATION_FAILED', error: 'S.', params: { violations: [null] } }],+ ['dotted field with an unknown leaf', { code: 'REQUIRED', error: 'S.', params: { field: 'a.b' } }],+ ['upper-case path', { code: 'NOT_A_NUMBER', error: 'S.', params: { field: 'A.b' } }],+ ['empty path segment', { code: 'NOT_A_NUMBER', error: 'S.', params: { field: 'a..b' } }],+ ])('malformed body (%s) never throws and falls back to the server sentence', (_n, data) => {+ expect(apiErrorMessage(body(422, data), 'x')).toBe('S.')+ })++ it('null params on a code that needs none still renders its text', () => {+ expect(apiErrorMessage(body(409, { code: 'EMAIL_TAKEN', error: 'S.', params: null }), 'x')).toBe(en.errors.api.codes.EMAIL_TAKEN)+ })++ describe('codes do not change which failures end a session', () => {+ const realAdapter = axios.defaults.adapter+ afterEach(() => { axios.defaults.adapter = realAdapter })++ const httpError = (status: number, config: any, data: any) => {+ const err: any = new Error(`Request failed with status code ${status}`)+ err.config = config+ err.response = { status, data, statusText: '', headers: {}, config }+ return err+ }++ const setup = (dataStatus: number, dataBody: any, refresh: (config: any) => Promise<any>) => {+ const store = memStorage()+ let signedOut = false+ const client = createClient(store, { onAuthFailure: () => { signedOut = true } })+ let refreshed = 0+ client.api.defaults.adapter = async (config: any) => { throw httpError(dataStatus, config, dataBody) }+ axios.defaults.adapter = (async (config: any) => { refreshed++; return refresh(config) }) as any+ return { client, store, wasSignedOut: () => signedOut, refreshCount: () => refreshed }+ }++ const signedIn = async (store: StorageAdapter) => {+ await store.set(STORAGE_KEYS.access, 'live-access')+ await store.set(STORAGE_KEYS.refresh, 'live-refresh')+ }++ it('a refresh answering 401 SESSION_EXPIRED still signs out', async () => {+ const { client, store, wasSignedOut } = setup(401, { code: 'SESSION_EXPIRED' }, async (config) => {+ throw httpError(401, config, { code: 'SESSION_EXPIRED', error: 'x' })+ })+ await signedIn(store)+ await expect(client.userAPI.me()).rejects.toBeDefined()+ expect(wasSignedOut()).toBe(true)+ expect(await store.get(STORAGE_KEYS.refresh)).toBeNull()+ })++ it('a refresh answering 503 DATABASE_BUSY keeps the session', async () => {+ const { client, store, wasSignedOut } = setup(401, {}, async (config) => {+ throw httpError(503, config, { code: 'DATABASE_BUSY', error: 'x' })+ })+ await signedIn(store)+ await expect(client.userAPI.me()).rejects.toBeDefined()+ expect(wasSignedOut()).toBe(false)+ expect(await store.get(STORAGE_KEYS.refresh)).toBe('live-refresh')+ })++ it('/me/password answering 401 WRONG_CURRENT_PASSWORD neither refreshes nor signs out', async () => {+ const { client, store, wasSignedOut, refreshCount } = setup(401, { code: 'WRONG_CURRENT_PASSWORD', error: 'x' }, async () => ({}))+ await signedIn(store)+ await expect(client.userAPI.changePassword({ current_password: 'a', new_password: 'bbbbbbbb' })).rejects.toBeDefined()+ expect(refreshCount()).toBe(0)+ expect(wasSignedOut()).toBe(false)+ })+ })+})diff --git a/packages/shared/src/client.ts b/packages/shared/src/client.tsindex f1a1ac6..6d808c9 100644--- a/packages/shared/src/client.ts+++ b/packages/shared/src/client.ts@@ -27,7 +27,57 @@ export interface ServerInfo {demo_mode?: boolean}-// Turn an axios error into an actionable message. Proxy misconfig (404/405) is+// The server's own words, in the user's language. The server sends a stable `code` beside its+// English `error`; wording for the codes lives in the catalog (errors.api.codes). Null means+// "not ours to say": no code (an older server), a code this build has no wording for, or a+// param we cannot fill. In every such case the caller falls back to the server's sentence, so+// a half-translated message is never shown.+const CODE_ID = /^[A-Z][A-Z0-9_]*$/+// A field is a JSON name, or the dotted path of a nested one (exercises.sets.weight) when a+// body could not be bound; the catalog labels the last segment.+const FIELD_PATH = /^[a-z][a-z0-9_]*(\.[a-z][a-z0-9_]*)*$/++const codedMessage = (body: any): string | null => {+ const t = i18n.t as (key: string, params?: Record<string, unknown>) => string++ const one = (code: unknown, params: unknown): string | null => {+ if (typeof code !== 'string' || !CODE_ID.test(code)) return null+ const key = `errors.api.codes.${code}`+ if (!i18n.exists(key)) return null+ const values: Record<string, unknown> = {}+ if (params !== null && params !== undefined) {+ if (typeof params !== 'object' || Array.isArray(params)) return null+ Object.assign(values, params)+ }+ if ('field' in values) {+ const field = values.field+ if (typeof field !== 'string' || !FIELD_PATH.test(field)) return null+ const fieldKey = `errors.api.fields.${field.split('.').pop()}`+ if (!i18n.exists(fieldKey)) return null+ values.field = t(fieldKey)+ }+ // `replace` keeps a param named count, lng, ns or context from steering the lookup.+ const text = t(key, { replace: values })+ return text.includes('{{') ? null : text+ }++ if (!body || typeof body !== 'object') return null+ const violations = body.params?.violations+ if (violations !== undefined) {+ if (!Array.isArray(violations) || violations.length === 0) return null+ const parts: string[] = []+ for (const v of violations) {+ const text = one(v?.code, v?.params)+ if (text === null) return null+ parts.push(text)+ }+ return parts.join(' ')+ }+ return one(body.code, body.params)+}++// Turn an axios error into an actionable message. Order: the server's code in our wording,+// then the server's own sentence, then the status, then the caller's fallback. Proxy misconfig (404/405) is// distinguished from real auth and server errors, so connectivity problems don't// masquerade as "Registration failed." Response-less failures go to the classifier,// which separates a blocked-cleartext or untrusted-certificate failure from a genuinely@@ -41,6 +91,8 @@ export interface ServerInfo {export const isNotFound = (err: any): boolean => err?.response?.status === 404export const apiErrorMessage = (err: any, fallback: string, detail: MessageDetail = 'brief'): string => {if (err?.response) {+ const coded = codedMessage(err.response.data)+ if (coded) return codedconst serverError = err.response.data?.errorif (serverError) return serverErrorconst status = err.response.statusdiff --git a/packages/shared/src/i18n/locales/README.md b/packages/shared/src/i18n/locales/README.mdindex 0be7669..81e0148 100644--- a/packages/shared/src/i18n/locales/README.md+++ b/packages/shared/src/i18n/locales/README.md@@ -15,6 +15,8 @@ from `LANGUAGE_NAMES`.How to add a language, and the key-naming rules: see the "Translations" section of[CONTRIBUTING.md](../../../../../CONTRIBUTING.md).+`errors.api.codes` keys are the API's error codes (UPPER_SNAKE, an exception to the camelCase key rule because they are wire identifiers), and `errors.api.fields` keys are API field names. `backend/utils/codes_test.go` fails when they disagree with the server.+## Spanish: voice and glossary`es.json` is machine-translated from `en.json` and has not been reviewed by a nativediff --git a/packages/shared/src/i18n/locales/en.json b/packages/shared/src/i18n/locales/en.jsonindex 125abc0..67ac867 100644--- a/packages/shared/src/i18n/locales/en.json+++ b/packages/shared/src/i18n/locales/en.json@@ -298,7 +298,136 @@"misconfigured": "Server URL looks misconfigured — the API endpoint wasn't found. Check Server settings.","restarting": "The server is restarting or unreachable. Try again in a moment.","notApi": "That address returned a web page, not the Lyftr API. Check Server settings.",- "serverError": "Server error. Please try again shortly."+ "serverError": "Server error. Please try again shortly.",+ "codes": {+ "VALIDATION_FAILED": "Some of the details you entered aren't valid.",+ "INVALID_CREDENTIALS": "Invalid email or password.",+ "EMAIL_TAKEN": "That email is already registered.",+ "REGISTRATION_CLOSED": "Registration is closed on this server.",+ "PASSWORD_TOO_LONG": "Password must be 72 bytes or fewer — accented letters and emoji count for more than one.",+ "PASSWORD_UNCHANGED": "Your new password must be different from your current one.",+ "WRONG_CURRENT_PASSWORD": "Your current password is incorrect.",+ "ACCOUNT_NOT_FOUND": "That account no longer exists.",+ "PASSWORD_CHANGED_ELSEWHERE": "Your password was changed elsewhere. Please try again.",+ "PASSWORD_CHANGED_SIGN_IN_AGAIN": "Your password changed. Please sign in again.",+ "EMAIL_CHANGED_SIGN_IN_AGAIN": "Your email changed. Please sign in again.",+ "SIGN_IN_REQUIRED": "You need to sign in to do that.",+ "SESSION_INVALID": "Your session isn't valid. Please sign in again.",+ "SESSION_EXPIRED": "Your session expired. Please sign in again.",+ "WRONG_TOKEN_TYPE": "That token can't be used here.",+ "INTERNAL_ERROR": "Something went wrong on the server.",+ "DATABASE_BUSY": "The database is busy. Try again in a moment.",+ "RATE_LIMITED": "Too many requests. Wait a moment and try again.",+ "REQUIRED": "{{field}} is a required field.",+ "INVALID_EMAIL": "{{field}} must be a valid email address.",+ "TOO_SHORT": "{{field}} must be at least {{min}} characters in length.",+ "TOO_LONG": "{{field}} must be a maximum of {{max}} characters in length.",+ "TOO_MANY_ITEMS": "{{field}} must contain at maximum {{max}} items.",+ "BELOW_MINIMUM": "{{field}} must be {{min}} or greater.",+ "NOT_ABOVE_MINIMUM": "{{field}} must be greater than {{min}}.",+ "ABOVE_MAXIMUM": "{{field}} must be {{max}} or less.",+ "NOT_AN_OPTION": "{{field}} must be one of: {{options}}.",+ "TOO_MANY_WORKOUT_SETS": "A workout can't have more than {{max}} sets.",+ "TOO_MANY_PROGRAM_ROWS": "A program can't have more than {{max}} days, exercises and sets combined.",+ "INVALID_FIELD": "{{field}} isn't valid.",+ "INVALID_ID": "That id isn't valid.",+ "INVALID_EXERCISE_ID": "That exercise id isn't valid.",+ "INVALID_PROGRAM_ID": "That program id isn't valid.",+ "INVALID_WORKOUT_ID": "That workout id isn't valid.",+ "ENTRY_NOT_FOUND": "That entry no longer exists.",+ "SAVED_FOOD_NOT_FOUND": "That saved food no longer exists.",+ "EXERCISE_NOT_FOUND": "That exercise no longer exists.",+ "PROGRAM_NOT_FOUND": "That program no longer exists.",+ "WORKOUT_NOT_FOUND": "That workout no longer exists.",+ "UNKNOWN_EXERCISES": "One or more of those exercises no longer exist.",+ "INVALID_DATE": "Date must be in YYYY-MM-DD format.",+ "INVALID_LOGGED_ON": "Logged on must be in YYYY-MM-DD format.",+ "INVALID_FROM_DATE": "From must be in YYYY-MM-DD format.",+ "INVALID_TO_DATE": "To must be in YYYY-MM-DD format.",+ "FOOD_NAME_TOO_LONG": "Name must be {{max}} characters or fewer.",+ "FOOD_BRAND_TOO_LONG": "Brand must be {{max}} characters or fewer.",+ "SERVING_SIZE_TOO_LONG": "Serving size must be {{max}} characters or fewer.",+ "BARCODE_TOO_LONG": "Barcode must be {{max}} characters or fewer.",+ "IMAGE_URL_TOO_LONG": "Image URL must be {{max}} characters or fewer.",+ "SEARCH_TERM_REQUIRED": "A search term is required.",+ "INVALID_BARCODE": "That barcode isn't valid.",+ "PRODUCT_NOT_FOUND": "No product matched that barcode.",+ "FOOD_DATABASE_TIMEOUT": "The food database didn't respond in time. Try again.",+ "FOOD_DATABASE_UNREACHABLE": "Couldn't reach the food database.",+ "FOOD_SEARCH_UNAVAILABLE": "Food search is temporarily unavailable.",+ "BARCODE_LOOKUP_UNAVAILABLE": "Barcode lookup is temporarily unavailable.",+ "NO_EXERCISE_CATALOG": "This server has no exercise catalog configured.",+ "DISPLAY_NAME_CONTROL_CHARS": "A name can't contain line breaks or other control characters.",+ "TIMEZONE_EMPTY": "Timezone can't be empty.",+ "UNKNOWN_TIMEZONE": "Unknown timezone: {{timezone}}.",+ "NOT_A_NUMBER": "{{field}} must be a number.",+ "NOT_TEXT": "{{field}} must be text.",+ "NOT_TRUE_OR_FALSE": "{{field}} must be true or false.",+ "NOT_A_LIST": "{{field}} must be a list.",+ "NOT_AN_OBJECT": "{{field}} must be an object.",+ "BODY_WRONG_TYPE": "The request body had a field of the wrong type.",+ "BODY_NOT_JSON": "The request body wasn't valid JSON.",+ "BODY_EMPTY": "The request body was empty.",+ "BODY_UNREADABLE": "The request couldn't be read.",+ "INVALID_FIELDS": "Some of the details you entered aren't valid."+ },+ "fields": {+ "accept": "Accept",+ "barcode": "Barcode",+ "brand": "Brand",+ "calorie_target": "Calorie target",+ "calories": "Calories",+ "carb_target": "Carb target",+ "carbs": "Carbs",+ "current_password": "Current password",+ "data": "Data",+ "day_ids_known": "Day ids known",+ "days": "Days",+ "dismiss": "Dismiss",+ "display_name": "Display name",+ "distance": "Distance",+ "duration": "Duration",+ "email": "Email",+ "exercise_id": "Exercise id",+ "exercises": "Exercises",+ "fat": "Fat",+ "fat_target": "Fat target",+ "fiber": "Fiber",+ "id": "Id",+ "image_url": "Image url",+ "is_rest_day": "Is rest day",+ "is_warmup": "Is warmup",+ "logged_at": "Logged at",+ "logged_on": "Logged on",+ "meal": "Meal",+ "name": "Name",+ "new_password": "New password",+ "notes": "Notes",+ "order_index": "Order index",+ "password": "Password",+ "program_day_id": "Program day id",+ "program_id": "Program id",+ "program_set_id": "Program set id",+ "protein": "Protein",+ "protein_target": "Protein target",+ "refresh_token": "Refresh token",+ "reps": "Reps",+ "rest_seconds": "Rest seconds",+ "rpe": "Rpe",+ "serving_quantity": "Serving quantity",+ "serving_size": "Serving size",+ "serving_unit": "Serving unit",+ "servings": "Servings",+ "set_number": "Set number",+ "sets": "Sets",+ "started_at": "Started at",+ "target_reps": "Target reps",+ "target_weight": "Target weight",+ "timezone": "Timezone",+ "tz_offset_minutes": "Tz offset minutes",+ "weight": "Weight",+ "weight_unit": "Weight unit"+ }},"network": {"brief": {diff --git a/packages/shared/src/i18n/locales/es.json b/packages/shared/src/i18n/locales/es.jsonindex 2650c53..fb29205 100644--- a/packages/shared/src/i18n/locales/es.json+++ b/packages/shared/src/i18n/locales/es.json@@ -305,7 +305,136 @@"misconfigured": "La URL del servidor parece mal configurada — no se encontró el endpoint de la API. Revisa los ajustes del servidor.","restarting": "El servidor se está reiniciando o no está disponible. Inténtalo de nuevo en un momento.","notApi": "Esa dirección devolvió una página web, no la API de Lyftr. Revisa los ajustes del servidor.",- "serverError": "Error del servidor. Inténtalo de nuevo en breve."+ "serverError": "Error del servidor. Inténtalo de nuevo en breve.",+ "codes": {+ "VALIDATION_FAILED": "Algunos de los datos que ingresaste no son válidos.",+ "INVALID_CREDENTIALS": "Correo o contraseña incorrectos.",+ "EMAIL_TAKEN": "Ese correo ya está registrado.",+ "REGISTRATION_CLOSED": "El registro está cerrado en este servidor.",+ "PASSWORD_TOO_LONG": "La contraseña debe tener 72 bytes o menos: las letras con acento y los emojis cuentan más de uno.",+ "PASSWORD_UNCHANGED": "Tu nueva contraseña debe ser distinta de la actual.",+ "WRONG_CURRENT_PASSWORD": "Tu contraseña actual es incorrecta.",+ "ACCOUNT_NOT_FOUND": "Esa cuenta ya no existe.",+ "PASSWORD_CHANGED_ELSEWHERE": "Tu contraseña se cambió en otro lugar. Inténtalo de nuevo.",+ "PASSWORD_CHANGED_SIGN_IN_AGAIN": "Tu contraseña cambió. Inicia sesión de nuevo.",+ "EMAIL_CHANGED_SIGN_IN_AGAIN": "Tu correo cambió. Inicia sesión de nuevo.",+ "SIGN_IN_REQUIRED": "Debes iniciar sesión para hacer eso.",+ "SESSION_INVALID": "Tu sesión no es válida. Inicia sesión de nuevo.",+ "SESSION_EXPIRED": "Tu sesión caducó. Inicia sesión de nuevo.",+ "WRONG_TOKEN_TYPE": "Ese token no se puede usar aquí.",+ "INTERNAL_ERROR": "Algo salió mal en el servidor.",+ "DATABASE_BUSY": "La base de datos está ocupada. Inténtalo de nuevo en un momento.",+ "RATE_LIMITED": "Demasiadas solicitudes. Espera un momento e inténtalo de nuevo.",+ "REQUIRED": "El campo {{field}} es obligatorio.",+ "INVALID_EMAIL": "El campo {{field}} debe ser un correo electrónico válido.",+ "TOO_SHORT": "El campo {{field}} debe tener al menos {{min}} caracteres.",+ "TOO_LONG": "El campo {{field}} debe tener como máximo {{max}} caracteres.",+ "TOO_MANY_ITEMS": "El campo {{field}} debe tener como máximo {{max}} elementos.",+ "BELOW_MINIMUM": "El campo {{field}} debe ser {{min}} o más.",+ "NOT_ABOVE_MINIMUM": "El campo {{field}} debe ser mayor que {{min}}.",+ "ABOVE_MAXIMUM": "El campo {{field}} debe ser {{max}} o menos.",+ "NOT_AN_OPTION": "El campo {{field}} debe ser uno de estos: {{options}}.",+ "TOO_MANY_WORKOUT_SETS": "Un entrenamiento no puede tener más de {{max}} series.",+ "TOO_MANY_PROGRAM_ROWS": "Un programa no puede tener más de {{max}} días, ejercicios y series en total.",+ "INVALID_FIELD": "El campo {{field}} no es válido.",+ "INVALID_ID": "Ese identificador no es válido.",+ "INVALID_EXERCISE_ID": "Ese identificador de ejercicio no es válido.",+ "INVALID_PROGRAM_ID": "Ese identificador de programa no es válido.",+ "INVALID_WORKOUT_ID": "Ese identificador de entrenamiento no es válido.",+ "ENTRY_NOT_FOUND": "Ese registro ya no existe.",+ "SAVED_FOOD_NOT_FOUND": "Ese alimento guardado ya no existe.",+ "EXERCISE_NOT_FOUND": "Ese ejercicio ya no existe.",+ "PROGRAM_NOT_FOUND": "Ese programa ya no existe.",+ "WORKOUT_NOT_FOUND": "Ese entrenamiento ya no existe.",+ "UNKNOWN_EXERCISES": "Uno o más de esos ejercicios ya no existen.",+ "INVALID_DATE": "La fecha debe tener el formato AAAA-MM-DD.",+ "INVALID_LOGGED_ON": "La fecha del registro debe tener el formato AAAA-MM-DD.",+ "INVALID_FROM_DATE": "La fecha inicial debe tener el formato AAAA-MM-DD.",+ "INVALID_TO_DATE": "La fecha final debe tener el formato AAAA-MM-DD.",+ "FOOD_NAME_TOO_LONG": "El nombre debe tener {{max}} caracteres o menos.",+ "FOOD_BRAND_TOO_LONG": "La marca debe tener {{max}} caracteres o menos.",+ "SERVING_SIZE_TOO_LONG": "El tamaño de la porción debe tener {{max}} caracteres o menos.",+ "BARCODE_TOO_LONG": "El código de barras debe tener {{max}} caracteres o menos.",+ "IMAGE_URL_TOO_LONG": "La URL de la imagen debe tener {{max}} caracteres o menos.",+ "SEARCH_TERM_REQUIRED": "Se necesita un término de búsqueda.",+ "INVALID_BARCODE": "Ese código de barras no es válido.",+ "PRODUCT_NOT_FOUND": "Ningún producto coincide con ese código de barras.",+ "FOOD_DATABASE_TIMEOUT": "La base de datos de alimentos no respondió a tiempo. Inténtalo de nuevo.",+ "FOOD_DATABASE_UNREACHABLE": "No se pudo conectar con la base de datos de alimentos.",+ "FOOD_SEARCH_UNAVAILABLE": "La búsqueda de alimentos no está disponible por ahora.",+ "BARCODE_LOOKUP_UNAVAILABLE": "La búsqueda por código de barras no está disponible por ahora.",+ "NO_EXERCISE_CATALOG": "Este servidor no tiene un catálogo de ejercicios configurado.",+ "DISPLAY_NAME_CONTROL_CHARS": "Un nombre no puede contener saltos de línea ni otros caracteres de control.",+ "TIMEZONE_EMPTY": "La zona horaria no puede estar vacía.",+ "UNKNOWN_TIMEZONE": "Zona horaria desconocida: {{timezone}}.",+ "NOT_A_NUMBER": "El campo {{field}} debe ser un número.",+ "NOT_TEXT": "El campo {{field}} debe ser texto.",+ "NOT_TRUE_OR_FALSE": "El campo {{field}} debe ser verdadero o falso.",+ "NOT_A_LIST": "El campo {{field}} debe ser una lista.",+ "NOT_AN_OBJECT": "El campo {{field}} debe ser un objeto.",+ "BODY_WRONG_TYPE": "La solicitud tenía un campo de tipo incorrecto.",+ "BODY_NOT_JSON": "El cuerpo de la solicitud no era JSON válido.",+ "BODY_EMPTY": "El cuerpo de la solicitud estaba vacío.",+ "BODY_UNREADABLE": "No se pudo leer la solicitud.",+ "INVALID_FIELDS": "Algunos de los datos que ingresaste no son válidos."+ },+ "fields": {+ "accept": "Aceptadas",+ "barcode": "Código de barras",+ "brand": "Marca",+ "calorie_target": "Objetivo de calorías",+ "calories": "Calorías",+ "carb_target": "Objetivo de carbohidratos",+ "carbs": "Carbohidratos",+ "current_password": "Contraseña actual",+ "data": "Datos",+ "day_ids_known": "Identificadores de días",+ "days": "Días",+ "dismiss": "Descartadas",+ "display_name": "Nombre para mostrar",+ "distance": "Distancia",+ "duration": "Duración",+ "email": "Correo electrónico",+ "exercise_id": "Ejercicio",+ "exercises": "Ejercicios",+ "fat": "Grasas",+ "fat_target": "Objetivo de grasas",+ "fiber": "Fibra",+ "id": "Identificador",+ "image_url": "URL de la imagen",+ "is_rest_day": "Día de descanso",+ "is_warmup": "Calentamiento",+ "logged_at": "Hora del registro",+ "logged_on": "Fecha del registro",+ "meal": "Comida",+ "name": "Nombre",+ "new_password": "Contraseña nueva",+ "notes": "Notas",+ "order_index": "Orden",+ "password": "Contraseña",+ "program_day_id": "Día del programa",+ "program_id": "Programa",+ "program_set_id": "Serie del programa",+ "protein": "Proteínas",+ "protein_target": "Objetivo de proteínas",+ "refresh_token": "Token de actualización",+ "reps": "Repeticiones",+ "rest_seconds": "Descanso",+ "rpe": "RPE",+ "serving_quantity": "Cantidad de la porción",+ "serving_size": "Tamaño de la porción",+ "serving_unit": "Unidad de la porción",+ "servings": "Porciones",+ "set_number": "Número de serie",+ "sets": "Series",+ "started_at": "Inicio",+ "target_reps": "Repeticiones objetivo",+ "target_weight": "Peso objetivo",+ "timezone": "Zona horaria",+ "tz_offset_minutes": "Diferencia horaria",+ "weight": "Peso",+ "weight_unit": "Unidad de peso"+ }},"network": {"brief": {diff --git a/packages/shared/src/stores/auth.test.ts b/packages/shared/src/stores/auth.test.tsindex e2c69c3..b38a964 100644--- a/packages/shared/src/stores/auth.test.ts+++ b/packages/shared/src/stores/auth.test.ts@@ -68,6 +68,27 @@ describe('auth store (storage-adapter DI)', () => {}})+ it('es then en: a coded login failure in the store re-renders in the active language', async () => {+ const client = {+ authAPI: {+ login: async () => { throw { response: { status: 401, data: { error: 'Invalid email or password.', code: 'INVALID_CREDENTIALS' } } } },+ register: async () => { throw new Error('unused') },+ },+ } as unknown as LyftrClient+ const useAuth = createAuthStore(client, createMemoryStorage())++ await expect(useAuth.getState().login('[email protected]', 'nope')).rejects.toBeTruthy()+ const failure = useAuth.getState().error!+ try {+ await i18n.changeLanguage('es')+ expect(uiMessage(failure)).toBe(es.errors.api.codes.INVALID_CREDENTIALS)+ await i18n.changeLanguage('en')+ expect(uiMessage(failure)).toBe('Invalid email or password.')+ } finally {+ await i18n.changeLanguage('en')+ }+ })+it('logout clears storage and state', async () => {const storage = createMemoryStorage()const useAuth = createAuthStore(fakeClient(), storage)diff --git a/web/src/pages/Login.test.tsx b/web/src/pages/Login.test.tsxnew file mode 100644index 0000000..754a1af--- /dev/null+++ b/web/src/pages/Login.test.tsx@@ -0,0 +1,38 @@+import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest'+import { render, fireEvent, waitFor, act } from '@testing-library/react'+import { MemoryRouter } from 'react-router-dom'+import Login from './Login'+import { i18n } from '@lyftr/shared'+import es from '../../../packages/shared/src/i18n/locales/es.json'++const login = vi.fn()++vi.mock('../stores/auth', () => ({+ useAuthStore: () => ({ login }),+}))+vi.mock('../hooks/useServerInfo', () => ({ useServerInfo: () => null }))+vi.mock('../components/ServerSettings', () => ({ default: () => null }))++const submit = (container: HTMLElement) => {+ fireEvent.change(container.querySelector('#email')!, { target: { value: '[email protected]' } })+ fireEvent.change(container.querySelector('#password')!, { target: { value: 'wrongpassword' } })+ fireEvent.submit(container.querySelector('form')!)+}++describe('Login server errors', () => {+ beforeEach(() => { login.mockReset() })+ afterEach(async () => { await i18n.changeLanguage('en') })++ it('es: INVALID_CREDENTIALS shows Spanish and follows a switch back to English', async () => {+ await i18n.changeLanguage('es')+ login.mockRejectedValue({+ response: { status: 401, data: { error: 'Invalid email or password.', code: 'INVALID_CREDENTIALS' } },+ })+ const { container } = render(<MemoryRouter><Login /></MemoryRouter>)+ submit(container)++ await waitFor(() => expect(container.querySelector('.alert-error')?.textContent).toBe(es.errors.api.codes.INVALID_CREDENTIALS))+ await act(async () => { await i18n.changeLanguage('en') })+ expect(container.querySelector('.alert-error')?.textContent).toBe('Invalid email or password.')+ })+})diff --git a/web/src/pages/Register.test.tsx b/web/src/pages/Register.test.tsxnew file mode 100644index 0000000..7ff6d31--- /dev/null+++ b/web/src/pages/Register.test.tsx@@ -0,0 +1,49 @@+import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest'+import { render, fireEvent, waitFor } from '@testing-library/react'+import { MemoryRouter } from 'react-router-dom'+import Register from './Register'+import { i18n } from '@lyftr/shared'+import es from '../../../packages/shared/src/i18n/locales/es.json'++const register = vi.fn()++vi.mock('../stores/auth', () => ({+ useAuthStore: () => ({ register }),+}))+vi.mock('../hooks/useServerInfo', () => ({ useServerInfo: () => ({ name: 'Lyftr', version: '1', registration_open: true }) }))+vi.mock('../components/ServerSettings', () => ({ default: () => null }))++const submit = (container: HTMLElement) => {+ fireEvent.change(container.querySelector('#email')!, { target: { value: '[email protected]' } })+ fireEvent.change(container.querySelector('#password')!, { target: { value: 'password123' } })+ fireEvent.change(container.querySelector('#password-confirm')!, { target: { value: 'password123' } })+ fireEvent.submit(container.querySelector('form')!)+}++const renderPage = () => render(<MemoryRouter><Register /></MemoryRouter>)++describe('Register server errors', () => {+ beforeEach(() => { register.mockReset() })+ afterEach(async () => { await i18n.changeLanguage('en') })++ it('es: EMAIL_TAKEN shows Spanish', async () => {+ await i18n.changeLanguage('es')+ register.mockRejectedValue({+ response: { status: 409, data: { error: 'That email is already registered.', code: 'EMAIL_TAKEN' } },+ })+ const { container } = renderPage()+ submit(container)++ await waitFor(() => expect(container.querySelector('.alert-error')?.textContent).toBe(es.errors.api.codes.EMAIL_TAKEN))+ })++ it('a response without a code shows the server sentence', async () => {+ register.mockRejectedValue({+ response: { status: 409, data: { error: 'That email is already registered.' } },+ })+ const { container } = renderPage()+ submit(container)++ await waitFor(() => expect(container.querySelector('.alert-error')?.textContent).toBe('That email is already registered.'))+ })+})